Deploy AIOS web (React glide grid + FastAPI slice)
Browse filesThis view is limited to 50 files because it contains too many changes. Β See raw diff
- RELEASES.json +1 -1
- VERSION +1 -1
- api/automation_control.py +17 -1
- api/automation_engine.py +12 -1
- api/routes_admin.py +35 -3
- api/routes_customers.py +650 -143
- api/routes_geo.py +81 -9
- api/routes_grid.py +170 -13
- api/routes_nav.py +4 -1
- api/routes_shares.py +430 -13
- api/routes_tables.py +163 -25
- platform/aios_grid.py +92 -10
- platform/aios_grid_fields.json +2 -0
- platform/core/field_permissions.py +225 -21
- platform/core/grid_events.py +23 -7
- platform/core/route_system.py +345 -10
- platform/core/shared_overlay.py +100 -3
- platform/core/table_store.py +26 -7
- platform/core/user_tables.py +157 -5
- platform/harness/semantic.py +68 -5
- platform/model/topics/sales_lines.yml +12 -0
- web/public/sample_customers.json +1 -0
- web/src/automation/AutomationBuilder.tsx +114 -48
- web/src/automation/AutomationDetail.tsx +33 -18
- web/src/automation/AutomationSurface.tsx +19 -3
- web/src/automation/VoiceAgentProperties.tsx +396 -77
- web/src/automation/automationApi.ts +204 -3
- web/src/automation/voiceAgentTypes.ts +62 -19
- web/src/customer-grid/CatalogView.tsx +3 -2
- web/src/customer-grid/ColumnMenu.tsx +409 -51
- web/src/customer-grid/CustomerGrid.tsx +359 -78
- web/src/customer-grid/FieldProperties.tsx +3 -3
- web/src/customer-grid/FormInterface.tsx +4 -3
- web/src/customer-grid/MapView.tsx +687 -264
- web/src/customer-grid/RecordDetail.tsx +2 -2
- web/src/customer-grid/RouteNav.tsx +540 -29
- web/src/customer-grid/ScriptViewPanel.tsx +3 -2
- web/src/customer-grid/TimeSeriesPanel.tsx +4 -3
- web/src/customer-grid/Toolbar.tsx +64 -8
- web/src/customer-grid/ViewSidebar.tsx +714 -63
- web/src/customer-grid/apiBridge.ts +140 -0
- web/src/customer-grid/dataPath.ts +154 -1
- web/src/customer-grid/formulaEngine.ts +434 -9
- web/src/customer-grid/map.css +65 -24
- web/src/customer-grid/navFold.ts +19 -0
- web/src/customer-grid/routeLinks.ts +52 -0
- web/src/customer-grid/routeStopMove.ts +87 -0
- web/src/customer-grid/routeZoneApi.ts +72 -0
- web/src/customer-grid/routeZoneTypes.ts +76 -2
- web/src/customer-grid/types.ts +251 -7
RELEASES.json
CHANGED
|
@@ -1,5 +1,5 @@
|
|
| 1 |
{
|
| 2 |
-
"current": "
|
| 3 |
"releases": [
|
| 4 |
{
|
| 5 |
"version": "v54",
|
|
|
|
| 1 |
{
|
| 2 |
+
"current": "0e72b16",
|
| 3 |
"releases": [
|
| 4 |
{
|
| 5 |
"version": "v54",
|
VERSION
CHANGED
|
@@ -1 +1 @@
|
|
| 1 |
-
|
|
|
|
| 1 |
+
0e72b16
|
api/automation_control.py
CHANGED
|
@@ -19,6 +19,7 @@ import os
|
|
| 19 |
import re
|
| 20 |
import time
|
| 21 |
import uuid
|
|
|
|
| 22 |
|
| 23 |
import requests
|
| 24 |
|
|
@@ -124,6 +125,21 @@ def _base_job(tenant: str, defn: dict, mode: str) -> dict:
|
|
| 124 |
"scheduledTime": "<aws.scheduler.scheduled-time>"}
|
| 125 |
|
| 126 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 127 |
def recurring_specs(tenant: str, defn: dict) -> list[dict]:
|
| 128 |
scope = schedule_scope(tenant, defn.get("id"))
|
| 129 |
specs: list[dict] = []
|
|
@@ -131,7 +147,7 @@ def recurring_specs(tenant: str, defn: dict) -> list[dict]:
|
|
| 131 |
if schedule.get("enabled"):
|
| 132 |
for index, expression in enumerate(aws_cron_expressions(schedule.get("cron") or "")):
|
| 133 |
specs.append({"name": f"{scope}-schedule-{index}", "mode": "schedule",
|
| 134 |
-
"expression": expression, "timezone":
|
| 135 |
"job": _base_job(tenant, defn, "schedule")})
|
| 136 |
trigger = defn.get("trigger") or {}
|
| 137 |
if (trigger.get("key") == "email" and trigger.get("enabled", True)
|
|
|
|
| 19 |
import re
|
| 20 |
import time
|
| 21 |
import uuid
|
| 22 |
+
from zoneinfo import ZoneInfo, ZoneInfoNotFoundError
|
| 23 |
|
| 24 |
import requests
|
| 25 |
|
|
|
|
| 125 |
"scheduledTime": "<aws.scheduler.scheduled-time>"}
|
| 126 |
|
| 127 |
|
| 128 |
+
def _recurring_timezone(defn: dict) -> str:
|
| 129 |
+
"""Use a Route's frozen wall-clock Zone; every other automation remains UTC."""
|
| 130 |
+
if str(defn.get("kind") or "") != "route_delivery":
|
| 131 |
+
return "UTC"
|
| 132 |
+
schedule = defn.get("schedule") if isinstance(defn.get("schedule"), dict) else {}
|
| 133 |
+
config = defn.get("config") if isinstance(defn.get("config"), dict) else {}
|
| 134 |
+
snapshot = config.get("routeSnapshot") if isinstance(config.get("routeSnapshot"), dict) else {}
|
| 135 |
+
timezone = str(schedule.get("timezone") or snapshot.get("timezone") or "").strip()
|
| 136 |
+
try:
|
| 137 |
+
ZoneInfo(timezone)
|
| 138 |
+
except (ZoneInfoNotFoundError, ValueError):
|
| 139 |
+
raise ValueError("a scheduled route needs a recognized IANA timezone") from None
|
| 140 |
+
return timezone
|
| 141 |
+
|
| 142 |
+
|
| 143 |
def recurring_specs(tenant: str, defn: dict) -> list[dict]:
|
| 144 |
scope = schedule_scope(tenant, defn.get("id"))
|
| 145 |
specs: list[dict] = []
|
|
|
|
| 147 |
if schedule.get("enabled"):
|
| 148 |
for index, expression in enumerate(aws_cron_expressions(schedule.get("cron") or "")):
|
| 149 |
specs.append({"name": f"{scope}-schedule-{index}", "mode": "schedule",
|
| 150 |
+
"expression": expression, "timezone": _recurring_timezone(defn),
|
| 151 |
"job": _base_job(tenant, defn, "schedule")})
|
| 152 |
trigger = defn.get("trigger") or {}
|
| 153 |
if (trigger.get("key") == "email" and trigger.get("enabled", True)
|
api/automation_engine.py
CHANGED
|
@@ -35,6 +35,7 @@ import socket
|
|
| 35 |
import threading
|
| 36 |
import time
|
| 37 |
from urllib.parse import urljoin, urlparse
|
|
|
|
| 38 |
|
| 39 |
import requests
|
| 40 |
|
|
@@ -1670,14 +1671,19 @@ def clean_config(kind, raw, previous=None):
|
|
| 1670 |
revision = str(snap.get("sourceViewRevision") or "").strip()[:128]
|
| 1671 |
recipient = str(raw.get("recipient") or "").strip()[:120]
|
| 1672 |
timezone = str(snap.get("timezone") or raw.get("timezone") or "UTC").strip()[:80]
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1673 |
source_name = " ".join(str(snap.get("sourceViewName") or "").split())[:120]
|
|
|
|
| 1674 |
route_field = str(snap.get("routeField") or "").strip()[:120]
|
| 1675 |
try:
|
| 1676 |
links_per_map = int(snap.get("mapsPerLink", raw.get("mapsPerLink", 10)))
|
| 1677 |
except (TypeError, ValueError):
|
| 1678 |
links_per_map = 10
|
| 1679 |
# R5: Google directions requires at least an origin and destination. The map UI exposes
|
| 1680 |
-
# the same 2
|
| 1681 |
links_per_map = max(2, min(10, links_per_map))
|
| 1682 |
ordered = []
|
| 1683 |
seen = set()
|
|
@@ -1700,6 +1706,7 @@ def clean_config(kind, raw, previous=None):
|
|
| 1700 |
return {
|
| 1701 |
"recipient": recipient,
|
| 1702 |
"routeSnapshot": {
|
|
|
|
| 1703 |
"sourceViewId": source_view,
|
| 1704 |
"sourceViewRevision": revision,
|
| 1705 |
"sourceViewName": source_name or source_view,
|
|
@@ -2340,6 +2347,10 @@ def clean_definition(raw, previous=None, username="", notes=None, rt=None):
|
|
| 2340 |
else prev.get("schedule"), prev.get("schedule"))
|
| 2341 |
except ValueError as e:
|
| 2342 |
return None, str(e)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2343 |
# (`clean_trigger` ran at the top β law 1 needs the trigger before the kind.)
|
| 2344 |
flow_raw = raw.get("flow") if "flow" in raw else prev.get("flow")
|
| 2345 |
# β EVERY CLEAN, NOT ONLY THE EDGE (owner ruling 6 β see `_ensure_ig_action`). The edge-only
|
|
|
|
| 35 |
import threading
|
| 36 |
import time
|
| 37 |
from urllib.parse import urljoin, urlparse
|
| 38 |
+
from zoneinfo import ZoneInfo, ZoneInfoNotFoundError
|
| 39 |
|
| 40 |
import requests
|
| 41 |
|
|
|
|
| 1671 |
revision = str(snap.get("sourceViewRevision") or "").strip()[:128]
|
| 1672 |
recipient = str(raw.get("recipient") or "").strip()[:120]
|
| 1673 |
timezone = str(snap.get("timezone") or raw.get("timezone") or "UTC").strip()[:80]
|
| 1674 |
+
try:
|
| 1675 |
+
ZoneInfo(timezone)
|
| 1676 |
+
except (ZoneInfoNotFoundError, ValueError):
|
| 1677 |
+
return None, "a scheduled route needs a recognized IANA timezone"
|
| 1678 |
source_name = " ".join(str(snap.get("sourceViewName") or "").split())[:120]
|
| 1679 |
+
route_id = str(snap.get("routeId") or "").strip()[:96]
|
| 1680 |
route_field = str(snap.get("routeField") or "").strip()[:120]
|
| 1681 |
try:
|
| 1682 |
links_per_map = int(snap.get("mapsPerLink", raw.get("mapsPerLink", 10)))
|
| 1683 |
except (TypeError, ValueError):
|
| 1684 |
links_per_map = 10
|
| 1685 |
# R5: Google directions requires at least an origin and destination. The map UI exposes
|
| 1686 |
+
# the same 2-10 bound; this server normalisation is the wall for hand-written bodies too.
|
| 1687 |
links_per_map = max(2, min(10, links_per_map))
|
| 1688 |
ordered = []
|
| 1689 |
seen = set()
|
|
|
|
| 1706 |
return {
|
| 1707 |
"recipient": recipient,
|
| 1708 |
"routeSnapshot": {
|
| 1709 |
+
"routeId": route_id,
|
| 1710 |
"sourceViewId": source_view,
|
| 1711 |
"sourceViewRevision": revision,
|
| 1712 |
"sourceViewName": source_name or source_view,
|
|
|
|
| 2347 |
else prev.get("schedule"), prev.get("schedule"))
|
| 2348 |
except ValueError as e:
|
| 2349 |
return None, str(e)
|
| 2350 |
+
if kind == "route_delivery":
|
| 2351 |
+
# Native cron interprets this wall clock in the exact validated Zone frozen beside the
|
| 2352 |
+
# Route. Ordinary automations intentionally retain their historical UTC default.
|
| 2353 |
+
schedule["timezone"] = config["routeSnapshot"]["timezone"]
|
| 2354 |
# (`clean_trigger` ran at the top β law 1 needs the trigger before the kind.)
|
| 2355 |
flow_raw = raw.get("flow") if "flow" in raw else prev.get("flow")
|
| 2356 |
# β EVERY CLEAN, NOT ONLY THE EDGE (owner ruling 6 β see `_ensure_ig_action`). The edge-only
|
api/routes_admin.py
CHANGED
|
@@ -843,7 +843,7 @@ def _module_fields(key, session=None):
|
|
| 843 |
if isinstance(_uf, dict) and _uf.get("key") and _uf["key"] not in _have:
|
| 844 |
_have.add(_uf["key"])
|
| 845 |
src.append(_uf)
|
| 846 |
-
known = _server_side_vocabularies()
|
| 847 |
out = []
|
| 848 |
for f in src:
|
| 849 |
if not isinstance(f, dict) or not f.get("key"):
|
|
@@ -1019,7 +1019,7 @@ BLANK = "(none)"
|
|
| 1019 |
_VOCAB_CACHE = None
|
| 1020 |
|
| 1021 |
|
| 1022 |
-
def _server_side_vocabularies():
|
| 1023 |
"""`{field key: [choice, β¦]}` for choice columns whose vocabulary is CLOSED and known here,
|
| 1024 |
but which the grid contract does not declare.
|
| 1025 |
|
|
@@ -1090,8 +1090,36 @@ def _server_side_vocabularies():
|
|
| 1090 |
it. Recorded because the ask, not a guess, is what settled it.
|
| 1091 |
"""
|
| 1092 |
global _VOCAB_CACHE
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1093 |
if _VOCAB_CACHE is not None:
|
| 1094 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1095 |
|
| 1096 |
out = {}
|
| 1097 |
|
|
@@ -1199,6 +1227,10 @@ def _server_side_vocabularies():
|
|
| 1199 |
_agents, _salespeople)])
|
| 1200 |
if complete:
|
| 1201 |
_VOCAB_CACHE = dict(out)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1202 |
return out
|
| 1203 |
|
| 1204 |
|
|
|
|
| 843 |
if isinstance(_uf, dict) and _uf.get("key") and _uf["key"] not in _have:
|
| 844 |
_have.add(_uf["key"])
|
| 845 |
src.append(_uf)
|
| 846 |
+
known = _server_side_vocabularies(session=session)
|
| 847 |
out = []
|
| 848 |
for f in src:
|
| 849 |
if not isinstance(f, dict) or not f.get("key"):
|
|
|
|
| 1019 |
_VOCAB_CACHE = None
|
| 1020 |
|
| 1021 |
|
| 1022 |
+
def _server_side_vocabularies(session=None):
|
| 1023 |
"""`{field key: [choice, β¦]}` for choice columns whose vocabulary is CLOSED and known here,
|
| 1024 |
but which the grid contract does not declare.
|
| 1025 |
|
|
|
|
| 1090 |
it. Recorded because the ask, not a guess, is what settled it.
|
| 1091 |
"""
|
| 1092 |
global _VOCAB_CACHE
|
| 1093 |
+
|
| 1094 |
+
def _product_shared_choices():
|
| 1095 |
+
"""Tenant-owned options for the editable Product taxonomy columns.
|
| 1096 |
+
|
| 1097 |
+
These nine fields are ordinary shared Product fields. Their vocabulary is admitted by
|
| 1098 |
+
the same atomic cell+choice write that stores an edit, so the permission editor must read
|
| 1099 |
+
the tenant's shared definition rather than inventing a global list or loading the whole
|
| 1100 |
+
Product pool. A missing runtime honestly supplies nothing; a value from another tenant
|
| 1101 |
+
must never be borrowed from the process cache below.
|
| 1102 |
+
"""
|
| 1103 |
+
if session is None:
|
| 1104 |
+
return {}
|
| 1105 |
+
import core.shared_overlay as shared_overlay
|
| 1106 |
+
import modules.product_data as product_data
|
| 1107 |
+
|
| 1108 |
+
stored = shared_overlay.fields(product_data.TABLE_KEY, st=session.runtime) or {}
|
| 1109 |
+
keys = ("collection", "color", "finish", "main_category", "material",
|
| 1110 |
+
"occassion", "shape_style", "size", "sub_category")
|
| 1111 |
+
return {key: (stored.get(key) or {}).get("options") or () for key in keys}
|
| 1112 |
+
|
| 1113 |
if _VOCAB_CACHE is not None:
|
| 1114 |
+
out = dict(_VOCAB_CACHE)
|
| 1115 |
+
try:
|
| 1116 |
+
for key, values in _product_shared_choices().items():
|
| 1117 |
+
clean = sorted({str(v) for v in values if str(v or "").strip()})
|
| 1118 |
+
if clean:
|
| 1119 |
+
out[key] = clean
|
| 1120 |
+
except Exception: # noqa: BLE001
|
| 1121 |
+
pass
|
| 1122 |
+
return out
|
| 1123 |
|
| 1124 |
out = {}
|
| 1125 |
|
|
|
|
| 1227 |
_agents, _salespeople)])
|
| 1228 |
if complete:
|
| 1229 |
_VOCAB_CACHE = dict(out)
|
| 1230 |
+
# Tenant-owned choices are deliberately added AFTER the process cache is stamped. Caching
|
| 1231 |
+
# them beside Odoo's shared Royal vocabulary would leak one tenant's Product taxonomy into
|
| 1232 |
+
# another tenant's permission editor for the life of the worker.
|
| 1233 |
+
arm(_product_shared_choices)
|
| 1234 |
return out
|
| 1235 |
|
| 1236 |
|
api/routes_customers.py
CHANGED
|
@@ -190,7 +190,11 @@ def shared_fields(st=None):
|
|
| 190 |
try:
|
| 191 |
field_permissions.migrate_legacy_fields(
|
| 192 |
_shared_key(), st=st, grant_topic="customer_data", shared_key=_shared_key())
|
| 193 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 194 |
except Exception: # noqa: BLE001
|
| 195 |
# Lenient like every other display read: an unreachable store degrades to "nothing is
|
| 196 |
# shared yet", never to a 500 on a grid that would otherwise render. The WALL does not
|
|
@@ -198,6 +202,11 @@ def shared_fields(st=None):
|
|
| 198 |
return {}
|
| 199 |
|
| 200 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 201 |
def shared_cells(pids, st=None):
|
| 202 |
"""`{"<pid>": {key: value}}` for the rows named by `pids`, and ONLY those.
|
| 203 |
|
|
@@ -213,7 +222,14 @@ def shared_cells(pids, st=None):
|
|
| 213 |
return {}
|
| 214 |
|
| 215 |
|
| 216 |
-
def
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 217 |
"""`fields` PLUS the tenant-wide columns this topic declares β `routes_tables._ut_shared_fields`
|
| 218 |
on the customer topic.
|
| 219 |
|
|
@@ -225,12 +241,33 @@ def _merge_shared_fields(fields, defs, session=None):
|
|
| 225 |
β A key the canonical contract already declares WINS. A shared column is an ADDITION to this
|
| 226 |
database's contract, never a redefinition of a column it already has.
|
| 227 |
"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 228 |
if not defs:
|
| 229 |
return fields
|
| 230 |
-
have = {f.get("key") for f in (fields or ()) if isinstance(f, dict)}
|
| 231 |
projected = []
|
| 232 |
for k, f in defs.items():
|
| 233 |
-
if
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 234 |
continue
|
| 235 |
item = dict(f, source="overlay", shared=True)
|
| 236 |
if session is not None:
|
|
@@ -240,8 +277,29 @@ def _merge_shared_fields(fields, defs, session=None):
|
|
| 240 |
is_admin=session.admin, st=session.runtime)
|
| 241 |
if role:
|
| 242 |
item["sharedRole"] = role
|
| 243 |
-
|
| 244 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 245 |
|
| 246 |
|
| 247 |
def grid_assembly(session: Session, scope: str = "customer", storage_key: str = "",
|
|
@@ -305,9 +363,10 @@ def grid_assembly(session: Session, scope: str = "customer", storage_key: str =
|
|
| 305 |
# dict on one request (the write ctx's wall, the read merge, and the closure), and letting each
|
| 306 |
# take its own copy is the shape D-214 spent a whole ticket removing one document over.
|
| 307 |
_defs = shared_fields(st=rt)
|
|
|
|
| 308 |
ws = grid_events.table_workspace(
|
| 309 |
-
|
| 310 |
-
consume_corrections=consume_corrections)
|
| 311 |
# ββ W38-T20 / D-425 β THE TENANT-WIDE CELLS, LAYERED OVER THE PER-USER ONES, IN THE
|
| 312 |
# ASSEMBLY SO EVERY CONSUMER SEES ONE TRUTH. `routes_grid`'s /workspace route serves
|
| 313 |
# `workspace["overlays"] = g["ws"].get("overlays")` verbatim and `_payload` hands the same
|
|
@@ -333,7 +392,8 @@ def grid_assembly(session: Session, scope: str = "customer", storage_key: str =
|
|
| 333 |
# ββ W38-T20 β AND THE COLUMN DEFINITIONS, BEFORE THE WALL. See `_merge_shared_fields`: this
|
| 334 |
# position is load-bearing twice, once for the transitive closure and once because it is the
|
| 335 |
# only order in which the per-field grant marker is ever presented to `hidden_keys`.
|
| 336 |
-
|
|
|
|
| 337 |
# Legacy `Destination N` definitions remain in the shared document for rollback/audit, but
|
| 338 |
# once the dedicated migration recorded its independent parity proof they are display-hidden.
|
| 339 |
# This is intentionally a projection only: no field or cell is deleted here.
|
|
@@ -341,6 +401,9 @@ def grid_assembly(session: Session, scope: str = "customer", storage_key: str =
|
|
| 341 |
_legacy_migrations = route_system.read(rt).get("legacyMigrations") or {}
|
| 342 |
fields = [field for field in fields if not (
|
| 343 |
isinstance(field, dict) and (_legacy_migrations.get(str(field.get("key"))) or {}).get("verified"))]
|
|
|
|
|
|
|
|
|
|
| 344 |
# ββ W41-T01 / RULING R5 / CONTRACTS C1 + C8 β **THE THREE BADGES, STAMPED ONCE, HERE.**
|
| 345 |
#
|
| 346 |
# C1 makes `field_permissions.field_class` the ONE producer of `{origin, audience, sharedBy,
|
|
@@ -384,7 +447,8 @@ def grid_assembly(session: Session, scope: str = "customer", storage_key: str =
|
|
| 384 |
try:
|
| 385 |
from core import field_permissions as _fp
|
| 386 |
_classes = _fp.field_classes(fields, session.uname, table_key=_shared_key(),
|
| 387 |
-
grant_topic=SHARE_TOPIC, values_shared=set(_defs),
|
|
|
|
| 388 |
fields = [dict(f, **{"class": _classes[f["key"]]})
|
| 389 |
if isinstance(f, dict) and _classes.get(f.get("key")) else f
|
| 390 |
for f in fields]
|
|
@@ -406,6 +470,22 @@ def grid_assembly(session: Session, scope: str = "customer", storage_key: str =
|
|
| 406 |
# makes this degrade safe: a client renders NOTHING for a missing `class` rather than a
|
| 407 |
# wrong badge, so a registry that will not open costs the badges and not the grid.
|
| 408 |
pass
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 409 |
# THE FIELD WALL β a TRANSITIVE closure (C-PERM amendment 5), so hiding a field also hides
|
| 410 |
# every formula computed FROM it. Formulas evaluate in the browser from `{ref}`s, so
|
| 411 |
# shipping a dependent formula while withholding its input either leaks the input through
|
|
@@ -483,7 +563,9 @@ def grid_assembly(session: Session, scope: str = "customer", storage_key: str =
|
|
| 483 |
|
| 484 |
# Route stops and Zone membership are normalized system relations. They project into two
|
| 485 |
# read-only customer fields; neither is a generic Link or an editable user-table cell.
|
| 486 |
-
|
|
|
|
|
|
|
| 487 |
normalized_zones = route_system.list_zones(rt, rows_src)
|
| 488 |
fields = [field for field in fields if field.get("key") not in {"routes", "zone"}]
|
| 489 |
fields.extend(route_system.customer_projection_fields(normalized_routes, normalized_zones))
|
|
@@ -642,20 +724,153 @@ def _route_input_pids(raw):
|
|
| 642 |
return offered
|
| 643 |
|
| 644 |
|
| 645 |
-
def
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 646 |
from core import route_system
|
| 647 |
allowed = {int(pid) for pid in allowed}
|
| 648 |
stops = [stop for stop in route_system.ordered_stops(route)
|
| 649 |
if int(stop.get("customerPid")) in allowed]
|
| 650 |
visible = [int(stop["customerPid"]) for stop in stops]
|
| 651 |
active = {int(pid) for pid in active if int(pid) in allowed}
|
|
|
|
|
|
|
|
|
|
|
|
|
| 652 |
dto = {"id": route["id"], "name": route["name"], "color": route["color"],
|
| 653 |
"number": route["number"], "visibleStopIds": visible,
|
| 654 |
"outsideFilter": bool(active) and not bool(active.intersection(visible)),
|
| 655 |
-
"permission": {"canEdit":
|
|
|
|
| 656 |
"sourceViewId": route.get("sourceViewId")},
|
| 657 |
"source": {"viewId": route.get("sourceViewId"),
|
| 658 |
-
"revision": route.get("sourceViewRevision")}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 659 |
if route.get("mapsUrl"):
|
| 660 |
dto["mapsUrl"] = route["mapsUrl"]
|
| 661 |
return dto
|
|
@@ -672,8 +887,7 @@ def _query_pids(raw):
|
|
| 672 |
|
| 673 |
|
| 674 |
def _route_or_404(session, route_id):
|
| 675 |
-
|
| 676 |
-
route = next((item for item in route_system.list_routes(session.runtime)
|
| 677 |
if item.get("id") == str(route_id)), None)
|
| 678 |
if route is None:
|
| 679 |
raise err(404, "route_not_found", "that Route does not exist")
|
|
@@ -681,26 +895,61 @@ def _route_or_404(session, route_id):
|
|
| 681 |
|
| 682 |
|
| 683 |
def _route_mutation_allowed(session, route, requested_source=None):
|
|
|
|
|
|
|
|
|
|
| 684 |
source = requested_source if requested_source is not None else route.get("sourceViewId")
|
| 685 |
if not _route_view_can_edit(session, source):
|
| 686 |
raise err(403, "route_view_read_only", "only an editor of the Route source View can change it")
|
| 687 |
|
| 688 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 689 |
@router.get("/customers/routes")
|
| 690 |
def routes(visiblePids: str = "", currentPids: str = "",
|
| 691 |
session: Session = Depends(module_gate(MODULE))):
|
| 692 |
"""Route picker DTO consumed by C1/C3; only permitted stops ever leave the server."""
|
| 693 |
-
from core import route_system
|
| 694 |
allowed = allowed_pids(session)
|
| 695 |
active = _query_pids(currentPids or visiblePids)
|
| 696 |
-
|
| 697 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 698 |
|
| 699 |
|
| 700 |
@router.post("/customers/routes", status_code=201)
|
| 701 |
def create_route(body: dict = Body(default=None), session: Session = Depends(module_gate(MODULE))):
|
| 702 |
from core import route_system
|
| 703 |
raw = dict(body or {})
|
|
|
|
| 704 |
if not _route_view_can_edit(session, raw.get("sourceViewId")):
|
| 705 |
raise err(403, "route_view_read_only", "a Route requires an editable source View")
|
| 706 |
permitted = allowed_pids(session)
|
|
@@ -709,9 +958,34 @@ def create_route(body: dict = Body(default=None), session: Session = Depends(mod
|
|
| 709 |
route = route_system.put_route(session.runtime, raw, tenant_id=session.tenant, created_by=session.uname)
|
| 710 |
if route is None:
|
| 711 |
raise err(400, "invalid_route", "a Route needs a name and an optional HTTPS Google Maps URL")
|
|
|
|
| 712 |
return {"route": _route_dto(route, permitted, (), session)}
|
| 713 |
|
| 714 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 715 |
@router.patch("/customers/routes/{route_id}")
|
| 716 |
def update_route(route_id: str, body: dict = Body(default=None),
|
| 717 |
session: Session = Depends(module_gate(MODULE))):
|
|
@@ -725,6 +999,7 @@ def update_route(route_id: str, body: dict = Body(default=None),
|
|
| 725 |
route = route_system.put_route(session.runtime, raw, tenant_id=session.tenant, created_by=session.uname)
|
| 726 |
if route is None:
|
| 727 |
raise err(400, "invalid_route", "a Route needs a name and an optional HTTPS Google Maps URL")
|
|
|
|
| 728 |
return {"route": _route_dto(route, allowed_pids(session), (), session)}
|
| 729 |
|
| 730 |
|
|
@@ -750,26 +1025,168 @@ def move_route_stop(route_id: str, body: dict = Body(default=None),
|
|
| 750 |
return {"route": _route_dto(route, allowed_pids(session), (), session)}
|
| 751 |
|
| 752 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 753 |
@router.delete("/customers/routes/{route_id}")
|
| 754 |
def remove_route(route_id: str, session: Session = Depends(module_gate(MODULE))):
|
| 755 |
from core import route_system
|
| 756 |
route = _route_or_404(session, route_id)
|
| 757 |
_route_mutation_allowed(session, route)
|
| 758 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 759 |
return {"deleted": True}
|
| 760 |
|
| 761 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 762 |
@router.post("/customers/routes/selection")
|
| 763 |
def route_selection(body: dict = Body(default=None), session: Session = Depends(module_gate(MODULE))):
|
| 764 |
"""Dedicated managed-OR mutation; user filter clauses are returned byte-for-byte intact."""
|
| 765 |
from core import route_system
|
| 766 |
raw = dict(body or {})
|
| 767 |
chosen = [str(item) for item in raw.get("routeIds") or ()]
|
| 768 |
-
|
|
|
|
| 769 |
if any(route_id not in known for route_id in chosen):
|
| 770 |
raise err(404, "route_not_found", "a selected Route does not exist")
|
| 771 |
state = route_system.apply_managed_route_selection(
|
| 772 |
-
raw.get("viewState"), chosen,
|
| 773 |
return {"viewState": state, "managedBy": route_system.MANAGED_BY}
|
| 774 |
|
| 775 |
|
|
@@ -873,10 +1290,20 @@ def _zone_can_edit(session, source_view_id):
|
|
| 873 |
def _zone_dto(zone, allowed, session):
|
| 874 |
return {"id": zone["id"], "name": zone["name"], "color": zone["color"],
|
| 875 |
"geometryGeoJson": zone.get("geometryGeoJson"), "zipCodes": zone.get("zipCodes") or [],
|
| 876 |
-
|
|
|
|
|
|
|
|
|
|
| 877 |
"membershipRevision": zone.get("membershipRevision", 0),
|
|
|
|
|
|
|
|
|
|
|
|
|
| 878 |
"visible": zone.get("visible", True),
|
| 879 |
-
"permission": {
|
|
|
|
|
|
|
|
|
|
| 880 |
|
| 881 |
|
| 882 |
@router.get("/customers/zones")
|
|
@@ -892,6 +1319,7 @@ def zones(session: Session = Depends(module_gate(MODULE))):
|
|
| 892 |
def create_zone(body: dict = Body(default=None), session: Session = Depends(module_gate(MODULE))):
|
| 893 |
from core import route_system
|
| 894 |
raw = dict(body or {})
|
|
|
|
| 895 |
if not _zone_can_edit(session, raw.get("sourceViewId")):
|
| 896 |
raise err(403, "zone_view_read_only", "a Zone requires an editable source View")
|
| 897 |
zone = route_system.put_zone(session.runtime, raw, rows=_pool_rows(session),
|
|
@@ -910,8 +1338,12 @@ def update_zone(zone_id: str, body: dict = Body(default=None),
|
|
| 910 |
if prior is None:
|
| 911 |
raise err(404, "zone_not_found", "that Zone does not exist")
|
| 912 |
raw = dict(body or {})
|
| 913 |
-
|
|
|
|
|
|
|
|
|
|
| 914 |
raise err(403, "zone_view_read_only", "a Zone requires an editable source View")
|
|
|
|
| 915 |
raw["id"] = prior["id"]
|
| 916 |
zone = route_system.put_zone(session.runtime, raw, rows=_pool_rows(session),
|
| 917 |
tenant_id=session.tenant, created_by=session.uname)
|
|
@@ -980,9 +1412,10 @@ def _patch_route_ranks(session, ctx, pid, pool, updates):
|
|
| 980 |
`patch_customer` routes everything else through `grid_events` rather than writing the store.
|
| 981 |
|
| 982 |
β UNIQUENESS IS MAINTAINED OVER THE ROWS THIS CALLER CAN SEE, and that is a limit worth
|
| 983 |
-
stating rather than hiding. `shared_overlay.
|
| 984 |
-
|
| 985 |
-
looked for inside this session's book
|
|
|
|
| 986 |
`route_order_write` REFUSES a body carrying a pid outside the writer's pool, so every number in
|
| 987 |
a route order was written by somebody whose book contained all of them.
|
| 988 |
"""
|
|
@@ -998,49 +1431,30 @@ def _patch_route_ranks(session, ctx, pid, pool, updates):
|
|
| 998 |
#: value the caller did NOT ask for.
|
| 999 |
taken, swaps = set(), []
|
| 1000 |
|
| 1001 |
-
def
|
| 1002 |
-
"""
|
| 1003 |
|
| 1004 |
-
|
| 1005 |
-
|
|
|
|
| 1006 |
"""
|
| 1007 |
-
|
| 1008 |
-
|
| 1009 |
-
|
| 1010 |
-
|
| 1011 |
-
|
| 1012 |
-
|
| 1013 |
-
|
| 1014 |
-
|
| 1015 |
-
out[int(raw_pid)] = int(str(cell).strip())
|
| 1016 |
-
except (TypeError, ValueError):
|
| 1017 |
-
continue
|
| 1018 |
-
return out
|
| 1019 |
|
| 1020 |
for key, raw in updates.items():
|
| 1021 |
defn = defs.get(key) or {}
|
| 1022 |
-
held = _held()
|
| 1023 |
-
|
| 1024 |
-
def _stored():
|
| 1025 |
-
"""ββ A REFUSAL REPORTS WHAT THE CELL ACTUALLY HOLDS, AND THAT IS NOT TIDINESS.
|
| 1026 |
-
|
| 1027 |
-
`patchTopicRow` adopts `body.updates` into the browser's optimistic copy and rolls
|
| 1028 |
-
back only on a non-2xx. A refused key that is simply ABSENT from `updates` is a key
|
| 1029 |
-
the client never hears about: the response is 200, the rollback never fires, `adopt`
|
| 1030 |
-
has nothing to write, and the typed text goes on painting a value the store rejected
|
| 1031 |
-
until something unrelated forces a refetch. On a `select` the option normaliser made
|
| 1032 |
-
this unreachable; item 7 made the column an `int`, so `14.5` or a stray letter is now
|
| 1033 |
-
an ordinary typo away. `patchTopicRow`'s own docstring already states the rule β
|
| 1034 |
-
keep only what the server actually took β and this is that rule with its hole closed.
|
| 1035 |
-
"""
|
| 1036 |
-
n = held.get(pid)
|
| 1037 |
-
return "" if n is None else str(n)
|
| 1038 |
|
| 1039 |
if key in hidden:
|
| 1040 |
-
accepted[key] = _stored()
|
| 1041 |
continue
|
| 1042 |
if not grid_events._may_edit_field_value(ctx, key, defn):
|
| 1043 |
-
accepted[key] = _stored()
|
| 1044 |
continue
|
| 1045 |
# An empty cell is "not on this route". Legal, and the only way to take a stop off the
|
| 1046 |
# day without re-solving the whole column.
|
|
@@ -1052,30 +1466,22 @@ def _patch_route_ranks(session, ctx, pid, pool, updates):
|
|
| 1052 |
# β A BOOL IS AN `int` IN PYTHON, so `True` would store as visit number 1. Excluded by
|
| 1053 |
# name here exactly as `route_order_write` excludes it, rather than by hoping.
|
| 1054 |
if isinstance(raw, bool):
|
| 1055 |
-
accepted[key] = _stored()
|
| 1056 |
continue
|
| 1057 |
try:
|
| 1058 |
want = int(str(raw).strip())
|
| 1059 |
except (TypeError, ValueError):
|
| 1060 |
-
accepted[key] = _stored()
|
| 1061 |
continue
|
| 1062 |
if want < 1:
|
| 1063 |
-
accepted[key] = _stored()
|
| 1064 |
continue
|
| 1065 |
|
| 1066 |
-
|
| 1067 |
-
|
| 1068 |
-
|
| 1069 |
-
|
| 1070 |
-
|
| 1071 |
-
writes = {pid: {key: str(want)}}
|
| 1072 |
-
holder = next((p for p, n in held.items() if n == want and p != pid), None)
|
| 1073 |
-
if holder is not None:
|
| 1074 |
-
moved = prior if prior is not None else max(held.values()) + 1
|
| 1075 |
-
writes[holder] = {key: str(moved)}
|
| 1076 |
-
swaps.append({"pid": holder, "field": key, "value": str(moved)})
|
| 1077 |
-
shared_overlay.put_rows(_shared_key(), writes, st=session.runtime)
|
| 1078 |
-
accepted[key] = str(want)
|
| 1079 |
taken.add(key)
|
| 1080 |
return accepted, swaps, taken
|
| 1081 |
|
|
@@ -1209,6 +1615,8 @@ ROUTE_KEY_PREFIX = "route_"
|
|
| 1209 |
#: the client; never inferred from the key, because a prefix is a naming convention and a
|
| 1210 |
#: convention is not a declaration.
|
| 1211 |
ROUTE_KIND = "route_order"
|
|
|
|
|
|
|
| 1212 |
|
| 1213 |
#: ββ W41-T05 / CONTRACT C3 β THE DESCRIPTION EVERY ROUTE COLUMN IS BORN WITH.
|
| 1214 |
#:
|
|
@@ -1591,6 +1999,9 @@ def route_order_write(body: dict = Body(default=None),
|
|
| 1591 |
"source": "overlay",
|
| 1592 |
"shared": True,
|
| 1593 |
"kind": ROUTE_KIND,
|
|
|
|
|
|
|
|
|
|
| 1594 |
# ββ W41-T05 β THE DESCRIPTION, CARRIED BY **PRESENCE** AND NOT BY TRUTHINESS.
|
| 1595 |
# `ROUTE_FIELD_NOTE` says why the column cannot be born without one and why `""` has to
|
| 1596 |
# survive a re-solve: `route_order_rename` clears a description by storing exactly that,
|
|
@@ -1922,6 +2333,7 @@ def _route_delivery_wire(defn):
|
|
| 1922 |
"recipient": str(cfg.get("recipient") or ""),
|
| 1923 |
"schedule": dict(defn.get("schedule") or {}),
|
| 1924 |
"snapshot": {
|
|
|
|
| 1925 |
"sourceViewId": str(snap.get("sourceViewId") or ""),
|
| 1926 |
"sourceViewRevision": str(snap.get("sourceViewRevision") or ""),
|
| 1927 |
"sourceViewName": str(snap.get("sourceViewName") or ""),
|
|
@@ -1935,11 +2347,19 @@ def _route_delivery_wire(defn):
|
|
| 1935 |
}
|
| 1936 |
|
| 1937 |
|
| 1938 |
-
def _route_delivery_recipient_or_400(raw):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1939 |
recipient = str(raw or "").strip()
|
| 1940 |
try:
|
| 1941 |
-
|
| 1942 |
-
|
|
|
|
|
|
|
| 1943 |
except Exception: # registry unavailable is not permission to queue a phantom Inbox delivery
|
| 1944 |
user = None
|
| 1945 |
if not recipient or not isinstance(user, dict) or not user.get("active", True):
|
|
@@ -1961,89 +2381,141 @@ def _route_view_revision(view_id, config):
|
|
| 1961 |
return "view-config-v2-" + hashlib.sha256(canonical.encode("utf-8")).hexdigest()[:24]
|
| 1962 |
|
| 1963 |
|
| 1964 |
-
def
|
| 1965 |
-
|
|
|
|
| 1966 |
|
| 1967 |
-
|
| 1968 |
-
|
| 1969 |
-
|
| 1970 |
-
concurrency guard, not another persisted configuration copy.
|
| 1971 |
"""
|
| 1972 |
-
|
| 1973 |
-
|
| 1974 |
-
|
| 1975 |
-
|
| 1976 |
-
|
| 1977 |
-
|
| 1978 |
-
|
| 1979 |
-
|
| 1980 |
-
|
| 1981 |
-
|
| 1982 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1983 |
"sourceViewId": source_view_id,
|
| 1984 |
"sourceViewRevision": _route_view_revision(source_view_id, source_config),
|
| 1985 |
"sourceViewName": str(source_view.get("name") or source_view_id),
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1986 |
}
|
| 1987 |
|
| 1988 |
|
| 1989 |
-
|
| 1990 |
-
def route_delivery_list(session: Session = Depends(module_gate(MODULE))):
|
| 1991 |
-
"""Saved C2 route deliveries owned by the caller (or all for an administrator)."""
|
| 1992 |
import automation_engine as engine
|
| 1993 |
out = []
|
| 1994 |
for defn in (engine.all_definitions(session.runtime) or {}).values():
|
| 1995 |
if not isinstance(defn, dict) or defn.get("kind") != "route_delivery":
|
| 1996 |
continue
|
| 1997 |
-
# A recipient can see the delivery arriving in their Inbox; the edit index is the owner's
|
| 1998 |
-
# configuration surface. Admins can support either one.
|
| 1999 |
if not session.admin and str(defn.get("createdBy") or "") != session.uname:
|
| 2000 |
continue
|
| 2001 |
-
|
| 2002 |
-
|
|
|
|
|
|
|
|
|
|
| 2003 |
|
| 2004 |
|
| 2005 |
-
|
| 2006 |
-
|
| 2007 |
-
|
| 2008 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2009 |
import automation_control
|
| 2010 |
import automation_engine as engine
|
| 2011 |
|
| 2012 |
if not session.runtime.available():
|
| 2013 |
raise err(503, "store_unavailable", "the tenant store is unavailable. Nothing was saved")
|
| 2014 |
-
|
| 2015 |
-
recipient =
|
| 2016 |
-
|
| 2017 |
-
# A route snapshot is allowed to freeze its *stops*, never to invent its View provenance.
|
| 2018 |
-
# `map-current`/a route-plan fingerprint were a synthetic fallback that made an automation
|
| 2019 |
-
# impossible to audit back to the actual filtered View. Resolve the submitted id against
|
| 2020 |
-
# this reader's visible View contract, compare the complete config, and mint its revision
|
| 2021 |
-
# server-side; a valid View id with a forged/stale revision is still not an honest snapshot.
|
| 2022 |
-
source_view_id = str(snapshot.get("sourceViewId") or "").strip()
|
| 2023 |
-
if not source_view_id or source_view_id == "map-current":
|
| 2024 |
-
raise err(400, "invalid_route_source_view",
|
| 2025 |
-
"choose an active saved View for this frozen route")
|
| 2026 |
-
source_views = {str(view.get("id") or ""): view for view in
|
| 2027 |
-
(grid_assembly(session, consume_corrections=False).get("views") or [])
|
| 2028 |
-
if isinstance(view, dict) and view.get("id")}
|
| 2029 |
-
source_view = source_views.get(source_view_id)
|
| 2030 |
-
if source_view is None:
|
| 2031 |
-
raise err(400, "unknown_route_source_view",
|
| 2032 |
-
"the route source View is no longer visible to this account")
|
| 2033 |
-
snapshot = _route_snapshot_for_view_or_409(snapshot, source_view)
|
| 2034 |
raw = {
|
| 2035 |
-
"name": " "
|
| 2036 |
"kind": "route_delivery",
|
| 2037 |
"trigger": {"key": "manual"},
|
| 2038 |
-
|
| 2039 |
-
|
| 2040 |
-
"
|
| 2041 |
-
|
| 2042 |
-
"routeSnapshot": {
|
| 2043 |
-
**snapshot,
|
| 2044 |
-
"mapsPerLink": snapshot.get("mapsPerLink", body.get("mapsPerLink", 10)),
|
| 2045 |
-
},
|
| 2046 |
-
},
|
| 2047 |
"flow": {"actions": []},
|
| 2048 |
}
|
| 2049 |
defn, problem = engine.create(session.runtime, raw, username=session.uname)
|
|
@@ -2052,22 +2524,41 @@ def route_delivery_create(body: dict = Body(default=None),
|
|
| 2052 |
try:
|
| 2053 |
automation_control.sync_definition(session.tenant, defn)
|
| 2054 |
except automation_control.ControlPlaneError as exc:
|
| 2055 |
-
# The definition exists but is not allowed to read as armed if its native schedule did not.
|
| 2056 |
raise err(503, "automation_control_unavailable",
|
| 2057 |
f"the route was saved, but its daily schedule could not be armed: {exc}")
|
| 2058 |
return {"delivery": _route_delivery_wire(defn)}
|
| 2059 |
|
| 2060 |
|
| 2061 |
-
@router.
|
| 2062 |
-
def
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2063 |
session: Session = Depends(module_gate(MODULE))):
|
| 2064 |
-
"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2065 |
import automation_control
|
| 2066 |
import automation_engine as engine
|
| 2067 |
|
| 2068 |
defn = (engine.all_definitions(session.runtime) or {}).get(str(delivery_id))
|
| 2069 |
if not isinstance(defn, dict) or defn.get("kind") != "route_delivery":
|
| 2070 |
raise err(404, "unknown_route_delivery", "no scheduled route with that id")
|
|
|
|
|
|
|
|
|
|
| 2071 |
if not session.admin and str(defn.get("createdBy") or "") != session.uname:
|
| 2072 |
raise err(403, "forbidden", "only the route creator or an administrator can remove its schedule")
|
| 2073 |
engine.remove(session.runtime, str(delivery_id))
|
|
@@ -2077,3 +2568,19 @@ def route_delivery_delete(delivery_id: str,
|
|
| 2077 |
raise err(503, "automation_control_unavailable",
|
| 2078 |
f"the route schedule was removed, but its native schedule could not be removed: {exc}")
|
| 2079 |
return {"deleted": str(delivery_id)}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 190 |
try:
|
| 191 |
field_permissions.migrate_legacy_fields(
|
| 192 |
_shared_key(), st=st, grant_topic="customer_data", shared_key=_shared_key())
|
| 193 |
+
fields = shared_overlay.fields(_shared_key(), st=st)
|
| 194 |
+
# Normalized Routes use an invisible field-shaped bridge so the established Share dialog
|
| 195 |
+
# and grant registry can be reused. It is object metadata, never a customer column.
|
| 196 |
+
return {key: value for key, value in fields.items()
|
| 197 |
+
if not _is_route_share_bridge(value)}
|
| 198 |
except Exception: # noqa: BLE001
|
| 199 |
# Lenient like every other display read: an unreachable store degrades to "nothing is
|
| 200 |
# shared yet", never to a 500 on a grid that would otherwise render. The WALL does not
|
|
|
|
| 202 |
return {}
|
| 203 |
|
| 204 |
|
| 205 |
+
def _is_route_share_bridge(definition):
|
| 206 |
+
route = definition.get("route") if isinstance(definition, dict) else None
|
| 207 |
+
return bool(isinstance(route, dict) and route.get("normalizedId"))
|
| 208 |
+
|
| 209 |
+
|
| 210 |
def shared_cells(pids, st=None):
|
| 211 |
"""`{"<pid>": {key: value}}` for the rows named by `pids`, and ONLY those.
|
| 212 |
|
|
|
|
| 222 |
return {}
|
| 223 |
|
| 224 |
|
| 225 |
+
def _canonical_field_keys():
|
| 226 |
+
"""Keys declared by the product contract, not by a user's workspace stratum."""
|
| 227 |
+
import aios_grid
|
| 228 |
+
return {str(field.get("key") or "").strip()
|
| 229 |
+
for field in (aios_grid.FIELDS or ()) if isinstance(field, dict)}
|
| 230 |
+
|
| 231 |
+
|
| 232 |
+
def _merge_shared_fields(fields, defs, session=None, strata=None):
|
| 233 |
"""`fields` PLUS the tenant-wide columns this topic declares β `routes_tables._ut_shared_fields`
|
| 234 |
on the customer topic.
|
| 235 |
|
|
|
|
| 241 |
β A key the canonical contract already declares WINS. A shared column is an ADDITION to this
|
| 242 |
database's contract, never a redefinition of a column it already has.
|
| 243 |
"""
|
| 244 |
+
incoming = list(fields or ())
|
| 245 |
+
canonical = _canonical_field_keys()
|
| 246 |
+
lent = strata if isinstance(strata, dict) else None
|
| 247 |
+
have = {}
|
| 248 |
+
for index, field in enumerate(incoming):
|
| 249 |
+
if not isinstance(field, dict):
|
| 250 |
+
continue
|
| 251 |
+
key = str(field.get("key") or "").strip()
|
| 252 |
+
if not key or key in have:
|
| 253 |
+
continue
|
| 254 |
+
have[key] = index
|
| 255 |
+
if lent is not None:
|
| 256 |
+
lent[key] = "contract" if key in canonical else "personal"
|
| 257 |
+
|
| 258 |
if not defs:
|
| 259 |
return fields
|
|
|
|
| 260 |
projected = []
|
| 261 |
for k, f in defs.items():
|
| 262 |
+
if _is_route_share_bridge(f):
|
| 263 |
+
continue
|
| 264 |
+
k = str(k or "").strip()
|
| 265 |
+
if not k:
|
| 266 |
+
continue
|
| 267 |
+
index = have.get(k)
|
| 268 |
+
# A tenant-wide definition may never redefine a built-in contract field. For any other
|
| 269 |
+
# same-key collision (including a saved route), the shared definition wins in place.
|
| 270 |
+
if index is not None and k in canonical:
|
| 271 |
continue
|
| 272 |
item = dict(f, source="overlay", shared=True)
|
| 273 |
if session is not None:
|
|
|
|
| 277 |
is_admin=session.admin, st=session.runtime)
|
| 278 |
if role:
|
| 279 |
item["sharedRole"] = role
|
| 280 |
+
if index is None:
|
| 281 |
+
projected.append(item)
|
| 282 |
+
else:
|
| 283 |
+
local = incoming[index] if isinstance(incoming[index], dict) else {}
|
| 284 |
+
item["superseded"] = {
|
| 285 |
+
"stratum": "personal",
|
| 286 |
+
"owner": str(local.get("createdBy") or "").strip() or None,
|
| 287 |
+
"label": str(local.get("label") or "").strip() or None,
|
| 288 |
+
}
|
| 289 |
+
incoming[index] = item
|
| 290 |
+
if lent is not None:
|
| 291 |
+
lent[k] = "shared"
|
| 292 |
+
return incoming + projected
|
| 293 |
+
|
| 294 |
+
|
| 295 |
+
def _mark_offerability(fields):
|
| 296 |
+
"""Withhold stored route-order fields from pickers without deleting them from the payload."""
|
| 297 |
+
return [dict(field, **{OFFERABLE_KEY: False})
|
| 298 |
+
if (isinstance(field, dict)
|
| 299 |
+
and field.get("kind") == ROUTE_KIND
|
| 300 |
+
and str(field.get("key") or "").strip() != ROUTE_PROJECTION_KEY)
|
| 301 |
+
else field
|
| 302 |
+
for field in (fields or ())]
|
| 303 |
|
| 304 |
|
| 305 |
def grid_assembly(session: Session, scope: str = "customer", storage_key: str = "",
|
|
|
|
| 363 |
# dict on one request (the write ctx's wall, the read merge, and the closure), and letting each
|
| 364 |
# take its own copy is the shape D-214 spent a whole ticket removing one document over.
|
| 365 |
_defs = shared_fields(st=rt)
|
| 366 |
+
_workspace_ctx = _ctx_for(session, pids, defs=_defs)
|
| 367 |
ws = grid_events.table_workspace(
|
| 368 |
+
_workspace_ctx, allowed_pids=pids,
|
| 369 |
+
consume_corrections=consume_corrections, capture_document=True)
|
| 370 |
# ββ W38-T20 / D-425 β THE TENANT-WIDE CELLS, LAYERED OVER THE PER-USER ONES, IN THE
|
| 371 |
# ASSEMBLY SO EVERY CONSUMER SEES ONE TRUTH. `routes_grid`'s /workspace route serves
|
| 372 |
# `workspace["overlays"] = g["ws"].get("overlays")` verbatim and `_payload` hands the same
|
|
|
|
| 392 |
# ββ W38-T20 β AND THE COLUMN DEFINITIONS, BEFORE THE WALL. See `_merge_shared_fields`: this
|
| 393 |
# position is load-bearing twice, once for the transitive closure and once because it is the
|
| 394 |
# only order in which the per-field grant marker is ever presented to `hidden_keys`.
|
| 395 |
+
_strata = {}
|
| 396 |
+
fields = _merge_shared_fields(fields, _defs, session=session, strata=_strata)
|
| 397 |
# Legacy `Destination N` definitions remain in the shared document for rollback/audit, but
|
| 398 |
# once the dedicated migration recorded its independent parity proof they are display-hidden.
|
| 399 |
# This is intentionally a projection only: no field or cell is deleted here.
|
|
|
|
| 401 |
_legacy_migrations = route_system.read(rt).get("legacyMigrations") or {}
|
| 402 |
fields = [field for field in fields if not (
|
| 403 |
isinstance(field, dict) and (_legacy_migrations.get(str(field.get("key"))) or {}).get("verified"))]
|
| 404 |
+
# Presentation only: legacy route-order definitions remain served/manageable where W44 has
|
| 405 |
+
# not migrated them, but no generic field picker may offer one as a data dimension.
|
| 406 |
+
fields = _mark_offerability(fields)
|
| 407 |
# ββ W41-T01 / RULING R5 / CONTRACTS C1 + C8 β **THE THREE BADGES, STAMPED ONCE, HERE.**
|
| 408 |
#
|
| 409 |
# C1 makes `field_permissions.field_class` the ONE producer of `{origin, audience, sharedBy,
|
|
|
|
| 447 |
try:
|
| 448 |
from core import field_permissions as _fp
|
| 449 |
_classes = _fp.field_classes(fields, session.uname, table_key=_shared_key(),
|
| 450 |
+
grant_topic=SHARE_TOPIC, values_shared=set(_defs),
|
| 451 |
+
strata=_strata, st=rt)
|
| 452 |
fields = [dict(f, **{"class": _classes[f["key"]]})
|
| 453 |
if isinstance(f, dict) and _classes.get(f.get("key")) else f
|
| 454 |
for f in fields]
|
|
|
|
| 470 |
# makes this degrade safe: a client renders NOTHING for a missing `class` rather than a
|
| 471 |
# wrong badge, so a registry that will not open costs the badges and not the grid.
|
| 472 |
pass
|
| 473 |
+
# C4 parity: the topic grid reuses the same whole-workspace usage producer as user databases.
|
| 474 |
+
# The captured document avoids another store read; MODULE remains the memo/permission topic,
|
| 475 |
+
# while `_shared_key()` remains the independently named workspace document.
|
| 476 |
+
try:
|
| 477 |
+
from routes_tables import _field_usage as _fu
|
| 478 |
+
_usage_source = getattr(_workspace_ctx, "workspace_document", None)
|
| 479 |
+
if not isinstance(_usage_source, dict):
|
| 480 |
+
_usage_source = rt
|
| 481 |
+
_usage = _fu(session, MODULE, fields, None,
|
| 482 |
+
_usage_source, _shared_key(), st=rt)
|
| 483 |
+
except Exception: # noqa: BLE001
|
| 484 |
+
_usage = {}
|
| 485 |
+
if _usage:
|
| 486 |
+
fields = [dict(f, usage=dict(_usage[f["key"]]))
|
| 487 |
+
if isinstance(f, dict) and _usage.get(f.get("key")) else f
|
| 488 |
+
for f in fields]
|
| 489 |
# THE FIELD WALL β a TRANSITIVE closure (C-PERM amendment 5), so hiding a field also hides
|
| 490 |
# every formula computed FROM it. Formulas evaluate in the browser from `{ref}`s, so
|
| 491 |
# shipping a dependent formula while withholding its input either leaks the input through
|
|
|
|
| 563 |
|
| 564 |
# Route stops and Zone membership are normalized system relations. They project into two
|
| 565 |
# read-only customer fields; neither is a generic Link or an editable user-table cell.
|
| 566 |
+
# Route names and membership are object data too: a private Route must not leak through the
|
| 567 |
+
# derived customer column while its navigator correctly hides it.
|
| 568 |
+
normalized_routes = [route for route, _mark in _visible_normalized_routes(session)]
|
| 569 |
normalized_zones = route_system.list_zones(rt, rows_src)
|
| 570 |
fields = [field for field in fields if field.get("key") not in {"routes", "zone"}]
|
| 571 |
fields.extend(route_system.customer_projection_fields(normalized_routes, normalized_zones))
|
|
|
|
| 724 |
return offered
|
| 725 |
|
| 726 |
|
| 727 |
+
def _reject_client_create_id(raw, subject):
|
| 728 |
+
"""Keep POST as create-only; object identities are minted by the server.
|
| 729 |
+
|
| 730 |
+
``route_system.put_*`` intentionally remains an upsert primitive for PATCH and migrations.
|
| 731 |
+
Passing any browser-supplied ``id`` key from POST into that primitive would turn the create
|
| 732 |
+
door into an undocumented update door, including across owners. Key presence is the wall:
|
| 733 |
+
null, false, zero, blank, whitespace, arrays, and objects are all refused. Refuse loudly
|
| 734 |
+
instead of silently stripping the id so a malformed caller learns to use PATCH.
|
| 735 |
+
"""
|
| 736 |
+
if isinstance(raw, dict) and "id" in raw:
|
| 737 |
+
slug = str(subject or "object").strip().lower().replace(" ", "_") or "object"
|
| 738 |
+
raise err(400, f"server_managed_{slug}_id",
|
| 739 |
+
f"{subject} ids are server-managed; omit id when creating and use PATCH "
|
| 740 |
+
f"to update an existing {subject}")
|
| 741 |
+
|
| 742 |
+
|
| 743 |
+
def _legacy_route_defs_readonly(session):
|
| 744 |
+
"""Visible legacy route definitions from the shared stratum, with no reconciliation write."""
|
| 745 |
+
import aios_grid
|
| 746 |
+
import core.perm_scope as perm_scope
|
| 747 |
+
from core import route_system, shared_overlay
|
| 748 |
+
|
| 749 |
+
try:
|
| 750 |
+
all_defs = shared_overlay.fields(_shared_key(), st=session.runtime) or {}
|
| 751 |
+
except Exception:
|
| 752 |
+
all_defs = {}
|
| 753 |
+
migrated = route_system.read(session.runtime).get("legacyMigrations") or {}
|
| 754 |
+
defs = {key: definition for key, definition in all_defs.items()
|
| 755 |
+
if isinstance(definition, dict) and definition.get("kind") == ROUTE_KIND
|
| 756 |
+
and not _is_route_share_bridge(definition)
|
| 757 |
+
and not bool((migrated.get(key) or {}).get("verified"))}
|
| 758 |
+
if not defs:
|
| 759 |
+
return {}
|
| 760 |
+
hidden = perm_scope.hidden_keys(
|
| 761 |
+
session.user, MODULE, _merge_shared_fields(list(aios_grid.FIELDS), all_defs),
|
| 762 |
+
st=session.runtime)
|
| 763 |
+
return {key: definition for key, definition in defs.items() if key not in hidden}
|
| 764 |
+
|
| 765 |
+
|
| 766 |
+
def _route_share_records(session):
|
| 767 |
+
"""One normalized registry read for list visibility and every share mark."""
|
| 768 |
+
from core import field_permissions
|
| 769 |
+
return field_permissions.grant_records(SHARE_TOPIC, st=session.runtime) or {}
|
| 770 |
+
|
| 771 |
+
|
| 772 |
+
def _route_share_mark(session, route, records=None):
|
| 773 |
+
"""C6's exact owner/shared/shared-out projection from the generic field registry."""
|
| 774 |
+
from core import route_system, shares
|
| 775 |
+
records = records if isinstance(records, dict) else _route_share_records(session)
|
| 776 |
+
key = str(route.get("shareKey") or route_system.route_share_key(route.get("id")))
|
| 777 |
+
rec = records.get(key) or {}
|
| 778 |
+
entries = rec.get("entries") or []
|
| 779 |
+
me = str(session.uname or "").strip().lower()
|
| 780 |
+
owner = (str(rec.get("owner") or "").strip().lower()
|
| 781 |
+
or str(route.get("createdBy") or "").strip().lower())
|
| 782 |
+
role = None
|
| 783 |
+
if me and owner != me:
|
| 784 |
+
for entry in entries:
|
| 785 |
+
if str(entry.get("user") or "").lower() not in (me, shares.EVERYONE):
|
| 786 |
+
continue
|
| 787 |
+
if entry.get("role") == "edit":
|
| 788 |
+
role = "edit"
|
| 789 |
+
break
|
| 790 |
+
role = role or "view"
|
| 791 |
+
mine = bool(me and owner == me)
|
| 792 |
+
return {"shareId": f"customer_data:{key}", "owner": owner,
|
| 793 |
+
"shared": role is not None, "sharedOut": bool(mine and entries),
|
| 794 |
+
"hasShares": bool(entries), "sharedRole": role,
|
| 795 |
+
"visible": bool(session.admin or mine or role)}
|
| 796 |
+
|
| 797 |
+
|
| 798 |
+
def _visible_normalized_routes(session, records=None):
|
| 799 |
+
from core import route_system
|
| 800 |
+
records = records if isinstance(records, dict) else _route_share_records(session)
|
| 801 |
+
visible = []
|
| 802 |
+
for route in route_system.list_routes(session.runtime):
|
| 803 |
+
mark = _route_share_mark(session, route, records)
|
| 804 |
+
if mark["visible"]:
|
| 805 |
+
visible.append((route, mark))
|
| 806 |
+
return visible
|
| 807 |
+
|
| 808 |
+
|
| 809 |
+
def _compatible_routes(session, permitted=None, records=None):
|
| 810 |
+
"""Visible normalized Routes plus a read-only projection of legacy route-order fields.
|
| 811 |
+
|
| 812 |
+
Wave 44 introduced a normalized Route store while production already held saved route-order
|
| 813 |
+
columns. Requiring an administrator to run the migration before a GET made those existing
|
| 814 |
+
Routes disappear from the Map. This projection uses the same field and row walls as the old
|
| 815 |
+
route-order picker and performs no store update; the explicit migration remains a separate,
|
| 816 |
+
independently verified write operation.
|
| 817 |
+
"""
|
| 818 |
+
from core import route_system
|
| 819 |
+
permitted = allowed_pids(session) if permitted is None else frozenset(permitted)
|
| 820 |
+
normalized = [route for route, _mark in _visible_normalized_routes(session, records)]
|
| 821 |
+
return route_system.compatible_routes(
|
| 822 |
+
normalized,
|
| 823 |
+
_legacy_route_defs_readonly(session),
|
| 824 |
+
shared_cells(permitted, st=session.runtime),
|
| 825 |
+
tenant_id=session.tenant,
|
| 826 |
+
created_by=session.uname,
|
| 827 |
+
)
|
| 828 |
+
|
| 829 |
+
|
| 830 |
+
def _legacy_route_navigation(session):
|
| 831 |
+
"""Wave 42 per-reader Route folders, used only as a no-write migration fallback."""
|
| 832 |
+
try:
|
| 833 |
+
ws = _customer_table(session).workspace(session.uname, consume_corrections=False)
|
| 834 |
+
except Exception:
|
| 835 |
+
return [], {}
|
| 836 |
+
folders = ws.get("folders") or {}
|
| 837 |
+
return (list(folders.get("routes") or []) if isinstance(folders, dict) else [],
|
| 838 |
+
dict((ws.get("itemFolders") or {}).get("routes") or {}))
|
| 839 |
+
|
| 840 |
+
|
| 841 |
+
def _route_navigation(session, routes):
|
| 842 |
+
from core import route_system
|
| 843 |
+
folders, placements = _legacy_route_navigation(session)
|
| 844 |
+
return route_system.route_navigation(
|
| 845 |
+
session.runtime, session.uname, routes,
|
| 846 |
+
legacy_folders=folders, legacy_placements=placements)
|
| 847 |
+
|
| 848 |
+
|
| 849 |
+
def _route_dto(route, allowed, active, session, share_mark=None):
|
| 850 |
from core import route_system
|
| 851 |
allowed = {int(pid) for pid in allowed}
|
| 852 |
stops = [stop for stop in route_system.ordered_stops(route)
|
| 853 |
if int(stop.get("customerPid")) in allowed]
|
| 854 |
visible = [int(stop["customerPid"]) for stop in stops]
|
| 855 |
active = {int(pid) for pid in active if int(pid) in allowed}
|
| 856 |
+
compatibility = route.get("compatibility")
|
| 857 |
+
mark = share_mark if isinstance(share_mark, dict) else _route_share_mark(session, route)
|
| 858 |
+
owns_route = bool(session.admin or (
|
| 859 |
+
mark.get("owner") and mark.get("owner") == str(session.uname or "").strip().lower()))
|
| 860 |
dto = {"id": route["id"], "name": route["name"], "color": route["color"],
|
| 861 |
"number": route["number"], "visibleStopIds": visible,
|
| 862 |
"outsideFilter": bool(active) and not bool(active.intersection(visible)),
|
| 863 |
+
"permission": {"canEdit": (False if compatibility else owns_route and
|
| 864 |
+
_route_view_can_edit(session, route.get("sourceViewId"))),
|
| 865 |
"sourceViewId": route.get("sourceViewId")},
|
| 866 |
"source": {"viewId": route.get("sourceViewId"),
|
| 867 |
+
"revision": route.get("sourceViewRevision")},
|
| 868 |
+
"owner": mark["owner"], "shared": mark["shared"],
|
| 869 |
+
"sharedOut": mark["sharedOut"], "hasShares": mark["hasShares"],
|
| 870 |
+
"sharedRole": mark["sharedRole"], "shareId": mark["shareId"],
|
| 871 |
+
"folderId": route.get("folderId"), "navOrder": route.get("navOrder", 0)}
|
| 872 |
+
if compatibility == "legacy-route-order":
|
| 873 |
+
dto["compatibility"] = compatibility
|
| 874 |
if route.get("mapsUrl"):
|
| 875 |
dto["mapsUrl"] = route["mapsUrl"]
|
| 876 |
return dto
|
|
|
|
| 887 |
|
| 888 |
|
| 889 |
def _route_or_404(session, route_id):
|
| 890 |
+
route = next((item for item, _mark in _visible_normalized_routes(session)
|
|
|
|
| 891 |
if item.get("id") == str(route_id)), None)
|
| 892 |
if route is None:
|
| 893 |
raise err(404, "route_not_found", "that Route does not exist")
|
|
|
|
| 895 |
|
| 896 |
|
| 897 |
def _route_mutation_allowed(session, route, requested_source=None):
|
| 898 |
+
owner = str(_route_share_mark(session, route).get("owner") or "").strip().lower()
|
| 899 |
+
if not (session.admin or (owner and owner == str(session.uname or "").strip().lower())):
|
| 900 |
+
raise err(403, "route_not_owner", "only the Route owner or an administrator can change it")
|
| 901 |
source = requested_source if requested_source is not None else route.get("sourceViewId")
|
| 902 |
if not _route_view_can_edit(session, source):
|
| 903 |
raise err(403, "route_view_read_only", "only an editor of the Route source View can change it")
|
| 904 |
|
| 905 |
|
| 906 |
+
def _ensure_route_share_bridge(session, route):
|
| 907 |
+
"""Materialize the invisible field-shaped object consumed by the existing Share dialog."""
|
| 908 |
+
from core import route_system, shared_overlay
|
| 909 |
+
key = str(route.get("shareKey") or route_system.route_share_key(route.get("id")))
|
| 910 |
+
shared_overlay.put_field(_shared_key(), key, {
|
| 911 |
+
"key": key, "label": route.get("name") or "Route", "type": "text",
|
| 912 |
+
"source": "overlay", "kind": ROUTE_KIND, "custom": True,
|
| 913 |
+
"createdBy": route.get("createdBy") or session.uname,
|
| 914 |
+
"note": "Access bridge for a saved Route.", "shared": True, "granted": True,
|
| 915 |
+
"route": {"normalizedId": route.get("id"), "routeObject": True},
|
| 916 |
+
}, st=session.runtime)
|
| 917 |
+
return key
|
| 918 |
+
|
| 919 |
+
|
| 920 |
+
def _drop_route_share_bridge(session, route):
|
| 921 |
+
from core import route_system, shared_overlay, shares
|
| 922 |
+
key = str(route.get("shareKey") or route_system.route_share_key(route.get("id")))
|
| 923 |
+
shared_overlay.drop_field(_shared_key(), key, st=session.runtime)
|
| 924 |
+
shares.drop_objects([("field", shares.field_oid(SHARE_TOPIC, key))], st=session.runtime)
|
| 925 |
+
|
| 926 |
+
|
| 927 |
+
def _route_nav_mutation_context(session):
|
| 928 |
+
routes = _compatible_routes(session)
|
| 929 |
+
folders, placements = _legacy_route_navigation(session)
|
| 930 |
+
return routes, folders, placements
|
| 931 |
+
|
| 932 |
+
|
| 933 |
@router.get("/customers/routes")
|
| 934 |
def routes(visiblePids: str = "", currentPids: str = "",
|
| 935 |
session: Session = Depends(module_gate(MODULE))):
|
| 936 |
"""Route picker DTO consumed by C1/C3; only permitted stops ever leave the server."""
|
|
|
|
| 937 |
allowed = allowed_pids(session)
|
| 938 |
active = _query_pids(currentPids or visiblePids)
|
| 939 |
+
records = _route_share_records(session)
|
| 940 |
+
navigation = _route_navigation(session, _compatible_routes(session, allowed, records))
|
| 941 |
+
return {"routes": [_route_dto(
|
| 942 |
+
route, allowed, active, session,
|
| 943 |
+
_route_share_mark(session, route, records))
|
| 944 |
+
for route in navigation["routes"]],
|
| 945 |
+
"folders": navigation["folders"]}
|
| 946 |
|
| 947 |
|
| 948 |
@router.post("/customers/routes", status_code=201)
|
| 949 |
def create_route(body: dict = Body(default=None), session: Session = Depends(module_gate(MODULE))):
|
| 950 |
from core import route_system
|
| 951 |
raw = dict(body or {})
|
| 952 |
+
_reject_client_create_id(raw, "Route")
|
| 953 |
if not _route_view_can_edit(session, raw.get("sourceViewId")):
|
| 954 |
raise err(403, "route_view_read_only", "a Route requires an editable source View")
|
| 955 |
permitted = allowed_pids(session)
|
|
|
|
| 958 |
route = route_system.put_route(session.runtime, raw, tenant_id=session.tenant, created_by=session.uname)
|
| 959 |
if route is None:
|
| 960 |
raise err(400, "invalid_route", "a Route needs a name and an optional HTTPS Google Maps URL")
|
| 961 |
+
_ensure_route_share_bridge(session, route)
|
| 962 |
return {"route": _route_dto(route, permitted, (), session)}
|
| 963 |
|
| 964 |
|
| 965 |
+
@router.post("/customers/routes/{route_id}/duplicate", status_code=201)
|
| 966 |
+
def duplicate_route(route_id: str, body: dict = Body(default=None),
|
| 967 |
+
session: Session = Depends(module_gate(MODULE))):
|
| 968 |
+
from core import route_system
|
| 969 |
+
prior = _route_or_404(session, route_id)
|
| 970 |
+
if not _route_view_can_edit(session, prior.get("sourceViewId")):
|
| 971 |
+
raise err(403, "route_view_read_only", "an editable source View is required to duplicate this Route")
|
| 972 |
+
route = route_system.duplicate_route(
|
| 973 |
+
session.runtime, route_id, tenant_id=session.tenant, created_by=session.uname,
|
| 974 |
+
name=(body or {}).get("name"))
|
| 975 |
+
if route is None:
|
| 976 |
+
raise err(404, "route_not_found", "that Route does not exist")
|
| 977 |
+
_ensure_route_share_bridge(session, route)
|
| 978 |
+
return {"route": _route_dto(route, allowed_pids(session), (), session)}
|
| 979 |
+
|
| 980 |
+
|
| 981 |
+
@router.post("/customers/routes/{route_id}/share-ready")
|
| 982 |
+
def route_share_ready(route_id: str, session: Session = Depends(module_gate(MODULE))):
|
| 983 |
+
route = _route_or_404(session, route_id)
|
| 984 |
+
_route_mutation_allowed(session, route)
|
| 985 |
+
key = _ensure_route_share_bridge(session, route)
|
| 986 |
+
return {"kind": "field", "id": f"customer_data:{key}", "label": route.get("name")}
|
| 987 |
+
|
| 988 |
+
|
| 989 |
@router.patch("/customers/routes/{route_id}")
|
| 990 |
def update_route(route_id: str, body: dict = Body(default=None),
|
| 991 |
session: Session = Depends(module_gate(MODULE))):
|
|
|
|
| 999 |
route = route_system.put_route(session.runtime, raw, tenant_id=session.tenant, created_by=session.uname)
|
| 1000 |
if route is None:
|
| 1001 |
raise err(400, "invalid_route", "a Route needs a name and an optional HTTPS Google Maps URL")
|
| 1002 |
+
_ensure_route_share_bridge(session, route)
|
| 1003 |
return {"route": _route_dto(route, allowed_pids(session), (), session)}
|
| 1004 |
|
| 1005 |
|
|
|
|
| 1025 |
return {"route": _route_dto(route, allowed_pids(session), (), session)}
|
| 1026 |
|
| 1027 |
|
| 1028 |
+
@router.post("/customers/routes/{route_id}/stops/membership")
|
| 1029 |
+
def set_route_stop_membership(route_id: str, body: dict = Body(default=None),
|
| 1030 |
+
session: Session = Depends(module_gate(MODULE))):
|
| 1031 |
+
"""Add or remove one permitted customer while preserving every other ordered stop."""
|
| 1032 |
+
from core import route_system
|
| 1033 |
+
prior = _route_or_404(session, route_id)
|
| 1034 |
+
_route_mutation_allowed(session, prior)
|
| 1035 |
+
raw = dict(body or {})
|
| 1036 |
+
candidate = raw.get("customerPid")
|
| 1037 |
+
present = raw.get("present")
|
| 1038 |
+
if isinstance(candidate, bool) or not isinstance(present, bool):
|
| 1039 |
+
raise err(400, "invalid_route_membership",
|
| 1040 |
+
"customerPid and a true or false present value are required")
|
| 1041 |
+
try:
|
| 1042 |
+
pid = int(candidate)
|
| 1043 |
+
except (TypeError, ValueError):
|
| 1044 |
+
raise err(400, "invalid_route_membership",
|
| 1045 |
+
"customerPid and a true or false present value are required")
|
| 1046 |
+
permitted = allowed_pids(session)
|
| 1047 |
+
if pid not in permitted:
|
| 1048 |
+
raise err(403, "out_of_scope", "that customer is not in your book")
|
| 1049 |
+
route = route_system.set_stop_membership(
|
| 1050 |
+
session.runtime, route_id, pid, present,
|
| 1051 |
+
tenant_id=session.tenant, created_by=session.uname)
|
| 1052 |
+
if route is None:
|
| 1053 |
+
raise err(404, "route_not_found", "that Route does not exist")
|
| 1054 |
+
return {"route": _route_dto(route, permitted, (), session)}
|
| 1055 |
+
|
| 1056 |
+
|
| 1057 |
@router.delete("/customers/routes/{route_id}")
|
| 1058 |
def remove_route(route_id: str, session: Session = Depends(module_gate(MODULE))):
|
| 1059 |
from core import route_system
|
| 1060 |
route = _route_or_404(session, route_id)
|
| 1061 |
_route_mutation_allowed(session, route)
|
| 1062 |
+
linked_delivery_ids = _linked_route_delivery_ids(session.runtime, route_id)
|
| 1063 |
+
if linked_delivery_ids:
|
| 1064 |
+
visible_delivery_ids = {
|
| 1065 |
+
str(delivery.get("id") or "")
|
| 1066 |
+
for delivery in _route_delivery_definitions(session, route_id)
|
| 1067 |
+
if isinstance(delivery, dict)
|
| 1068 |
+
}
|
| 1069 |
+
if not session.admin and not set(linked_delivery_ids).issubset(visible_delivery_ids):
|
| 1070 |
+
raise err(409, "route_deliveries_exist",
|
| 1071 |
+
"Ask an administrator to remove this Route's scheduled deliveries, "
|
| 1072 |
+
"then delete the Route")
|
| 1073 |
+
raise err(409, "route_deliveries_exist",
|
| 1074 |
+
"Remove this Route's scheduled deliveries first, then delete the Route")
|
| 1075 |
+
if not route_system.delete_route(session.runtime, route_id):
|
| 1076 |
+
raise err(404, "route_not_found", "that Route does not exist")
|
| 1077 |
+
_drop_route_share_bridge(session, route)
|
| 1078 |
return {"deleted": True}
|
| 1079 |
|
| 1080 |
|
| 1081 |
+
@router.patch("/customers/routes/{route_id}/folder")
|
| 1082 |
+
def move_route_to_folder(route_id: str, body: dict = Body(default=None),
|
| 1083 |
+
session: Session = Depends(module_gate(MODULE))):
|
| 1084 |
+
from core import route_system
|
| 1085 |
+
routes, legacy_folders, legacy_placements = _route_nav_mutation_context(session)
|
| 1086 |
+
if str(route_id) not in {str(route.get("id")) for route in routes}:
|
| 1087 |
+
raise err(404, "route_not_found", "that Route does not exist")
|
| 1088 |
+
folder_id = (body or {}).get("folderId")
|
| 1089 |
+
if folder_id is not None and not isinstance(folder_id, str):
|
| 1090 |
+
raise err(400, "invalid_route_folder", "folderId must be a folder id or null")
|
| 1091 |
+
if folder_id and not any(folder.get("id") == folder_id for folder in _route_navigation(session, routes)["folders"]):
|
| 1092 |
+
raise err(409, "route_folder_not_found", "that Route folder no longer exists")
|
| 1093 |
+
route_system.place_route(
|
| 1094 |
+
session.runtime, session.uname, route_id, folder_id, routes,
|
| 1095 |
+
legacy_folders=legacy_folders, legacy_placements=legacy_placements)
|
| 1096 |
+
navigation = _route_navigation(session, routes)
|
| 1097 |
+
moved = next(route for route in navigation["routes"] if route.get("id") == str(route_id))
|
| 1098 |
+
return {"route": _route_dto(moved, allowed_pids(session), (), session),
|
| 1099 |
+
"folders": navigation["folders"]}
|
| 1100 |
+
|
| 1101 |
+
|
| 1102 |
+
@router.post("/customers/routes/reorder")
|
| 1103 |
+
def reorder_route_navigation(body: dict = Body(default=None),
|
| 1104 |
+
session: Session = Depends(module_gate(MODULE))):
|
| 1105 |
+
from core import route_system
|
| 1106 |
+
routes, legacy_folders, legacy_placements = _route_nav_mutation_context(session)
|
| 1107 |
+
order = (body or {}).get("order")
|
| 1108 |
+
if not isinstance(order, list):
|
| 1109 |
+
raise err(400, "invalid_route_order", "order must be a list of visible Route ids")
|
| 1110 |
+
result = route_system.reorder_routes(
|
| 1111 |
+
session.runtime, session.uname, order, routes,
|
| 1112 |
+
legacy_folders=legacy_folders, legacy_placements=legacy_placements)
|
| 1113 |
+
if result is None:
|
| 1114 |
+
raise err(409, "invalid_route_order", "Route order contains an unknown or duplicate id")
|
| 1115 |
+
return {"order": result}
|
| 1116 |
+
|
| 1117 |
+
|
| 1118 |
+
@router.post("/customers/route-folders", status_code=201)
|
| 1119 |
+
def create_route_folder(body: dict = Body(default=None),
|
| 1120 |
+
session: Session = Depends(module_gate(MODULE))):
|
| 1121 |
+
from core import route_system
|
| 1122 |
+
routes, legacy_folders, legacy_placements = _route_nav_mutation_context(session)
|
| 1123 |
+
folder = route_system.put_route_folder(
|
| 1124 |
+
session.runtime, session.uname, body or {}, routes,
|
| 1125 |
+
legacy_folders=legacy_folders, legacy_placements=legacy_placements)
|
| 1126 |
+
if folder is None:
|
| 1127 |
+
raise err(400, "invalid_route_folder", "a Route folder needs a name and a valid parent")
|
| 1128 |
+
return {"folder": folder, "folders": _route_navigation(session, routes)["folders"]}
|
| 1129 |
+
|
| 1130 |
+
|
| 1131 |
+
@router.patch("/customers/route-folders/{folder_id}")
|
| 1132 |
+
def update_route_folder(folder_id: str, body: dict = Body(default=None),
|
| 1133 |
+
session: Session = Depends(module_gate(MODULE))):
|
| 1134 |
+
from core import route_system
|
| 1135 |
+
routes, legacy_folders, legacy_placements = _route_nav_mutation_context(session)
|
| 1136 |
+
current = next((folder for folder in _route_navigation(session, routes)["folders"]
|
| 1137 |
+
if folder.get("id") == folder_id), None)
|
| 1138 |
+
if current is None:
|
| 1139 |
+
raise err(404, "route_folder_not_found", "that Route folder does not exist")
|
| 1140 |
+
raw = dict(current)
|
| 1141 |
+
raw.update(body or {})
|
| 1142 |
+
raw["id"] = folder_id
|
| 1143 |
+
folder = route_system.put_route_folder(
|
| 1144 |
+
session.runtime, session.uname, raw, routes,
|
| 1145 |
+
legacy_folders=legacy_folders, legacy_placements=legacy_placements)
|
| 1146 |
+
if folder is None:
|
| 1147 |
+
raise err(409, "invalid_route_folder", "that folder move would create an invalid path")
|
| 1148 |
+
return {"folder": folder, "folders": _route_navigation(session, routes)["folders"]}
|
| 1149 |
+
|
| 1150 |
+
|
| 1151 |
+
@router.delete("/customers/route-folders/{folder_id}")
|
| 1152 |
+
def remove_route_folder(folder_id: str, session: Session = Depends(module_gate(MODULE))):
|
| 1153 |
+
from core import route_system
|
| 1154 |
+
routes, legacy_folders, legacy_placements = _route_nav_mutation_context(session)
|
| 1155 |
+
if not route_system.delete_route_folder(
|
| 1156 |
+
session.runtime, session.uname, folder_id, routes,
|
| 1157 |
+
legacy_folders=legacy_folders, legacy_placements=legacy_placements):
|
| 1158 |
+
raise err(404, "route_folder_not_found", "that Route folder does not exist")
|
| 1159 |
+
return {"deleted": True, "folders": _route_navigation(session, routes)["folders"]}
|
| 1160 |
+
|
| 1161 |
+
|
| 1162 |
+
@router.post("/customers/route-folders/reorder")
|
| 1163 |
+
def reorder_route_folder_navigation(body: dict = Body(default=None),
|
| 1164 |
+
session: Session = Depends(module_gate(MODULE))):
|
| 1165 |
+
from core import route_system
|
| 1166 |
+
routes, legacy_folders, legacy_placements = _route_nav_mutation_context(session)
|
| 1167 |
+
order = (body or {}).get("order")
|
| 1168 |
+
if not isinstance(order, list):
|
| 1169 |
+
raise err(400, "invalid_route_folder_order", "order must be a list of Route folder ids")
|
| 1170 |
+
result = route_system.reorder_route_folders(
|
| 1171 |
+
session.runtime, session.uname, order, routes,
|
| 1172 |
+
legacy_folders=legacy_folders, legacy_placements=legacy_placements)
|
| 1173 |
+
if result is None:
|
| 1174 |
+
raise err(409, "invalid_route_folder_order", "folder order contains an unknown or duplicate id")
|
| 1175 |
+
return {"order": result}
|
| 1176 |
+
|
| 1177 |
+
|
| 1178 |
@router.post("/customers/routes/selection")
|
| 1179 |
def route_selection(body: dict = Body(default=None), session: Session = Depends(module_gate(MODULE))):
|
| 1180 |
"""Dedicated managed-OR mutation; user filter clauses are returned byte-for-byte intact."""
|
| 1181 |
from core import route_system
|
| 1182 |
raw = dict(body or {})
|
| 1183 |
chosen = [str(item) for item in raw.get("routeIds") or ()]
|
| 1184 |
+
compatible = _compatible_routes(session)
|
| 1185 |
+
known = {route["id"] for route in compatible}
|
| 1186 |
if any(route_id not in known for route_id in chosen):
|
| 1187 |
raise err(404, "route_not_found", "a selected Route does not exist")
|
| 1188 |
state = route_system.apply_managed_route_selection(
|
| 1189 |
+
raw.get("viewState"), chosen, compatible)
|
| 1190 |
return {"viewState": state, "managedBy": route_system.MANAGED_BY}
|
| 1191 |
|
| 1192 |
|
|
|
|
| 1290 |
def _zone_dto(zone, allowed, session):
|
| 1291 |
return {"id": zone["id"], "name": zone["name"], "color": zone["color"],
|
| 1292 |
"geometryGeoJson": zone.get("geometryGeoJson"), "zipCodes": zone.get("zipCodes") or [],
|
| 1293 |
+
# MapView and the read-only Customer ``Zone`` field consume this same normalized
|
| 1294 |
+
# membership. Returning a second ``visibleMemberIds`` dialect made the map paint an
|
| 1295 |
+
# empty Zone while the grid projection named the customer as a member.
|
| 1296 |
+
"memberships": [int(pid) for pid in zone.get("memberPids") or [] if int(pid) in allowed],
|
| 1297 |
"membershipRevision": zone.get("membershipRevision", 0),
|
| 1298 |
+
"sourceViewId": zone.get("sourceViewId"),
|
| 1299 |
+
"geographicField": str(zone.get("geographicField") or ""),
|
| 1300 |
+
"createdBy": str(zone.get("createdBy") or ""),
|
| 1301 |
+
"createdAt": str(zone.get("createdAt") or ""),
|
| 1302 |
"visible": zone.get("visible", True),
|
| 1303 |
+
"permission": {
|
| 1304 |
+
"canEdit": _zone_can_edit(session, zone.get("sourceViewId")),
|
| 1305 |
+
"canDelete": bool(session.admin),
|
| 1306 |
+
}}
|
| 1307 |
|
| 1308 |
|
| 1309 |
@router.get("/customers/zones")
|
|
|
|
| 1319 |
def create_zone(body: dict = Body(default=None), session: Session = Depends(module_gate(MODULE))):
|
| 1320 |
from core import route_system
|
| 1321 |
raw = dict(body or {})
|
| 1322 |
+
_reject_client_create_id(raw, "Zone")
|
| 1323 |
if not _zone_can_edit(session, raw.get("sourceViewId")):
|
| 1324 |
raise err(403, "zone_view_read_only", "a Zone requires an editable source View")
|
| 1325 |
zone = route_system.put_zone(session.runtime, raw, rows=_pool_rows(session),
|
|
|
|
| 1338 |
if prior is None:
|
| 1339 |
raise err(404, "zone_not_found", "that Zone does not exist")
|
| 1340 |
raw = dict(body or {})
|
| 1341 |
+
# A Zone keeps the View it was authored from. Editing its colour or boundary is not a
|
| 1342 |
+
# second door for silently rebasing its permission wall onto another View.
|
| 1343 |
+
source_view_id = prior.get("sourceViewId") or raw.get("sourceViewId")
|
| 1344 |
+
if not _zone_can_edit(session, source_view_id):
|
| 1345 |
raise err(403, "zone_view_read_only", "a Zone requires an editable source View")
|
| 1346 |
+
raw["sourceViewId"] = source_view_id
|
| 1347 |
raw["id"] = prior["id"]
|
| 1348 |
zone = route_system.put_zone(session.runtime, raw, rows=_pool_rows(session),
|
| 1349 |
tenant_id=session.tenant, created_by=session.uname)
|
|
|
|
| 1412 |
`patch_customer` routes everything else through `grid_events` rather than writing the store.
|
| 1413 |
|
| 1414 |
β UNIQUENESS IS MAINTAINED OVER THE ROWS THIS CALLER CAN SEE, and that is a limit worth
|
| 1415 |
+
stating rather than hiding. `shared_overlay.transpose_rank` requires the scoped pool BY
|
| 1416 |
+
SIGNATURE, then reads it inside the same store-update callback that writes both rows. The
|
| 1417 |
+
holder of a displaced number is therefore looked for inside this session's book, but never
|
| 1418 |
+
from a stale pre-write snapshot. In practice the whole column lives there anyway:
|
| 1419 |
`route_order_write` REFUSES a body carrying a pid outside the writer's pool, so every number in
|
| 1420 |
a route order was written by somebody whose book contained all of them.
|
| 1421 |
"""
|
|
|
|
| 1431 |
#: value the caller did NOT ask for.
|
| 1432 |
taken, swaps = set(), []
|
| 1433 |
|
| 1434 |
+
def _stored(key):
|
| 1435 |
+
"""The current rank for a refused key, scoped to this one admitted row.
|
| 1436 |
|
| 1437 |
+
Valid nonblank assignments never use this read: ``transpose_rank`` reads the whole scoped
|
| 1438 |
+
column inside the atomic update that writes it. This helper exists only so a refusal can
|
| 1439 |
+
repaint the store's truth in the optimistic client.
|
| 1440 |
"""
|
| 1441 |
+
row = ((shared_cells([pid], st=session.runtime) or {}).get(str(pid)) or {})
|
| 1442 |
+
cell = row.get(key) if isinstance(row, dict) else None
|
| 1443 |
+
if cell in (None, ""):
|
| 1444 |
+
return ""
|
| 1445 |
+
try:
|
| 1446 |
+
return str(int(str(cell).strip()))
|
| 1447 |
+
except (TypeError, ValueError):
|
| 1448 |
+
return ""
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1449 |
|
| 1450 |
for key, raw in updates.items():
|
| 1451 |
defn = defs.get(key) or {}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1452 |
|
| 1453 |
if key in hidden:
|
| 1454 |
+
accepted[key] = _stored(key)
|
| 1455 |
continue
|
| 1456 |
if not grid_events._may_edit_field_value(ctx, key, defn):
|
| 1457 |
+
accepted[key] = _stored(key)
|
| 1458 |
continue
|
| 1459 |
# An empty cell is "not on this route". Legal, and the only way to take a stop off the
|
| 1460 |
# day without re-solving the whole column.
|
|
|
|
| 1466 |
# β A BOOL IS AN `int` IN PYTHON, so `True` would store as visit number 1. Excluded by
|
| 1467 |
# name here exactly as `route_order_write` excludes it, rather than by hoping.
|
| 1468 |
if isinstance(raw, bool):
|
| 1469 |
+
accepted[key] = _stored(key)
|
| 1470 |
continue
|
| 1471 |
try:
|
| 1472 |
want = int(str(raw).strip())
|
| 1473 |
except (TypeError, ValueError):
|
| 1474 |
+
accepted[key] = _stored(key)
|
| 1475 |
continue
|
| 1476 |
if want < 1:
|
| 1477 |
+
accepted[key] = _stored(key)
|
| 1478 |
continue
|
| 1479 |
|
| 1480 |
+
moved = shared_overlay.transpose_rank(
|
| 1481 |
+
_shared_key(), pid, key, want, pool, st=session.runtime)
|
| 1482 |
+
if moved.get("swap"):
|
| 1483 |
+
swaps.append(moved["swap"])
|
| 1484 |
+
accepted[key] = moved["value"]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1485 |
taken.add(key)
|
| 1486 |
return accepted, swaps, taken
|
| 1487 |
|
|
|
|
| 1615 |
#: the client; never inferred from the key, because a prefix is a naming convention and a
|
| 1616 |
#: convention is not a declaration.
|
| 1617 |
ROUTE_KIND = "route_order"
|
| 1618 |
+
OFFERABLE_KEY = "offerable"
|
| 1619 |
+
ROUTE_PROJECTION_KEY = "routes"
|
| 1620 |
|
| 1621 |
#: ββ W41-T05 / CONTRACT C3 β THE DESCRIPTION EVERY ROUTE COLUMN IS BORN WITH.
|
| 1622 |
#:
|
|
|
|
| 1999 |
"source": "overlay",
|
| 2000 |
"shared": True,
|
| 2001 |
"kind": ROUTE_KIND,
|
| 2002 |
+
# Stored as well as projected so every read door starts from the same explicit contract.
|
| 2003 |
+
# This is presentation metadata: the route stays visible/manageable and its values remain.
|
| 2004 |
+
OFFERABLE_KEY: False,
|
| 2005 |
# ββ W41-T05 β THE DESCRIPTION, CARRIED BY **PRESENCE** AND NOT BY TRUTHINESS.
|
| 2006 |
# `ROUTE_FIELD_NOTE` says why the column cannot be born without one and why `""` has to
|
| 2007 |
# survive a re-solve: `route_order_rename` clears a description by storing exactly that,
|
|
|
|
| 2333 |
"recipient": str(cfg.get("recipient") or ""),
|
| 2334 |
"schedule": dict(defn.get("schedule") or {}),
|
| 2335 |
"snapshot": {
|
| 2336 |
+
"routeId": str(snap.get("routeId") or ""),
|
| 2337 |
"sourceViewId": str(snap.get("sourceViewId") or ""),
|
| 2338 |
"sourceViewRevision": str(snap.get("sourceViewRevision") or ""),
|
| 2339 |
"sourceViewName": str(snap.get("sourceViewName") or ""),
|
|
|
|
| 2347 |
}
|
| 2348 |
|
| 2349 |
|
| 2350 |
+
def _route_delivery_recipient_or_400(session, raw, directory=None):
|
| 2351 |
+
"""Resolve one active Inbox account behind the narrow directory seam.
|
| 2352 |
+
|
| 2353 |
+
``session`` is intentionally part of the seam even though the ordinary registry does not
|
| 2354 |
+
consume it yet. Staging-only identities can extend this one helper without leaking fixture
|
| 2355 |
+
logic into Route persistence or falling through to a different account plane.
|
| 2356 |
+
"""
|
| 2357 |
recipient = str(raw or "").strip()
|
| 2358 |
try:
|
| 2359 |
+
if directory is None:
|
| 2360 |
+
import core.users as users
|
| 2361 |
+
directory = users.registry
|
| 2362 |
+
user = (directory() or {}).get(recipient)
|
| 2363 |
except Exception: # registry unavailable is not permission to queue a phantom Inbox delivery
|
| 2364 |
user = None
|
| 2365 |
if not recipient or not isinstance(user, dict) or not user.get("active", True):
|
|
|
|
| 2381 |
return "view-config-v2-" + hashlib.sha256(canonical.encode("utf-8")).hexdigest()[:24]
|
| 2382 |
|
| 2383 |
|
| 2384 |
+
def _route_delivery_snapshot_for_route_or_400(
|
| 2385 |
+
session, route, body, *, source_views=None, permitted=None, recipient_directory=None):
|
| 2386 |
+
"""Build the immutable delivery exclusively from a normalized Route and server reads.
|
| 2387 |
|
| 2388 |
+
The browser may choose the recipient, timezone, and bounded Maps chunk size. It cannot send
|
| 2389 |
+
View configuration, revision, Route name, or stop ids: all of those are resolved again here
|
| 2390 |
+
from the saved Route and its real source View at the moment the schedule is created.
|
|
|
|
| 2391 |
"""
|
| 2392 |
+
from core import route_system
|
| 2393 |
+
from zoneinfo import ZoneInfo, ZoneInfoNotFoundError
|
| 2394 |
+
|
| 2395 |
+
body = body if isinstance(body, dict) else {}
|
| 2396 |
+
recipient = _route_delivery_recipient_or_400(
|
| 2397 |
+
session, body.get("recipient"), directory=recipient_directory)
|
| 2398 |
+
source_view_id = str(route.get("sourceViewId") or "").strip()
|
| 2399 |
+
if not source_view_id:
|
| 2400 |
+
raise err(409, "route_source_view_missing",
|
| 2401 |
+
"this Route has no saved source View and cannot be scheduled")
|
| 2402 |
+
|
| 2403 |
+
if source_views is None:
|
| 2404 |
+
source_views = grid_assembly(session, consume_corrections=False).get("views") or []
|
| 2405 |
+
source_by_id = {str(view.get("id") or ""): view for view in source_views
|
| 2406 |
+
if isinstance(view, dict) and view.get("id")}
|
| 2407 |
+
source_view = source_by_id.get(source_view_id)
|
| 2408 |
+
source_config = source_view.get("config") if isinstance(source_view, dict) else None
|
| 2409 |
+
if not isinstance(source_config, dict):
|
| 2410 |
+
raise err(409, "route_source_view_unavailable",
|
| 2411 |
+
"the Route source View is no longer visible; restore it before scheduling")
|
| 2412 |
+
|
| 2413 |
+
ordered_stop_ids = [int(stop["customerPid"]) for stop in route_system.ordered_stops(route)]
|
| 2414 |
+
if len(ordered_stop_ids) < 2:
|
| 2415 |
+
raise err(400, "route_delivery_needs_stops",
|
| 2416 |
+
"add at least two ordered stops before scheduling this Route")
|
| 2417 |
+
permitted = allowed_pids(session) if permitted is None else frozenset(int(pid) for pid in permitted)
|
| 2418 |
+
if any(pid not in permitted for pid in ordered_stop_ids):
|
| 2419 |
+
raise err(409, "route_delivery_scope_changed",
|
| 2420 |
+
"one or more Route stops are outside your current customer book; update the Route first")
|
| 2421 |
+
|
| 2422 |
+
timezone = str(body.get("timezone") or "UTC").strip()[:80] or "UTC"
|
| 2423 |
+
try:
|
| 2424 |
+
ZoneInfo(timezone)
|
| 2425 |
+
except (ZoneInfoNotFoundError, ValueError):
|
| 2426 |
+
raise err(400, "invalid_route_timezone", "choose a recognized timezone for this delivery")
|
| 2427 |
+
|
| 2428 |
+
raw_maps_per_link = body.get("mapsPerLink", 10)
|
| 2429 |
+
if isinstance(raw_maps_per_link, bool):
|
| 2430 |
+
raise err(400, "invalid_route_maps_per_link", "Maps links must contain between 2 and 10 stops")
|
| 2431 |
+
try:
|
| 2432 |
+
maps_per_link = int(raw_maps_per_link)
|
| 2433 |
+
except (TypeError, ValueError):
|
| 2434 |
+
raise err(400, "invalid_route_maps_per_link", "Maps links must contain between 2 and 10 stops")
|
| 2435 |
+
if maps_per_link < 2 or maps_per_link > 10:
|
| 2436 |
+
raise err(400, "invalid_route_maps_per_link", "Maps links must contain between 2 and 10 stops")
|
| 2437 |
+
|
| 2438 |
+
return recipient, {
|
| 2439 |
+
"routeId": str(route.get("id") or ""),
|
| 2440 |
"sourceViewId": source_view_id,
|
| 2441 |
"sourceViewRevision": _route_view_revision(source_view_id, source_config),
|
| 2442 |
"sourceViewName": str(source_view.get("name") or source_view_id),
|
| 2443 |
+
"timezone": timezone,
|
| 2444 |
+
"routeField": str(route.get("id") or ""),
|
| 2445 |
+
"orderedStopIds": ordered_stop_ids,
|
| 2446 |
+
"mapsPerLink": maps_per_link,
|
| 2447 |
}
|
| 2448 |
|
| 2449 |
|
| 2450 |
+
def _route_delivery_definitions(session, route_id=None):
|
|
|
|
|
|
|
| 2451 |
import automation_engine as engine
|
| 2452 |
out = []
|
| 2453 |
for defn in (engine.all_definitions(session.runtime) or {}).values():
|
| 2454 |
if not isinstance(defn, dict) or defn.get("kind") != "route_delivery":
|
| 2455 |
continue
|
|
|
|
|
|
|
| 2456 |
if not session.admin and str(defn.get("createdBy") or "") != session.uname:
|
| 2457 |
continue
|
| 2458 |
+
wire = _route_delivery_wire(defn)
|
| 2459 |
+
if route_id is not None and wire["snapshot"]["routeId"] != str(route_id):
|
| 2460 |
+
continue
|
| 2461 |
+
out.append(wire)
|
| 2462 |
+
return sorted(out, key=lambda row: (row["name"].casefold(), row["id"]))
|
| 2463 |
|
| 2464 |
|
| 2465 |
+
def _linked_route_delivery_ids(runtime, route_id):
|
| 2466 |
+
"""Return every tenant delivery linked to a Route, regardless of its creator.
|
| 2467 |
+
|
| 2468 |
+
The user-facing delivery list is intentionally filtered by caller. A Route delete guard is a
|
| 2469 |
+
referential-integrity question instead: a collaborator-owned delivery is still a live link and
|
| 2470 |
+
must block deletion just like an owner-created one.
|
| 2471 |
+
"""
|
| 2472 |
+
import automation_engine as engine
|
| 2473 |
+
|
| 2474 |
+
wanted = str(route_id or "")
|
| 2475 |
+
linked = []
|
| 2476 |
+
for definition_id, defn in (engine.all_definitions(runtime) or {}).items():
|
| 2477 |
+
if not isinstance(defn, dict) or defn.get("kind") != "route_delivery":
|
| 2478 |
+
continue
|
| 2479 |
+
snapshot = ((defn.get("config") or {}).get("routeSnapshot")
|
| 2480 |
+
if isinstance(defn.get("config"), dict) else None)
|
| 2481 |
+
if not isinstance(snapshot, dict) or str(snapshot.get("routeId") or "") != wanted:
|
| 2482 |
+
continue
|
| 2483 |
+
linked.append(str(defn.get("id") or definition_id))
|
| 2484 |
+
return sorted(set(linked))
|
| 2485 |
+
|
| 2486 |
+
|
| 2487 |
+
@router.get("/customers/route-deliveries")
|
| 2488 |
+
def route_delivery_list(session: Session = Depends(module_gate(MODULE))):
|
| 2489 |
+
"""Saved C2 route deliveries owned by the caller (or all for an administrator)."""
|
| 2490 |
+
return {"deliveries": _route_delivery_definitions(session)}
|
| 2491 |
+
|
| 2492 |
+
|
| 2493 |
+
@router.get("/customers/routes/{route_id}/deliveries")
|
| 2494 |
+
def normalized_route_delivery_list(route_id: str,
|
| 2495 |
+
session: Session = Depends(module_gate(MODULE))):
|
| 2496 |
+
"""Deliveries for the one normalized Route whose detail is open."""
|
| 2497 |
+
_route_or_404(session, route_id)
|
| 2498 |
+
return {"deliveries": _route_delivery_definitions(session, route_id)}
|
| 2499 |
+
|
| 2500 |
+
|
| 2501 |
+
def _create_route_delivery_for_route(session, route, body):
|
| 2502 |
+
"""Persist and arm one server-authored snapshot; never execute its runner here."""
|
| 2503 |
import automation_control
|
| 2504 |
import automation_engine as engine
|
| 2505 |
|
| 2506 |
if not session.runtime.available():
|
| 2507 |
raise err(503, "store_unavailable", "the tenant store is unavailable. Nothing was saved")
|
| 2508 |
+
_route_mutation_allowed(session, route)
|
| 2509 |
+
recipient, snapshot = _route_delivery_snapshot_for_route_or_400(session, route, body)
|
| 2510 |
+
route_name = " ".join(str(route.get("name") or "Route").split())[:120] or "Route"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2511 |
raw = {
|
| 2512 |
+
"name": f"{route_name} delivery"[:120],
|
| 2513 |
"kind": "route_delivery",
|
| 2514 |
"trigger": {"key": "manual"},
|
| 2515 |
+
# The normalized Route UI promises one deliberately boring cadence. A browser cannot
|
| 2516 |
+
# smuggle a different cron or an immediate run into this creation request.
|
| 2517 |
+
"schedule": {"cron": "0 8 * * *", "enabled": True},
|
| 2518 |
+
"config": {"recipient": recipient, "routeSnapshot": snapshot},
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2519 |
"flow": {"actions": []},
|
| 2520 |
}
|
| 2521 |
defn, problem = engine.create(session.runtime, raw, username=session.uname)
|
|
|
|
| 2524 |
try:
|
| 2525 |
automation_control.sync_definition(session.tenant, defn)
|
| 2526 |
except automation_control.ControlPlaneError as exc:
|
|
|
|
| 2527 |
raise err(503, "automation_control_unavailable",
|
| 2528 |
f"the route was saved, but its daily schedule could not be armed: {exc}")
|
| 2529 |
return {"delivery": _route_delivery_wire(defn)}
|
| 2530 |
|
| 2531 |
|
| 2532 |
+
@router.post("/customers/routes/{route_id}/deliveries", status_code=201)
|
| 2533 |
+
def normalized_route_delivery_create(route_id: str, body: dict = Body(default=None),
|
| 2534 |
+
session: Session = Depends(module_gate(MODULE))):
|
| 2535 |
+
"""Schedule a named normalized Route from its server-resolved View and stop relation."""
|
| 2536 |
+
return _create_route_delivery_for_route(
|
| 2537 |
+
session, _route_or_404(session, route_id), body if isinstance(body, dict) else {})
|
| 2538 |
+
|
| 2539 |
+
|
| 2540 |
+
@router.post("/customers/route-deliveries")
|
| 2541 |
+
def route_delivery_create(body: dict = Body(default=None),
|
| 2542 |
session: Session = Depends(module_gate(MODULE))):
|
| 2543 |
+
"""Compatibility door: a normalized Route id is still mandatory and server-resolved."""
|
| 2544 |
+
body = body if isinstance(body, dict) else {}
|
| 2545 |
+
route_id = str(body.get("routeId") or "").strip()
|
| 2546 |
+
if not route_id:
|
| 2547 |
+
raise err(400, "normalized_route_required",
|
| 2548 |
+
"choose a saved Route before scheduling its delivery")
|
| 2549 |
+
return _create_route_delivery_for_route(session, _route_or_404(session, route_id), body)
|
| 2550 |
+
|
| 2551 |
+
|
| 2552 |
+
def _delete_route_delivery(session, delivery_id, route_id=None):
|
| 2553 |
import automation_control
|
| 2554 |
import automation_engine as engine
|
| 2555 |
|
| 2556 |
defn = (engine.all_definitions(session.runtime) or {}).get(str(delivery_id))
|
| 2557 |
if not isinstance(defn, dict) or defn.get("kind") != "route_delivery":
|
| 2558 |
raise err(404, "unknown_route_delivery", "no scheduled route with that id")
|
| 2559 |
+
wire = _route_delivery_wire(defn)
|
| 2560 |
+
if route_id is not None and wire["snapshot"]["routeId"] != str(route_id):
|
| 2561 |
+
raise err(404, "unknown_route_delivery", "no scheduled delivery for this Route with that id")
|
| 2562 |
if not session.admin and str(defn.get("createdBy") or "") != session.uname:
|
| 2563 |
raise err(403, "forbidden", "only the route creator or an administrator can remove its schedule")
|
| 2564 |
engine.remove(session.runtime, str(delivery_id))
|
|
|
|
| 2568 |
raise err(503, "automation_control_unavailable",
|
| 2569 |
f"the route schedule was removed, but its native schedule could not be removed: {exc}")
|
| 2570 |
return {"deleted": str(delivery_id)}
|
| 2571 |
+
|
| 2572 |
+
|
| 2573 |
+
@router.delete("/customers/routes/{route_id}/deliveries/{delivery_id}")
|
| 2574 |
+
def normalized_route_delivery_delete(route_id: str, delivery_id: str,
|
| 2575 |
+
session: Session = Depends(module_gate(MODULE))):
|
| 2576 |
+
"""Remove one delivery from the normalized Route detail that owns it."""
|
| 2577 |
+
route = _route_or_404(session, route_id)
|
| 2578 |
+
_route_mutation_allowed(session, route)
|
| 2579 |
+
return _delete_route_delivery(session, delivery_id, route_id)
|
| 2580 |
+
|
| 2581 |
+
|
| 2582 |
+
@router.delete("/customers/route-deliveries/{delivery_id}")
|
| 2583 |
+
def route_delivery_delete(delivery_id: str,
|
| 2584 |
+
session: Session = Depends(module_gate(MODULE))):
|
| 2585 |
+
"""Compatibility removal for existing schedule links."""
|
| 2586 |
+
return _delete_route_delivery(session, delivery_id)
|
api/routes_geo.py
CHANGED
|
@@ -123,7 +123,9 @@ _CACHE_MAX = 4096
|
|
| 123 |
ZONES_KEY = "map_zones"
|
| 124 |
MAX_ZONES = 200
|
| 125 |
MAX_ZONE_MEMBERSHIPS = 10_000
|
|
|
|
| 126 |
_ZONE_COLORS = ("#9DBFF2", "#A5D8B4", "#F5D989", "#F0A8A0", "#C7B7E8")
|
|
|
|
| 127 |
|
| 128 |
|
| 129 |
def _zone_id(raw):
|
|
@@ -173,6 +175,25 @@ def _clean_geometry(raw):
|
|
| 173 |
"type": "MultiPolygon", "coordinates": cleaned_polys}
|
| 174 |
|
| 175 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 176 |
def _clean_zone(raw, previous=None, *, zone_id=""):
|
| 177 |
raw = raw if isinstance(raw, dict) else {}
|
| 178 |
previous = previous if isinstance(previous, dict) else {}
|
|
@@ -182,8 +203,13 @@ def _clean_zone(raw, previous=None, *, zone_id=""):
|
|
| 182 |
color = str(raw.get("color") if "color" in raw else previous.get("color") or _ZONE_COLORS[0]).upper()
|
| 183 |
if not re.fullmatch(r"#[0-9A-F]{6}", color):
|
| 184 |
raise ValueError("a Zone color is a six-digit hex color")
|
| 185 |
-
|
| 186 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 187 |
geographic = str(raw.get("geographicField") if "geographicField" in raw
|
| 188 |
else previous.get("geographicField") or "").strip()[:80]
|
| 189 |
memberships = raw.get("memberships") if "memberships" in raw else previous.get("memberships") or []
|
|
@@ -209,6 +235,7 @@ def _clean_zone(raw, previous=None, *, zone_id=""):
|
|
| 209 |
"name": name,
|
| 210 |
"color": color,
|
| 211 |
"geometryGeoJson": geometry,
|
|
|
|
| 212 |
"visible": bool(raw.get("visible")) if "visible" in raw else bool(previous.get("visible", True)),
|
| 213 |
"geographicField": geographic,
|
| 214 |
"memberships": member_ids,
|
|
@@ -217,7 +244,8 @@ def _clean_zone(raw, previous=None, *, zone_id=""):
|
|
| 217 |
|
| 218 |
def _zone_wire(zone):
|
| 219 |
wire = {key: zone.get(key) for key in ("id", "name", "color", "geometryGeoJson", "visible",
|
| 220 |
-
"geographicField", "
|
|
|
|
| 221 |
# Storage keeps ids as strings because table records may originate in several backends; Map
|
| 222 |
# selection is numeric `pid`s. The wire performs that one boundary conversion explicitly.
|
| 223 |
members = []
|
|
@@ -229,9 +257,50 @@ def _zone_wire(zone):
|
|
| 229 |
if pid > 0:
|
| 230 |
members.append(pid)
|
| 231 |
wire["memberships"] = members
|
|
|
|
| 232 |
return wire
|
| 233 |
|
| 234 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 235 |
def _zone_context(session, raw_table_key):
|
| 236 |
"""One table-scoped Zone context, using the existing grid assemblies as permission walls."""
|
| 237 |
table_key = str(raw_table_key or "").strip()
|
|
@@ -250,7 +319,7 @@ def _zone_context(session, raw_table_key):
|
|
| 250 |
raise err(400, "invalid_zone_table", "choose a database before working with Zones")
|
| 251 |
fields = {str(field.get("key") or "") for field in (grid.get("fields") or [])
|
| 252 |
if isinstance(field, dict) and field.get("key")}
|
| 253 |
-
return table_key, fields, set(grid.get("pids") or ())
|
| 254 |
|
| 255 |
|
| 256 |
def _zone_subject(session, table_key, zone_id):
|
|
@@ -437,13 +506,14 @@ def geo_providers(session: Session = Depends(require_session)):
|
|
| 437 |
def geo_zones(tableKey: str = Query(default=""), session: Session = Depends(require_session)):
|
| 438 |
"""The canonical table-scoped Zone DTOs a Map may draw or filter by."""
|
| 439 |
from core import user_tables
|
| 440 |
-
table_key, _fields,
|
| 441 |
zones = user_tables.zones(table_key, st=session.runtime)
|
| 442 |
# A hidden Zone remains recoverable to its creator/admin, but cannot become visible through a
|
| 443 |
# second table simply because row ids happen to collide there.
|
| 444 |
visible = [zone for zone in zones if zone.get("visible", True)
|
| 445 |
or session.admin or str(zone.get("createdBy") or "") == session.uname]
|
| 446 |
-
|
|
|
|
| 447 |
key=lambda zone: (str(zone.get("name") or "").casefold(), str(zone.get("id") or "")))]}
|
| 448 |
|
| 449 |
|
|
@@ -452,9 +522,10 @@ def geo_zone_create(body: dict = Body(default=None), session: Session = Depends(
|
|
| 452 |
"""Persist one Zone in the existing table-scoped Zone store and field/filter contract."""
|
| 453 |
from core import user_tables
|
| 454 |
body = body if isinstance(body, dict) else {}
|
| 455 |
-
table_key, field_keys, pids = _zone_context(session, body.get("tableKey"))
|
| 456 |
try:
|
| 457 |
zone = _clean_zone(body)
|
|
|
|
| 458 |
except ValueError as exc:
|
| 459 |
raise err(400, "invalid_zone", str(exc))
|
| 460 |
if not zone["id"]:
|
|
@@ -476,10 +547,11 @@ def geo_zone_update(zone_id: str, body: dict = Body(default=None),
|
|
| 476 |
"""Edit a table-scoped Zone while retaining creator, geometry and membership invariants."""
|
| 477 |
from core import user_tables
|
| 478 |
body = body if isinstance(body, dict) else {}
|
| 479 |
-
table_key, field_keys, pids = _zone_context(session, body.get("tableKey"))
|
| 480 |
previous = _zone_subject(session, table_key, zone_id)
|
| 481 |
try:
|
| 482 |
zone = _clean_zone(body, previous, zone_id=str(zone_id))
|
|
|
|
| 483 |
except ValueError as exc:
|
| 484 |
raise err(400, "invalid_zone", str(exc))
|
| 485 |
saved = user_tables.upsert_zone(table_key, zone, field_keys=field_keys,
|
|
@@ -495,7 +567,7 @@ def geo_zone_delete(zone_id: str, body: dict = Body(default=None),
|
|
| 495 |
session: Session = Depends(require_session)):
|
| 496 |
"""Delete exactly one table-scoped Zone; record values are never mutated here."""
|
| 497 |
body = body if isinstance(body, dict) else {}
|
| 498 |
-
table_key, _fields, _pids = _zone_context(session, body.get("tableKey"))
|
| 499 |
_zone_subject(session, table_key, zone_id)
|
| 500 |
from core import user_tables
|
| 501 |
if not user_tables.delete_zone(table_key, zone_id, st=session.runtime):
|
|
|
|
| 123 |
ZONES_KEY = "map_zones"
|
| 124 |
MAX_ZONES = 200
|
| 125 |
MAX_ZONE_MEMBERSHIPS = 10_000
|
| 126 |
+
MAX_ZONE_ZIP_CODES = 500
|
| 127 |
_ZONE_COLORS = ("#9DBFF2", "#A5D8B4", "#F5D989", "#F0A8A0", "#C7B7E8")
|
| 128 |
+
_ZONE_ZIP_RE = re.compile(r"^\d{5}(?:-\d{4})?$")
|
| 129 |
|
| 130 |
|
| 131 |
def _zone_id(raw):
|
|
|
|
| 175 |
"type": "MultiPolygon", "coordinates": cleaned_polys}
|
| 176 |
|
| 177 |
|
| 178 |
+
def _clean_zip_codes(raw):
|
| 179 |
+
"""A bounded US ZIP list. Invalid input is refused rather than silently losing a boundary."""
|
| 180 |
+
if raw is None:
|
| 181 |
+
return []
|
| 182 |
+
if not isinstance(raw, list):
|
| 183 |
+
raise ValueError("Zone ZIP codes must be a list")
|
| 184 |
+
if len(raw) > MAX_ZONE_ZIP_CODES:
|
| 185 |
+
raise ValueError(f"a Zone can contain at most {MAX_ZONE_ZIP_CODES:,} ZIP codes")
|
| 186 |
+
out, seen = [], set()
|
| 187 |
+
for value in raw:
|
| 188 |
+
zip_code = str(value or "").strip().upper()
|
| 189 |
+
if not _ZONE_ZIP_RE.fullmatch(zip_code):
|
| 190 |
+
raise ValueError("each Zone ZIP code must be five digits or ZIP+4")
|
| 191 |
+
if zip_code not in seen:
|
| 192 |
+
seen.add(zip_code)
|
| 193 |
+
out.append(zip_code)
|
| 194 |
+
return out
|
| 195 |
+
|
| 196 |
+
|
| 197 |
def _clean_zone(raw, previous=None, *, zone_id=""):
|
| 198 |
raw = raw if isinstance(raw, dict) else {}
|
| 199 |
previous = previous if isinstance(previous, dict) else {}
|
|
|
|
| 203 |
color = str(raw.get("color") if "color" in raw else previous.get("color") or _ZONE_COLORS[0]).upper()
|
| 204 |
if not re.fullmatch(r"#[0-9A-F]{6}", color):
|
| 205 |
raise ValueError("a Zone color is a six-digit hex color")
|
| 206 |
+
geometry_raw = (raw.get("geometryGeoJson") if "geometryGeoJson" in raw
|
| 207 |
+
else previous.get("geometryGeoJson"))
|
| 208 |
+
geometry = _clean_geometry(geometry_raw) if geometry_raw is not None else None
|
| 209 |
+
zip_codes = _clean_zip_codes(raw.get("zipCodes") if "zipCodes" in raw
|
| 210 |
+
else previous.get("zipCodes"))
|
| 211 |
+
if geometry is None and not zip_codes:
|
| 212 |
+
raise ValueError("a Zone needs GeoJSON Polygon or MultiPolygon geometry or a ZIP code")
|
| 213 |
geographic = str(raw.get("geographicField") if "geographicField" in raw
|
| 214 |
else previous.get("geographicField") or "").strip()[:80]
|
| 215 |
memberships = raw.get("memberships") if "memberships" in raw else previous.get("memberships") or []
|
|
|
|
| 235 |
"name": name,
|
| 236 |
"color": color,
|
| 237 |
"geometryGeoJson": geometry,
|
| 238 |
+
"zipCodes": zip_codes,
|
| 239 |
"visible": bool(raw.get("visible")) if "visible" in raw else bool(previous.get("visible", True)),
|
| 240 |
"geographicField": geographic,
|
| 241 |
"memberships": member_ids,
|
|
|
|
| 244 |
|
| 245 |
def _zone_wire(zone):
|
| 246 |
wire = {key: zone.get(key) for key in ("id", "name", "color", "geometryGeoJson", "visible",
|
| 247 |
+
"geographicField", "zipCodes", "memberships",
|
| 248 |
+
"createdBy", "createdAt")}
|
| 249 |
# Storage keeps ids as strings because table records may originate in several backends; Map
|
| 250 |
# selection is numeric `pid`s. The wire performs that one boundary conversion explicitly.
|
| 251 |
members = []
|
|
|
|
| 257 |
if pid > 0:
|
| 258 |
members.append(pid)
|
| 259 |
wire["memberships"] = members
|
| 260 |
+
wire["zipCodes"] = list(zone.get("zipCodes") or ())
|
| 261 |
return wire
|
| 262 |
|
| 263 |
|
| 264 |
+
def _zone_membership_union(zone, rows, allowed_pids, *, refuse_overflow=False):
|
| 265 |
+
"""Return a scoped selected/polygon/ZIP union without mutating the stored Zone.
|
| 266 |
+
|
| 267 |
+
C3's durable ``memberships`` snapshot is retained for existing Zones and explicit geography
|
| 268 |
+
groups. Wave 44 adds current polygon/ZIP matches from the already permission-walled rows.
|
| 269 |
+
GET calls this pure projection too, so an address change can update the visible chooser while
|
| 270 |
+
tenant data remains untouched.
|
| 271 |
+
"""
|
| 272 |
+
from core import route_system
|
| 273 |
+
|
| 274 |
+
allowed = {str(pid) for pid in allowed_pids or ()}
|
| 275 |
+
prepared = []
|
| 276 |
+
geographic = str(zone.get("geographicField") or "")
|
| 277 |
+
geographic_is_zip = bool(re.search(r"zip|postal", geographic, re.IGNORECASE))
|
| 278 |
+
for raw in rows or ():
|
| 279 |
+
if not isinstance(raw, dict):
|
| 280 |
+
continue
|
| 281 |
+
item = raw
|
| 282 |
+
if geographic_is_zip and geographic in raw and not any(
|
| 283 |
+
raw.get(key) not in (None, "")
|
| 284 |
+
for key in ("zip", "zip_code", "postal_code", "postalCode")):
|
| 285 |
+
item = {**raw, "zip": raw.get(geographic)}
|
| 286 |
+
prepared.append(item)
|
| 287 |
+
derived = route_system.zone_members(zone, prepared)
|
| 288 |
+
members, seen = [], set()
|
| 289 |
+
for value in list(zone.get("memberships") or ()) + list(derived):
|
| 290 |
+
try:
|
| 291 |
+
pid = int(value)
|
| 292 |
+
except (TypeError, ValueError):
|
| 293 |
+
continue
|
| 294 |
+
marker = str(pid)
|
| 295 |
+
if pid <= 0 or marker in seen or marker not in allowed:
|
| 296 |
+
continue
|
| 297 |
+
seen.add(marker)
|
| 298 |
+
members.append(pid)
|
| 299 |
+
if refuse_overflow and len(members) > MAX_ZONE_MEMBERSHIPS:
|
| 300 |
+
raise ValueError(f"a Zone can contain at most {MAX_ZONE_MEMBERSHIPS:,} record IDs")
|
| 301 |
+
return {**zone, "memberships": members}
|
| 302 |
+
|
| 303 |
+
|
| 304 |
def _zone_context(session, raw_table_key):
|
| 305 |
"""One table-scoped Zone context, using the existing grid assemblies as permission walls."""
|
| 306 |
table_key = str(raw_table_key or "").strip()
|
|
|
|
| 319 |
raise err(400, "invalid_zone_table", "choose a database before working with Zones")
|
| 320 |
fields = {str(field.get("key") or "") for field in (grid.get("fields") or [])
|
| 321 |
if isinstance(field, dict) and field.get("key")}
|
| 322 |
+
return table_key, fields, set(grid.get("pids") or ()), list(grid.get("rows_src") or ())
|
| 323 |
|
| 324 |
|
| 325 |
def _zone_subject(session, table_key, zone_id):
|
|
|
|
| 506 |
def geo_zones(tableKey: str = Query(default=""), session: Session = Depends(require_session)):
|
| 507 |
"""The canonical table-scoped Zone DTOs a Map may draw or filter by."""
|
| 508 |
from core import user_tables
|
| 509 |
+
table_key, _fields, pids, rows = _zone_context(session, tableKey)
|
| 510 |
zones = user_tables.zones(table_key, st=session.runtime)
|
| 511 |
# A hidden Zone remains recoverable to its creator/admin, but cannot become visible through a
|
| 512 |
# second table simply because row ids happen to collide there.
|
| 513 |
visible = [zone for zone in zones if zone.get("visible", True)
|
| 514 |
or session.admin or str(zone.get("createdBy") or "") == session.uname]
|
| 515 |
+
projected = [_zone_membership_union(zone, rows, pids) for zone in visible]
|
| 516 |
+
return {"zones": [_zone_wire(zone) for zone in sorted(projected,
|
| 517 |
key=lambda zone: (str(zone.get("name") or "").casefold(), str(zone.get("id") or "")))]}
|
| 518 |
|
| 519 |
|
|
|
|
| 522 |
"""Persist one Zone in the existing table-scoped Zone store and field/filter contract."""
|
| 523 |
from core import user_tables
|
| 524 |
body = body if isinstance(body, dict) else {}
|
| 525 |
+
table_key, field_keys, pids, rows = _zone_context(session, body.get("tableKey"))
|
| 526 |
try:
|
| 527 |
zone = _clean_zone(body)
|
| 528 |
+
zone = _zone_membership_union(zone, rows, pids, refuse_overflow=True)
|
| 529 |
except ValueError as exc:
|
| 530 |
raise err(400, "invalid_zone", str(exc))
|
| 531 |
if not zone["id"]:
|
|
|
|
| 547 |
"""Edit a table-scoped Zone while retaining creator, geometry and membership invariants."""
|
| 548 |
from core import user_tables
|
| 549 |
body = body if isinstance(body, dict) else {}
|
| 550 |
+
table_key, field_keys, pids, rows = _zone_context(session, body.get("tableKey"))
|
| 551 |
previous = _zone_subject(session, table_key, zone_id)
|
| 552 |
try:
|
| 553 |
zone = _clean_zone(body, previous, zone_id=str(zone_id))
|
| 554 |
+
zone = _zone_membership_union(zone, rows, pids, refuse_overflow=True)
|
| 555 |
except ValueError as exc:
|
| 556 |
raise err(400, "invalid_zone", str(exc))
|
| 557 |
saved = user_tables.upsert_zone(table_key, zone, field_keys=field_keys,
|
|
|
|
| 567 |
session: Session = Depends(require_session)):
|
| 568 |
"""Delete exactly one table-scoped Zone; record values are never mutated here."""
|
| 569 |
body = body if isinstance(body, dict) else {}
|
| 570 |
+
table_key, _fields, _pids, _rows = _zone_context(session, body.get("tableKey"))
|
| 571 |
_zone_subject(session, table_key, zone_id)
|
| 572 |
from core import user_tables
|
| 573 |
if not user_tables.delete_zone(table_key, zone_id, st=session.runtime):
|
api/routes_grid.py
CHANGED
|
@@ -24,7 +24,7 @@ back. A 200 over a write that evaporated is the failure this rule exists to prev
|
|
| 24 |
import datetime as dt
|
| 25 |
import time
|
| 26 |
|
| 27 |
-
from fastapi import APIRouter, Body, Depends
|
| 28 |
|
| 29 |
from deps import Session, err, module_gate, perms, require_session
|
| 30 |
|
|
@@ -1071,6 +1071,9 @@ def grid_events_route(body: dict = Body(default=None),
|
|
| 1071 |
#: [[date-window-vocabulary]]. This is a RENAME and nothing else. `all` resolves to `(None, None)`.
|
| 1072 |
PIVOT_WINDOWS = {"all": "all_time", "last12m": "ltm", "ytd": "ytd"}
|
| 1073 |
|
|
|
|
|
|
|
|
|
|
| 1074 |
#: The DECLARED pivot routes: `(source, target) -> the edge that answers it`. A pair with no entry
|
| 1075 |
#: is a 400, never an empty grid β "there is no way to get there" and "nothing is related" are two
|
| 1076 |
#: different answers and only one of them is true.
|
|
@@ -1094,13 +1097,75 @@ _PIVOT_ROUTES = {
|
|
| 1094 |
"measure": "revenue",
|
| 1095 |
"scope_key": "customer", # the cohort bucket the SOURCE tree's cohort leaves name
|
| 1096 |
"source_dim": "order_partner",
|
| 1097 |
-
"source_key": "pid",
|
| 1098 |
"target_dim": "product_code",
|
| 1099 |
"target_key": "code",
|
| 1100 |
},
|
| 1101 |
}
|
| 1102 |
|
| 1103 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1104 |
def _pivot_today():
|
| 1105 |
"""The tenant's today, ISO. One clock, so the window and any date leaf agree."""
|
| 1106 |
import core.periods as periods
|
|
@@ -1233,12 +1298,12 @@ def grid_pivot(body: dict = Body(default=None),
|
|
| 1233 |
f"window must be one of {', '.join(sorted(PIVOT_WINDOWS))}. Refusing to guess "
|
| 1234 |
f"which period was meant, because guessing 'all time' would widen the answer "
|
| 1235 |
f"under a count nobody would doubt")
|
| 1236 |
-
|
| 1237 |
-
|
| 1238 |
-
|
| 1239 |
-
|
| 1240 |
-
|
| 1241 |
-
|
| 1242 |
|
| 1243 |
# ββ THE WALL, ON BOTH SIDES OF THE JOIN (R12) ββββββββββββββββββββββββββββββββββββββββββββ
|
| 1244 |
src, refusal = _pivot_side(session, source)
|
|
@@ -1251,6 +1316,9 @@ def grid_pivot(body: dict = Body(default=None),
|
|
| 1251 |
src_fields, src_rows = src
|
| 1252 |
tgt_fields, tgt_rows = tgt
|
| 1253 |
|
|
|
|
|
|
|
|
|
|
| 1254 |
today = _pivot_today()
|
| 1255 |
columns = filter_eval._columns_map(src_fields)
|
| 1256 |
unanswerable = _pivot_unanswerable(filters, columns)
|
|
@@ -1275,10 +1343,6 @@ def grid_pivot(body: dict = Body(default=None),
|
|
| 1275 |
for cid, c in cohort_mod.scoped(route["scope_key"]).visible(
|
| 1276 |
session.uname, pool_pids).items()}
|
| 1277 |
|
| 1278 |
-
if route["source_key"] != "pid":
|
| 1279 |
-
raise err(500, "pivot_source_key",
|
| 1280 |
-
f"this pivot names '{route['source_key']}' as the source identity and the row "
|
| 1281 |
-
f"engine reads 'pid'. Refusing rather than pivoting on the wrong column")
|
| 1282 |
member = sorted({p for p in filter_eval.visible_pids(
|
| 1283 |
{"conj": filter_conj, "nodes": filters}, src_rows, src_fields,
|
| 1284 |
ctx=filter_eval.EvalCtx(cohort_sets=cohort_sets, today=today))
|
|
@@ -1300,8 +1364,20 @@ def grid_pivot(body: dict = Body(default=None),
|
|
| 1300 |
filters={route["source_dim"]: member},
|
| 1301 |
date_from=date_from, date_to=date_to, team_id=team_id, today=today,
|
| 1302 |
limit=semantic.MAX_GROUPS)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1303 |
except semantic.ModelError as exc:
|
| 1304 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1305 |
|
| 1306 |
# β `truncated` IS READ, NOT ASSUMED FALSE. `store_query` returns groups plus a flag, and a
|
| 1307 |
# grouped query's groups ARE the answer, so a dropped one is missing data with nothing to
|
|
@@ -1401,3 +1477,84 @@ def _register_topic_rows():
|
|
| 1401 |
_PRODUCT_MODULE = "product_data"
|
| 1402 |
|
| 1403 |
_C1_ROW_SOURCES = _register_topic_rows()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 24 |
import datetime as dt
|
| 25 |
import time
|
| 26 |
|
| 27 |
+
from fastapi import APIRouter, Body, Depends, HTTPException
|
| 28 |
|
| 29 |
from deps import Session, err, module_gate, perms, require_session
|
| 30 |
|
|
|
|
| 1071 |
#: [[date-window-vocabulary]]. This is a RENAME and nothing else. `all` resolves to `(None, None)`.
|
| 1072 |
PIVOT_WINDOWS = {"all": "all_time", "last12m": "ltm", "ytd": "ytd"}
|
| 1073 |
|
| 1074 |
+
# The required subset of a stored semantic `via` bag consumed by the pivot door.
|
| 1075 |
+
_PIVOT_VIA_REQUIRED = ("topic", "measure", "scope_key", "source_dim", "target_dim", "target_key")
|
| 1076 |
+
|
| 1077 |
#: The DECLARED pivot routes: `(source, target) -> the edge that answers it`. A pair with no entry
|
| 1078 |
#: is a 400, never an empty grid β "there is no way to get there" and "nothing is related" are two
|
| 1079 |
#: different answers and only one of them is true.
|
|
|
|
| 1097 |
"measure": "revenue",
|
| 1098 |
"scope_key": "customer", # the cohort bucket the SOURCE tree's cohort leaves name
|
| 1099 |
"source_dim": "order_partner",
|
|
|
|
| 1100 |
"target_dim": "product_code",
|
| 1101 |
"target_key": "code",
|
| 1102 |
},
|
| 1103 |
}
|
| 1104 |
|
| 1105 |
|
| 1106 |
+
def _pivot_route(fields, source, target, via_field):
|
| 1107 |
+
"""Resolve a visible link field first; allow only the single dated A23 fallback."""
|
| 1108 |
+
try:
|
| 1109 |
+
return _pivot_route_via(fields, source, target, via_field)
|
| 1110 |
+
except HTTPException as exc:
|
| 1111 |
+
detail = exc.detail if isinstance(exc.detail, dict) else {}
|
| 1112 |
+
if (detail.get("error") or {}).get("code") != "no_pivot_route":
|
| 1113 |
+
raise
|
| 1114 |
+
tombstone = _PIVOT_ROUTES.get((source, target))
|
| 1115 |
+
if tombstone is None:
|
| 1116 |
+
raise
|
| 1117 |
+
return dict(tombstone)
|
| 1118 |
+
|
| 1119 |
+
|
| 1120 |
+
def _pivot_route_via(fields, source, target, via_field):
|
| 1121 |
+
"""Return the `via` bag from the link field named by the request, or refuse by name."""
|
| 1122 |
+
via_field = str(via_field or "").strip()
|
| 1123 |
+
if not via_field:
|
| 1124 |
+
raise err(400, "no_pivot_route",
|
| 1125 |
+
f"this pivot did not name a link field, so there is no edge to answer it with. "
|
| 1126 |
+
f"Send 'viaField' naming a link field on '{source}' that points at '{target}'")
|
| 1127 |
+
|
| 1128 |
+
match = None
|
| 1129 |
+
for field in fields or ():
|
| 1130 |
+
if not isinstance(field, dict):
|
| 1131 |
+
continue
|
| 1132 |
+
if str(field.get("key") or "") == via_field and field.get("type") == "link":
|
| 1133 |
+
match = field
|
| 1134 |
+
break
|
| 1135 |
+
if match is None:
|
| 1136 |
+
raise err(400, "no_pivot_route",
|
| 1137 |
+
f"this account cannot resolve a link field named '{via_field}' on '{source}', "
|
| 1138 |
+
f"so there is no declared edge to '{target}'. Pivot from a link field this "
|
| 1139 |
+
f"account can see on that grid")
|
| 1140 |
+
|
| 1141 |
+
link = match.get("link") if isinstance(match.get("link"), dict) else {}
|
| 1142 |
+
points_at = str(link.get("table") or "")
|
| 1143 |
+
if points_at != target:
|
| 1144 |
+
raise err(400, "no_pivot_route",
|
| 1145 |
+
f"the link field '{via_field}' points at "
|
| 1146 |
+
f"'{points_at or 'nothing this door can name'}', not at '{target}'. Refusing "
|
| 1147 |
+
f"rather than pivoting through an edge nobody asked for")
|
| 1148 |
+
|
| 1149 |
+
via = link.get("via") if isinstance(link.get("via"), dict) else None
|
| 1150 |
+
if not via:
|
| 1151 |
+
raise err(400, "no_pivot_route",
|
| 1152 |
+
f"the link field '{via_field}' joins '{source}' to '{target}' directly and "
|
| 1153 |
+
f"carries no 'via' declaration, so this door has no fact table to ask")
|
| 1154 |
+
missing = [key for key in _PIVOT_VIA_REQUIRED if not via.get(key)]
|
| 1155 |
+
if missing:
|
| 1156 |
+
raise err(400, "no_pivot_route",
|
| 1157 |
+
f"the 'via' declaration on link field '{via_field}' is missing "
|
| 1158 |
+
f"{', '.join(missing)}, so the edge is not fully described")
|
| 1159 |
+
return via
|
| 1160 |
+
|
| 1161 |
+
|
| 1162 |
+
_PIVOT_AUTHORING = (
|
| 1163 |
+
"unknown metric", "unknown topic", "belong to another topic", "is company-level",
|
| 1164 |
+
"at least one measure required", "filter tree", "filter rule", "must reference",
|
| 1165 |
+
"grain must be", "is store-only", "unknown dim", "has no name column",
|
| 1166 |
+
)
|
| 1167 |
+
|
| 1168 |
+
|
| 1169 |
def _pivot_today():
|
| 1170 |
"""The tenant's today, ISO. One clock, so the window and any date leaf agree."""
|
| 1171 |
import core.periods as periods
|
|
|
|
| 1298 |
f"window must be one of {', '.join(sorted(PIVOT_WINDOWS))}. Refusing to guess "
|
| 1299 |
f"which period was meant, because guessing 'all time' would widen the answer "
|
| 1300 |
f"under a count nobody would doubt")
|
| 1301 |
+
# Permission and path validity are decided before either database is fetched.
|
| 1302 |
+
scope = perm_scope.pivot_scope(session.user, source, target, st=session.runtime)
|
| 1303 |
+
if not scope.permitted:
|
| 1304 |
+
return _pivot_reply(source, target, [], [], 0, 0,
|
| 1305 |
+
refusal=scope.refusal(),
|
| 1306 |
+
limits=scope.limits(st=session.runtime))
|
| 1307 |
|
| 1308 |
# ββ THE WALL, ON BOTH SIDES OF THE JOIN (R12) ββββββββββββββββββββββββββββββββββββββββββββ
|
| 1309 |
src, refusal = _pivot_side(session, source)
|
|
|
|
| 1316 |
src_fields, src_rows = src
|
| 1317 |
tgt_fields, tgt_rows = tgt
|
| 1318 |
|
| 1319 |
+
# Resolve the relationship from the visible link field the request actually named.
|
| 1320 |
+
route = _pivot_route(src_fields, source, target, body.get("viaField"))
|
| 1321 |
+
|
| 1322 |
today = _pivot_today()
|
| 1323 |
columns = filter_eval._columns_map(src_fields)
|
| 1324 |
unanswerable = _pivot_unanswerable(filters, columns)
|
|
|
|
| 1343 |
for cid, c in cohort_mod.scoped(route["scope_key"]).visible(
|
| 1344 |
session.uname, pool_pids).items()}
|
| 1345 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1346 |
member = sorted({p for p in filter_eval.visible_pids(
|
| 1347 |
{"conj": filter_conj, "nodes": filters}, src_rows, src_fields,
|
| 1348 |
ctx=filter_eval.EvalCtx(cohort_sets=cohort_sets, today=today))
|
|
|
|
| 1364 |
filters={route["source_dim"]: member},
|
| 1365 |
date_from=date_from, date_to=date_to, team_id=team_id, today=today,
|
| 1366 |
limit=semantic.MAX_GROUPS)
|
| 1367 |
+
except semantic.UnknownColumnError as exc:
|
| 1368 |
+
others = [column for column in (exc.columns or ()) if column != exc.column]
|
| 1369 |
+
also = f" It also names {', '.join(others)}." if others else ""
|
| 1370 |
+
raise err(400, "pivot_unknown_column",
|
| 1371 |
+
f"{str(exc).rstrip('. ')}. The column this pivot could not resolve is "
|
| 1372 |
+
f"'{exc.column}'.{also} Fix the link field's 'via' declaration, or pivot "
|
| 1373 |
+
f"through a link field whose dims this topic actually carries")
|
| 1374 |
except semantic.ModelError as exc:
|
| 1375 |
+
sentence = str(exc)
|
| 1376 |
+
if any(needle in sentence.lower() for needle in _PIVOT_AUTHORING):
|
| 1377 |
+
raise err(400, "pivot_bad_edge",
|
| 1378 |
+
f"{sentence.rstrip('. ')}. This pivot's edge comes from the link "
|
| 1379 |
+
f"field's 'via' declaration, so that declaration is what needs correcting")
|
| 1380 |
+
raise err(503, "pivot_unavailable", sentence)
|
| 1381 |
|
| 1382 |
# β `truncated` IS READ, NOT ASSUMED FALSE. `store_query` returns groups plus a flag, and a
|
| 1383 |
# grouped query's groups ARE the answer, so a dropped one is missing data with nothing to
|
|
|
|
| 1477 |
_PRODUCT_MODULE = "product_data"
|
| 1478 |
|
| 1479 |
_C1_ROW_SOURCES = _register_topic_rows()
|
| 1480 |
+
|
| 1481 |
+
|
| 1482 |
+
# W42-T07 / C2: model-derived operands for the one-hop link editor. This deliberately reads
|
| 1483 |
+
# model files, not a tenant store, so a cold/locked store cannot silently empty the picker.
|
| 1484 |
+
_HOP_CACHE = {}
|
| 1485 |
+
_HOP_FIELD_SOURCE = "topic"
|
| 1486 |
+
_HOP_FIELD_TYPES = ("text", "int", "date", "currency", "pct")
|
| 1487 |
+
|
| 1488 |
+
|
| 1489 |
+
def _hop_dim_type(columns, dim_key):
|
| 1490 |
+
field_type = ((columns or {}).get(dim_key) or {}).get("type")
|
| 1491 |
+
return field_type if field_type in _HOP_FIELD_TYPES else "text"
|
| 1492 |
+
|
| 1493 |
+
|
| 1494 |
+
def _hop_topic_offer():
|
| 1495 |
+
"""Return answerable topics plus the exact windows accepted by `_clean_via`."""
|
| 1496 |
+
if _HOP_CACHE.get("offer"):
|
| 1497 |
+
return _HOP_CACHE["offer"]
|
| 1498 |
+
from harness import semantic as sem
|
| 1499 |
+
from harness import windows as window_model
|
| 1500 |
+
import core.user_tables as user_tables
|
| 1501 |
+
|
| 1502 |
+
topics, metrics = sem.topics(), sem.metrics()
|
| 1503 |
+
by_topic = {}
|
| 1504 |
+
for key, metric in metrics.items():
|
| 1505 |
+
if metric.get("agg") in ("ratio", "derived"):
|
| 1506 |
+
continue
|
| 1507 |
+
by_topic.setdefault(metric.get("topic"), []).append({
|
| 1508 |
+
"key": key,
|
| 1509 |
+
"label": metric.get("label") or key,
|
| 1510 |
+
"format": metric.get("format") or "usd",
|
| 1511 |
+
"description": metric.get("description") or "",
|
| 1512 |
+
})
|
| 1513 |
+
|
| 1514 |
+
offered, omissions = [], []
|
| 1515 |
+
for topic_key, topic in sorted(topics.items()):
|
| 1516 |
+
dims = ((topic.get("store") or {}).get("dims")) or {}
|
| 1517 |
+
measures = by_topic.get(topic_key) or []
|
| 1518 |
+
label = topic.get("label") or topic_key
|
| 1519 |
+
if not dims or not measures:
|
| 1520 |
+
reasons = []
|
| 1521 |
+
if not dims:
|
| 1522 |
+
reasons.append("no_dims")
|
| 1523 |
+
if not measures:
|
| 1524 |
+
reasons.append("no_measures")
|
| 1525 |
+
omissions.append({"topic": topic_key, "label": label, "reasons": reasons})
|
| 1526 |
+
continue
|
| 1527 |
+
try:
|
| 1528 |
+
columns = sem.store_columns(topic_key, include_measures=False)
|
| 1529 |
+
except Exception:
|
| 1530 |
+
omissions.append({"topic": topic_key, "label": label,
|
| 1531 |
+
"reasons": ["no_store_columns"]})
|
| 1532 |
+
continue
|
| 1533 |
+
offered.append({
|
| 1534 |
+
"key": topic_key,
|
| 1535 |
+
"label": label,
|
| 1536 |
+
"grain": topic.get("grain") or "",
|
| 1537 |
+
"dims": [{
|
| 1538 |
+
"key": dim_key,
|
| 1539 |
+
"label": dim.get("label") or dim_key,
|
| 1540 |
+
"type": _hop_dim_type(columns, dim_key),
|
| 1541 |
+
"source": _HOP_FIELD_SOURCE,
|
| 1542 |
+
"keyedBy": "id" if dim.get("name_col") else "value",
|
| 1543 |
+
} for dim_key, dim in dims.items()],
|
| 1544 |
+
"measures": sorted(measures, key=lambda measure: measure["label"].lower()),
|
| 1545 |
+
})
|
| 1546 |
+
|
| 1547 |
+
windows = [{"key": key, "label": window_model.WINDOW_LABELS.get(key, key).format(n="N")}
|
| 1548 |
+
for key in user_tables.LINK_VIA_WINDOWS]
|
| 1549 |
+
offer = {"topics": offered, "windows": windows, "omissions": omissions}
|
| 1550 |
+
_HOP_CACHE["offer"] = offer
|
| 1551 |
+
return offer
|
| 1552 |
+
|
| 1553 |
+
|
| 1554 |
+
@router.get("/grid/hop-topics")
|
| 1555 |
+
def grid_hop_topics(session: Session = Depends(require_session)):
|
| 1556 |
+
"""Serve the one-hop authoring offer with an unconditional response shape."""
|
| 1557 |
+
import odoo_relational
|
| 1558 |
+
if not odoo_relational.is_royal(session.tenant):
|
| 1559 |
+
return {"topics": [], "windows": [], "omissions": []}
|
| 1560 |
+
return _hop_topic_offer()
|
api/routes_nav.py
CHANGED
|
@@ -914,7 +914,10 @@ def nav_schema(key: str, session: Session = Depends(require_session)):
|
|
| 914 |
# shared stratum and this ticket is not where it starts; widening the list handed to the
|
| 915 |
# closure can only ever ADD to the hidden set, never remove from it.
|
| 916 |
import routes_tables as _rt
|
| 917 |
-
|
|
|
|
|
|
|
|
|
|
| 918 |
hidden = _rt._ut_hidden(session, key,
|
| 919 |
_rt._ut_shared_fields(session, key, base),
|
| 920 |
st=session.runtime)
|
|
|
|
| 914 |
# shared stratum and this ticket is not where it starts; widening the list handed to the
|
| 915 |
# closure can only ever ADD to the hidden set, never remove from it.
|
| 916 |
import routes_tables as _rt
|
| 917 |
+
# Zone is a canonical derived field on the same pre-wall contract the grid uses. Shared
|
| 918 |
+
# tenant-wide fields remain schema-private here; this only prevents the two real doors
|
| 919 |
+
# from evaluating the Zone field on opposite sides of their common wall.
|
| 920 |
+
base = _rt._ut_contract_fields(key, defn.get("fields") or [], st=session.runtime)
|
| 921 |
hidden = _rt._ut_hidden(session, key,
|
| 922 |
_rt._ut_shared_fields(session, key, base),
|
| 923 |
st=session.runtime)
|
api/routes_shares.py
CHANGED
|
@@ -415,6 +415,415 @@ def _unremovable(held_rows, entries, uname):
|
|
| 415 |
stuck.add(user)
|
| 416 |
return stuck
|
| 417 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 418 |
|
| 419 |
@router.get("/share/mine")
|
| 420 |
def my_shares(session: Session = Depends(require_session)):
|
|
@@ -662,21 +1071,15 @@ def put_share(kind: str, oid: str, body: dict = Body(default=None),
|
|
| 662 |
# A field grant is a visibility and edit wall. Promote a private custom
|
| 663 |
# field exactly once, then keep the requested Share field role as the
|
| 664 |
# authoritative override for the legacy permissions bag.
|
| 665 |
-
|
|
|
|
|
|
|
|
|
|
| 666 |
table_key, field_key = shares.split_field_oid(oid)
|
| 667 |
-
|
| 668 |
-
|
| 669 |
-
if not isinstance(defn, dict):
|
| 670 |
raise err(404, "no_object", "no such field, or it is not shared with this account")
|
| 671 |
-
|
| 672 |
-
defn = field_permissions.promote_field(
|
| 673 |
-
workspace_key, shared_key, grant_topic,
|
| 674 |
-
session.uname, defn, st=session.runtime)
|
| 675 |
-
stamped = dict(defn)
|
| 676 |
-
stamped["shared"] = True
|
| 677 |
-
stamped["granted"] = True
|
| 678 |
-
shared_overlay.put_field(shared_key, field_key, stamped, st=session.runtime)
|
| 679 |
-
oid = shares.field_oid(grant_topic, field_key)
|
| 680 |
# ββ R4 / W40-T02 (D3) β OWNERSHIP NEVER MOVES ON A RE-SHARE, AND IT IS SAID HERE RATHER
|
| 681 |
# THAN LEFT TO FALL OUT. `set_grants`' owner is sticky, so the old `rec["owner"] or
|
| 682 |
# session.uname` already happened not to transfer ownership β incidentally, as a property of
|
|
@@ -706,6 +1109,20 @@ def put_share(kind: str, oid: str, body: dict = Body(default=None),
|
|
| 706 |
except shares.GrantsChanged as exc:
|
| 707 |
raise err(409, "grants_changed", str(exc))
|
| 708 |
_notify_new_grantees(session, kind, oid, before=rec["entries"], after=out.get("entries") or [])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 709 |
return out
|
| 710 |
|
| 711 |
|
|
|
|
| 415 |
stuck.add(user)
|
| 416 |
return stuck
|
| 417 |
|
| 418 |
+
# ββ ββ WAVE 42 Β· T25 β SHARING A VIEW SHARES THE FIELDS IT NAMES ββββββββββββββββββββββββββββββ
|
| 419 |
+
#
|
| 420 |
+
# A saved view is a SELECTION expressed in columns: an order, a visible set, a group, a colour,
|
| 421 |
+
# a sort and a filter tree, every one of which names a field key. Granting the view alone hands
|
| 422 |
+
# the receiver a rail row whose columns resolve to nothing they may read, so the feature that
|
| 423 |
+
# looked shipped puts an empty grid on their screen. This block closes that, and it refuses
|
| 424 |
+
# LOUDLY in the three places where a grant would otherwise be a lie.
|
| 425 |
+
#
|
| 426 |
+
# ββ TRAP 1 β A FIELD GRANT IS TOPIC-WIDE, NOT VIEW-SCOPED. It is keyed
|
| 427 |
+
# `shares.field_oid(topic, key)`, so it hands the receiver that column on EVERY view of that
|
| 428 |
+
# database, for as long as the grant stands. That is the existing grant primitive and this
|
| 429 |
+
# ticket does not narrow it; what it does is refuse to let the response PRETEND otherwise, which
|
| 430 |
+
# is why `sharedFieldScope` rides back beside the list.
|
| 431 |
+
#
|
| 432 |
+
# ββ TRAP 2 β THE SHARER CANNOT GRANT A COLUMN THEY DO NOT OWN. `field` is absent from
|
| 433 |
+
# `shares.RESHARE_KINDS` and `_owns_object`'s field branch demands `createdBy == session.uname`,
|
| 434 |
+
# so a view built over a colleague's column simply cannot carry that column with it. Silently
|
| 435 |
+
# skipping it ships an empty column; silently granting it is a permission hole. It is REFUSED
|
| 436 |
+
# BY NAME, inside the 200 response, with the sentence that says who to ask.
|
| 437 |
+
#
|
| 438 |
+
# ββ TRAP 3 β A GRANT CANNOT UN-HIDE AN ADMIN-WALLED COLUMN. `perm_scope.hidden_keys` UNIONS
|
| 439 |
+
# the administrator's `hiddenFields` with the field-grant source, so granting a walled column
|
| 440 |
+
# answers 200, writes the record, and the receiver still sees nothing: granted with no effect,
|
| 441 |
+
# which is the failure this ticket exists to end. Detected BEFORE the grant, refused by name,
|
| 442 |
+
# and the receiver it is walled from is named too.
|
| 443 |
+
#
|
| 444 |
+
# β THE WALL IS READ FROM THE ADMIN SOURCE DIRECTLY AND NEVER THROUGH `hidden_keys`, AND THAT IS
|
| 445 |
+
# NOT AN OPTIMISATION. `hidden_keys` unions `field_grant_hidden` β "hidden because you were not
|
| 446 |
+
# granted it" β which is true of every column this route is ABOUT to grant. Asking it here would
|
| 447 |
+
# refuse the whole set on the grounds that the grant has not happened yet.
|
| 448 |
+
|
| 449 |
+
|
| 450 |
+
def _view_configs(view):
|
| 451 |
+
"""The dicts a saved view keeps its column state in.
|
| 452 |
+
|
| 453 |
+
`SavedView.config` is the contract (`types.ts::ViewConfig`) and is where every key below
|
| 454 |
+
actually lives. The record ITSELF is read as well because a legacy row that stored the same
|
| 455 |
+
members flat costs one dict lookup to cover and would otherwise hand back an empty key set,
|
| 456 |
+
which is the shape that grants nothing and reports nothing wrong.
|
| 457 |
+
"""
|
| 458 |
+
out = []
|
| 459 |
+
if not isinstance(view, dict):
|
| 460 |
+
return out
|
| 461 |
+
cfg = view.get("config")
|
| 462 |
+
if isinstance(cfg, dict):
|
| 463 |
+
out.append(cfg)
|
| 464 |
+
out.append(view)
|
| 465 |
+
return out
|
| 466 |
+
|
| 467 |
+
|
| 468 |
+
def _view_field_keys(view):
|
| 469 |
+
"""Every field key this view NAMES, in the order a reader would meet them.
|
| 470 |
+
|
| 471 |
+
β `filters[].rhs` IS ONE OF THEM AND IS THE ONE THAT GETS DROPPED. A field-vs-field leaf
|
| 472 |
+
(`{colId: price, op: lt, rhs: {kind: field, colId: cost}}`) names TWO columns, and a share
|
| 473 |
+
carrying only the left one leaves the receiver a filter that cannot evaluate. `kind` `stat`
|
| 474 |
+
is not a column reference and is skipped, matching `perm_scope`'s own reader of the tree.
|
| 475 |
+
|
| 476 |
+
β AND `filters` IS A TREE, NOT A LIST. Condition groups nest under `children`, so the walk
|
| 477 |
+
recurses rather than iterating once: a column named only inside a group is still named.
|
| 478 |
+
"""
|
| 479 |
+
keys, seen = [], set()
|
| 480 |
+
|
| 481 |
+
def add(raw):
|
| 482 |
+
key = str(raw or "").strip()
|
| 483 |
+
if key and key not in seen:
|
| 484 |
+
seen.add(key)
|
| 485 |
+
keys.append(key)
|
| 486 |
+
|
| 487 |
+
def walk(node):
|
| 488 |
+
if isinstance(node, list):
|
| 489 |
+
for child in node:
|
| 490 |
+
walk(child)
|
| 491 |
+
return
|
| 492 |
+
if not isinstance(node, dict):
|
| 493 |
+
return
|
| 494 |
+
kids = node.get("children")
|
| 495 |
+
if isinstance(kids, list):
|
| 496 |
+
walk(kids)
|
| 497 |
+
add(node.get("colId"))
|
| 498 |
+
rhs = node.get("rhs")
|
| 499 |
+
if isinstance(rhs, dict) and rhs.get("kind") != "stat":
|
| 500 |
+
add(rhs.get("colId"))
|
| 501 |
+
|
| 502 |
+
for cfg in _view_configs(view):
|
| 503 |
+
for key in (cfg.get("order") or ()):
|
| 504 |
+
add(key)
|
| 505 |
+
for key in (cfg.get("visible") or ()):
|
| 506 |
+
add(key)
|
| 507 |
+
walk(cfg.get("filters"))
|
| 508 |
+
add(cfg.get("groupBy"))
|
| 509 |
+
colour = cfg.get("colorBy")
|
| 510 |
+
add(colour.get("colId") if isinstance(colour, dict) else colour)
|
| 511 |
+
sorts = cfg.get("sorts")
|
| 512 |
+
if isinstance(sorts, dict):
|
| 513 |
+
sorts = [sorts]
|
| 514 |
+
for spec in (sorts or ()):
|
| 515 |
+
if isinstance(spec, dict):
|
| 516 |
+
add(spec.get("colId"))
|
| 517 |
+
return keys
|
| 518 |
+
|
| 519 |
+
|
| 520 |
+
def _find_view_topic(session, oid):
|
| 521 |
+
"""`(topic, view)` for a saved view living in any personal stratum of any topic, else
|
| 522 |
+
`(None, None)`.
|
| 523 |
+
|
| 524 |
+
β THE TOPIC IS HALF THE ANSWER. A field grant is keyed by TOPIC, so resolving the view
|
| 525 |
+
without remembering which workspace answered would leave the caller guessing at the oid,
|
| 526 |
+
which is exactly how two arms of one route come to write two different keys for one column.
|
| 527 |
+
Same loop and same finder as `_owns_object`, which answers a different question about the
|
| 528 |
+
same lookup and is deliberately left alone.
|
| 529 |
+
"""
|
| 530 |
+
try:
|
| 531 |
+
import core.table_store as table_store
|
| 532 |
+
except Exception: # noqa: BLE001
|
| 533 |
+
return None, None
|
| 534 |
+
for topic in _topics(session):
|
| 535 |
+
try:
|
| 536 |
+
hit = table_store.make(f"{topic}_table_workspace", st=session.runtime).find_view(oid)
|
| 537 |
+
except Exception: # noqa: BLE001
|
| 538 |
+
continue
|
| 539 |
+
if hit:
|
| 540 |
+
return str(topic), (hit[1] if len(hit) > 1 else {})
|
| 541 |
+
return None, None
|
| 542 |
+
|
| 543 |
+
|
| 544 |
+
def _promote_field_for_grant(session, table_key, field_key):
|
| 545 |
+
"""Promote a private column exactly once, stamp it shared, and answer its GRANT OID.
|
| 546 |
+
|
| 547 |
+
ββ ONE SEQUENCE, TWO ARMS, AND THAT IS THE WHOLE REASON THIS IS A FUNCTION. `put_share`'s
|
| 548 |
+
`field` arm and its `view` arm (T25) both hand a column to somebody. Two spellings of
|
| 549 |
+
"promote, stamp, key the oid" is how two surfaces start disagreeing about what a grant
|
| 550 |
+
means, and the oid is the exact member that would drift: it is normalised through
|
| 551 |
+
`_field_storage_keys(...)[2]`, never built from whatever key the caller happened to hold.
|
| 552 |
+
|
| 553 |
+
Answers `None` for a key with no definition on that database, so the caller decides whether
|
| 554 |
+
that is a 404 (the `field` arm, where the column IS the request) or a named refusal (the
|
| 555 |
+
`view` arm, where it is one entry in a list).
|
| 556 |
+
"""
|
| 557 |
+
from core import field_permissions, shared_overlay
|
| 558 |
+
defn, already_shared, workspace_key, shared_key, grant_topic = _field_definition(
|
| 559 |
+
session, table_key, field_key)
|
| 560 |
+
if not isinstance(defn, dict):
|
| 561 |
+
return None
|
| 562 |
+
if not already_shared:
|
| 563 |
+
defn = field_permissions.promote_field(
|
| 564 |
+
workspace_key, shared_key, grant_topic,
|
| 565 |
+
session.uname, defn, st=session.runtime)
|
| 566 |
+
stamped = dict(defn)
|
| 567 |
+
stamped["shared"] = True
|
| 568 |
+
stamped["granted"] = True
|
| 569 |
+
shared_overlay.put_field(shared_key, field_key, stamped, st=session.runtime)
|
| 570 |
+
return shares.field_oid(grant_topic, field_key)
|
| 571 |
+
|
| 572 |
+
|
| 573 |
+
def _grant_receivers(session, entries):
|
| 574 |
+
"""`{username: display name}` for everybody a grant list actually reaches.
|
| 575 |
+
|
| 576 |
+
`shares.EVERYONE` is a real audience, not a placeholder, so it expands to the tenant roster
|
| 577 |
+
`_people` already computes for the picker. Reading it from a second place would be a second
|
| 578 |
+
answer to "who is in this workspace".
|
| 579 |
+
"""
|
| 580 |
+
people = None
|
| 581 |
+
out = {}
|
| 582 |
+
for entry in shares._clean_entries(entries):
|
| 583 |
+
who = str(entry.get("user") or "").strip().lower()
|
| 584 |
+
if not who:
|
| 585 |
+
continue
|
| 586 |
+
if who == shares.EVERYONE:
|
| 587 |
+
if people is None:
|
| 588 |
+
people = _people(session.tenant)
|
| 589 |
+
for person in people:
|
| 590 |
+
out.setdefault(str(person["username"]).strip().lower(), person["name"])
|
| 591 |
+
continue
|
| 592 |
+
out.setdefault(who, who)
|
| 593 |
+
if out:
|
| 594 |
+
try:
|
| 595 |
+
reg = users.registry() or {}
|
| 596 |
+
except Exception: # noqa: BLE001
|
| 597 |
+
reg = {}
|
| 598 |
+
for uname in list(out):
|
| 599 |
+
rec = reg.get(uname)
|
| 600 |
+
if isinstance(rec, dict) and rec.get("name"):
|
| 601 |
+
out[uname] = str(rec["name"])
|
| 602 |
+
return out
|
| 603 |
+
|
| 604 |
+
|
| 605 |
+
def _admin_walled(session, grant_topic, defs, receivers):
|
| 606 |
+
"""`{field key: [display names]}` for receivers an ADMINISTRATOR has already walled off.
|
| 607 |
+
|
| 608 |
+
β THE ADMIN SOURCE ONLY. `perm_scope.entry(rec, module)['hiddenFields']` is the half of
|
| 609 |
+
`hidden_keys` a field grant cannot overrule; the other half IS the field grant, so consulting
|
| 610 |
+
the closure here would report every column this route is about to grant as hidden and refuse
|
| 611 |
+
the lot (see the block note above).
|
| 612 |
+
|
| 613 |
+
β THE MEASURE BINDING IS BORROWED, NEVER RESPELLED. An administrator ticking
|
| 614 |
+
"Metric - Gross margin" stores `measure_margin`, while the COLUMNS carrying that number are
|
| 615 |
+
keyed `measure_margin_<rand>`; `perm_scope._measure_bound_keys` is the one evaluator that
|
| 616 |
+
joins the two, and a second copy here would be the first to drift.
|
| 617 |
+
|
| 618 |
+
β AN ADMINISTRATOR RECEIVER IS NEVER WALLED β `hidden_keys` answers an empty set for one
|
| 619 |
+
before it reads anything β so the same short circuit runs here, or this function would refuse
|
| 620 |
+
a grant to somebody who can already see the column.
|
| 621 |
+
|
| 622 |
+
β A RECEIVER WITH NO REGISTRY RECORD IS SKIPPED RATHER THAN TREATED AS WALLED: `perm_scope`
|
| 623 |
+
reads a permission block off the RECORD (`_rec` answers `{}` for a bare username), so a name
|
| 624 |
+
this tenant cannot resolve carries no admin wall to find. `_entries_or_400` has already
|
| 625 |
+
refused a grant list naming an account that does not exist.
|
| 626 |
+
"""
|
| 627 |
+
import core.perm_scope as perm_scope
|
| 628 |
+
import core.perms as perms
|
| 629 |
+
try:
|
| 630 |
+
reg = users.registry() or {}
|
| 631 |
+
except Exception: # noqa: BLE001
|
| 632 |
+
reg = {}
|
| 633 |
+
field_list = [dict(defn or {}, key=key) for key, defn in defs.items()
|
| 634 |
+
if isinstance(defn, dict)]
|
| 635 |
+
walled = {}
|
| 636 |
+
for uname, display in sorted(receivers.items()):
|
| 637 |
+
rec = reg.get(uname)
|
| 638 |
+
if not isinstance(rec, dict) or perms.is_admin(rec):
|
| 639 |
+
continue
|
| 640 |
+
try:
|
| 641 |
+
entry = perm_scope.entry(rec, grant_topic) or {}
|
| 642 |
+
except Exception: # noqa: BLE001
|
| 643 |
+
continue
|
| 644 |
+
hidden = {str(k) for k in (entry.get("hiddenFields") or ()) if k}
|
| 645 |
+
if not hidden:
|
| 646 |
+
continue
|
| 647 |
+
try:
|
| 648 |
+
hidden |= set(perm_scope._measure_bound_keys(hidden, field_list))
|
| 649 |
+
except Exception: # noqa: BLE001
|
| 650 |
+
pass
|
| 651 |
+
for key in defs:
|
| 652 |
+
if key in hidden:
|
| 653 |
+
walled.setdefault(key, []).append(display)
|
| 654 |
+
return walled
|
| 655 |
+
|
| 656 |
+
|
| 657 |
+
#: β THE THREE REASONS A VIEW'S COLUMN IS NOT GRANTED, EACH ITS OWN CODE. One fused
|
| 658 |
+
#: "could not share" would make the three walls unprovable apart, which is the
|
| 659 |
+
#: [[a-declared-gate-is-an-unchecked-claim]] failure `verify_field_doors` section 8 exists to
|
| 660 |
+
#: prevent: every cause fails by its own name, or it is not gated at all.
|
| 661 |
+
#: β STANDING RULE 2 β no em dash and no en dash in any sentence below; these reach a screen.
|
| 662 |
+
FIELD_REFUSAL_CODES = ("not_a_shared_column", "not_owned", "admin_hidden")
|
| 663 |
+
|
| 664 |
+
#: β TRAP 1, SAID OUT LOUD. A column grant is keyed by DATABASE, so it is not scoped to the view
|
| 665 |
+
#: that occasioned it. The response carries this sentence rather than letting a caller infer a
|
| 666 |
+
#: narrower promise than the store actually makes.
|
| 667 |
+
FIELD_GRANT_SCOPE = ("A column shared this way is shared on the whole database, so the people "
|
| 668 |
+
"you named can see it on every view of it, not only on this one.")
|
| 669 |
+
|
| 670 |
+
|
| 671 |
+
def _refusal(key, code, names=()):
|
| 672 |
+
"""One refused column, with the sentence a person reads."""
|
| 673 |
+
if code == "not_a_shared_column":
|
| 674 |
+
why = ('"{k}" belongs to the database itself rather than to a person, so there was '
|
| 675 |
+
'nothing to grant. Anybody who can open the database already sees it.')
|
| 676 |
+
elif code == "not_owned":
|
| 677 |
+
why = ('"{k}" is somebody else\'s column, and only its owner (or an administrator) can '
|
| 678 |
+
'share it. Ask them to share it, then share this view again.')
|
| 679 |
+
else:
|
| 680 |
+
why = ('"{k}" is hidden from {who} by an administrator, so sharing it would change '
|
| 681 |
+
'nothing. Ask an administrator to unhide it first.')
|
| 682 |
+
return {"field": key, "reason": code,
|
| 683 |
+
"message": why.format(k=key, who=_named(names) if names else "them")}
|
| 684 |
+
|
| 685 |
+
|
| 686 |
+
def _classify_view_fields(keys, owned, defined, walled):
|
| 687 |
+
"""`(sharedFieldKeys, refusedFieldKeys)` for the columns a view names. PURE.
|
| 688 |
+
|
| 689 |
+
β EVERY KEY IS DECIDED BEFORE ANY OF THEM IS WRITTEN, which is the same property the ceiling
|
| 690 |
+
block above claims for the three role walls: a refusal must not be able to leave part of the
|
| 691 |
+
set promoted and part of it untouched.
|
| 692 |
+
|
| 693 |
+
β THE ORDER OF THE CAUSES IS FIXED AND IT DECIDES WHICH SENTENCE A PERSON READS. A built-in
|
| 694 |
+
column is owned by nobody, so "there was nothing to grant" has to be asked before "you do not
|
| 695 |
+
own it", or every database column in `visible` would be reported as somebody else's.
|
| 696 |
+
"""
|
| 697 |
+
granted, refused = [], []
|
| 698 |
+
for key in keys:
|
| 699 |
+
if key not in defined:
|
| 700 |
+
refused.append(_refusal(key, "not_a_shared_column"))
|
| 701 |
+
elif key not in owned:
|
| 702 |
+
refused.append(_refusal(key, "not_owned"))
|
| 703 |
+
elif walled.get(key):
|
| 704 |
+
refused.append(_refusal(key, "admin_hidden", walled.get(key)))
|
| 705 |
+
else:
|
| 706 |
+
granted.append(key)
|
| 707 |
+
return granted, refused
|
| 708 |
+
|
| 709 |
+
|
| 710 |
+
def _merge_field_entries(existing, incoming):
|
| 711 |
+
"""A column's grant list with `incoming` ADDED to it. Nobody is removed, nobody is lowered.
|
| 712 |
+
|
| 713 |
+
ββ THE SHARE PUT REPLACES, AND A COLUMN'S AUDIENCE IS NOT THE VIEW'S AUDIENCE. This route's
|
| 714 |
+
contract is a REPLACING set (`PUT ... entries` at the top of the file), which is right for the
|
| 715 |
+
object the caller is looking at and catastrophic for the columns underneath it: a column grant
|
| 716 |
+
is TOPIC-WIDE, so handing the view's list straight to `set_grants` would rewrite the column's
|
| 717 |
+
audience to whoever this view happens to be shared with. A colleague granted that column
|
| 718 |
+
through the `field` door would lose it, on every view of the database, silently, inside a 200.
|
| 719 |
+
That is exactly the harm D-474 closed at the view door, arriving one door over.
|
| 720 |
+
|
| 721 |
+
β AND A LENGTH CHECK DOES NOT SEE IT. Replacing a one-person list with a different one-person
|
| 722 |
+
list keeps the count identical, so the gate asserts the HELD USER IS STILL THERE AT THEIR OWN
|
| 723 |
+
ROLE rather than counting rows.
|
| 724 |
+
|
| 725 |
+
β RAISED, NEVER LOWERED. A receiver already held at `view` who arrives on an `edit` share is
|
| 726 |
+
raised, because only the column's owner (or an administrator) reaches this path at all and
|
| 727 |
+
that is the access they just asked to hand over. An `edit` holder meeting a `view` share keeps
|
| 728 |
+
`edit`: a share is an addition, and nothing here is a revocation.
|
| 729 |
+
|
| 730 |
+
β `by` RIDES ON EXISTING ROWS AND IS NEVER TAKEN FROM AN INCOMING ONE. Provenance decides who
|
| 731 |
+
may revoke a grant (`_unremovable`), so an incoming payload must not be able to claim it;
|
| 732 |
+
`set_grants` stamps a genuinely new row from `granter`.
|
| 733 |
+
"""
|
| 734 |
+
rank = {"view": 0, "edit": 1}
|
| 735 |
+
order, merged = [], {}
|
| 736 |
+
for row in (existing or ()):
|
| 737 |
+
if not isinstance(row, dict):
|
| 738 |
+
continue
|
| 739 |
+
who = str(row.get("user") or "").strip().lower()
|
| 740 |
+
role = str(row.get("role") or "").strip().lower()
|
| 741 |
+
if not who or role not in rank or who in merged:
|
| 742 |
+
continue
|
| 743 |
+
kept = {"user": who, "role": role}
|
| 744 |
+
stamp = str(row.get("by") or "").strip().lower()
|
| 745 |
+
if stamp:
|
| 746 |
+
kept["by"] = stamp
|
| 747 |
+
merged[who] = kept
|
| 748 |
+
order.append(who)
|
| 749 |
+
for row in (incoming or ()):
|
| 750 |
+
if not isinstance(row, dict):
|
| 751 |
+
continue
|
| 752 |
+
who = str(row.get("user") or "").strip().lower()
|
| 753 |
+
role = str(row.get("role") or "").strip().lower()
|
| 754 |
+
if not who or role not in rank:
|
| 755 |
+
continue
|
| 756 |
+
if who not in merged:
|
| 757 |
+
merged[who] = {"user": who, "role": role}
|
| 758 |
+
order.append(who)
|
| 759 |
+
elif rank[role] > rank[merged[who]["role"]]:
|
| 760 |
+
merged[who]["role"] = role
|
| 761 |
+
return [merged[who] for who in order]
|
| 762 |
+
|
| 763 |
+
|
| 764 |
+
def _share_view_fields(session, oid, entries):
|
| 765 |
+
"""The `view` arm's field half: classify every column the view names, then grant the ones
|
| 766 |
+
that survive. `(sharedFieldKeys, refusedFieldKeys)`.
|
| 767 |
+
|
| 768 |
+
β CLASSIFY EVERYTHING, THEN WRITE. `_classify_view_fields` sees the whole key set before
|
| 769 |
+
`_promote_field_for_grant` touches a single definition, so a refusal cannot leave half the
|
| 770 |
+
view's columns promoted.
|
| 771 |
+
|
| 772 |
+
β THE VIEW'S OWN GRANT HAS ALREADY BEEN WRITTEN when this runs, and that order is the safe
|
| 773 |
+
one: a `409 grants_changed` on the view must not be preceded by a set of column promotions
|
| 774 |
+
for a share that then did not happen.
|
| 775 |
+
"""
|
| 776 |
+
topic, view = _find_view_topic(session, oid)
|
| 777 |
+
if not topic or not isinstance(view, dict):
|
| 778 |
+
return [], []
|
| 779 |
+
keys = _view_field_keys(view)
|
| 780 |
+
if not keys:
|
| 781 |
+
return [], []
|
| 782 |
+
table_key = f"{topic}_table_workspace"
|
| 783 |
+
grant_topic = _field_storage_keys(table_key)[2]
|
| 784 |
+
defs, defined, owned, owners = {}, set(), set(), {}
|
| 785 |
+
for key in keys:
|
| 786 |
+
defn, already_shared = _field_definition(session, table_key, key)[:2]
|
| 787 |
+
if not isinstance(defn, dict):
|
| 788 |
+
continue
|
| 789 |
+
defs[key] = defn
|
| 790 |
+
defined.add(key)
|
| 791 |
+
# β THE COLUMN'S OWNER, NOT THIS SESSION. `set_grants`' owner is sticky, so stamping the
|
| 792 |
+
# SHARER here would hand an administrator sharing somebody else's column the ownership
|
| 793 |
+
# of it as a side effect of sharing a view. Same resolver the claim wall uses.
|
| 794 |
+
owners[key] = _field_owner(session, defn, already_shared)
|
| 795 |
+
# β ONE OWNERSHIP PREDICATE. `_owns_object` is the wall the `field` arm claims through
|
| 796 |
+
# and the DELETE door reads; a second "does this person own this column" here is how the
|
| 797 |
+
# two answers come apart. It short circuits True for an administrator, which is right:
|
| 798 |
+
# an administrator may already share any column through the `field` door.
|
| 799 |
+
if _owns_object(session, "field", shares.field_oid(grant_topic, key)):
|
| 800 |
+
owned.add(key)
|
| 801 |
+
walled = _admin_walled(session, grant_topic, defs, _grant_receivers(session, entries))
|
| 802 |
+
granted, refused = _classify_view_fields(keys, owned, defined, walled)
|
| 803 |
+
written = []
|
| 804 |
+
for key in granted:
|
| 805 |
+
field_oid = _promote_field_for_grant(session, table_key, key)
|
| 806 |
+
if not field_oid:
|
| 807 |
+
refused.append(_refusal(key, "not_a_shared_column"))
|
| 808 |
+
continue
|
| 809 |
+
# ββ ADDED TO, NEVER REPLACED. `set_grants` writes the list it is given, and this route
|
| 810 |
+
# PUTs a REPLACING set, so handing it the view's `entries` would make the view's audience
|
| 811 |
+
# the COLUMN's audience: a colleague granted this column through the `field` door would
|
| 812 |
+
# lose it, on every view of the database, inside a 200. `_merge_field_entries` says what
|
| 813 |
+
# that sentence means once, and it is the only writer of a column list on this path.
|
| 814 |
+
held = shares.grants("field", field_oid, st=session.runtime)
|
| 815 |
+
# β NO `expect` HERE, AND THAT IS NOT AN OVERSIGHT. The compare-and-set on the view's own
|
| 816 |
+
# grant guards a record TWO PEOPLE ARE EDITING through the same dialog. A column's record
|
| 817 |
+
# was just read (and possibly created) inside this call, nobody is looking at it in a
|
| 818 |
+
# dialog, and a `409` raised at this point would fail a PUT whose view grant has ALREADY
|
| 819 |
+
# been written, which is the half-applied state the refusals above exist to avoid.
|
| 820 |
+
shares.set_grants("field", field_oid,
|
| 821 |
+
_merge_field_entries(held.get("entries"), entries),
|
| 822 |
+
owner=held.get("owner") or owners.get(key) or session.uname,
|
| 823 |
+
granter=session.uname, st=session.runtime)
|
| 824 |
+
written.append(key)
|
| 825 |
+
return written, refused
|
| 826 |
+
|
| 827 |
|
| 828 |
@router.get("/share/mine")
|
| 829 |
def my_shares(session: Session = Depends(require_session)):
|
|
|
|
| 1071 |
# A field grant is a visibility and edit wall. Promote a private custom
|
| 1072 |
# field exactly once, then keep the requested Share field role as the
|
| 1073 |
# authoritative override for the legacy permissions bag.
|
| 1074 |
+
# ββ W42-T25 β THE SEQUENCE MOVED INTO `_promote_field_for_grant` AND DID NOT CHANGE.
|
| 1075 |
+
# The `view` arm below now hands columns to people as well, and one function answering
|
| 1076 |
+
# "promote, stamp, key the oid" is what keeps the two arms writing the SAME oid for the
|
| 1077 |
+
# same column. `None` here still means the column does not exist on that database.
|
| 1078 |
table_key, field_key = shares.split_field_oid(oid)
|
| 1079 |
+
promoted = _promote_field_for_grant(session, table_key, field_key)
|
| 1080 |
+
if promoted is None:
|
|
|
|
| 1081 |
raise err(404, "no_object", "no such field, or it is not shared with this account")
|
| 1082 |
+
oid = promoted
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1083 |
# ββ R4 / W40-T02 (D3) β OWNERSHIP NEVER MOVES ON A RE-SHARE, AND IT IS SAID HERE RATHER
|
| 1084 |
# THAN LEFT TO FALL OUT. `set_grants`' owner is sticky, so the old `rec["owner"] or
|
| 1085 |
# session.uname` already happened not to transfer ownership β incidentally, as a property of
|
|
|
|
| 1109 |
except shares.GrantsChanged as exc:
|
| 1110 |
raise err(409, "grants_changed", str(exc))
|
| 1111 |
_notify_new_grantees(session, kind, oid, before=rec["entries"], after=out.get("entries") or [])
|
| 1112 |
+
# ββ W42-T25 β SHARING A VIEW SHARES THE FIELDS IT NAMES. A view is a selection expressed
|
| 1113 |
+
# in columns, so a grant that carries the view and none of its columns puts a rail row on
|
| 1114 |
+
# the receiver's screen over an empty grid. The three refusals are named rather than thrown:
|
| 1115 |
+
# this PUT succeeded, the view IS shared, and what could not follow it is reported by name
|
| 1116 |
+
# with the reason. Throwing instead would make the ordinary case (a view over one built-in
|
| 1117 |
+
# column) unshareable.
|
| 1118 |
+
# β THE EXISTING KEYS ARE UNTOUCHED. `{owner, entries}` is what every current client reads
|
| 1119 |
+
# off this route; the field report is additive, and a caller that ignores it is unaffected.
|
| 1120 |
+
if kind == "view":
|
| 1121 |
+
shared_fields, refused_fields = _share_view_fields(session, oid, entries)
|
| 1122 |
+
return {**out,
|
| 1123 |
+
"sharedFieldKeys": shared_fields,
|
| 1124 |
+
"refusedFieldKeys": refused_fields,
|
| 1125 |
+
"sharedFieldScope": FIELD_GRANT_SCOPE}
|
| 1126 |
return out
|
| 1127 |
|
| 1128 |
|
api/routes_tables.py
CHANGED
|
@@ -832,7 +832,19 @@ def _ut_hidden(session, table_key, fields, st=None):
|
|
| 832 |
return perm_scope.hidden_keys(session.user, table_key, fields, st=st)
|
| 833 |
|
| 834 |
|
| 835 |
-
def
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 836 |
"""`fields` PLUS this database's TENANT-WIDE columns β the read-side merge, W38-T16.
|
| 837 |
|
| 838 |
ββ WHY THIS DID NOT EXIST AND WHY THAT WAS A HOLE. `patch_shared_cell` has written into
|
|
@@ -849,12 +861,15 @@ def _ut_shared_fields(session, table_key, fields):
|
|
| 849 |
contract, never a redefinition of a column that database already has.
|
| 850 |
"""
|
| 851 |
from core import field_permissions, shared_overlay
|
|
|
|
|
|
|
| 852 |
field_permissions.migrate_legacy_fields(
|
| 853 |
f"{table_key}_table_workspace", st=session.runtime,
|
| 854 |
-
grant_topic=table_key, shared_key=table_key
|
| 855 |
-
|
|
|
|
| 856 |
if not defs:
|
| 857 |
-
return fields
|
| 858 |
have = {f.get("key") for f in (fields or ()) if isinstance(f, dict)}
|
| 859 |
from core import shares
|
| 860 |
projected = []
|
|
@@ -868,7 +883,8 @@ def _ut_shared_fields(session, table_key, fields):
|
|
| 868 |
if role:
|
| 869 |
item["sharedRole"] = role
|
| 870 |
projected.append(item)
|
| 871 |
-
|
|
|
|
| 872 |
|
| 873 |
|
| 874 |
def _ut_shared_cells(session, table_key, pids):
|
|
@@ -1082,7 +1098,7 @@ def _usage_column_refs(field):
|
|
| 1082 |
return rollup, automation
|
| 1083 |
|
| 1084 |
|
| 1085 |
-
def _field_usage(session, table_key, fields, defn,
|
| 1086 |
"""`{field_key: {views, filters, rollups, automations, permRules}}` β C8's `usage`, computed
|
| 1087 |
over the WHOLE workspace, or `{}` when it cannot be established.
|
| 1088 |
|
|
@@ -1129,26 +1145,18 @@ def _field_usage(session, table_key, fields, defn, ops, st=None, workspace_docum
|
|
| 1129 |
if isinstance(f, dict) and f.get("key")}
|
| 1130 |
if not keys:
|
| 1131 |
return {}
|
| 1132 |
-
# Usage is delete-safety data: without a verified caller identity we cannot decide which
|
| 1133 |
-
# tenant's permission records are relevant. Refuse before any workspace read rather than
|
| 1134 |
-
# returning a misleading zero or paying a partial read that cannot produce a safe answer.
|
| 1135 |
-
if not isinstance(getattr(session, "user", None), dict):
|
| 1136 |
-
return {}
|
| 1137 |
lent = st if st is not None else session.runtime
|
| 1138 |
memo_key = (str(getattr(session, "tenant", "") or ""), str(table_key))
|
| 1139 |
-
token = _usage_token(lent,
|
| 1140 |
if token is not None:
|
| 1141 |
hit = _USAGE_MEMO.get(memo_key)
|
| 1142 |
if hit and hit[0] == token:
|
| 1143 |
return hit[1]
|
| 1144 |
try:
|
| 1145 |
-
#
|
| 1146 |
-
#
|
| 1147 |
-
#
|
| 1148 |
-
|
| 1149 |
-
# the tenant's own document.
|
| 1150 |
-
ws_doc = (workspace_document if isinstance(workspace_document, dict)
|
| 1151 |
-
else (ops.st.get(ops.table_key) or {}))
|
| 1152 |
except Exception: # noqa: BLE001
|
| 1153 |
return {}
|
| 1154 |
try:
|
|
@@ -1301,7 +1309,9 @@ def ut_assembly(session: Session, table_key: str, storage_key: str = "",
|
|
| 1301 |
# `workspace_wire` and the wall, which is `routes_odoo_tables`' own position for the same two
|
| 1302 |
# lines and for the same reason: the closure must be recomputed on the MERGED contract or a
|
| 1303 |
# formula in a shared column reaches past it.
|
| 1304 |
-
fields = _ut_shared_fields(
|
|
|
|
|
|
|
| 1305 |
# W43C C2: store compact recurrence configuration, then derive next/preview under the
|
| 1306 |
# request's server day only after every field stratum is merged.
|
| 1307 |
_recurrence_today = time.strftime("%Y-%m-%d")
|
|
@@ -1345,14 +1355,30 @@ def ut_assembly(session: Session, table_key: str, storage_key: str = "",
|
|
| 1345 |
# β A COPY OF THE BAG, because `_field_usage` MEMOISES its answer: handing the memo's own dict
|
| 1346 |
# out would let anything downstream write into the number the next request reads.
|
| 1347 |
try:
|
| 1348 |
-
|
| 1349 |
-
|
|
|
|
|
|
|
|
|
|
| 1350 |
except Exception: # noqa: BLE001
|
| 1351 |
_usage = {}
|
| 1352 |
if _usage:
|
| 1353 |
fields = [dict(f, usage=dict(_usage[f["key"]]))
|
| 1354 |
if isinstance(f, dict) and _usage.get(f.get("key")) else f
|
| 1355 |
for f in fields]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1356 |
# ββ C8's `descriptionEdited`, AND IT CLOSES A CONSUMER THAT WAS ALREADY WRITTEN.
|
| 1357 |
# W41-T11 built the producer (`user_tables.description_edited`, R19's custody mark scoped to the
|
| 1358 |
# description) and correctly stopped at its own fence, which is one core file. Measured across
|
|
@@ -1379,10 +1405,8 @@ def ut_assembly(session: Session, table_key: str, storage_key: str = "",
|
|
| 1379 |
shared_cells = _ut_shared_cells(session, table_key, pids) if with_rows else {}
|
| 1380 |
# ββ W36-T21 / R6 β the READ half, in `grid_assembly`'s own position: after `workspace_wire`,
|
| 1381 |
# so the closure covers this user's `custom_` and `measure_` columns too.
|
|
|
|
| 1382 |
fields, rows_src, hidden = _ut_field_wall(session, table_key, fields, rows_src, st=st)
|
| 1383 |
-
# The canonical Zone field is derived from the same table-scoped store as the map DTO, so
|
| 1384 |
-
# FilterBuilder and saved Views use their ordinary multiselect path rather than a map-only one.
|
| 1385 |
-
fields = _ut().with_zone_field(table_key, fields, st=st)
|
| 1386 |
if hidden and shared_cells:
|
| 1387 |
# β BOTH WIRES, AND THE SHARED STRATUM IS A THIRD ONE. `strip_row` above cleaned the
|
| 1388 |
# DEFINITION rows; these cells arrived by a different door and one narrowing cannot speak
|
|
@@ -1889,6 +1913,15 @@ def create_table(body: dict = Body(default=None),
|
|
| 1889 |
if not session.runtime.available():
|
| 1890 |
raise err(503, "store_unavailable",
|
| 1891 |
"the tenant store is unavailable. Nothing was created")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1892 |
source = body.get("source")
|
| 1893 |
try:
|
| 1894 |
key = ut.create(label, session.uname, fields=body.get("fields"),
|
|
@@ -2501,6 +2534,9 @@ def _refusal_sentence(ut, session, body, table_key="", fkey=""):
|
|
| 2501 |
# column would otherwise be explained by the flow law -- "pick a flow, or make this an
|
| 2502 |
# ordinary column" -- which is the D-46 misdirection exactly, pointing at a control the user
|
| 2503 |
# never touched.
|
|
|
|
|
|
|
|
|
|
| 2504 |
if str((body or {}).get("type") or "").strip().lower() == "ai_enrich":
|
| 2505 |
bag = (body or {}).get("aiEnrich")
|
| 2506 |
if not isinstance(bag, dict) or not str(bag.get("prompt") or "").strip():
|
|
@@ -2689,6 +2725,108 @@ def delete_field(table_key: str, fkey: str, session: Session = Depends(require_s
|
|
| 2689 |
return {"deleted": fkey}
|
| 2690 |
|
| 2691 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2692 |
@router.delete("/tables/{table_key}/rows/{rid}")
|
| 2693 |
def delete_row(table_key: str, rid: str, session: Session = Depends(require_session)):
|
| 2694 |
# ββ W31 QA β ONE SNAPSHOT FOR THE WHOLE DELETE, and the owner reported what it cost.
|
|
|
|
| 832 |
return perm_scope.hidden_keys(session.user, table_key, fields, st=st)
|
| 833 |
|
| 834 |
|
| 835 |
+
def _ut_contract_fields(table_key, fields, st=None):
|
| 836 |
+
"""The base contract every `ut_*` read door presents before its field wall.
|
| 837 |
+
|
| 838 |
+
Zone is a real derived field, not a map-only decoration: saved filters and views address its
|
| 839 |
+
canonical key. It therefore joins the contract before the one field-wall evaluator runs.
|
| 840 |
+
Keeping this boundary named prevents `/nav/schema` and the grid from attaching it on
|
| 841 |
+
opposite sides of that wall.
|
| 842 |
+
"""
|
| 843 |
+
return _ut().with_zone_field(table_key, fields, st=st)
|
| 844 |
+
|
| 845 |
+
|
| 846 |
+
def _ut_shared_fields(session, table_key, fields, workspace_document=None,
|
| 847 |
+
shared_document=None, return_document=False):
|
| 848 |
"""`fields` PLUS this database's TENANT-WIDE columns β the read-side merge, W38-T16.
|
| 849 |
|
| 850 |
ββ WHY THIS DID NOT EXIST AND WHY THAT WAS A HOLE. `patch_shared_cell` has written into
|
|
|
|
| 861 |
contract, never a redefinition of a column that database already has.
|
| 862 |
"""
|
| 863 |
from core import field_permissions, shared_overlay
|
| 864 |
+
document = (shared_document if isinstance(shared_document, dict)
|
| 865 |
+
else shared_overlay.document(table_key, st=session.runtime))
|
| 866 |
field_permissions.migrate_legacy_fields(
|
| 867 |
f"{table_key}_table_workspace", st=session.runtime,
|
| 868 |
+
grant_topic=table_key, shared_key=table_key,
|
| 869 |
+
workspace_document=workspace_document, shared_document=document)
|
| 870 |
+
defs = shared_overlay.fields(table_key, st=session.runtime, document=document) or {}
|
| 871 |
if not defs:
|
| 872 |
+
return (fields, document) if return_document else fields
|
| 873 |
have = {f.get("key") for f in (fields or ()) if isinstance(f, dict)}
|
| 874 |
from core import shares
|
| 875 |
projected = []
|
|
|
|
| 883 |
if role:
|
| 884 |
item["sharedRole"] = role
|
| 885 |
projected.append(item)
|
| 886 |
+
merged = list(fields or ()) + projected
|
| 887 |
+
return (merged, document) if return_document else merged
|
| 888 |
|
| 889 |
|
| 890 |
def _ut_shared_cells(session, table_key, pids):
|
|
|
|
| 1098 |
return rollup, automation
|
| 1099 |
|
| 1100 |
|
| 1101 |
+
def _field_usage(session, table_key, fields, defn, ws_st, ws_key, st=None):
|
| 1102 |
"""`{field_key: {views, filters, rollups, automations, permRules}}` β C8's `usage`, computed
|
| 1103 |
over the WHOLE workspace, or `{}` when it cannot be established.
|
| 1104 |
|
|
|
|
| 1145 |
if isinstance(f, dict) and f.get("key")}
|
| 1146 |
if not keys:
|
| 1147 |
return {}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1148 |
lent = st if st is not None else session.runtime
|
| 1149 |
memo_key = (str(getattr(session, "tenant", "") or ""), str(table_key))
|
| 1150 |
+
token = _usage_token(lent, ws_key)
|
| 1151 |
if token is not None:
|
| 1152 |
hit = _USAGE_MEMO.get(memo_key)
|
| 1153 |
if hit and hit[0] == token:
|
| 1154 |
return hit[1]
|
| 1155 |
try:
|
| 1156 |
+
# The caller lends either its already-captured whole workspace document or the exact store
|
| 1157 |
+
# handle plus key that produced it. Customer's document is `customer_table_workspace`,
|
| 1158 |
+
# which cannot be reconstructed from its topic name `customer_data`.
|
| 1159 |
+
ws_doc = (ws_st if isinstance(ws_st, dict) else (ws_st.get(ws_key) or {}))
|
|
|
|
|
|
|
|
|
|
| 1160 |
except Exception: # noqa: BLE001
|
| 1161 |
return {}
|
| 1162 |
try:
|
|
|
|
| 1309 |
# `workspace_wire` and the wall, which is `routes_odoo_tables`' own position for the same two
|
| 1310 |
# lines and for the same reason: the closure must be recomputed on the MERGED contract or a
|
| 1311 |
# formula in a shared column reaches past it.
|
| 1312 |
+
fields, _shared_document = _ut_shared_fields(
|
| 1313 |
+
session, table_key, fields,
|
| 1314 |
+
workspace_document=getattr(ctx, "workspace_document", None), return_document=True)
|
| 1315 |
# W43C C2: store compact recurrence configuration, then derive next/preview under the
|
| 1316 |
# request's server day only after every field stratum is merged.
|
| 1317 |
_recurrence_today = time.strftime("%Y-%m-%d")
|
|
|
|
| 1355 |
# β A COPY OF THE BAG, because `_field_usage` MEMOISES its answer: handing the memo's own dict
|
| 1356 |
# out would let anything downstream write into the number the next request reads.
|
| 1357 |
try:
|
| 1358 |
+
_usage_source = getattr(ctx, "workspace_document", None)
|
| 1359 |
+
if not isinstance(_usage_source, dict):
|
| 1360 |
+
_usage_source = ops.st
|
| 1361 |
+
_usage = _field_usage(session, table_key, fields, defn,
|
| 1362 |
+
_usage_source, ops.table_key, st=st)
|
| 1363 |
except Exception: # noqa: BLE001
|
| 1364 |
_usage = {}
|
| 1365 |
if _usage:
|
| 1366 |
fields = [dict(f, usage=dict(_usage[f["key"]]))
|
| 1367 |
if isinstance(f, dict) and _usage.get(f.get("key")) else f
|
| 1368 |
for f in fields]
|
| 1369 |
+
# C4 parity: user databases carry the same field-class badges as topic grids. The batch
|
| 1370 |
+
# producer reads the grant registry once and the shared-value stratum once for the full list.
|
| 1371 |
+
try:
|
| 1372 |
+
from core import field_permissions as _fp
|
| 1373 |
+
_classes = _fp.field_classes(
|
| 1374 |
+
fields, session.uname, table_key=table_key, grant_topic=table_key,
|
| 1375 |
+
values_shared=((_shared_document.get("fields") or {}).keys()
|
| 1376 |
+
if isinstance(_shared_document, dict) else ()), st=st)
|
| 1377 |
+
fields = [dict(f, **{"class": _classes[f["key"]]})
|
| 1378 |
+
if isinstance(f, dict) and _classes.get(f.get("key")) else f
|
| 1379 |
+
for f in fields]
|
| 1380 |
+
except Exception: # noqa: BLE001
|
| 1381 |
+
pass
|
| 1382 |
# ββ C8's `descriptionEdited`, AND IT CLOSES A CONSUMER THAT WAS ALREADY WRITTEN.
|
| 1383 |
# W41-T11 built the producer (`user_tables.description_edited`, R19's custody mark scoped to the
|
| 1384 |
# description) and correctly stopped at its own fence, which is one core file. Measured across
|
|
|
|
| 1405 |
shared_cells = _ut_shared_cells(session, table_key, pids) if with_rows else {}
|
| 1406 |
# ββ W36-T21 / R6 β the READ half, in `grid_assembly`'s own position: after `workspace_wire`,
|
| 1407 |
# so the closure covers this user's `custom_` and `measure_` columns too.
|
| 1408 |
+
fields = _ut_contract_fields(table_key, fields, st=st)
|
| 1409 |
fields, rows_src, hidden = _ut_field_wall(session, table_key, fields, rows_src, st=st)
|
|
|
|
|
|
|
|
|
|
| 1410 |
if hidden and shared_cells:
|
| 1411 |
# β BOTH WIRES, AND THE SHARED STRATUM IS A THIRD ONE. `strip_row` above cleaned the
|
| 1412 |
# DEFINITION rows; these cells arrived by a different door and one narrowing cannot speak
|
|
|
|
| 1913 |
if not session.runtime.available():
|
| 1914 |
raise err(503, "store_unavailable",
|
| 1915 |
"the tenant store is unavailable. Nothing was created")
|
| 1916 |
+
# C8b: table creation is the bulk field-definition door. `clean_fields` deliberately drops
|
| 1917 |
+
# one invalid field while preserving valid siblings, so the route must narrate an over-cap
|
| 1918 |
+
# option list before that validator runs; otherwise the whole column disappears under 201.
|
| 1919 |
+
for raw_field in (body.get("fields") or []):
|
| 1920 |
+
if not isinstance(raw_field, dict):
|
| 1921 |
+
continue
|
| 1922 |
+
option_refusal = ut.option_cap_refusal(raw_field.get("options"))
|
| 1923 |
+
if option_refusal:
|
| 1924 |
+
raise err(400, "refused", option_refusal)
|
| 1925 |
source = body.get("source")
|
| 1926 |
try:
|
| 1927 |
key = ut.create(label, session.uname, fields=body.get("fields"),
|
|
|
|
| 2534 |
# column would otherwise be explained by the flow law -- "pick a flow, or make this an
|
| 2535 |
# ordinary column" -- which is the D-46 misdirection exactly, pointing at a control the user
|
| 2536 |
# never touched.
|
| 2537 |
+
option_refusal = ut.option_cap_refusal((body or {}).get("options"))
|
| 2538 |
+
if option_refusal:
|
| 2539 |
+
return option_refusal
|
| 2540 |
if str((body or {}).get("type") or "").strip().lower() == "ai_enrich":
|
| 2541 |
bag = (body or {}).get("aiEnrich")
|
| 2542 |
if not isinstance(bag, dict) or not str(bag.get("prompt") or "").strip():
|
|
|
|
| 2725 |
return {"deleted": fkey}
|
| 2726 |
|
| 2727 |
|
| 2728 |
+
_BULK_DELETE_SENTENCES = {
|
| 2729 |
+
"unknown_field": ("that column is not on this database. It may already have been removed, "
|
| 2730 |
+
"so reload and check before trying again"),
|
| 2731 |
+
"field_hidden": "this database has no column by that name that you may remove",
|
| 2732 |
+
"last_field": ("a database must keep at least one column, so this one cannot be removed. "
|
| 2733 |
+
"Add another column first, then remove this one"),
|
| 2734 |
+
"delete_failed": "that column could not be removed. Reload the database and try again",
|
| 2735 |
+
}
|
| 2736 |
+
|
| 2737 |
+
|
| 2738 |
+
def _bulk_delete_refusal(key, code):
|
| 2739 |
+
return {"key": key, "status": "refused", "code": code,
|
| 2740 |
+
"reason": _BULK_DELETE_SENTENCES.get(code, _BULK_DELETE_SENTENCES["delete_failed"])}
|
| 2741 |
+
|
| 2742 |
+
|
| 2743 |
+
def _contract_holds_field(ut, table_key, fkey, st):
|
| 2744 |
+
fields = (ut.get(table_key, st=st) or {}).get("fields") or []
|
| 2745 |
+
return any(isinstance(field, dict) and str(field.get("key")) == str(fkey)
|
| 2746 |
+
for field in fields)
|
| 2747 |
+
|
| 2748 |
+
|
| 2749 |
+
@router.post("/tables/{table_key}/fields/delete")
|
| 2750 |
+
@router.delete("/tables/{table_key}/fields")
|
| 2751 |
+
def delete_fields(table_key: str, body: dict = Body(default=None),
|
| 2752 |
+
session: Session = Depends(require_session)):
|
| 2753 |
+
"""Delete N schema fields once and return one explicit verdict for every requested key."""
|
| 2754 |
+
# Preserve W44's managed-database lifecycle wall on the plural door too.
|
| 2755 |
+
_managed_or_refuse(session, table_key, mutation=True)
|
| 2756 |
+
defn = _defn_or_refuse(session, table_key, scope_applied=True)
|
| 2757 |
+
ut = _ut()
|
| 2758 |
+
if not ut.is_user_table(table_key, st=session.runtime):
|
| 2759 |
+
raise err(400, "not_a_user_table",
|
| 2760 |
+
"only a user-created database has an editable schema. A connected source "
|
| 2761 |
+
"owns its own columns")
|
| 2762 |
+
raw = (body or {}).get("keys")
|
| 2763 |
+
if not isinstance(raw, list):
|
| 2764 |
+
raise err(400, "bad_keys", "send `keys`, the list of columns to remove")
|
| 2765 |
+
ordered = []
|
| 2766 |
+
for candidate in raw:
|
| 2767 |
+
key = str(candidate or "").strip()
|
| 2768 |
+
if key and key not in ordered:
|
| 2769 |
+
ordered.append(key)
|
| 2770 |
+
if not ordered:
|
| 2771 |
+
raise err(400, "bad_keys", "name at least one column to remove")
|
| 2772 |
+
|
| 2773 |
+
from core import field_permissions, shared_overlay
|
| 2774 |
+
declared = [field for field in (defn.get("fields") or []) if isinstance(field, dict)]
|
| 2775 |
+
contract_keys = {str(field.get("key")) for field in declared}
|
| 2776 |
+
hidden = _ut_hidden(session, table_key, declared)
|
| 2777 |
+
bucket_read = True
|
| 2778 |
+
try:
|
| 2779 |
+
shared_defs = shared_overlay.fields(table_key, st=session.runtime) or {}
|
| 2780 |
+
except Exception: # noqa: BLE001
|
| 2781 |
+
shared_defs, bucket_read = {}, False
|
| 2782 |
+
|
| 2783 |
+
results = []
|
| 2784 |
+
landed = []
|
| 2785 |
+
for key in ordered:
|
| 2786 |
+
field = next((item for item in declared if str(item.get("key")) == key), None)
|
| 2787 |
+
if field is None and isinstance(shared_defs.get(key), dict):
|
| 2788 |
+
field = shared_defs[key]
|
| 2789 |
+
if field is None:
|
| 2790 |
+
results.append(_bulk_delete_refusal(
|
| 2791 |
+
key, "unknown_field" if bucket_read else "delete_failed"))
|
| 2792 |
+
continue
|
| 2793 |
+
if key in hidden:
|
| 2794 |
+
results.append(_bulk_delete_refusal(key, "field_hidden"))
|
| 2795 |
+
continue
|
| 2796 |
+
refusal = ut.delete_field_refusal(
|
| 2797 |
+
table_key, key, session.uname, session.admin, session.runtime,
|
| 2798 |
+
field=field, grant_topic=table_key)
|
| 2799 |
+
if refusal is not None:
|
| 2800 |
+
results.append({"key": key, "status": "refused", "code": refusal,
|
| 2801 |
+
"reason": _delete_field_sentence(
|
| 2802 |
+
refusal, str(field.get("createdBy") or ""))})
|
| 2803 |
+
continue
|
| 2804 |
+
try:
|
| 2805 |
+
dropped = False
|
| 2806 |
+
if key in contract_keys:
|
| 2807 |
+
dropped = bool(ut.delete_field(table_key, key, st=session.runtime))
|
| 2808 |
+
if not dropped and _contract_holds_field(ut, table_key, key, session.runtime):
|
| 2809 |
+
results.append(_bulk_delete_refusal(key, "last_field"))
|
| 2810 |
+
continue
|
| 2811 |
+
removed = field_permissions.delete_field_everywhere(
|
| 2812 |
+
f"{table_key}_table_workspace", table_key, table_key, key,
|
| 2813 |
+
st=session.runtime)
|
| 2814 |
+
except Exception: # noqa: BLE001
|
| 2815 |
+
results.append(_bulk_delete_refusal(key, "delete_failed"))
|
| 2816 |
+
continue
|
| 2817 |
+
if not (dropped or removed.get("shared") or removed.get("personal")):
|
| 2818 |
+
results.append(_bulk_delete_refusal(key, "delete_failed"))
|
| 2819 |
+
continue
|
| 2820 |
+
landed.append(key)
|
| 2821 |
+
results.append({"key": key, "status": "deleted", "contract": dropped,
|
| 2822 |
+
"removed": removed})
|
| 2823 |
+
|
| 2824 |
+
if landed:
|
| 2825 |
+
_refresh_relations(session)
|
| 2826 |
+
return {"ok": True, "rerender": True, "results": results, "deleted": landed,
|
| 2827 |
+
"refused": [item["key"] for item in results if item["status"] == "refused"]}
|
| 2828 |
+
|
| 2829 |
+
|
| 2830 |
@router.delete("/tables/{table_key}/rows/{rid}")
|
| 2831 |
def delete_row(table_key: str, rid: str, session: Session = Depends(require_session)):
|
| 2832 |
# ββ W31 QA β ONE SNAPSHOT FOR THE WHOLE DELETE, and the owner reported what it cost.
|
platform/aios_grid.py
CHANGED
|
@@ -211,7 +211,9 @@ def _clean_code(raw):
|
|
| 211 |
#: Emitted with the cohort column's read-only mechanism β `source: 'odoo'` + `derived` β so
|
| 212 |
#: the client never offers an editor and the host never accepts a cell write for them.
|
| 213 |
READONLY_CUSTOM_TYPES = {"created_time", "formula"}
|
| 214 |
-
|
|
|
|
|
|
|
| 215 |
MAX_FORMULA_LEN = 500
|
| 216 |
#: `rating` bounds. Airtable caps at 10; below 2 a rating is a checkbox.
|
| 217 |
RATING_MAX_DEFAULT, RATING_MAX_MIN, RATING_MAX_MAX = 5, 2, 10
|
|
@@ -226,12 +228,25 @@ MEASURE_FIELD_PREFIX = "measure_"
|
|
| 226 |
MEASURE_FIELD_TYPES = {"currency", "int", "pct"}
|
| 227 |
|
| 228 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 229 |
def _clean_options(raw):
|
| 230 |
"""Choices for a `select`: strings, trimmed, de-duplicated case-insensitively, capped.
|
| 231 |
Mirrors types.ts parseOptions β a choice list that means one thing in the picker and
|
| 232 |
another in the filter dropdown is a column with two vocabularies."""
|
| 233 |
out, seen = [], set()
|
| 234 |
-
for v in list(raw or [])
|
| 235 |
if not isinstance(v, (str, int, float)) or isinstance(v, bool):
|
| 236 |
continue
|
| 237 |
s = str(v).strip()[:120]
|
|
@@ -239,7 +254,9 @@ def _clean_options(raw):
|
|
| 239 |
continue
|
| 240 |
seen.add(s.lower())
|
| 241 |
out.append(s)
|
| 242 |
-
|
|
|
|
|
|
|
| 243 |
|
| 244 |
|
| 245 |
def merge_choice_options(*sources):
|
|
@@ -440,19 +457,71 @@ def _clean_permissions(raw):
|
|
| 440 |
#: drift risk this file's docstring names. The charset says which characters may appear; the
|
| 441 |
#: engine says what they mean. `_quotes_balanced` below is the one structural rule the quote
|
| 442 |
#: character brings with it.
|
| 443 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 444 |
_FORMULA_REF = re.compile(r"\{([^{}]*)\}")
|
| 445 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 446 |
|
| 447 |
def _quotes_balanced(s):
|
| 448 |
-
"""
|
| 449 |
|
| 450 |
-
|
| 451 |
-
|
| 452 |
-
|
| 453 |
-
business, exactly as with parentheses.
|
| 454 |
"""
|
| 455 |
-
return
|
| 456 |
|
| 457 |
|
| 458 |
#: Wave-18 C5-AUTOFIELD. `kind` is a whitelist because an unknown kind would be a column that
|
|
@@ -537,6 +606,19 @@ def _clean_formula(raw, valid_keys=None):
|
|
| 537 |
return None
|
| 538 |
if not _quotes_balanced(s):
|
| 539 |
return None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 540 |
refs = _FORMULA_REF.findall(s)
|
| 541 |
leftover = _FORMULA_REF.sub("", s)
|
| 542 |
if "{" in leftover or "}" in leftover: # unbalanced / nested braces
|
|
|
|
| 211 |
#: Emitted with the cohort column's read-only mechanism β `source: 'odoo'` + `derived` β so
|
| 212 |
#: the client never offers an editor and the host never accepts a cell write for them.
|
| 213 |
READONLY_CUSTOM_TYPES = {"created_time", "formula"}
|
| 214 |
+
# Mirrored server persistence ceiling. ``core.route_system.MAX_OPTIONS`` owns what is published
|
| 215 |
+
# to clients; the focused contract gate keeps this import-free helper equal to that value.
|
| 216 |
+
MAX_FIELD_OPTIONS = 200
|
| 217 |
MAX_FORMULA_LEN = 500
|
| 218 |
#: `rating` bounds. Airtable caps at 10; below 2 a rating is a checkbox.
|
| 219 |
RATING_MAX_DEFAULT, RATING_MAX_MIN, RATING_MAX_MAX = 5, 2, 10
|
|
|
|
| 228 |
MEASURE_FIELD_TYPES = {"currency", "int", "pct"}
|
| 229 |
|
| 230 |
|
| 231 |
+
class OptionLimitExceeded(ValueError):
|
| 232 |
+
"""A choice vocabulary cannot be represented without discarding entered values."""
|
| 233 |
+
|
| 234 |
+
def __init__(self, entered):
|
| 235 |
+
self.entered = int(entered)
|
| 236 |
+
self.limit = MAX_FIELD_OPTIONS
|
| 237 |
+
self.rejected = max(0, self.entered - self.limit)
|
| 238 |
+
super().__init__(
|
| 239 |
+
f"This list has {self.entered} choices; the server limit is {self.limit}, so "
|
| 240 |
+
f"{self.rejected} would be rejected. Remove {self.rejected} choices, then save."
|
| 241 |
+
)
|
| 242 |
+
|
| 243 |
+
|
| 244 |
def _clean_options(raw):
|
| 245 |
"""Choices for a `select`: strings, trimmed, de-duplicated case-insensitively, capped.
|
| 246 |
Mirrors types.ts parseOptions β a choice list that means one thing in the picker and
|
| 247 |
another in the filter dropdown is a column with two vocabularies."""
|
| 248 |
out, seen = [], set()
|
| 249 |
+
for v in list(raw or []):
|
| 250 |
if not isinstance(v, (str, int, float)) or isinstance(v, bool):
|
| 251 |
continue
|
| 252 |
s = str(v).strip()[:120]
|
|
|
|
| 254 |
continue
|
| 255 |
seen.add(s.lower())
|
| 256 |
out.append(s)
|
| 257 |
+
if len(out) > MAX_FIELD_OPTIONS:
|
| 258 |
+
raise OptionLimitExceeded(len(out))
|
| 259 |
+
return out
|
| 260 |
|
| 261 |
|
| 262 |
def merge_choice_options(*sources):
|
|
|
|
| 457 |
#: drift risk this file's docstring names. The charset says which characters may appear; the
|
| 458 |
#: engine says what they mean. `_quotes_balanced` below is the one structural rule the quote
|
| 459 |
#: character brings with it.
|
| 460 |
+
#: WAVE 42 G7 (2026-08-25) -- THE SAME SCAR, WIDENED IN THE SAME CHANGE THIS TIME.
|
| 461 |
+
#:
|
| 462 |
+
#: The client engine gained REGEX_EXTRACT, REGEX_REPLACE, SUBSTITUTE, FIND, SWITCH, DATEADD,
|
| 463 |
+
#: DATETIME_DIFF and DATETIME_FORMAT. Each added character below is admitted because a token
|
| 464 |
+
#: the client's tokenizer parses would otherwise die here:
|
| 465 |
+
#:
|
| 466 |
+
#: ' a SINGLE-QUOTED literal. Airtable documents units and date formats that way.
|
| 467 |
+
#: [ ] a regex character class, the commonest construct there is: "[0-9]+".
|
| 468 |
+
#: | ? \\ : regex alternation, optional/non-capturing groups, and escapes.
|
| 469 |
+
#: @ SUBSTITUTE/FIND over an email or URL.
|
| 470 |
+
#: # $ % TEXT number formats already accepted by the client; `$` is also a regex anchor.
|
| 471 |
+
#:
|
| 472 |
+
#: `;` stays refused: no legal formula token needs a statement separator.
|
| 473 |
+
_FORMULA_CHARS = re.compile(r"^[\w\s{}()+\-*/.,<>=!^&\"'\[\]|?:\\#$%@]*$")
|
| 474 |
_FORMULA_REF = re.compile(r"\{([^{}]*)\}")
|
| 475 |
|
| 476 |
+
#: Longest single regex-pattern literal. The client independently caps both pattern and subject.
|
| 477 |
+
MAX_FORMULA_LITERAL_LEN = 200
|
| 478 |
+
|
| 479 |
+
#: Catastrophic-backtracking shape, applied to STRING LITERALS only. Applying this to the whole
|
| 480 |
+
#: source would also match ordinary arithmetic such as `({a} + {b}) * 2`.
|
| 481 |
+
_NESTED_QUANT = re.compile(r"\((?:[^()\\]|\\.)*[*+](?:[^()\\]|\\.)*\)\??\s*[*+]")
|
| 482 |
+
|
| 483 |
+
|
| 484 |
+
def _string_literals(s):
|
| 485 |
+
"""Return literal bodies, or None for an unterminated quote.
|
| 486 |
+
|
| 487 |
+
This mirrors the client tokenizer's structural rule: single and double quoted strings are
|
| 488 |
+
equivalent, a doubled opening quote escapes itself, and the other quote kind is ordinary
|
| 489 |
+
text. It assigns no formula meaning; it only locates literal boundaries.
|
| 490 |
+
"""
|
| 491 |
+
out = []
|
| 492 |
+
i = 0
|
| 493 |
+
n = len(s)
|
| 494 |
+
while i < n:
|
| 495 |
+
quote = s[i]
|
| 496 |
+
if quote not in ('"', "'"):
|
| 497 |
+
i += 1
|
| 498 |
+
continue
|
| 499 |
+
j = i + 1
|
| 500 |
+
body = []
|
| 501 |
+
while True:
|
| 502 |
+
if j >= n:
|
| 503 |
+
return None
|
| 504 |
+
if s[j] == quote:
|
| 505 |
+
if j + 1 < n and s[j + 1] == quote:
|
| 506 |
+
body.append(quote)
|
| 507 |
+
j += 2
|
| 508 |
+
continue
|
| 509 |
+
break
|
| 510 |
+
body.append(s[j])
|
| 511 |
+
j += 1
|
| 512 |
+
out.append("".join(body))
|
| 513 |
+
i = j + 1
|
| 514 |
+
return out
|
| 515 |
+
|
| 516 |
|
| 517 |
def _quotes_balanced(s):
|
| 518 |
+
"""Whether every single- or double-quoted literal is structurally closed.
|
| 519 |
|
| 520 |
+
A parity count is not sound now that both spellings are legal: the double quote inside
|
| 521 |
+
``'5" pipe'`` is ordinary text, not an opener. The shared scanner answers exactly the same
|
| 522 |
+
boundary question as the client tokenizer without assigning meaning to the literal.
|
|
|
|
| 523 |
"""
|
| 524 |
+
return _string_literals(s) is not None
|
| 525 |
|
| 526 |
|
| 527 |
#: Wave-18 C5-AUTOFIELD. `kind` is a whitelist because an unknown kind would be a column that
|
|
|
|
| 606 |
return None
|
| 607 |
if not _quotes_balanced(s):
|
| 608 |
return None
|
| 609 |
+
# Regex patterns are user input reaching JavaScript's regex engine. The client owns the
|
| 610 |
+
# load-bearing runtime bounds (pattern AND subject); this structural wall rejects an obvious
|
| 611 |
+
# unsafe literal before it is stored. Run it on read too: literal shape is intrinsic and
|
| 612 |
+
# cannot become invalid merely because the table's field set later changes.
|
| 613 |
+
literals = _string_literals(s)
|
| 614 |
+
if literals is None:
|
| 615 |
+
return None
|
| 616 |
+
regexy = 'REGEX_' in s.upper()
|
| 617 |
+
for literal in literals:
|
| 618 |
+
if regexy and len(literal) > MAX_FORMULA_LITERAL_LEN:
|
| 619 |
+
return None
|
| 620 |
+
if _NESTED_QUANT.search(literal):
|
| 621 |
+
return None
|
| 622 |
refs = _FORMULA_REF.findall(s)
|
| 623 |
leftover = _FORMULA_REF.sub("", s)
|
| 624 |
if "{" in leftover or "}" in leftover: # unbalanced / nested braces
|
platform/aios_grid_fields.json
CHANGED
|
@@ -1,5 +1,6 @@
|
|
| 1 |
{
|
| 2 |
"_comment": "CANONICAL field contract for the AIOS Airtable-style grid β the SINGLE source of truth. Consumed by platform/aios_grid.py (embed/Space host) and aios-web/api/main.py (standalone API), and regenerated into aios-web/web/public/sample_customers.json. Edit HERE only, then run aios-web/verify_fields_contract.py. source=odoo is READ-ONLY; source=overlay is the editable stratum (notes/tags) outside Odoo. type in {text,status,select,multiselect,currency,int,date,pct,url} (select = a fixed-choice READ-ONLY brand attribute; dba is the first, wave 2026-08-02. multiselect = one cell holding a comma-joined SET, so a choice list offers the MEMBERS, not the joined string; customer tags and product supplier are the first, wave 40 W40-T06. url = a link cell, GridCellKind.Uri, drawn by cells.ts and opened by CustomerGrid's scheme-guarded click path; maps_url is the first, wave 40 W40-T08). W40-T08 also adds created_on, the uniform records-created DATE column every database carries (owner I24). It is a plain date field and NOT the created_time TYPE on purpose: created_time renders the row-level _created datum and its value never lives at the field's own key, so it is invisible to the semantic topic, to a stored-cell read and to any host-side export, while a date field is an ordinary cell that all three can see. The _created datum still rides every row for a created_time column a user creates. `description` (wave 5) is the CANONICAL per-field description β every field must carry one, and since wave 7 (owner W8, 2026-07-28) every description is ONE SHORT PLAIN sentence (two only when a fact would otherwise mislead): what the field IS, nothing else β no filter tips, no '(none)' coaching, no rationale; the user's workspace NOTE overrides it in the (i) hover, never in this file. BUILDER FACT (documented here, deliberately NOT in user-facing text): blank connector attributes display as '(none)' (they are no longer all `text`: W40-T06 retyped eight of them to `select` and `tags` to `multiselect`, and the sentinel is a real member of every one of those vocabularies), so `is '(none)'` β not `is empty` β finds the blanks on agent/city/state/country/zip/payment_terms/pricelist/tags. filterable:false = the CONDITION BUILDER does not offer it (still displayed, still sortable); every such field must have a replacement declared in aios-web/verify_fields_contract.py. 2026-07-27 partner attributes: country/zip/payment_terms/pricelist/tags/customer_since all ship default:false. zip is TEXT because a postal code has leading zeros. Odoo's credit_limit (1% populated) and user_id salesperson (2%) are deliberately ABSENT; agent_ids is the salesperson field and AR is where credit exposure comes from. Wave-5 item 8 (2026-07-27): ltm_rev and at_risk are DELETED β LTM's replacement is a creatable Sales measure column (the demo column IS Sales Β· the last 12 months), at_risk's replacement is a formula field, e.g. MAX(0, {revenue_ly} - {revenue_ytd}). Wave-6 item 8 (2026-07-27, the no-buildable-presets rule): revenue_ytd, revenue_ly, orders_24m, aov and yoy_pct are DELETED β every one is self-buildable, so a frozen pre-set beside the builder was two ways to ask one question. Replacements (recorded in verify_fields_contract.py): creatable measure columns for Sales / Orders / Avg order $ over any period (harness/measure_filter.py ADMITTED carries revenue, orders and the composite aov), and a formula over two measure columns for YoY, e.g. ({sales_ytd} - {sales_ly}) / {sales_ly}. Stale view colIds naming the five self-heal on the next autosave (the established rule).",
|
|
|
|
| 3 |
"fields": [
|
| 4 |
{
|
| 5 |
"key": "customer",
|
|
@@ -113,6 +114,7 @@
|
|
| 113 |
"label": "Google Maps",
|
| 114 |
"type": "url",
|
| 115 |
"source": "odoo",
|
|
|
|
| 116 |
"default": true,
|
| 117 |
"description": "A Google Maps link to this customer's address."
|
| 118 |
},
|
|
|
|
| 1 |
{
|
| 2 |
"_comment": "CANONICAL field contract for the AIOS Airtable-style grid β the SINGLE source of truth. Consumed by platform/aios_grid.py (embed/Space host) and aios-web/api/main.py (standalone API), and regenerated into aios-web/web/public/sample_customers.json. Edit HERE only, then run aios-web/verify_fields_contract.py. source=odoo is READ-ONLY; source=overlay is the editable stratum (notes/tags) outside Odoo. type in {text,status,select,multiselect,currency,int,date,pct,url} (select = a fixed-choice READ-ONLY brand attribute; dba is the first, wave 2026-08-02. multiselect = one cell holding a comma-joined SET, so a choice list offers the MEMBERS, not the joined string; customer tags and product supplier are the first, wave 40 W40-T06. url = a link cell, GridCellKind.Uri, drawn by cells.ts and opened by CustomerGrid's scheme-guarded click path; maps_url is the first, wave 40 W40-T08). W40-T08 also adds created_on, the uniform records-created DATE column every database carries (owner I24). It is a plain date field and NOT the created_time TYPE on purpose: created_time renders the row-level _created datum and its value never lives at the field's own key, so it is invisible to the semantic topic, to a stored-cell read and to any host-side export, while a date field is an ordinary cell that all three can see. The _created datum still rides every row for a created_time column a user creates. `description` (wave 5) is the CANONICAL per-field description β every field must carry one, and since wave 7 (owner W8, 2026-07-28) every description is ONE SHORT PLAIN sentence (two only when a fact would otherwise mislead): what the field IS, nothing else β no filter tips, no '(none)' coaching, no rationale; the user's workspace NOTE overrides it in the (i) hover, never in this file. BUILDER FACT (documented here, deliberately NOT in user-facing text): blank connector attributes display as '(none)' (they are no longer all `text`: W40-T06 retyped eight of them to `select` and `tags` to `multiselect`, and the sentinel is a real member of every one of those vocabularies), so `is '(none)'` β not `is empty` β finds the blanks on agent/city/state/country/zip/payment_terms/pricelist/tags. filterable:false = the CONDITION BUILDER does not offer it (still displayed, still sortable); every such field must have a replacement declared in aios-web/verify_fields_contract.py. 2026-07-27 partner attributes: country/zip/payment_terms/pricelist/tags/customer_since all ship default:false. zip is TEXT because a postal code has leading zeros. Odoo's credit_limit (1% populated) and user_id salesperson (2%) are deliberately ABSENT; agent_ids is the salesperson field and AR is where credit exposure comes from. Wave-5 item 8 (2026-07-27): ltm_rev and at_risk are DELETED β LTM's replacement is a creatable Sales measure column (the demo column IS Sales Β· the last 12 months), at_risk's replacement is a formula field, e.g. MAX(0, {revenue_ly} - {revenue_ytd}). Wave-6 item 8 (2026-07-27, the no-buildable-presets rule): revenue_ytd, revenue_ly, orders_24m, aov and yoy_pct are DELETED β every one is self-buildable, so a frozen pre-set beside the builder was two ways to ask one question. Replacements (recorded in verify_fields_contract.py): creatable measure columns for Sales / Orders / Avg order $ over any period (harness/measure_filter.py ADMITTED carries revenue, orders and the composite aov), and a formula over two measure columns for YoY, e.g. ({sales_ytd} - {sales_ly}) / {sales_ly}. Stale view colIds naming the five self-heal on the next autosave (the established rule).",
|
| 3 |
+
"_valueOverride": "A source field remains immutable unless its exact contract carries valueOverride=overlay; maps_url is the only admitted source-backed override.",
|
| 4 |
"fields": [
|
| 5 |
{
|
| 6 |
"key": "customer",
|
|
|
|
| 114 |
"label": "Google Maps",
|
| 115 |
"type": "url",
|
| 116 |
"source": "odoo",
|
| 117 |
+
"valueOverride": "overlay",
|
| 118 |
"default": true,
|
| 119 |
"description": "A Google Maps link to this customer's address."
|
| 120 |
},
|
platform/core/field_permissions.py
CHANGED
|
@@ -26,6 +26,26 @@ FIELD_ORIGINS = ("preset", "user")
|
|
| 26 |
FIELD_AUDIENCES = ("private", "users", "everyone")
|
| 27 |
FIELD_VALUE_STRATA = ("shared", "personal")
|
| 28 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 29 |
#: `permissions_from_grants`' edit vocabulary -> C1's audience vocabulary. The two answer the SAME
|
| 30 |
#: question in different words (who can reach this column), so this map is the whole of the
|
| 31 |
#: translation and there is no second derivation to drift from it
|
|
@@ -200,6 +220,82 @@ def field_origin(field):
|
|
| 200 |
return "preset"
|
| 201 |
|
| 202 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 203 |
def _shared_value_keys(table_key, st=None):
|
| 204 |
"""The columns of `table_key` whose VALUES are one tenant-wide stratum."""
|
| 205 |
key = str(table_key or "").strip()
|
|
@@ -272,12 +368,24 @@ def grant_records(grant_topic, st=None):
|
|
| 272 |
|
| 273 |
|
| 274 |
def field_class(field, viewer, grants=None, *, table_key=None, grant_topic=None,
|
| 275 |
-
values_shared=None, st=None):
|
| 276 |
"""ββ W41-T01 / R5 / CONTRACT C1 β **THE ONE PRODUCER OF A FIELD'S THREE BADGES.**
|
| 277 |
|
| 278 |
-
Returns `{origin, audience, sharedBy, values, owner}` and nothing else derives a badge
|
| 279 |
-
independently. The
|
| 280 |
-
`class`, its members are `origin`, `audience`, `sharedBy`, `values`, `owner`.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 281 |
|
| 282 |
`viewer` is a USERNAME STRING (`session.uname`), never a user dict β a dict compares unequal to
|
| 283 |
every stored name, which would make `sharedBy` silently never match and `owner` never equal the
|
|
@@ -326,6 +434,19 @@ def field_class(field, viewer, grants=None, *, table_key=None, grant_topic=None,
|
|
| 326 |
contract-declared one), else `personal`. This is R5's new information and it is INDEPENDENT of
|
| 327 |
audience: a route column is `private` with `shared` values, Supplier is `everyone` with `shared`
|
| 328 |
values, and a column you made is `private` with `personal` ones.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 329 |
β `values_shared` IS LENT BY THE CALLER because the key set is a MODULE-level fact
|
| 330 |
(`product_data.SHARED_KEYS()`), and `core` never imports up. Absent, it is derived from
|
| 331 |
`shared_overlay.fields(table_key)`, which is right for an overlay topic and blind to a
|
|
@@ -342,8 +463,45 @@ def field_class(field, viewer, grants=None, *, table_key=None, grant_topic=None,
|
|
| 342 |
me = _uname(viewer)
|
| 343 |
|
| 344 |
origin = field_origin(field)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 345 |
record = grants if isinstance(grants, dict) else _grant_record(
|
| 346 |
key, table_key=table_key, grant_topic=grant_topic, st=st)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 347 |
owner = _uname(record.get("owner")) or None
|
| 348 |
entries = [e for e in (record.get("entries") or ()) if isinstance(e, dict)]
|
| 349 |
|
|
@@ -354,10 +512,19 @@ def field_class(field, viewer, grants=None, *, table_key=None, grant_topic=None,
|
|
| 354 |
if _governed(field):
|
| 355 |
audience = _AUDIENCE_FROM_EDIT.get(
|
| 356 |
permissions_from_grants(entries).get("edit"), "private")
|
| 357 |
-
elif values == "shared" or origin == "preset":
|
| 358 |
# Ungoverned AND tenant-wide: the database's holders all hold this column. `origin` covers
|
| 359 |
# a contract-declared column whose VALUES are per-user (a canonical Odoo column); the
|
| 360 |
# `values` leg covers a shared-stratum column the contract never named.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 361 |
audience = "everyone"
|
| 362 |
else:
|
| 363 |
audience = "private"
|
|
@@ -372,13 +539,30 @@ def field_class(field, viewer, grants=None, *, table_key=None, grant_topic=None,
|
|
| 372 |
if shared_by == me:
|
| 373 |
shared_by = None
|
| 374 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 375 |
return {"origin": origin, "audience": audience, "sharedBy": shared_by,
|
| 376 |
-
"values": values, "owner": owner or _uname(field.get("createdBy")) or None
|
|
|
|
| 377 |
|
| 378 |
|
| 379 |
def field_classes(fields, viewer, *, table_key=None, grant_topic=None, values_shared=None,
|
| 380 |
-
st=None):
|
| 381 |
-
"""`{field_key: <C1 bag>}` for a whole field list, on ONE registry read. See `grant_records`.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 382 |
|
| 383 |
β EVERY COLUMN GETS A BAG, INCLUDING ONE THE REGISTRY HAS NEVER HEARD OF: the missing record is
|
| 384 |
substituted explicitly rather than left to `field_class` to re-read, which is what keeps the
|
|
@@ -389,6 +573,7 @@ def field_classes(fields, viewer, *, table_key=None, grant_topic=None, values_sh
|
|
| 389 |
if values_shared is None:
|
| 390 |
values_shared = _shared_value_keys(table_key, st=st)
|
| 391 |
shared_keys = {str(k) for k in (values_shared or ())}
|
|
|
|
| 392 |
out = {}
|
| 393 |
for field in (fields or ()):
|
| 394 |
if not isinstance(field, dict):
|
|
@@ -398,7 +583,7 @@ def field_classes(fields, viewer, *, table_key=None, grant_topic=None, values_sh
|
|
| 398 |
continue
|
| 399 |
out[key] = field_class(field, viewer, grants=records.get(key) or _empty_record(),
|
| 400 |
table_key=table_key, grant_topic=topic,
|
| 401 |
-
values_shared=shared_keys, st=st)
|
| 402 |
return out
|
| 403 |
|
| 404 |
|
|
@@ -416,7 +601,7 @@ def _same_classification(left, right):
|
|
| 416 |
return set(left.get("users") or ()) == set(right.get("users") or ())
|
| 417 |
|
| 418 |
|
| 419 |
-
def reconcile_shared_permissions(shared_key, grant_topic, st=None):
|
| 420 |
"""Re-derive every SHARED definition's `permissions` bag from the grant registry. Returns the
|
| 421 |
number of definitions actually rewritten.
|
| 422 |
|
|
@@ -463,7 +648,8 @@ def reconcile_shared_permissions(shared_key, grant_topic, st=None):
|
|
| 463 |
if not bucket or st is None:
|
| 464 |
return 0
|
| 465 |
rewritten = 0
|
| 466 |
-
for field_key, defn in list(shared_overlay.fields(
|
|
|
|
| 467 |
# β EACH DEFINITION IS GUARDED ON ITS OWN. `shares.field_oid` RAISES on an empty key, and
|
| 468 |
# the caller wraps this whole function in one swallowing except β so a single malformed
|
| 469 |
# entry would otherwise skip every REMAINING column, including the one the owner reported,
|
|
@@ -494,6 +680,8 @@ def reconcile_shared_permissions(shared_key, grant_topic, st=None):
|
|
| 494 |
updated = dict(defn)
|
| 495 |
updated["permissions"] = derived
|
| 496 |
shared_overlay.put_field(bucket, key, updated, st=st)
|
|
|
|
|
|
|
| 497 |
rewritten += 1
|
| 498 |
except Exception:
|
| 499 |
continue
|
|
@@ -648,12 +836,14 @@ def _field_is_migratable(field):
|
|
| 648 |
and field.get("source") == "overlay")
|
| 649 |
|
| 650 |
|
| 651 |
-
def migrate_legacy_fields(table_key, st=None, known_users=None, grant_topic=None, shared_key=None
|
|
|
|
| 652 |
"""Promote legacy shared-looking custom fields into the shared field stratum.
|
| 653 |
|
| 654 |
The operation is intentionally idempotent and copy-before-remove. A failed request can
|
| 655 |
therefore leave a private shadow behind, but it cannot lose the creator's values. The next
|
| 656 |
-
read retries the promotion and the shared definition wins.
|
|
|
|
| 657 |
"""
|
| 658 |
key = str(table_key or "").strip()
|
| 659 |
grant_key = str(grant_topic or key).strip()
|
|
@@ -679,14 +869,25 @@ def migrate_legacy_fields(table_key, st=None, known_users=None, grant_topic=None
|
|
| 679 |
# finds no grant record, the "no record" arm fires for every column, and the reconcile
|
| 680 |
# silently does nothing at all.
|
| 681 |
try:
|
| 682 |
-
reclassified = reconcile_shared_permissions(
|
|
|
|
| 683 |
except Exception:
|
| 684 |
reclassified = 0
|
| 685 |
-
|
| 686 |
-
|
| 687 |
-
|
| 688 |
-
|
| 689 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 690 |
if not isinstance(document, dict):
|
| 691 |
return {"promoted": 0, "normalized": 0, "reclassified": reclassified,
|
| 692 |
"suppressed": 0, "purged": 0}
|
|
@@ -730,7 +931,8 @@ def migrate_legacy_fields(table_key, st=None, known_users=None, grant_topic=None
|
|
| 730 |
normalized += 1
|
| 731 |
continue
|
| 732 |
|
| 733 |
-
existing = shared_overlay.fields(
|
|
|
|
| 734 |
if isinstance(existing, dict):
|
| 735 |
# A completed promotion is authoritative. Remove a duplicate personal copy
|
| 736 |
# only when it has the same creator; a collision from another owner fails closed.
|
|
@@ -744,6 +946,8 @@ def migrate_legacy_fields(table_key, st=None, known_users=None, grant_topic=None
|
|
| 744 |
"createdBy": original.get("createdBy") or owner,
|
| 745 |
"source": "overlay", "custom": True})
|
| 746 |
shared_overlay.put_field(shared_key, field_key, shared, st=st)
|
|
|
|
|
|
|
| 747 |
promoted += 1
|
| 748 |
|
| 749 |
rows = {}
|
|
@@ -790,7 +994,7 @@ def migrate_legacy_fields(table_key, st=None, known_users=None, grant_topic=None
|
|
| 790 |
purged = 0
|
| 791 |
if tombstoned:
|
| 792 |
try:
|
| 793 |
-
live = shared_overlay.fields(shared_key, st=st)
|
| 794 |
except Exception: # noqa: BLE001
|
| 795 |
live = {}
|
| 796 |
for dead in tombstoned:
|
|
|
|
| 26 |
FIELD_AUDIENCES = ("private", "users", "everyone")
|
| 27 |
FIELD_VALUE_STRATA = ("shared", "personal")
|
| 28 |
|
| 29 |
+
#: ββ W42-T47 / RULING R15 / CONTRACT C10 β WHICH STRATUM A DEFINITION WAS READ FROM.
|
| 30 |
+
#:
|
| 31 |
+
#: C10: *"`field_classes` reports, beside `{origin, audience, sharedBy, values, owner}`, WHICH
|
| 32 |
+
#: STRATUM the definition was read from, so the client sections on ownership without re-deriving
|
| 33 |
+
#: it."* The three are the three places a field definition can physically live in this codebase:
|
| 34 |
+
#:
|
| 35 |
+
#: * ``contract`` β the canonical contract file (`aios_grid_fields.json`) or a module's declared
|
| 36 |
+
#: columns. Nobody made it here; it is the same document for every account.
|
| 37 |
+
#: * ``shared`` β `shared_overlay`'s tenant-wide bucket (`<topic>_table_workspace__shared`),
|
| 38 |
+
#: which is where `mint_field` and `promote_field` put a definition. ONE document, read by
|
| 39 |
+
#: every account.
|
| 40 |
+
#: * ``personal`` β the reader's OWN member of the `<topic>_table_workspace` document. A
|
| 41 |
+
#: per-user definition: no other account ever receives it.
|
| 42 |
+
#:
|
| 43 |
+
#: β IT IS NOT `FIELD_VALUE_STRATA` WEARING A SECOND HAT, AND THE TWO MUST NOT BE COMPARED. That
|
| 44 |
+
#: tuple says where a column's VALUES live; this one says where its DEFINITION was read from. A
|
| 45 |
+
#: column can be `stratum='personal'` with `values='shared'` β that pair is R15's report, not R15's
|
| 46 |
+
#: bug (see `field_stratum`).
|
| 47 |
+
FIELD_DEFINITION_STRATA = ("contract", "shared", "personal")
|
| 48 |
+
|
| 49 |
#: `permissions_from_grants`' edit vocabulary -> C1's audience vocabulary. The two answer the SAME
|
| 50 |
#: question in different words (who can reach this column), so this map is the whole of the
|
| 51 |
#: translation and there is no second derivation to drift from it
|
|
|
|
| 220 |
return "preset"
|
| 221 |
|
| 222 |
|
| 223 |
+
def _grant_mark():
|
| 224 |
+
"""The name of the wall's own mark, read from `perm_scope` and never re-spelled locally.
|
| 225 |
+
|
| 226 |
+
β `_governed`'s note forbids a second reader by name: *"Re-spelling `f.get('granted') is True`
|
| 227 |
+
locally would be a second reader of the mark, and a second reader is how the two come apart."*
|
| 228 |
+
The stratum fallback below needs the same mark, so it takes the CONSTANT rather than the
|
| 229 |
+
literal, and the two cannot drift apart on a rename.
|
| 230 |
+
|
| 231 |
+
β THE FAILURE DIRECTION IS DELIBERATE AND IS THE OPPOSITE OF `_governed`'S. `_governed`
|
| 232 |
+
degrades to `False` (not governed), which is right for a WALL question. Here an unresolvable
|
| 233 |
+
import must not tip a definition toward `personal`, because `personal` zeroes the grant record
|
| 234 |
+
in `field_class`; falling back to the mark's own spelling keeps the conservative answer
|
| 235 |
+
(`shared`, i.e. trust the registry) when `core.perm_scope` cannot be loaded at all.
|
| 236 |
+
"""
|
| 237 |
+
try:
|
| 238 |
+
import core.perm_scope as perm_scope
|
| 239 |
+
return str(perm_scope.FIELD_GRANT_MARK)
|
| 240 |
+
except Exception: # noqa: BLE001
|
| 241 |
+
return "granted"
|
| 242 |
+
|
| 243 |
+
|
| 244 |
+
def field_stratum(field):
|
| 245 |
+
"""ββ W42-T47 / R15 / C10 β THE **FALLBACK** DERIVATION OF WHICH STRATUM A DEFINITION CAME
|
| 246 |
+
FROM, for a caller that cannot lend the fact. See `FIELD_DEFINITION_STRATA`.
|
| 247 |
+
|
| 248 |
+
ββ IT IS A FALLBACK AND NOT THE ANSWER, AND THE REASON IS THE WHOLE OF THIS TICKET: **NOTHING
|
| 249 |
+
ON A FIELD DEFINITION RECORDS WHICH DOCUMENT IT WAS READ FROM.** Every mark that looks like
|
| 250 |
+
evidence survives being COPIED OUT of that document:
|
| 251 |
+
|
| 252 |
+
* `routes_customers._merge_shared_fields` projects a shared definition as
|
| 253 |
+
`dict(f, source="overlay", shared=True)`;
|
| 254 |
+
* that merged list reaches `grid_events.field_upsert`, whose fork-minting branch is
|
| 255 |
+
`base = field_by_key[key]` then `field = {**base, 'note': ...}` β `{**base}` copies EVERY
|
| 256 |
+
key, `shared` and `granted` and `source` included;
|
| 257 |
+
* `TableStore.save_field` then writes that copy into THIS user's own workspace member.
|
| 258 |
+
|
| 259 |
+
So a personal fork of a tenant-wide route carries `shared: True` verbatim, and a mark-based
|
| 260 |
+
test calls it `shared`. That is R15's own reproduction (gabriel mints `route_x`; another
|
| 261 |
+
account forks it through Format or Summary), which is exactly the case this member exists to
|
| 262 |
+
report, so the mark test cannot be the producer of the answer.
|
| 263 |
+
|
| 264 |
+
β ADDING MORE MARKS DOES NOT RESCUE IT. `source == "overlay"` is copied by the same `{**base}`
|
| 265 |
+
and fails identically. A key-keyed store (the grant registry, `shared_overlay.fields()`
|
| 266 |
+
membership, the lent `values_shared`) fails the other way: it answers about whichever
|
| 267 |
+
definition of that key lives in ITS document, which on a fork is a DIFFERENT definition from
|
| 268 |
+
the dict in hand, so it can never report the conflict either.
|
| 269 |
+
|
| 270 |
+
β THE BLIND SPOT, STATED RATHER THAN HIDDEN: **this fallback cannot see a fork, and names one
|
| 271 |
+
`shared`.** A documented blind spot beats a silent one; the honest answer is lent by the
|
| 272 |
+
assembly that DID the reading, through `field_class(stratum=...)` / `field_classes(strata=...)`.
|
| 273 |
+
|
| 274 |
+
The marks are still the best available evidence for everything else, and the polarity matches
|
| 275 |
+
`field_origin`'s: unmarked plus a demonstrable author is `personal`, everything else `contract`.
|
| 276 |
+
"""
|
| 277 |
+
if not isinstance(field, dict):
|
| 278 |
+
return "contract"
|
| 279 |
+
if field.get("shared") is True or field.get(_grant_mark()) is True:
|
| 280 |
+
return "shared"
|
| 281 |
+
if field_origin(field) == "user":
|
| 282 |
+
return "personal"
|
| 283 |
+
return "contract"
|
| 284 |
+
|
| 285 |
+
|
| 286 |
+
def _clean_stratum(value, field=None):
|
| 287 |
+
"""One lent stratum, canonicalised, falling back to `field_stratum` on anything unrecognised.
|
| 288 |
+
|
| 289 |
+
β AN UNKNOWN TOKEN FALLS BACK RATHER THAN FAILING CLOSED TO `personal`. `personal` is not the
|
| 290 |
+
safe direction here: it ZEROES the grant record in `field_class`, so a typo in a lent map would
|
| 291 |
+
silently strip the owner and the audience off every column it named.
|
| 292 |
+
"""
|
| 293 |
+
token = str(value or "").strip().lower()
|
| 294 |
+
if token in FIELD_DEFINITION_STRATA:
|
| 295 |
+
return token
|
| 296 |
+
return field_stratum(field)
|
| 297 |
+
|
| 298 |
+
|
| 299 |
def _shared_value_keys(table_key, st=None):
|
| 300 |
"""The columns of `table_key` whose VALUES are one tenant-wide stratum."""
|
| 301 |
key = str(table_key or "").strip()
|
|
|
|
| 368 |
|
| 369 |
|
| 370 |
def field_class(field, viewer, grants=None, *, table_key=None, grant_topic=None,
|
| 371 |
+
values_shared=None, stratum=None, st=None):
|
| 372 |
"""ββ W41-T01 / R5 / CONTRACT C1 β **THE ONE PRODUCER OF A FIELD'S THREE BADGES.**
|
| 373 |
|
| 374 |
+
Returns `{origin, audience, sharedBy, values, owner, stratum}` and nothing else derives a badge
|
| 375 |
+
independently. The member spellings are C1's and C10's, and they are the wire's: the payload key
|
| 376 |
+
is `class`, its members are `origin`, `audience`, `sharedBy`, `values`, `owner`, `stratum`.
|
| 377 |
+
|
| 378 |
+
**stratum** β ββ W42-T47 / R15 / C10, and it is the member the other five are now ANCHORED to.
|
| 379 |
+
`contract` | `shared` | `personal`: WHICH DOCUMENT this definition was read from. The client
|
| 380 |
+
sections on ownership (My fields / From my colleagues / Built in) from `stratum` plus `owner`
|
| 381 |
+
WITHOUT re-deriving either.
|
| 382 |
+
β IT IS **LENT BY THE CALLER**, for `values_shared`'s reason turned up one notch: not merely
|
| 383 |
+
that `core` never imports up, but that the fact is not present in ANY of this function's
|
| 384 |
+
inputs. Nothing on a definition records the document it came from, because every mark on it
|
| 385 |
+
survives being copied out of that document (`field_stratum` carries the proof and the copying
|
| 386 |
+
doors). Only the assembly that DID the reading knows, so it lends
|
| 387 |
+
`field_classes(strata={key: stratum})`, and absent that the derivation falls back to
|
| 388 |
+
`field_stratum`, whose blind spot is stated there rather than hidden here.
|
| 389 |
|
| 390 |
`viewer` is a USERNAME STRING (`session.uname`), never a user dict β a dict compares unequal to
|
| 391 |
every stored name, which would make `sharedBy` silently never match and `owner` never equal the
|
|
|
|
| 434 |
contract-declared one), else `personal`. This is R5's new information and it is INDEPENDENT of
|
| 435 |
audience: a route column is `private` with `shared` values, Supplier is `everyone` with `shared`
|
| 436 |
values, and a column you made is `private` with `personal` ones.
|
| 437 |
+
ββ W42-T47 / R15 β `values` AND `audience` KEEP READING GENUINELY DIFFERENT STORES, AND THEY
|
| 438 |
+
ARE STILL INCAPABLE OF DESCRIBING DIFFERENT DEFINITIONS. The independence is required (one is
|
| 439 |
+
membership of the shared-overlay stratum, the other is `shares.grants`), so it is not removed;
|
| 440 |
+
what is removed is the second opinion about WHICH DEFINITION is being described. `stratum` is
|
| 441 |
+
computed once, from the definition in hand, and both legs are anchored to it: the registry is
|
| 442 |
+
not consulted at all on a `personal` definition, and `values` no longer decides an audience for
|
| 443 |
+
one. R15's *"`Private` + `Shared values` is NOT a state to preserve, it IS the bug"* is
|
| 444 |
+
therefore answered by making the pair UNAMBIGUOUS rather than by suppressing either member: a
|
| 445 |
+
column whose cells come from the shared pool but whose definition is the reader's own now reads
|
| 446 |
+
`{stratum: 'personal', values: 'shared', audience: 'private', owner: <its own author>}`, which
|
| 447 |
+
is one coherent sentence and the exact fact the owner reported, instead of two badges that
|
| 448 |
+
contradict each other about who has this column.
|
| 449 |
+
|
| 450 |
β `values_shared` IS LENT BY THE CALLER because the key set is a MODULE-level fact
|
| 451 |
(`product_data.SHARED_KEYS()`), and `core` never imports up. Absent, it is derived from
|
| 452 |
`shared_overlay.fields(table_key)`, which is right for an overlay topic and blind to a
|
|
|
|
| 463 |
me = _uname(viewer)
|
| 464 |
|
| 465 |
origin = field_origin(field)
|
| 466 |
+
# ββ W42-T47 β AN **ASSERTED** STRATUM ANCHORS THE BAG; A GUESSED ONE REPORTS AND NOTHING MORE.
|
| 467 |
+
# `user_tables._field_badges` calls `field_class` on a RIGHTS path: `delete_field_refusal` reads
|
| 468 |
+
# `bag['owner']` and returns `NOT_FIELD_OWNER` on a mismatch, so anything that moves `owner`
|
| 469 |
+
# moves a delete. That caller lends no stratum, and the fallback derivation is a guess by its
|
| 470 |
+
# own docstring, so letting a guess re-source `owner` could hand somebody a delete they did not
|
| 471 |
+
# have. This ticket makes a REPORT honest; it moves no wall, and this line is where that
|
| 472 |
+
# promise is kept rather than asserted. A caller that KNOWS which document it read (C10's lent
|
| 473 |
+
# map) gets the anchored answer; every existing caller keeps today's behaviour byte for byte.
|
| 474 |
+
asserted = str(stratum or "").strip().lower() in FIELD_DEFINITION_STRATA
|
| 475 |
+
stratum = _clean_stratum(stratum, field)
|
| 476 |
+
anchored_personal = asserted and stratum == "personal"
|
| 477 |
record = grants if isinstance(grants, dict) else _grant_record(
|
| 478 |
key, table_key=table_key, grant_topic=grant_topic, st=st)
|
| 479 |
+
# ββ W42-T47 / R15 / C10 β THE REGISTRY RECORD IS KEYED BY FIELD **KEY**, SO ON A PERSONAL
|
| 480 |
+
# DEFINITION IT DESCRIBES A DIFFERENT DEFINITION AND IS DROPPED ENTIRELY.
|
| 481 |
+
#
|
| 482 |
+
# `shares.field_oid(topic, key)` names a KEY, not a document. A grant record for `route_x` was
|
| 483 |
+
# written about the definition in the tenant-wide bucket; when the dict in hand came from the
|
| 484 |
+
# reader's own workspace member instead, those are two different definitions of one key, and
|
| 485 |
+
# `routes_customers._merge_shared_fields` makes that routine rather than exotic β its rule is
|
| 486 |
+
# `if k in have: continue`, so a reader holding ANY same-key entry silently keeps their own and
|
| 487 |
+
# never sees the shared one (that merge is W42-T46's, not this ticket's).
|
| 488 |
+
#
|
| 489 |
+
# Reading `owner`, `sharedBy` and `audience` off that record while reading `origin`, `values`
|
| 490 |
+
# and the marks off the personal dict is how ONE bag came to describe TWO definitions, which is
|
| 491 |
+
# R15's *"Gabriel created the Route and it ends up being MY field"* β the owner fact and the
|
| 492 |
+
# audience were answering about different documents. Zeroing the record here is what makes the
|
| 493 |
+
# anchoring STRUCTURAL: after this line there is no path by which a registry-derived member can
|
| 494 |
+
# describe a definition the `stratum` member does not name.
|
| 495 |
+
#
|
| 496 |
+
# β NO PERMISSION MOVES, AND IT IS CHECKED RATHER THAN REASONED β BUT NOT FOR THE REASON IT
|
| 497 |
+
# FIRST LOOKS LIKE. A fork carries `granted: True` copied verbatim, so a `personal` definition
|
| 498 |
+
# CAN be one the wall does consult the registry about; this arm is exactly where R15's fork
|
| 499 |
+
# lands. What makes it safe is that the wall reads the registry ITSELF
|
| 500 |
+
# (`perm_scope.field_grant_hidden` -> `shares.role_for`) and never reads this bag, so zeroing
|
| 501 |
+
# here changes the REPORT and nothing else. The report is the thing that was wrong: a personal
|
| 502 |
+
# definition's grant record describes a document the reader is not reading.
|
| 503 |
+
if anchored_personal:
|
| 504 |
+
record = _empty_record()
|
| 505 |
owner = _uname(record.get("owner")) or None
|
| 506 |
entries = [e for e in (record.get("entries") or ()) if isinstance(e, dict)]
|
| 507 |
|
|
|
|
| 512 |
if _governed(field):
|
| 513 |
audience = _AUDIENCE_FROM_EDIT.get(
|
| 514 |
permissions_from_grants(entries).get("edit"), "private")
|
| 515 |
+
elif not anchored_personal and (values == "shared" or origin == "preset"):
|
| 516 |
# Ungoverned AND tenant-wide: the database's holders all hold this column. `origin` covers
|
| 517 |
# a contract-declared column whose VALUES are per-user (a canonical Odoo column); the
|
| 518 |
# `values` leg covers a shared-stratum column the contract never named.
|
| 519 |
+
#
|
| 520 |
+
# β W42-T47 β THE `stratum != "personal"` GUARD IS THIS TICKET'S BEHAVIOUR CHANGE, AND IT
|
| 521 |
+
# FIRES ON EXACTLY ONE SHAPE: a definition read from the reader's OWN workspace member
|
| 522 |
+
# whose key ALSO has a definition (and therefore shared cells) in the tenant-wide bucket.
|
| 523 |
+
# Without it, `values` β a fact about the SHARED document β promoted a definition nobody
|
| 524 |
+
# else can even receive to `everyone`. The reader would be told the whole tenant can see a
|
| 525 |
+
# column that exists only in their own stratum, which is a promise the merge cannot keep.
|
| 526 |
+
# β It cannot touch a shared or contract definition: both answer a `stratum` this test
|
| 527 |
+
# admits, so Supplier and every minted route badge exactly as they did before.
|
| 528 |
audience = "everyone"
|
| 529 |
else:
|
| 530 |
audience = "private"
|
|
|
|
| 539 |
if shared_by == me:
|
| 540 |
shared_by = None
|
| 541 |
|
| 542 |
+
# β THE `createdBy` FALLBACK IS NOW THE WHOLE ANSWER ON A PERSONAL DEFINITION, not merely the
|
| 543 |
+
# create-window stopgap it was written as, because `record` was zeroed above. That is the
|
| 544 |
+
# intended reading of C10's *"whose it is"*: the author mark rides on the definition that was
|
| 545 |
+
# read, so `owner` and `stratum` cannot name different documents.
|
| 546 |
return {"origin": origin, "audience": audience, "sharedBy": shared_by,
|
| 547 |
+
"values": values, "owner": owner or _uname(field.get("createdBy")) or None,
|
| 548 |
+
"stratum": stratum}
|
| 549 |
|
| 550 |
|
| 551 |
def field_classes(fields, viewer, *, table_key=None, grant_topic=None, values_shared=None,
|
| 552 |
+
strata=None, st=None):
|
| 553 |
+
"""`{field_key: <C1 + C10 bag>}` for a whole field list, on ONE registry read. See `grant_records`.
|
| 554 |
+
|
| 555 |
+
ββ W42-T47 / C10 β every bag carries `stratum` (`contract` | `shared` | `personal`), so a
|
| 556 |
+
caller sections on ownership without re-deriving it.
|
| 557 |
+
|
| 558 |
+
β `strata` IS THE LENT MAP AND IT IS THE ONLY HONEST SOURCE: `{field_key: <one of
|
| 559 |
+
FIELD_DEFINITION_STRATA>}`, supplied by the assembly that READ each definition and therefore
|
| 560 |
+
knows which document each entry of `fields` came out of. Partial maps are fine β a key the map
|
| 561 |
+
does not name falls back to `field_stratum`, per key, so a caller can lend only the keys it is
|
| 562 |
+
sure about. β THE PER-FIELD ANSWER IS NOT DERIVABLE FROM ANYTHING THIS FUNCTION HOLDS:
|
| 563 |
+
`records` and `values_shared` are both keyed by field key, so they describe whichever
|
| 564 |
+
definition of that key lives in THEIR store, which on a forked column is a different definition
|
| 565 |
+
from the one in `fields`. That is why the fact is lent rather than computed here.
|
| 566 |
|
| 567 |
β EVERY COLUMN GETS A BAG, INCLUDING ONE THE REGISTRY HAS NEVER HEARD OF: the missing record is
|
| 568 |
substituted explicitly rather than left to `field_class` to re-read, which is what keeps the
|
|
|
|
| 573 |
if values_shared is None:
|
| 574 |
values_shared = _shared_value_keys(table_key, st=st)
|
| 575 |
shared_keys = {str(k) for k in (values_shared or ())}
|
| 576 |
+
lent = {str(k).strip(): v for k, v in strata.items()} if isinstance(strata, dict) else {}
|
| 577 |
out = {}
|
| 578 |
for field in (fields or ()):
|
| 579 |
if not isinstance(field, dict):
|
|
|
|
| 583 |
continue
|
| 584 |
out[key] = field_class(field, viewer, grants=records.get(key) or _empty_record(),
|
| 585 |
table_key=table_key, grant_topic=topic,
|
| 586 |
+
values_shared=shared_keys, stratum=lent.get(key), st=st)
|
| 587 |
return out
|
| 588 |
|
| 589 |
|
|
|
|
| 601 |
return set(left.get("users") or ()) == set(right.get("users") or ())
|
| 602 |
|
| 603 |
|
| 604 |
+
def reconcile_shared_permissions(shared_key, grant_topic, st=None, shared_document=None):
|
| 605 |
"""Re-derive every SHARED definition's `permissions` bag from the grant registry. Returns the
|
| 606 |
number of definitions actually rewritten.
|
| 607 |
|
|
|
|
| 648 |
if not bucket or st is None:
|
| 649 |
return 0
|
| 650 |
rewritten = 0
|
| 651 |
+
for field_key, defn in list(shared_overlay.fields(
|
| 652 |
+
bucket, st=st, document=shared_document).items()):
|
| 653 |
# β EACH DEFINITION IS GUARDED ON ITS OWN. `shares.field_oid` RAISES on an empty key, and
|
| 654 |
# the caller wraps this whole function in one swallowing except β so a single malformed
|
| 655 |
# entry would otherwise skip every REMAINING column, including the one the owner reported,
|
|
|
|
| 680 |
updated = dict(defn)
|
| 681 |
updated["permissions"] = derived
|
| 682 |
shared_overlay.put_field(bucket, key, updated, st=st)
|
| 683 |
+
if isinstance(shared_document, dict):
|
| 684 |
+
shared_document.setdefault("fields", {})[key] = updated
|
| 685 |
rewritten += 1
|
| 686 |
except Exception:
|
| 687 |
continue
|
|
|
|
| 836 |
and field.get("source") == "overlay")
|
| 837 |
|
| 838 |
|
| 839 |
+
def migrate_legacy_fields(table_key, st=None, known_users=None, grant_topic=None, shared_key=None,
|
| 840 |
+
workspace_document=None, shared_document=None):
|
| 841 |
"""Promote legacy shared-looking custom fields into the shared field stratum.
|
| 842 |
|
| 843 |
The operation is intentionally idempotent and copy-before-remove. A failed request can
|
| 844 |
therefore leave a private shadow behind, but it cannot lose the creator's values. The next
|
| 845 |
+
read retries the promotion and the shared definition wins. A caller that already captured
|
| 846 |
+
the workspace document may lend that read-only snapshot to avoid reopening the same key.
|
| 847 |
"""
|
| 848 |
key = str(table_key or "").strip()
|
| 849 |
grant_key = str(grant_topic or key).strip()
|
|
|
|
| 869 |
# finds no grant record, the "no record" arm fires for every column, and the reconcile
|
| 870 |
# silently does nothing at all.
|
| 871 |
try:
|
| 872 |
+
reclassified = reconcile_shared_permissions(
|
| 873 |
+
shared_key, grant_key, st=st, shared_document=shared_document)
|
| 874 |
except Exception:
|
| 875 |
reclassified = 0
|
| 876 |
+
# W44 predecessor replay: a table assembly has already read this exact document through
|
| 877 |
+
# `TableStore.workspace(..., include_document=True)`. Reopening it here paid a third whole
|
| 878 |
+
# `<key>_table_workspace` copy for the same rows request. Accept that captured snapshot when
|
| 879 |
+
# supplied; every historical/cold caller still takes the original `st.get(key)` path.
|
| 880 |
+
#
|
| 881 |
+
# A non-dict is NOT treated as an empty captured document. It falls back to the store so a
|
| 882 |
+
# malformed optional argument cannot suppress an existing migration by manufacturing `{}`.
|
| 883 |
+
if isinstance(workspace_document, dict):
|
| 884 |
+
document = workspace_document
|
| 885 |
+
else:
|
| 886 |
+
try:
|
| 887 |
+
document = st.get(key) or {}
|
| 888 |
+
except Exception:
|
| 889 |
+
return {"promoted": 0, "normalized": 0, "reclassified": reclassified,
|
| 890 |
+
"suppressed": 0, "purged": 0}
|
| 891 |
if not isinstance(document, dict):
|
| 892 |
return {"promoted": 0, "normalized": 0, "reclassified": reclassified,
|
| 893 |
"suppressed": 0, "purged": 0}
|
|
|
|
| 931 |
normalized += 1
|
| 932 |
continue
|
| 933 |
|
| 934 |
+
existing = shared_overlay.fields(
|
| 935 |
+
shared_key, st=st, document=shared_document).get(field_key)
|
| 936 |
if isinstance(existing, dict):
|
| 937 |
# A completed promotion is authoritative. Remove a duplicate personal copy
|
| 938 |
# only when it has the same creator; a collision from another owner fails closed.
|
|
|
|
| 946 |
"createdBy": original.get("createdBy") or owner,
|
| 947 |
"source": "overlay", "custom": True})
|
| 948 |
shared_overlay.put_field(shared_key, field_key, shared, st=st)
|
| 949 |
+
if isinstance(shared_document, dict):
|
| 950 |
+
shared_document.setdefault("fields", {})[field_key] = dict(shared)
|
| 951 |
promoted += 1
|
| 952 |
|
| 953 |
rows = {}
|
|
|
|
| 994 |
purged = 0
|
| 995 |
if tombstoned:
|
| 996 |
try:
|
| 997 |
+
live = shared_overlay.fields(shared_key, st=st, document=shared_document)
|
| 998 |
except Exception: # noqa: BLE001
|
| 999 |
live = {}
|
| 1000 |
for dead in tombstoned:
|
platform/core/grid_events.py
CHANGED
|
@@ -333,6 +333,18 @@ def _may_edit_field_value(ctx, key, definition):
|
|
| 333 |
str(user).lower() for user in (perms.get('users') or [])})
|
| 334 |
|
| 335 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 336 |
def _cohorts(ctx):
|
| 337 |
"""The COHORT store this ctx operates on β `_tops`'s sibling, and here for the same reason.
|
| 338 |
|
|
@@ -1266,10 +1278,8 @@ def handle_one(event, ctx):
|
|
| 1266 |
# vocabulary is absent (ordinary customer and legacy in-memory contexts have none).
|
| 1267 |
pass
|
| 1268 |
valid_keys = set(field_by_key)
|
| 1269 |
-
overlay_keys = {f['key'] for f in fields
|
| 1270 |
-
|
| 1271 |
-
if any(f.get('key') == 'maps_url' and f.get('source') == 'odoo' for f in fields):
|
| 1272 |
-
overlay_keys.add('maps_url')
|
| 1273 |
# Event validation is not a render payload. It must not consume a one-shot label
|
| 1274 |
# correction before the browser has had a chance to receive it.
|
| 1275 |
ws = table_workspace(
|
|
@@ -1806,7 +1816,10 @@ def handle_one(event, ctx):
|
|
| 1806 |
# its list and visual treatment rather than silently preserving a
|
| 1807 |
# read-only source projection.
|
| 1808 |
if field.get('type') in ('select', 'multiselect') and 'options' in raw:
|
| 1809 |
-
|
|
|
|
|
|
|
|
|
|
| 1810 |
if not options:
|
| 1811 |
return _refuse(
|
| 1812 |
ctx, 'no_options', 'a select column needs at least one choice', key)
|
|
@@ -1914,7 +1927,10 @@ def handle_one(event, ctx):
|
|
| 1914 |
# choices are the tenant's accounts, resolved fresh on every render, so persisting
|
| 1915 |
# a snapshot here would go stale the moment somebody joins or leaves.
|
| 1916 |
if ftype in ('select', 'multiselect'):
|
| 1917 |
-
|
|
|
|
|
|
|
|
|
|
| 1918 |
if not field['options']:
|
| 1919 |
# a select with no choices can never hold a value
|
| 1920 |
return _refuse(
|
|
@@ -3124,7 +3140,7 @@ def handle_one(event, ctx):
|
|
| 3124 |
# A choice value is DATA, not a precondition the field editor must have visited.
|
| 3125 |
# Pasted/imported/API values therefore mint an option through this same write
|
| 3126 |
# door. It is deliberately still bounded and case-canonical: "ET" then "et"
|
| 3127 |
-
# is one option, and the
|
| 3128 |
# picker the contract cannot represent.
|
| 3129 |
import aios_grid as _ag_choices
|
| 3130 |
options = _ag_choices.merge_choice_options(definition.get('options'))
|
|
|
|
| 333 |
str(user).lower() for user in (perms.get('users') or [])})
|
| 334 |
|
| 335 |
|
| 336 |
+
def _may_override_source_value(definition):
|
| 337 |
+
"""One source-backed value may write through the ordinary overlay door.
|
| 338 |
+
|
| 339 |
+
The canonical field contract must carry the capability and the field identity must still be
|
| 340 |
+
Maps. Requiring both prevents a copied or caller-forged flag from widening every Odoo field.
|
| 341 |
+
"""
|
| 342 |
+
return (isinstance(definition, dict)
|
| 343 |
+
and definition.get('key') == 'maps_url'
|
| 344 |
+
and definition.get('source') == 'odoo'
|
| 345 |
+
and definition.get('valueOverride') == 'overlay')
|
| 346 |
+
|
| 347 |
+
|
| 348 |
def _cohorts(ctx):
|
| 349 |
"""The COHORT store this ctx operates on β `_tops`'s sibling, and here for the same reason.
|
| 350 |
|
|
|
|
| 1278 |
# vocabulary is absent (ordinary customer and legacy in-memory contexts have none).
|
| 1279 |
pass
|
| 1280 |
valid_keys = set(field_by_key)
|
| 1281 |
+
overlay_keys = {f['key'] for f in fields
|
| 1282 |
+
if f.get('source') == 'overlay' or _may_override_source_value(f)}
|
|
|
|
|
|
|
| 1283 |
# Event validation is not a render payload. It must not consume a one-shot label
|
| 1284 |
# correction before the browser has had a chance to receive it.
|
| 1285 |
ws = table_workspace(
|
|
|
|
| 1816 |
# its list and visual treatment rather than silently preserving a
|
| 1817 |
# read-only source projection.
|
| 1818 |
if field.get('type') in ('select', 'multiselect') and 'options' in raw:
|
| 1819 |
+
try:
|
| 1820 |
+
options = _ag2._clean_options(raw.get('options'))
|
| 1821 |
+
except _ag2.OptionLimitExceeded as exc:
|
| 1822 |
+
return _refuse(ctx, 'option_limit', str(exc), key)
|
| 1823 |
if not options:
|
| 1824 |
return _refuse(
|
| 1825 |
ctx, 'no_options', 'a select column needs at least one choice', key)
|
|
|
|
| 1927 |
# choices are the tenant's accounts, resolved fresh on every render, so persisting
|
| 1928 |
# a snapshot here would go stale the moment somebody joins or leaves.
|
| 1929 |
if ftype in ('select', 'multiselect'):
|
| 1930 |
+
try:
|
| 1931 |
+
field['options'] = _ag2._clean_options(raw.get('options'))
|
| 1932 |
+
except _ag2.OptionLimitExceeded as exc:
|
| 1933 |
+
return _refuse(ctx, 'option_limit', str(exc), key)
|
| 1934 |
if not field['options']:
|
| 1935 |
# a select with no choices can never hold a value
|
| 1936 |
return _refuse(
|
|
|
|
| 3140 |
# A choice value is DATA, not a precondition the field editor must have visited.
|
| 3141 |
# Pasted/imported/API values therefore mint an option through this same write
|
| 3142 |
# door. It is deliberately still bounded and case-canonical: "ET" then "et"
|
| 3143 |
+
# is one option, and the 201st distinct label is refused rather than creating a
|
| 3144 |
# picker the contract cannot represent.
|
| 3145 |
import aios_grid as _ag_choices
|
| 3146 |
options = _ag_choices.merge_choice_options(definition.get('options'))
|
platform/core/route_system.py
CHANGED
|
@@ -8,6 +8,7 @@ from __future__ import annotations
|
|
| 8 |
|
| 9 |
import copy
|
| 10 |
import datetime as _dt
|
|
|
|
| 11 |
import math
|
| 12 |
import re
|
| 13 |
import uuid
|
|
@@ -21,6 +22,9 @@ SYSTEM_TABLES = {ROUTES_KEY: "Odoo Customers - Routes", ZONES_KEY: "Odoo Custome
|
|
| 21 |
# TenantRuntime namespaces this bucket. User-table rows are scalar user data; route stops are a
|
| 22 |
# protected relation (route id + customer id + order), so they cannot be a generic Link field.
|
| 23 |
STORE_KEY = "loopable_route_system"
|
|
|
|
|
|
|
|
|
|
| 24 |
_ROUTE_COLORS = ("#6E4AC7", "#1F4E78", "#C85A54", "#2F8F83", "#B57716", "#A14B8B")
|
| 25 |
_COLOR_RE = re.compile(r"^#[0-9A-Fa-f]{6}$")
|
| 26 |
_ZIP_RE = re.compile(r"^[A-Za-z0-9 -]{1,20}$")
|
|
@@ -86,11 +90,13 @@ def field_axes(field):
|
|
| 86 |
if authority not in {"source", "derived", "user-entered", "computed"} or scope not in {"source", "tenant", "view", "record"}:
|
| 87 |
raise ValueError("unapproved field axis")
|
| 88 |
field.update({"kind": kind, "origin": origin, "valueAuthority": authority, "scope": scope})
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
|
|
|
|
|
|
| 94 |
if ftype == "json":
|
| 95 |
field["label"] = "Table"
|
| 96 |
return field
|
|
@@ -173,11 +179,13 @@ def _route(raw, *, ordinal=0, created_by="", tenant_id="", prior=None):
|
|
| 173 |
if maps_url and not _GOOGLE_MAPS_URL_RE.match(maps_url):
|
| 174 |
return None
|
| 175 |
stamp = _now()
|
|
|
|
| 176 |
out = {"id": rid, "tenantId": str(tenant_id or prior.get("tenantId") or ""), "name": name,
|
| 177 |
"color": _color(raw.get("color", prior.get("color")), ordinal),
|
| 178 |
"number": int(prior.get("number") or ordinal + 1), "sourceViewId": source_view,
|
| 179 |
"sourceViewRevision": revision, "stops": _stops(stops_raw), "managedBy": MANAGED_BY,
|
| 180 |
"createdBy": str(prior.get("createdBy") or created_by or "")[:120],
|
|
|
|
| 181 |
"createdAt": prior.get("createdAt") or stamp, "updatedAt": stamp}
|
| 182 |
if maps_url:
|
| 183 |
out["mapsUrl"] = maps_url
|
|
@@ -233,11 +241,16 @@ def _zone(raw, *, ordinal=0, created_by="", tenant_id="", prior=None):
|
|
| 233 |
if not name or (geometry is not None and not isinstance(geometry, dict)) or (geometry is None and not zips):
|
| 234 |
return None
|
| 235 |
zid = str(raw.get("id") or prior.get("id") or "zone_" + uuid.uuid4().hex)[:96]
|
|
|
|
|
|
|
|
|
|
|
|
|
| 236 |
stamp = _now()
|
| 237 |
return {"id": zid, "tenantId": str(tenant_id or prior.get("tenantId") or ""), "name": name,
|
| 238 |
"color": _color(raw.get("color", prior.get("color")), ordinal),
|
| 239 |
"geometryGeoJson": copy.deepcopy(geometry) if isinstance(geometry, dict) else None,
|
| 240 |
"zipCodes": zips, "visible": raw.get("visible", prior.get("visible", True)) is not False,
|
|
|
|
| 241 |
"membershipRevision": int(prior.get("membershipRevision") or 0),
|
| 242 |
"memberPids": [int(pid) for pid in prior.get("memberPids") or [] if _pid(pid) is not None],
|
| 243 |
"managedBy": MANAGED_BY, "createdBy": str(prior.get("createdBy") or created_by or "")[:120],
|
|
@@ -299,6 +312,7 @@ def _persist(st, mutate):
|
|
| 299 |
state.setdefault("routes", [])
|
| 300 |
state.setdefault("zones", [])
|
| 301 |
state.setdefault("legacyMigrations", {})
|
|
|
|
| 302 |
next_state, value = mutate(state)
|
| 303 |
result["value"] = copy.deepcopy(value)
|
| 304 |
return next_state
|
|
@@ -312,6 +326,7 @@ def read(st, rows=None):
|
|
| 312 |
state.setdefault("routes", [])
|
| 313 |
state.setdefault("zones", [])
|
| 314 |
state.setdefault("legacyMigrations", {})
|
|
|
|
| 315 |
return refresh_zone_memberships(state, rows or ()) if rows is not None else state
|
| 316 |
|
| 317 |
|
|
@@ -319,6 +334,230 @@ def list_routes(st):
|
|
| 319 |
return [copy.deepcopy(route) for route in read(st).get("routes") or [] if isinstance(route, dict)]
|
| 320 |
|
| 321 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 322 |
def list_zones(st, rows=None):
|
| 323 |
return [copy.deepcopy(zone) for zone in read(st, rows).get("zones") or [] if isinstance(zone, dict)]
|
| 324 |
|
|
@@ -366,12 +605,65 @@ def move_stop(st, route_id, customer_pid, order, *, tenant_id, created_by):
|
|
| 366 |
return put_route(st, {**route, "stops": ids}, tenant_id=tenant_id, created_by=created_by)
|
| 367 |
|
| 368 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 369 |
def delete_route(st, route_id):
|
| 370 |
route_id = str(route_id or "").strip()
|
| 371 |
|
| 372 |
def mutate(state):
|
| 373 |
prior = list(state.get("routes") or [])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 374 |
state["routes"] = [item for item in prior if not (isinstance(item, dict) and item.get("id") == route_id)]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 375 |
return state, len(prior) != len(state["routes"])
|
| 376 |
|
| 377 |
return bool(_persist(st, mutate))
|
|
@@ -479,10 +771,14 @@ def apply_managed_route_selection(view_state, route_ids, routes):
|
|
| 479 |
return out
|
| 480 |
|
| 481 |
|
| 482 |
-
def legacy_route_plan(fields, cells, *, tenant_id, created_by):
|
| 483 |
-
"""
|
|
|
|
|
|
|
|
|
|
|
|
|
| 484 |
plans = []
|
| 485 |
-
for key, definition in (fields or {}).items():
|
| 486 |
if not isinstance(definition, dict) or definition.get("kind") != "route_order":
|
| 487 |
continue
|
| 488 |
migration_mark = definition.get("legacyRouteMigration")
|
|
@@ -502,20 +798,59 @@ def legacy_route_plan(fields, cells, *, tenant_id, created_by):
|
|
| 502 |
continue
|
| 503 |
plan = _route({"id": "legacy_" + str(key)[:72], "name": definition.get("label") or key,
|
| 504 |
"color": definition.get("color"),
|
|
|
|
| 505 |
"sourceViewId": (definition.get("route") or {}).get("sourceViewId"),
|
| 506 |
"sourceViewRevision": (definition.get("route") or {}).get("inputsHash"),
|
| 507 |
"stops": [pid for _rank, pid in ranks],
|
| 508 |
"migration": {"legacyField": key, "verified": True}},
|
| 509 |
-
ordinal=
|
|
|
|
|
|
|
| 510 |
if plan is not None:
|
| 511 |
plans.append({"field": key, "route": plan,
|
| 512 |
"expected": {pid: rank for rank, pid in ranks}})
|
| 513 |
return plans
|
| 514 |
|
| 515 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 516 |
def migrate_legacy_routes(st, fields, cells, *, tenant_id, created_by, zones=()):
|
| 517 |
"""Persist copied Routes and prove count/member/order/projection parity before hiding fields."""
|
| 518 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 519 |
if not plans:
|
| 520 |
return {"migrated": [], "verified": {}, "hide": []}
|
| 521 |
|
|
|
|
| 8 |
|
| 9 |
import copy
|
| 10 |
import datetime as _dt
|
| 11 |
+
import hashlib
|
| 12 |
import math
|
| 13 |
import re
|
| 14 |
import uuid
|
|
|
|
| 22 |
# TenantRuntime namespaces this bucket. User-table rows are scalar user data; route stops are a
|
| 23 |
# protected relation (route id + customer id + order), so they cannot be a generic Link field.
|
| 24 |
STORE_KEY = "loopable_route_system"
|
| 25 |
+
# C3 owns this ceiling on the server. Every field payload publishes it, and clients that do not
|
| 26 |
+
# receive it must refuse choice edits rather than guessing a local value.
|
| 27 |
+
MAX_OPTIONS = 200
|
| 28 |
_ROUTE_COLORS = ("#6E4AC7", "#1F4E78", "#C85A54", "#2F8F83", "#B57716", "#A14B8B")
|
| 29 |
_COLOR_RE = re.compile(r"^#[0-9A-Fa-f]{6}$")
|
| 30 |
_ZIP_RE = re.compile(r"^[A-Za-z0-9 -]{1,20}$")
|
|
|
|
| 90 |
if authority not in {"source", "derived", "user-entered", "computed"} or scope not in {"source", "tenant", "view", "record"}:
|
| 91 |
raise ValueError("unapproved field axis")
|
| 92 |
field.update({"kind": kind, "origin": origin, "valueAuthority": authority, "scope": scope})
|
| 93 |
+
# Publish the server-owned limit on EVERY field. The Add-field pane needs the contract before
|
| 94 |
+
# the choice field it is creating exists; restricting it to existing choice fields forces a
|
| 95 |
+
# client literal (or an unsafe guess) on an empty table. Overwrite caller-supplied values:
|
| 96 |
+
# stored metadata is not allowed to mint a different product limit.
|
| 97 |
+
limits = dict(field.get("limits") or {})
|
| 98 |
+
limits["maxOptions"] = MAX_OPTIONS
|
| 99 |
+
field["limits"] = limits
|
| 100 |
if ftype == "json":
|
| 101 |
field["label"] = "Table"
|
| 102 |
return field
|
|
|
|
| 179 |
if maps_url and not _GOOGLE_MAPS_URL_RE.match(maps_url):
|
| 180 |
return None
|
| 181 |
stamp = _now()
|
| 182 |
+
share_key = str(raw.get("shareKey") or prior.get("shareKey") or route_share_key(rid))[:80]
|
| 183 |
out = {"id": rid, "tenantId": str(tenant_id or prior.get("tenantId") or ""), "name": name,
|
| 184 |
"color": _color(raw.get("color", prior.get("color")), ordinal),
|
| 185 |
"number": int(prior.get("number") or ordinal + 1), "sourceViewId": source_view,
|
| 186 |
"sourceViewRevision": revision, "stops": _stops(stops_raw), "managedBy": MANAGED_BY,
|
| 187 |
"createdBy": str(prior.get("createdBy") or created_by or "")[:120],
|
| 188 |
+
"shareKey": share_key,
|
| 189 |
"createdAt": prior.get("createdAt") or stamp, "updatedAt": stamp}
|
| 190 |
if maps_url:
|
| 191 |
out["mapsUrl"] = maps_url
|
|
|
|
| 241 |
if not name or (geometry is not None and not isinstance(geometry, dict)) or (geometry is None and not zips):
|
| 242 |
return None
|
| 243 |
zid = str(raw.get("id") or prior.get("id") or "zone_" + uuid.uuid4().hex)[:96]
|
| 244 |
+
source_view = raw.get("sourceViewId", prior.get("sourceViewId"))
|
| 245 |
+
source_view = str(source_view or "").strip()[:120] or None
|
| 246 |
+
geographic_field = raw.get("geographicField", prior.get("geographicField"))
|
| 247 |
+
geographic_field = str(geographic_field or "").strip()[:120]
|
| 248 |
stamp = _now()
|
| 249 |
return {"id": zid, "tenantId": str(tenant_id or prior.get("tenantId") or ""), "name": name,
|
| 250 |
"color": _color(raw.get("color", prior.get("color")), ordinal),
|
| 251 |
"geometryGeoJson": copy.deepcopy(geometry) if isinstance(geometry, dict) else None,
|
| 252 |
"zipCodes": zips, "visible": raw.get("visible", prior.get("visible", True)) is not False,
|
| 253 |
+
"sourceViewId": source_view, "geographicField": geographic_field,
|
| 254 |
"membershipRevision": int(prior.get("membershipRevision") or 0),
|
| 255 |
"memberPids": [int(pid) for pid in prior.get("memberPids") or [] if _pid(pid) is not None],
|
| 256 |
"managedBy": MANAGED_BY, "createdBy": str(prior.get("createdBy") or created_by or "")[:120],
|
|
|
|
| 312 |
state.setdefault("routes", [])
|
| 313 |
state.setdefault("zones", [])
|
| 314 |
state.setdefault("legacyMigrations", {})
|
| 315 |
+
state.setdefault("routeNavigation", {})
|
| 316 |
next_state, value = mutate(state)
|
| 317 |
result["value"] = copy.deepcopy(value)
|
| 318 |
return next_state
|
|
|
|
| 326 |
state.setdefault("routes", [])
|
| 327 |
state.setdefault("zones", [])
|
| 328 |
state.setdefault("legacyMigrations", {})
|
| 329 |
+
state.setdefault("routeNavigation", {})
|
| 330 |
return refresh_zone_memberships(state, rows or ()) if rows is not None else state
|
| 331 |
|
| 332 |
|
|
|
|
| 334 |
return [copy.deepcopy(route) for route in read(st).get("routes") or [] if isinstance(route, dict)]
|
| 335 |
|
| 336 |
|
| 337 |
+
def route_share_key(route_id):
|
| 338 |
+
"""Stable generic-field bridge id for the existing share registry.
|
| 339 |
+
|
| 340 |
+
Route records are not generic columns, but the shipped share dialog and grant registry already
|
| 341 |
+
own the access workflow. A bounded digest keeps arbitrary Route ids out of field keys while
|
| 342 |
+
remaining deterministic for old normalized records that predate the stored ``shareKey``.
|
| 343 |
+
"""
|
| 344 |
+
digest = hashlib.sha256(str(route_id or "").encode("utf-8")).hexdigest()[:24]
|
| 345 |
+
return "route_object_" + digest
|
| 346 |
+
|
| 347 |
+
|
| 348 |
+
def duplicate_route(st, route_id, *, tenant_id, created_by, name=None):
|
| 349 |
+
"""Copy one normalized Route without aliasing its identity, ownership, or share grants."""
|
| 350 |
+
source = next((item for item in list_routes(st) if item.get("id") == str(route_id)), None)
|
| 351 |
+
if source is None:
|
| 352 |
+
return None
|
| 353 |
+
raw = {"name": _name(name) or f"{source.get('name') or 'Route'} copy",
|
| 354 |
+
"color": source.get("color"), "sourceViewId": source.get("sourceViewId"),
|
| 355 |
+
"sourceViewRevision": source.get("sourceViewRevision"),
|
| 356 |
+
"stops": [stop.get("customerPid") for stop in ordered_stops(source)]}
|
| 357 |
+
if source.get("mapsUrl"):
|
| 358 |
+
raw["mapsUrl"] = source["mapsUrl"]
|
| 359 |
+
return put_route(st, raw, tenant_id=tenant_id, created_by=created_by)
|
| 360 |
+
|
| 361 |
+
|
| 362 |
+
def _nav_user(username):
|
| 363 |
+
return str(username or "").strip().lower()[:120]
|
| 364 |
+
|
| 365 |
+
|
| 366 |
+
_NAV_REFUSED = object()
|
| 367 |
+
|
| 368 |
+
|
| 369 |
+
def _folder_name(raw):
|
| 370 |
+
return " ".join(str(raw or "").split())[:80]
|
| 371 |
+
|
| 372 |
+
|
| 373 |
+
def _clean_nav(raw, routes=(), legacy_folders=(), legacy_placements=None):
|
| 374 |
+
"""Pure, fail-closed current-reader Route navigation projection.
|
| 375 |
+
|
| 376 |
+
Old Wave 42 folders are accepted only as a read fallback. Invalid parents, cycles, excess
|
| 377 |
+
nesting, dangling placements and stale order ids resolve to root; a GET never writes repairs.
|
| 378 |
+
"""
|
| 379 |
+
raw = raw if isinstance(raw, dict) else {}
|
| 380 |
+
offered = raw.get("folders") if isinstance(raw.get("folders"), list) else legacy_folders
|
| 381 |
+
folders, seen = [], set()
|
| 382 |
+
for index, item in enumerate(offered or ()):
|
| 383 |
+
if not isinstance(item, dict):
|
| 384 |
+
continue
|
| 385 |
+
fid = str(item.get("id") or "").strip()[:96]
|
| 386 |
+
name = _folder_name(item.get("name"))
|
| 387 |
+
if not fid or not name or fid in seen:
|
| 388 |
+
continue
|
| 389 |
+
seen.add(fid)
|
| 390 |
+
try:
|
| 391 |
+
order = int(item.get("order", index))
|
| 392 |
+
except (TypeError, ValueError):
|
| 393 |
+
order = index
|
| 394 |
+
parent = str(item.get("parent") or "").strip()[:96] or None
|
| 395 |
+
folders.append({"id": fid, "name": name, "parent": parent, "order": order})
|
| 396 |
+
by_id = {item["id"]: item for item in folders}
|
| 397 |
+
for item in folders:
|
| 398 |
+
parent, trail, depth = item.get("parent"), {item["id"]}, 0
|
| 399 |
+
while parent:
|
| 400 |
+
if parent not in by_id or parent in trail or depth >= 9:
|
| 401 |
+
item["parent"] = None
|
| 402 |
+
break
|
| 403 |
+
trail.add(parent)
|
| 404 |
+
parent = by_id[parent].get("parent")
|
| 405 |
+
depth += 1
|
| 406 |
+
folders.sort(key=lambda item: (int(item.get("order") or 0), item["name"].lower(), item["id"]))
|
| 407 |
+
for index, item in enumerate(folders):
|
| 408 |
+
item["order"] = index
|
| 409 |
+
|
| 410 |
+
placement_raw = raw.get("placements") if isinstance(raw.get("placements"), dict) else legacy_placements or {}
|
| 411 |
+
known_folders = set(by_id)
|
| 412 |
+
route_keys = set()
|
| 413 |
+
for route in routes or ():
|
| 414 |
+
rid = str((route or {}).get("id") or "")
|
| 415 |
+
if rid:
|
| 416 |
+
route_keys.add(rid)
|
| 417 |
+
legacy = ((route or {}).get("migration") or {}).get("legacyField")
|
| 418 |
+
if legacy:
|
| 419 |
+
route_keys.add(str(legacy))
|
| 420 |
+
placements = {}
|
| 421 |
+
for key, folder_id in placement_raw.items():
|
| 422 |
+
key, folder_id = str(key), str(folder_id or "")
|
| 423 |
+
if key in route_keys and folder_id in known_folders:
|
| 424 |
+
placements[key] = folder_id
|
| 425 |
+
|
| 426 |
+
offered_order = raw.get("order") if isinstance(raw.get("order"), list) else []
|
| 427 |
+
canonical_ids = [str((route or {}).get("id") or "") for route in routes or ()]
|
| 428 |
+
order = []
|
| 429 |
+
for route_id in [*offered_order, *canonical_ids]:
|
| 430 |
+
route_id = str(route_id)
|
| 431 |
+
if route_id in canonical_ids and route_id not in order:
|
| 432 |
+
order.append(route_id)
|
| 433 |
+
return {"folders": folders, "placements": placements, "order": order}
|
| 434 |
+
|
| 435 |
+
|
| 436 |
+
def route_navigation(st, username, routes=(), *, legacy_folders=(), legacy_placements=None):
|
| 437 |
+
"""This reader's folders, placement and ordering; route object data remains tenant-wide."""
|
| 438 |
+
user = _nav_user(username)
|
| 439 |
+
raw = (read(st).get("routeNavigation") or {}).get(user) if user else None
|
| 440 |
+
nav = _clean_nav(raw, routes, legacy_folders, legacy_placements)
|
| 441 |
+
folders = nav["folders"]
|
| 442 |
+
placement = nav["placements"]
|
| 443 |
+
out_routes = []
|
| 444 |
+
rank = {rid: index for index, rid in enumerate(nav["order"])}
|
| 445 |
+
for route in routes or ():
|
| 446 |
+
item = copy.deepcopy(route)
|
| 447 |
+
legacy_key = ((item.get("migration") or {}).get("legacyField"))
|
| 448 |
+
item["folderId"] = placement.get(item.get("id"), placement.get(str(legacy_key)))
|
| 449 |
+
item["navOrder"] = rank.get(str(item.get("id")), len(rank))
|
| 450 |
+
out_routes.append(item)
|
| 451 |
+
out_routes.sort(key=lambda item: (int(item.get("navOrder") or 0), int(item.get("number") or 0)))
|
| 452 |
+
return {"folders": folders, "routes": out_routes}
|
| 453 |
+
|
| 454 |
+
|
| 455 |
+
def _mutate_nav(st, username, routes, change, *, legacy_folders=(), legacy_placements=None):
|
| 456 |
+
user = _nav_user(username)
|
| 457 |
+
if not user:
|
| 458 |
+
return None
|
| 459 |
+
|
| 460 |
+
def mutate(state):
|
| 461 |
+
navigation = dict(state.get("routeNavigation") or {})
|
| 462 |
+
current = _clean_nav(navigation.get(user), routes, legacy_folders, legacy_placements)
|
| 463 |
+
result = change(current)
|
| 464 |
+
if result is _NAV_REFUSED:
|
| 465 |
+
return state, None
|
| 466 |
+
navigation[user] = _clean_nav(current, routes)
|
| 467 |
+
state["routeNavigation"] = navigation
|
| 468 |
+
return state, result
|
| 469 |
+
return _persist(st, mutate)
|
| 470 |
+
|
| 471 |
+
|
| 472 |
+
def put_route_folder(st, username, raw, routes=(), *, legacy_folders=(), legacy_placements=None):
|
| 473 |
+
folder_id = str((raw or {}).get("id") or "route_folder_" + uuid.uuid4().hex)[:96]
|
| 474 |
+
name, parent = _folder_name((raw or {}).get("name")), str((raw or {}).get("parent") or "")[:96] or None
|
| 475 |
+
if not name:
|
| 476 |
+
return None
|
| 477 |
+
def change(nav):
|
| 478 |
+
folders = nav["folders"]
|
| 479 |
+
prior = next((item for item in folders if item["id"] == folder_id), None)
|
| 480 |
+
if parent == folder_id or (parent and not any(item["id"] == parent for item in folders)):
|
| 481 |
+
return _NAV_REFUSED
|
| 482 |
+
if parent:
|
| 483 |
+
by_id = {item["id"]: item for item in folders}
|
| 484 |
+
cursor, walked, depth = parent, set(), 1
|
| 485 |
+
while cursor:
|
| 486 |
+
if cursor == folder_id or cursor in walked or depth >= 10:
|
| 487 |
+
return _NAV_REFUSED
|
| 488 |
+
walked.add(cursor)
|
| 489 |
+
cursor = (by_id.get(cursor) or {}).get("parent")
|
| 490 |
+
depth += 1
|
| 491 |
+
if prior:
|
| 492 |
+
prior.update({"name": name, "parent": parent})
|
| 493 |
+
else:
|
| 494 |
+
prior = {"id": folder_id, "name": name, "parent": parent, "order": len(folders)}
|
| 495 |
+
folders.append(prior)
|
| 496 |
+
return copy.deepcopy(prior)
|
| 497 |
+
return _mutate_nav(st, username, routes, change,
|
| 498 |
+
legacy_folders=legacy_folders, legacy_placements=legacy_placements)
|
| 499 |
+
|
| 500 |
+
|
| 501 |
+
def delete_route_folder(st, username, folder_id, routes=(), *, legacy_folders=(), legacy_placements=None):
|
| 502 |
+
folder_id = str(folder_id or "")
|
| 503 |
+
def change(nav):
|
| 504 |
+
if not any(item["id"] == folder_id for item in nav["folders"]):
|
| 505 |
+
return _NAV_REFUSED
|
| 506 |
+
nav["folders"] = [item for item in nav["folders"] if item["id"] != folder_id]
|
| 507 |
+
for item in nav["folders"]:
|
| 508 |
+
if item.get("parent") == folder_id:
|
| 509 |
+
item["parent"] = None
|
| 510 |
+
nav["placements"] = {key: value for key, value in nav["placements"].items() if value != folder_id}
|
| 511 |
+
return True
|
| 512 |
+
return bool(_mutate_nav(st, username, routes, change,
|
| 513 |
+
legacy_folders=legacy_folders, legacy_placements=legacy_placements))
|
| 514 |
+
|
| 515 |
+
|
| 516 |
+
def place_route(st, username, route_id, folder_id, routes=(), *, legacy_folders=(), legacy_placements=None):
|
| 517 |
+
route_id, folder_id = str(route_id or ""), str(folder_id or "") or None
|
| 518 |
+
def change(nav):
|
| 519 |
+
if route_id not in {str((item or {}).get("id")) for item in routes or ()}:
|
| 520 |
+
return _NAV_REFUSED
|
| 521 |
+
if folder_id and not any(item["id"] == folder_id for item in nav["folders"]):
|
| 522 |
+
return _NAV_REFUSED
|
| 523 |
+
if folder_id:
|
| 524 |
+
nav["placements"][route_id] = folder_id
|
| 525 |
+
else:
|
| 526 |
+
nav["placements"].pop(route_id, None)
|
| 527 |
+
return folder_id
|
| 528 |
+
result = _mutate_nav(st, username, routes, change,
|
| 529 |
+
legacy_folders=legacy_folders, legacy_placements=legacy_placements)
|
| 530 |
+
return result
|
| 531 |
+
|
| 532 |
+
|
| 533 |
+
def reorder_routes(st, username, order, routes=(), *, legacy_folders=(), legacy_placements=None):
|
| 534 |
+
offered = [str(value) for value in order or ()]
|
| 535 |
+
def change(nav):
|
| 536 |
+
known = {str((item or {}).get("id")) for item in routes or ()}
|
| 537 |
+
if len(offered) != len(set(offered)) or any(value not in known for value in offered):
|
| 538 |
+
return _NAV_REFUSED
|
| 539 |
+
nav["order"] = [*offered, *(value for value in nav["order"] if value not in offered)]
|
| 540 |
+
return list(nav["order"])
|
| 541 |
+
return _mutate_nav(st, username, routes, change,
|
| 542 |
+
legacy_folders=legacy_folders, legacy_placements=legacy_placements)
|
| 543 |
+
|
| 544 |
+
|
| 545 |
+
def reorder_route_folders(st, username, order, routes=(), *, legacy_folders=(), legacy_placements=None):
|
| 546 |
+
offered = [str(value) for value in order or ()]
|
| 547 |
+
def change(nav):
|
| 548 |
+
known = {item["id"] for item in nav["folders"]}
|
| 549 |
+
if len(offered) != len(set(offered)) or any(value not in known for value in offered):
|
| 550 |
+
return _NAV_REFUSED
|
| 551 |
+
rank = [*offered, *(item["id"] for item in nav["folders"] if item["id"] not in offered)]
|
| 552 |
+
positions = {folder_id: index for index, folder_id in enumerate(rank)}
|
| 553 |
+
nav["folders"].sort(key=lambda item: positions[item["id"]])
|
| 554 |
+
for index, item in enumerate(nav["folders"]):
|
| 555 |
+
item["order"] = index
|
| 556 |
+
return rank
|
| 557 |
+
return _mutate_nav(st, username, routes, change,
|
| 558 |
+
legacy_folders=legacy_folders, legacy_placements=legacy_placements)
|
| 559 |
+
|
| 560 |
+
|
| 561 |
def list_zones(st, rows=None):
|
| 562 |
return [copy.deepcopy(zone) for zone in read(st, rows).get("zones") or [] if isinstance(zone, dict)]
|
| 563 |
|
|
|
|
| 605 |
return put_route(st, {**route, "stops": ids}, tenant_id=tenant_id, created_by=created_by)
|
| 606 |
|
| 607 |
|
| 608 |
+
def set_stop_membership(st, route_id, customer_pid, present, *, tenant_id, created_by):
|
| 609 |
+
"""Add or remove exactly one protected stop without replacing the Route snapshot.
|
| 610 |
+
|
| 611 |
+
The mutation runs inside the store update so two concurrent pin confirmations cannot read the
|
| 612 |
+
same old stop list and then overwrite one another. In particular, callers never submit the
|
| 613 |
+
filtered ``visibleStopIds`` DTO as the full Route: every stop outside the current View remains
|
| 614 |
+
in its original relative order, and ``_route`` re-densifies the resulting relation.
|
| 615 |
+
"""
|
| 616 |
+
pid = _pid(customer_pid)
|
| 617 |
+
route_id = str(route_id or "").strip()
|
| 618 |
+
if pid is None or not isinstance(present, bool) or not route_id:
|
| 619 |
+
return None
|
| 620 |
+
|
| 621 |
+
def mutate(state):
|
| 622 |
+
routes = list(state.get("routes") or [])
|
| 623 |
+
prior_index = next((index for index, item in enumerate(routes)
|
| 624 |
+
if isinstance(item, dict) and item.get("id") == route_id), None)
|
| 625 |
+
if prior_index is None:
|
| 626 |
+
return state, None
|
| 627 |
+
prior = routes[prior_index]
|
| 628 |
+
ids = [stop.get("customerPid") for stop in ordered_stops(prior)]
|
| 629 |
+
if present:
|
| 630 |
+
if pid not in ids:
|
| 631 |
+
ids.append(pid)
|
| 632 |
+
else:
|
| 633 |
+
ids = [item for item in ids if item != pid]
|
| 634 |
+
clean = _route({**prior, "stops": ids}, ordinal=prior_index, created_by=created_by,
|
| 635 |
+
tenant_id=tenant_id, prior=prior)
|
| 636 |
+
if clean is None:
|
| 637 |
+
return state, None
|
| 638 |
+
routes[prior_index] = clean
|
| 639 |
+
state["routes"] = routes
|
| 640 |
+
return state, clean
|
| 641 |
+
|
| 642 |
+
return _persist(st, mutate)
|
| 643 |
+
|
| 644 |
+
|
| 645 |
def delete_route(st, route_id):
|
| 646 |
route_id = str(route_id or "").strip()
|
| 647 |
|
| 648 |
def mutate(state):
|
| 649 |
prior = list(state.get("routes") or [])
|
| 650 |
+
removed_keys = {route_id}
|
| 651 |
+
for item in prior:
|
| 652 |
+
if isinstance(item, dict) and item.get("id") == route_id:
|
| 653 |
+
legacy_key = (item.get("migration") or {}).get("legacyField")
|
| 654 |
+
if legacy_key:
|
| 655 |
+
removed_keys.add(str(legacy_key))
|
| 656 |
state["routes"] = [item for item in prior if not (isinstance(item, dict) and item.get("id") == route_id)]
|
| 657 |
+
navigation = dict(state.get("routeNavigation") or {})
|
| 658 |
+
for username, raw in navigation.items():
|
| 659 |
+
if not isinstance(raw, dict):
|
| 660 |
+
continue
|
| 661 |
+
nav = dict(raw)
|
| 662 |
+
nav["placements"] = {key: value for key, value in (nav.get("placements") or {}).items()
|
| 663 |
+
if str(key) not in removed_keys}
|
| 664 |
+
nav["order"] = [value for value in nav.get("order") or () if str(value) != route_id]
|
| 665 |
+
navigation[username] = nav
|
| 666 |
+
state["routeNavigation"] = navigation
|
| 667 |
return state, len(prior) != len(state["routes"])
|
| 668 |
|
| 669 |
return bool(_persist(st, mutate))
|
|
|
|
| 771 |
return out
|
| 772 |
|
| 773 |
|
| 774 |
+
def legacy_route_plan(fields, cells, *, tenant_id, created_by, ordinal_offset=0):
|
| 775 |
+
"""Project legacy route-order fields without writing the normalized store.
|
| 776 |
+
|
| 777 |
+
The same pure projection feeds the explicit parity migration and the compatibility read path.
|
| 778 |
+
A field key becomes the stable Route id, so repeated GETs cannot manufacture duplicate Routes.
|
| 779 |
+
"""
|
| 780 |
plans = []
|
| 781 |
+
for key, definition in sorted((fields or {}).items(), key=lambda item: str(item[0])):
|
| 782 |
if not isinstance(definition, dict) or definition.get("kind") != "route_order":
|
| 783 |
continue
|
| 784 |
migration_mark = definition.get("legacyRouteMigration")
|
|
|
|
| 798 |
continue
|
| 799 |
plan = _route({"id": "legacy_" + str(key)[:72], "name": definition.get("label") or key,
|
| 800 |
"color": definition.get("color"),
|
| 801 |
+
"shareKey": key,
|
| 802 |
"sourceViewId": (definition.get("route") or {}).get("sourceViewId"),
|
| 803 |
"sourceViewRevision": (definition.get("route") or {}).get("inputsHash"),
|
| 804 |
"stops": [pid for _rank, pid in ranks],
|
| 805 |
"migration": {"legacyField": key, "verified": True}},
|
| 806 |
+
ordinal=max(0, int(ordinal_offset)) + len(plans),
|
| 807 |
+
tenant_id=tenant_id,
|
| 808 |
+
created_by=definition.get("createdBy") or created_by)
|
| 809 |
if plan is not None:
|
| 810 |
plans.append({"field": key, "route": plan,
|
| 811 |
"expected": {pid: rank for rank, pid in ranks}})
|
| 812 |
return plans
|
| 813 |
|
| 814 |
|
| 815 |
+
def compatible_routes(routes, fields, cells, *, tenant_id, created_by):
|
| 816 |
+
"""Read-through view of normalized Routes plus still-live legacy route-order fields.
|
| 817 |
+
|
| 818 |
+
This function is intentionally store-free. Listing a Route must never mutate tenant data or
|
| 819 |
+
require an administrator to run a migration first. If an independently verified migration
|
| 820 |
+
already produced the same stable ``legacy_<field>`` id, the normalized record wins and the
|
| 821 |
+
compatibility projection disappears rather than rendering a duplicate.
|
| 822 |
+
"""
|
| 823 |
+
out = [copy.deepcopy(route) for route in routes or () if isinstance(route, dict)]
|
| 824 |
+
existing_ids = {str(route.get("id") or "") for route in out}
|
| 825 |
+
last_number = max(
|
| 826 |
+
(int(route.get("number") or 0) for route in out
|
| 827 |
+
if str(route.get("number") or "").lstrip("-").isdigit()),
|
| 828 |
+
default=0,
|
| 829 |
+
)
|
| 830 |
+
plans = legacy_route_plan(
|
| 831 |
+
fields, cells, tenant_id=tenant_id, created_by=created_by,
|
| 832 |
+
ordinal_offset=last_number,
|
| 833 |
+
)
|
| 834 |
+
for plan in plans:
|
| 835 |
+
route = plan.get("route") if isinstance(plan, dict) else None
|
| 836 |
+
if not isinstance(route, dict) or str(route.get("id") or "") in existing_ids:
|
| 837 |
+
continue
|
| 838 |
+
existing_ids.add(str(route.get("id") or ""))
|
| 839 |
+
# Transient marker only: a compatibility projection has no normalized write target yet.
|
| 840 |
+
# A successfully migrated Route with this same stable id remains an ordinary editable
|
| 841 |
+
# normalized record because it wins above and never receives this marker.
|
| 842 |
+
out.append({**copy.deepcopy(route), "compatibility": "legacy-route-order"})
|
| 843 |
+
return out
|
| 844 |
+
|
| 845 |
+
|
| 846 |
def migrate_legacy_routes(st, fields, cells, *, tenant_id, created_by, zones=()):
|
| 847 |
"""Persist copied Routes and prove count/member/order/projection parity before hiding fields."""
|
| 848 |
+
current_routes = list_routes(st)
|
| 849 |
+
last_number = max((int(route.get("number") or 0) for route in current_routes), default=0)
|
| 850 |
+
plans = legacy_route_plan(
|
| 851 |
+
fields, cells, tenant_id=tenant_id, created_by=created_by,
|
| 852 |
+
ordinal_offset=last_number,
|
| 853 |
+
)
|
| 854 |
if not plans:
|
| 855 |
return {"migrated": [], "verified": {}, "hide": []}
|
| 856 |
|
platform/core/shared_overlay.py
CHANGED
|
@@ -101,7 +101,8 @@ ALLOWED_FIELD_KEYS = frozenset({
|
|
| 101 |
'note', 'description', '_note',
|
| 102 |
# display and behaviour
|
| 103 |
'format', 'agg', 'options', 'optionColors', 'colorCodeOptions', 'default', 'pinned',
|
| 104 |
-
'filterable', 'multi', 'max', 'derived', 'preset', 'custom', 'profile', 'link',
|
|
|
|
| 105 |
# the created strata's computation bags
|
| 106 |
'formula', 'measure', 'metric', 'rollup', 'geocode', 'code', 'automation', 'aiEnrich',
|
| 107 |
'scope',
|
|
@@ -148,6 +149,17 @@ def _read(table_key, st=None):
|
|
| 148 |
'cells': dict(data.get('cells') or {})}
|
| 149 |
|
| 150 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 151 |
def _write(table_key, change, st=None, flush='async'):
|
| 152 |
"""Read-modify-write one shared stratum.
|
| 153 |
|
|
@@ -188,14 +200,15 @@ def _value(value):
|
|
| 188 |
|
| 189 |
|
| 190 |
# ----------------------------------------------------------------- the column DEFINITIONS
|
| 191 |
-
def fields(table_key, st=None):
|
| 192 |
"""`{field_key: Field}` β the columns this topic shares tenant-wide.
|
| 193 |
|
| 194 |
Unscoped on purpose, and it is the one thing here that is: a shared column's EXISTENCE is
|
| 195 |
tenant-wide by definition β that is the whole feature, and it is what stops a shared view
|
| 196 |
naming a column half the workspace lacks. Its VALUES are scoped by `cells()`.
|
| 197 |
"""
|
| 198 |
-
|
|
|
|
| 199 |
|
| 200 |
|
| 201 |
def is_shared(table_key, field_key, st=None):
|
|
@@ -482,6 +495,90 @@ def put_cells_and_choice_options(table_key, pid, values, choice_values, st=None)
|
|
| 482 |
return clean
|
| 483 |
|
| 484 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 485 |
def put_rows(table_key, rows, st=None):
|
| 486 |
"""Write shared cells on MANY rows in ONE store update. Returns `{row_id: {key: value}}`.
|
| 487 |
|
|
|
|
| 101 |
'note', 'description', '_note',
|
| 102 |
# display and behaviour
|
| 103 |
'format', 'agg', 'options', 'optionColors', 'colorCodeOptions', 'default', 'pinned',
|
| 104 |
+
'filterable', 'offerable', 'multi', 'max', 'derived', 'preset', 'custom', 'profile', 'link',
|
| 105 |
+
'recurrence',
|
| 106 |
# the created strata's computation bags
|
| 107 |
'formula', 'measure', 'metric', 'rollup', 'geocode', 'code', 'automation', 'aiEnrich',
|
| 108 |
'scope',
|
|
|
|
| 149 |
'cells': dict(data.get('cells') or {})}
|
| 150 |
|
| 151 |
|
| 152 |
+
def document(table_key, st=None):
|
| 153 |
+
"""One captured shared-stratum document for consumers in a single request.
|
| 154 |
+
|
| 155 |
+
A field-contract assembly asks three questions of the same small bucket: reconcile its
|
| 156 |
+
stored permission word, merge its definitions, and classify the resulting fields. They are
|
| 157 |
+
one request's view of one document, so reopening it for each question buys no freshness and
|
| 158 |
+
pays three deep copies. Callers that do not hold one keep the historical read path.
|
| 159 |
+
"""
|
| 160 |
+
return _read(table_key, st=st)
|
| 161 |
+
|
| 162 |
+
|
| 163 |
def _write(table_key, change, st=None, flush='async'):
|
| 164 |
"""Read-modify-write one shared stratum.
|
| 165 |
|
|
|
|
| 200 |
|
| 201 |
|
| 202 |
# ----------------------------------------------------------------- the column DEFINITIONS
|
| 203 |
+
def fields(table_key, st=None, document=None):
|
| 204 |
"""`{field_key: Field}` β the columns this topic shares tenant-wide.
|
| 205 |
|
| 206 |
Unscoped on purpose, and it is the one thing here that is: a shared column's EXISTENCE is
|
| 207 |
tenant-wide by definition β that is the whole feature, and it is what stops a shared view
|
| 208 |
naming a column half the workspace lacks. Its VALUES are scoped by `cells()`.
|
| 209 |
"""
|
| 210 |
+
data = document if isinstance(document, dict) else _read(table_key, st)
|
| 211 |
+
return dict(data.get('fields') or {})
|
| 212 |
|
| 213 |
|
| 214 |
def is_shared(table_key, field_key, st=None):
|
|
|
|
| 495 |
return clean
|
| 496 |
|
| 497 |
|
| 498 |
+
def transpose_rank(table_key, pid, field_key, rank, pids, st=None):
|
| 499 |
+
"""Atomically assign one positive integer rank within an explicitly scoped row set.
|
| 500 |
+
|
| 501 |
+
If another scoped row holds ``rank``, that row receives this row's prior rank. A row that did
|
| 502 |
+
not previously have a rank sends the displaced holder to ``max + 1``. The returned ``swap``
|
| 503 |
+
is shaped for the HTTP caller that must invalidate the other row it changed.
|
| 504 |
+
|
| 505 |
+
The scope is required for the same reason it is required by :func:`cells`: this persistence
|
| 506 |
+
primitive must never discover or mutate a row the caller was not already allowed to see.
|
| 507 |
+
|
| 508 |
+
The read and both writes deliberately live inside ONE ``store.update`` callback. Reading the
|
| 509 |
+
ranks first and then calling :func:`put_rows` is not equivalent: two concurrent requests can
|
| 510 |
+
both choose a holder from the same stale snapshot, serialize their precomputed writes, and
|
| 511 |
+
leave duplicate ranks. Both the Postgres row lock and the HF conflict-replay path protect the
|
| 512 |
+
callback itself, so the second request computes against the first request's landed result.
|
| 513 |
+
"""
|
| 514 |
+
row_id = _pid(pid)
|
| 515 |
+
key = str(field_key or '').strip()
|
| 516 |
+
if not key:
|
| 517 |
+
raise ValueError('shared_overlay.transpose_rank: a field key is required')
|
| 518 |
+
if isinstance(rank, bool):
|
| 519 |
+
raise ValueError('shared_overlay.transpose_rank: a rank is a positive whole number')
|
| 520 |
+
try:
|
| 521 |
+
want = int(rank)
|
| 522 |
+
except (TypeError, ValueError) as exc:
|
| 523 |
+
raise ValueError(
|
| 524 |
+
'shared_overlay.transpose_rank: a rank is a positive whole number') from exc
|
| 525 |
+
if want < 1:
|
| 526 |
+
raise ValueError('shared_overlay.transpose_rank: a rank is a positive whole number')
|
| 527 |
+
try:
|
| 528 |
+
scope = {_pid(item) for item in pids}
|
| 529 |
+
except TypeError as exc:
|
| 530 |
+
raise ValueError(
|
| 531 |
+
'shared_overlay.transpose_rank: scoped pids are required') from exc
|
| 532 |
+
if row_id not in scope:
|
| 533 |
+
raise ValueError(
|
| 534 |
+
'shared_overlay.transpose_rank: the target pid must be in the scoped row set')
|
| 535 |
+
|
| 536 |
+
outcome = {}
|
| 537 |
+
|
| 538 |
+
def _transpose(data):
|
| 539 |
+
# Numeric pid order makes the holder deterministic if an already-corrupt document has
|
| 540 |
+
# more than one. A healthy route has at most one; this function preserves that invariant.
|
| 541 |
+
ordered_scope = sorted(scope, key=int)
|
| 542 |
+
held = {}
|
| 543 |
+
for scoped_pid in ordered_scope:
|
| 544 |
+
row = data['cells'].get(scoped_pid)
|
| 545 |
+
if not isinstance(row, dict):
|
| 546 |
+
continue
|
| 547 |
+
value = row.get(key)
|
| 548 |
+
if value in (None, ''):
|
| 549 |
+
continue
|
| 550 |
+
try:
|
| 551 |
+
held[scoped_pid] = int(str(value).strip())
|
| 552 |
+
except (TypeError, ValueError):
|
| 553 |
+
continue
|
| 554 |
+
|
| 555 |
+
prior = held.get(row_id)
|
| 556 |
+
max_rank = max(held.values(), default=0)
|
| 557 |
+
holder = None if prior == want else next(
|
| 558 |
+
(other_pid for other_pid in ordered_scope
|
| 559 |
+
if other_pid != row_id and held.get(other_pid) == want),
|
| 560 |
+
None)
|
| 561 |
+
moved = None
|
| 562 |
+
|
| 563 |
+
data['cells'].setdefault(row_id, {})[key] = str(want)
|
| 564 |
+
if holder is not None:
|
| 565 |
+
moved = prior if prior is not None else max_rank + 1
|
| 566 |
+
data['cells'].setdefault(holder, {})[key] = str(moved)
|
| 567 |
+
|
| 568 |
+
# ``store.update`` may replay this callback over a newer HF document. Replace, rather
|
| 569 |
+
# than append to, the captured outcome so the caller receives the final replay's truth.
|
| 570 |
+
outcome.clear()
|
| 571 |
+
outcome.update({
|
| 572 |
+
'value': str(want),
|
| 573 |
+
'prior': '' if prior is None else str(prior),
|
| 574 |
+
'swap': ({'pid': int(holder), 'field': key, 'value': str(moved)}
|
| 575 |
+
if holder is not None else None),
|
| 576 |
+
})
|
| 577 |
+
|
| 578 |
+
_write(table_key, _transpose, st, flush='sync')
|
| 579 |
+
return dict(outcome)
|
| 580 |
+
|
| 581 |
+
|
| 582 |
def put_rows(table_key, rows, st=None):
|
| 583 |
"""Write shared cells on MANY rows in ONE store update. Returns `{row_id: {key: value}}`.
|
| 584 |
|
platform/core/table_store.py
CHANGED
|
@@ -1153,25 +1153,44 @@ class TableStore:
|
|
| 1153 |
"""Persist cell updates and newly admitted choice labels in one workspace update.
|
| 1154 |
|
| 1155 |
The event wall has already checked field visibility, edit permission, label size, and the
|
| 1156 |
-
50-choice cap. This method owns only residency and atomicity:
|
| 1157 |
-
|
| 1158 |
-
|
|
|
|
|
|
|
|
|
|
| 1159 |
"""
|
| 1160 |
clean = dict(updates or {})
|
|
|
|
| 1161 |
additions = {str(key): list(values or ()) for key, values in
|
| 1162 |
-
(choice_values or {}).items()
|
|
|
|
| 1163 |
if not clean:
|
| 1164 |
return
|
| 1165 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1166 |
def _patch(ws):
|
| 1167 |
-
ws['overlays'].setdefault(str(int(pid)), {}).update(
|
| 1168 |
-
if not
|
| 1169 |
return
|
| 1170 |
# Import here rather than at module load: `aios_grid` is intentionally independent
|
| 1171 |
# of `core`, while this lower persistence layer may use its pure canonical cleaner.
|
| 1172 |
from aios_grid import merge_choice_options
|
| 1173 |
fields = ws.setdefault('fields', {})
|
| 1174 |
-
for key, values in
|
| 1175 |
prior = fields.get(key)
|
| 1176 |
entry = dict(prior) if isinstance(prior, dict) else {}
|
| 1177 |
entry['options'] = merge_choice_options(entry.get('options'), values)
|
|
|
|
| 1153 |
"""Persist cell updates and newly admitted choice labels in one workspace update.
|
| 1154 |
|
| 1155 |
The event wall has already checked field visibility, edit permission, label size, and the
|
| 1156 |
+
50-choice cap. This method owns only residency and atomicity: each cell and its vocabulary
|
| 1157 |
+
must land together in the stratum that owns the field. A shared value written into the
|
| 1158 |
+
caller's private workspace is shadowed by the shared read layer and therefore appears to
|
| 1159 |
+
reset after refresh (D-423); a private option written into the shared schema leaks another
|
| 1160 |
+
user's vocabulary. Choice additions are admitted only beside an update for the same key,
|
| 1161 |
+
so a stale or mismatched additions bag cannot resurrect a field in either stratum.
|
| 1162 |
"""
|
| 1163 |
clean = dict(updates or {})
|
| 1164 |
+
clean_keys = {str(key) for key in clean if str(key)}
|
| 1165 |
additions = {str(key): list(values or ()) for key, values in
|
| 1166 |
+
(choice_values or {}).items()
|
| 1167 |
+
if str(key) in clean_keys and values}
|
| 1168 |
if not clean:
|
| 1169 |
return
|
| 1170 |
|
| 1171 |
+
wide = self._tenant_wide_keys()
|
| 1172 |
+
shared = {key: value for key, value in clean.items() if key in wide}
|
| 1173 |
+
personal = {key: value for key, value in clean.items() if key not in wide}
|
| 1174 |
+
shared_additions = {key: values for key, values in additions.items() if key in shared}
|
| 1175 |
+
personal_additions = {key: values for key, values in additions.items() if key in personal}
|
| 1176 |
+
|
| 1177 |
+
if shared:
|
| 1178 |
+
import core.shared_overlay as shared_overlay
|
| 1179 |
+
shared_overlay.put_cells_and_choice_options(
|
| 1180 |
+
self.table_key, pid, shared, shared_additions, st=self._st)
|
| 1181 |
+
|
| 1182 |
+
if not personal:
|
| 1183 |
+
return
|
| 1184 |
+
|
| 1185 |
def _patch(ws):
|
| 1186 |
+
ws['overlays'].setdefault(str(int(pid)), {}).update(personal)
|
| 1187 |
+
if not personal_additions:
|
| 1188 |
return
|
| 1189 |
# Import here rather than at module load: `aios_grid` is intentionally independent
|
| 1190 |
# of `core`, while this lower persistence layer may use its pure canonical cleaner.
|
| 1191 |
from aios_grid import merge_choice_options
|
| 1192 |
fields = ws.setdefault('fields', {})
|
| 1193 |
+
for key, values in personal_additions.items():
|
| 1194 |
prior = fields.get(key)
|
| 1195 |
entry = dict(prior) if isinstance(prior, dict) else {}
|
| 1196 |
entry['options'] = merge_choice_options(entry.get('options'), values)
|
platform/core/user_tables.py
CHANGED
|
@@ -52,6 +52,7 @@ import re
|
|
| 52 |
import uuid as _uuid
|
| 53 |
|
| 54 |
import core.store as store
|
|
|
|
| 55 |
|
| 56 |
STORE_KEY = 'user_tables'
|
| 57 |
ZONE_STORE_KEY = 'table_zones'
|
|
@@ -814,10 +815,19 @@ FIELD_AGGS = ('sum', 'average', 'median', 'min', 'max', 'count')
|
|
| 814 |
#: A choice colour, as the client's editor spells one. `#RRGGBB`, upper-cased on the way in so a
|
| 815 |
#: stored value has exactly ONE spelling and two fields cannot disagree about `#ebf6ef`.
|
| 816 |
_OPTION_COLOR_RE = re.compile(r'#[0-9A-F]{6}')
|
| 817 |
-
_MAX_CHOICE_OPTIONS = 50
|
| 818 |
_MAX_CHOICE_LABEL = 60
|
| 819 |
|
| 820 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 821 |
def _clean_option_colors(raw, options):
|
| 822 |
"""`{option label β #RRGGBB}`, capped to the field's own option vocabulary (wave-29 C1).
|
| 823 |
|
|
@@ -890,7 +900,7 @@ def _hydrate_choice_options(fields, value_maps):
|
|
| 890 |
continue
|
| 891 |
for option in _choice_values(field, values[key]):
|
| 892 |
folded = option.casefold()
|
| 893 |
-
if folded in known or len(options) >=
|
| 894 |
continue
|
| 895 |
options.append(option)
|
| 896 |
known.add(folded)
|
|
@@ -980,8 +990,12 @@ def clean_fields(raw):
|
|
| 980 |
if note:
|
| 981 |
entry['note'] = note
|
| 982 |
if ftype in ('select', 'multiselect'):
|
|
|
|
|
|
|
| 983 |
opts = [' '.join(str(o).split())[:60] for o in (f.get('options') or [])
|
| 984 |
-
if str(o).strip()]
|
|
|
|
|
|
|
| 985 |
entry['options'] = opts
|
| 986 |
if f.get('default') is True:
|
| 987 |
entry['default'] = True
|
|
@@ -1159,7 +1173,9 @@ def get(table_key, st=None):
|
|
| 1159 |
_ZONE_ID_RE = re.compile(r'^[A-Za-z0-9_-]{1,96}$')
|
| 1160 |
_ZONE_FIELD_RE = re.compile(r'^[A-Za-z][A-Za-z0-9_]{0,79}$')
|
| 1161 |
_ZONE_COLOR_RE = re.compile(r'^#[0-9A-Fa-f]{6}$')
|
|
|
|
| 1162 |
_ZONE_GEOMETRIES = frozenset({'Polygon', 'MultiPolygon'})
|
|
|
|
| 1163 |
|
| 1164 |
|
| 1165 |
def _zone_position(raw):
|
|
@@ -1218,11 +1234,25 @@ def clean_zone(raw, field_keys=None, allowed_row_ids=None):
|
|
| 1218 |
# cannot be legal inside one Zone label without making one Zone appear as two filter choices.
|
| 1219 |
name = ' '.join(str(raw.get('name') or '').replace(',', ' ').split())[:120]
|
| 1220 |
geometry = _clean_zone_geometry(raw.get('geometryGeoJson'))
|
| 1221 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1222 |
return None
|
| 1223 |
out = {'name': name,
|
| 1224 |
'color': (str(raw.get('color') or '#1F4E78').upper()),
|
| 1225 |
'geometryGeoJson': geometry,
|
|
|
|
| 1226 |
'visible': raw.get('visible') is not False}
|
| 1227 |
if not _ZONE_COLOR_RE.fullmatch(out['color']):
|
| 1228 |
return None
|
|
@@ -1948,6 +1978,117 @@ def is_linkable_target(table_key):
|
|
| 1948 |
return key.startswith(KEY_PREFIX) and len(key) > len(KEY_PREFIX)
|
| 1949 |
|
| 1950 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1951 |
def _clean_link(raw):
|
| 1952 |
"""One `link` bag β the stored shape, or None (refused).
|
| 1953 |
|
|
@@ -2007,6 +2148,15 @@ def _clean_link(raw):
|
|
| 2007 |
# than dropped: a bag half of which is silently ignored is [[wrong-parent-not-broken-control]]
|
| 2008 |
# with the control still on screen.
|
| 2009 |
return None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2010 |
if reciprocal:
|
| 2011 |
out['reciprocal'] = reciprocal
|
| 2012 |
if raw.get('single') is True:
|
|
@@ -2558,7 +2708,9 @@ def _clean_field(raw, previous=None):
|
|
| 2558 |
# a valid, new select indistinguishable from a malformed text field on its read path.
|
| 2559 |
# Keep the empty list deliberately: the type is the contract; options are its current
|
| 2560 |
# vocabulary, not a prerequisite for the column to exist.
|
| 2561 |
-
opts = [' '.join(str(o).split())[:60] for o in (opts_raw or []) if str(o).strip()]
|
|
|
|
|
|
|
| 2562 |
out['options'] = opts
|
| 2563 |
# ββ WAVE-29 CONTRACT C1 (owner item 13) β **THE OPTION COLOURS, WHICH THIS DOOR DROPPED.**
|
| 2564 |
#
|
|
|
|
| 52 |
import uuid as _uuid
|
| 53 |
|
| 54 |
import core.store as store
|
| 55 |
+
from core.route_system import MAX_OPTIONS
|
| 56 |
|
| 57 |
STORE_KEY = 'user_tables'
|
| 58 |
ZONE_STORE_KEY = 'table_zones'
|
|
|
|
| 815 |
#: A choice colour, as the client's editor spells one. `#RRGGBB`, upper-cased on the way in so a
|
| 816 |
#: stored value has exactly ONE spelling and two fields cannot disagree about `#ebf6ef`.
|
| 817 |
_OPTION_COLOR_RE = re.compile(r'#[0-9A-F]{6}')
|
|
|
|
| 818 |
_MAX_CHOICE_LABEL = 60
|
| 819 |
|
| 820 |
|
| 821 |
+
def option_cap_refusal(raw_options):
|
| 822 |
+
"""Name an over-cap choice declaration, including entered, limit, and rejected counts."""
|
| 823 |
+
entered = len([option for option in (raw_options or []) if str(option).strip()])
|
| 824 |
+
if entered <= MAX_OPTIONS:
|
| 825 |
+
return None
|
| 826 |
+
rejected = entered - MAX_OPTIONS
|
| 827 |
+
return (f'That column declares {entered} options; the server limit is {MAX_OPTIONS}, so '
|
| 828 |
+
f'{rejected} would be rejected. Remove {rejected} options, then save.')
|
| 829 |
+
|
| 830 |
+
|
| 831 |
def _clean_option_colors(raw, options):
|
| 832 |
"""`{option label β #RRGGBB}`, capped to the field's own option vocabulary (wave-29 C1).
|
| 833 |
|
|
|
|
| 900 |
continue
|
| 901 |
for option in _choice_values(field, values[key]):
|
| 902 |
folded = option.casefold()
|
| 903 |
+
if folded in known or len(options) >= MAX_OPTIONS:
|
| 904 |
continue
|
| 905 |
options.append(option)
|
| 906 |
known.add(folded)
|
|
|
|
| 990 |
if note:
|
| 991 |
entry['note'] = note
|
| 992 |
if ftype in ('select', 'multiselect'):
|
| 993 |
+
# Refuse the field instead of storing a silently shortened vocabulary. This list
|
| 994 |
+
# validator already drops one malformed field while preserving valid siblings.
|
| 995 |
opts = [' '.join(str(o).split())[:60] for o in (f.get('options') or [])
|
| 996 |
+
if str(o).strip()]
|
| 997 |
+
if len(opts) > MAX_OPTIONS:
|
| 998 |
+
continue
|
| 999 |
entry['options'] = opts
|
| 1000 |
if f.get('default') is True:
|
| 1001 |
entry['default'] = True
|
|
|
|
| 1173 |
_ZONE_ID_RE = re.compile(r'^[A-Za-z0-9_-]{1,96}$')
|
| 1174 |
_ZONE_FIELD_RE = re.compile(r'^[A-Za-z][A-Za-z0-9_]{0,79}$')
|
| 1175 |
_ZONE_COLOR_RE = re.compile(r'^#[0-9A-Fa-f]{6}$')
|
| 1176 |
+
_ZONE_ZIP_RE = re.compile(r'^\d{5}(?:-\d{4})?$')
|
| 1177 |
_ZONE_GEOMETRIES = frozenset({'Polygon', 'MultiPolygon'})
|
| 1178 |
+
MAX_ZONE_ZIP_CODES = 500
|
| 1179 |
|
| 1180 |
|
| 1181 |
def _zone_position(raw):
|
|
|
|
| 1234 |
# cannot be legal inside one Zone label without making one Zone appear as two filter choices.
|
| 1235 |
name = ' '.join(str(raw.get('name') or '').replace(',', ' ').split())[:120]
|
| 1236 |
geometry = _clean_zone_geometry(raw.get('geometryGeoJson'))
|
| 1237 |
+
raw_zips = raw.get('zipCodes') or []
|
| 1238 |
+
if not isinstance(raw_zips, (list, tuple)) or len(raw_zips) > MAX_ZONE_ZIP_CODES:
|
| 1239 |
+
return None
|
| 1240 |
+
zip_codes, seen_zips = [], set()
|
| 1241 |
+
for value in raw_zips:
|
| 1242 |
+
zip_code = str(value or '').strip().upper()
|
| 1243 |
+
if not _ZONE_ZIP_RE.fullmatch(zip_code):
|
| 1244 |
+
return None
|
| 1245 |
+
if zip_code not in seen_zips:
|
| 1246 |
+
seen_zips.add(zip_code)
|
| 1247 |
+
zip_codes.append(zip_code)
|
| 1248 |
+
# Existing polygon Zones remain valid byte-for-byte. Wave 44 also permits a ZIP-only Zone;
|
| 1249 |
+
# the two shapes share this record rather than inventing a second persistence model.
|
| 1250 |
+
if not name or (geometry is None and not zip_codes):
|
| 1251 |
return None
|
| 1252 |
out = {'name': name,
|
| 1253 |
'color': (str(raw.get('color') or '#1F4E78').upper()),
|
| 1254 |
'geometryGeoJson': geometry,
|
| 1255 |
+
'zipCodes': zip_codes,
|
| 1256 |
'visible': raw.get('visible') is not False}
|
| 1257 |
if not _ZONE_COLOR_RE.fullmatch(out['color']):
|
| 1258 |
return None
|
|
|
|
| 1978 |
return key.startswith(KEY_PREFIX) and len(key) > len(KEY_PREFIX)
|
| 1979 |
|
| 1980 |
|
| 1981 |
+
# W42-T03 / R1 / C1: a user-created link may carry exactly one governed semantic hop.
|
| 1982 |
+
# Keep this tuple tied to the literal reads in `_clean_via`: verify_pivot extracts those reads
|
| 1983 |
+
# from the AST and compares them to both this allow-list and the client emitter.
|
| 1984 |
+
LINK_VIA_KEYS = ('topic', 'source_dim', 'target_dim', 'target_key', 'scope_key', 'measure',
|
| 1985 |
+
'filter', 'filterConj', 'window')
|
| 1986 |
+
LINK_VIA_CONJ = ('and', 'or')
|
| 1987 |
+
LINK_VIA_WINDOWS = ROLLUP_SOURCE_WINDOWS
|
| 1988 |
+
|
| 1989 |
+
|
| 1990 |
+
def _topic_dims(topic):
|
| 1991 |
+
"""Return model-declared dimensions without opening a tenant store; fail closed."""
|
| 1992 |
+
if not topic:
|
| 1993 |
+
return None
|
| 1994 |
+
try:
|
| 1995 |
+
from harness import semantic as _sem
|
| 1996 |
+
definition = (_sem.topics() or {}).get(topic)
|
| 1997 |
+
except Exception:
|
| 1998 |
+
return None
|
| 1999 |
+
if not definition:
|
| 2000 |
+
return None
|
| 2001 |
+
dims = ((definition.get('store') or {}).get('dims')) or {}
|
| 2002 |
+
return frozenset(dims) or None
|
| 2003 |
+
|
| 2004 |
+
|
| 2005 |
+
def _clean_via_filter(raw, depth=1, budget=None):
|
| 2006 |
+
"""Shape-check a hop filter without silently trimming a widening condition."""
|
| 2007 |
+
import aios_grid as _agv
|
| 2008 |
+
if budget is None:
|
| 2009 |
+
budget = [_agv.MAX_FILTER_NODES]
|
| 2010 |
+
if not isinstance(raw, list) or len(raw) > _agv.MAX_FILTER_SIBLINGS:
|
| 2011 |
+
return None
|
| 2012 |
+
out = []
|
| 2013 |
+
for node in raw:
|
| 2014 |
+
if not isinstance(node, dict):
|
| 2015 |
+
return None
|
| 2016 |
+
budget[0] -= 1
|
| 2017 |
+
if budget[0] < 0:
|
| 2018 |
+
return None
|
| 2019 |
+
children = node.get('children')
|
| 2020 |
+
if isinstance(children, list):
|
| 2021 |
+
if depth >= _agv.MAX_FILTER_DEPTH:
|
| 2022 |
+
return None
|
| 2023 |
+
kids = _clean_via_filter(children, depth + 1, budget)
|
| 2024 |
+
if kids is None:
|
| 2025 |
+
return None
|
| 2026 |
+
out.append({'conj': 'or' if node.get('conj') == 'or' else 'and',
|
| 2027 |
+
'children': kids})
|
| 2028 |
+
continue
|
| 2029 |
+
leaf = {}
|
| 2030 |
+
for key, value in node.items():
|
| 2031 |
+
if not isinstance(key, str):
|
| 2032 |
+
return None
|
| 2033 |
+
if isinstance(value, str):
|
| 2034 |
+
leaf[key] = value[:500]
|
| 2035 |
+
elif isinstance(value, (int, float, bool)) or value is None:
|
| 2036 |
+
leaf[key] = value
|
| 2037 |
+
elif isinstance(value, (list, dict)):
|
| 2038 |
+
leaf[key] = value
|
| 2039 |
+
else:
|
| 2040 |
+
return None
|
| 2041 |
+
out.append(leaf)
|
| 2042 |
+
return out
|
| 2043 |
+
|
| 2044 |
+
|
| 2045 |
+
def _clean_via(raw):
|
| 2046 |
+
"""One semantic `via` bag, or None. Nested hops and partial bags are refused."""
|
| 2047 |
+
if not isinstance(raw, dict):
|
| 2048 |
+
return None
|
| 2049 |
+
if 'via' in raw:
|
| 2050 |
+
return None
|
| 2051 |
+
for key in raw:
|
| 2052 |
+
if key not in LINK_VIA_KEYS:
|
| 2053 |
+
return None
|
| 2054 |
+
# These are deliberately literal reads: verify_pivot mechanically extracts the accepted set.
|
| 2055 |
+
topic = str(raw.get('topic') or '').strip()
|
| 2056 |
+
dims = _topic_dims(topic)
|
| 2057 |
+
if not dims:
|
| 2058 |
+
return None
|
| 2059 |
+
source_dim = str(raw.get('source_dim') or '').strip()
|
| 2060 |
+
target_dim = str(raw.get('target_dim') or '').strip()
|
| 2061 |
+
if source_dim not in dims or target_dim not in dims:
|
| 2062 |
+
return None
|
| 2063 |
+
# Required target/scope identities are not topic dimensions and are never defaulted.
|
| 2064 |
+
target_key = _field_key(raw.get('target_key'))
|
| 2065 |
+
scope_key = _field_key(raw.get('scope_key'))
|
| 2066 |
+
measure = _field_key(raw.get('measure'))
|
| 2067 |
+
if not target_key or not scope_key or not measure:
|
| 2068 |
+
return None
|
| 2069 |
+
out = {'topic': topic, 'source_dim': source_dim, 'target_dim': target_dim,
|
| 2070 |
+
'target_key': target_key, 'scope_key': scope_key, 'measure': measure}
|
| 2071 |
+
raw_filter = raw.get('filter')
|
| 2072 |
+
if raw_filter is not None:
|
| 2073 |
+
nodes = _clean_via_filter(raw_filter)
|
| 2074 |
+
if nodes is None:
|
| 2075 |
+
return None
|
| 2076 |
+
out['filter'] = nodes
|
| 2077 |
+
raw_conj = raw.get('filterConj')
|
| 2078 |
+
if raw_conj is not None:
|
| 2079 |
+
conj = str(raw_conj).strip().lower()
|
| 2080 |
+
if conj not in LINK_VIA_CONJ:
|
| 2081 |
+
return None
|
| 2082 |
+
out['filterConj'] = conj
|
| 2083 |
+
raw_window = raw.get('window')
|
| 2084 |
+
if raw_window is not None:
|
| 2085 |
+
window = str(raw_window).strip().lower()
|
| 2086 |
+
if window not in LINK_VIA_WINDOWS:
|
| 2087 |
+
return None
|
| 2088 |
+
out['window'] = window
|
| 2089 |
+
return out
|
| 2090 |
+
|
| 2091 |
+
|
| 2092 |
def _clean_link(raw):
|
| 2093 |
"""One `link` bag β the stored shape, or None (refused).
|
| 2094 |
|
|
|
|
| 2148 |
# than dropped: a bag half of which is silently ignored is [[wrong-parent-not-broken-control]]
|
| 2149 |
# with the control still on screen.
|
| 2150 |
return None
|
| 2151 |
+
# A semantic hop is meaningful only on a derived link with a first join to travel from.
|
| 2152 |
+
# Its absence preserves the historical one-hop bag byte-for-byte.
|
| 2153 |
+
if raw.get('via') is not None:
|
| 2154 |
+
if 'on' not in out:
|
| 2155 |
+
return None
|
| 2156 |
+
via = _clean_via(raw.get('via'))
|
| 2157 |
+
if via is None:
|
| 2158 |
+
return None
|
| 2159 |
+
out['via'] = via
|
| 2160 |
if reciprocal:
|
| 2161 |
out['reciprocal'] = reciprocal
|
| 2162 |
if raw.get('single') is True:
|
|
|
|
| 2708 |
# a valid, new select indistinguishable from a malformed text field on its read path.
|
| 2709 |
# Keep the empty list deliberately: the type is the contract; options are its current
|
| 2710 |
# vocabulary, not a prerequisite for the column to exist.
|
| 2711 |
+
opts = [' '.join(str(o).split())[:60] for o in (opts_raw or []) if str(o).strip()]
|
| 2712 |
+
if len(opts) > MAX_OPTIONS:
|
| 2713 |
+
return None
|
| 2714 |
out['options'] = opts
|
| 2715 |
# ββ WAVE-29 CONTRACT C1 (owner item 13) β **THE OPTION COLOURS, WHICH THIS DOOR DROPPED.**
|
| 2716 |
#
|
platform/harness/semantic.py
CHANGED
|
@@ -71,6 +71,15 @@ class ModelError(Exception):
|
|
| 71 |
"""A model-file problem (unknown key, bad reference, unparseable expr)."""
|
| 72 |
|
| 73 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 74 |
# ---------------------------------------------------------------- loading
|
| 75 |
|
| 76 |
@functools.lru_cache(maxsize=1)
|
|
@@ -456,7 +465,7 @@ def _post_compute(row, key):
|
|
| 456 |
_FORMAT_TYPE = {"usd": "currency", "int": "int", "pct": "pct"}
|
| 457 |
|
| 458 |
|
| 459 |
-
def _clean_tree(tree, cols):
|
| 460 |
"""Run a filter tree through the SAME validator the client's view state goes through.
|
| 461 |
|
| 462 |
`filter_sql`'s documented input contract is "feed me CLEANED trees" β it is faithful to the
|
|
@@ -470,6 +479,9 @@ def _clean_tree(tree, cols):
|
|
| 470 |
module with zero imports of its own, so this cannot cycle.
|
| 471 |
"""
|
| 472 |
from aios_grid import (clean_filter_tree, COHORT_FIELD as _COHORT_FIELD,
|
|
|
|
|
|
|
|
|
|
| 473 |
MAX_FILTER_DEPTH, MAX_FILTER_NODES, MAX_FILTER_SIBLINGS)
|
| 474 |
|
| 475 |
# REFUSE an over-large tree rather than TRUNCATE it. clean_filter_tree caps siblings per
|
|
@@ -544,6 +556,53 @@ def _clean_tree(tree, cols):
|
|
| 544 |
f" β those are resolved to a set of ids by harness.measure_filter, not compiled into "
|
| 545 |
f"this query. Refusing rather than dropping or mis-compiling them, either of which "
|
| 546 |
f"would silently answer a different question under an authoritative count.")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 547 |
return clean_filter_tree(tree, set(cols))
|
| 548 |
|
| 549 |
|
|
@@ -782,7 +841,8 @@ def store_query(topic, measures, group_by=None, grain=None, date_from=None, date
|
|
| 782 |
gb = [g for g in (group_by or []) if g]
|
| 783 |
for g in gb:
|
| 784 |
if g not in dims:
|
| 785 |
-
raise
|
|
|
|
| 786 |
d = dims[g]
|
| 787 |
select.append(f"{d['col']} AS {g}_id" if d.get("name_col") else f"{d['col']} AS {g}")
|
| 788 |
group_cols.append(d["col"])
|
|
@@ -821,7 +881,8 @@ def store_query(topic, measures, group_by=None, grain=None, date_from=None, date
|
|
| 821 |
where.append(render_scope(s["service_filter"]))
|
| 822 |
for dim_key, vals in (filters or {}).items():
|
| 823 |
if dim_key not in dims:
|
| 824 |
-
raise
|
|
|
|
| 825 |
# id dims filter by int; TEXT dims (e.g. city) filter by the value itself β either way
|
| 826 |
# every VALUE stays parameterized (the whitelist covers identifiers only)
|
| 827 |
def _coerce(v):
|
|
@@ -953,7 +1014,9 @@ def store_rows(topic, date_from=None, date_to=None, team_id=None, filter_tree=No
|
|
| 953 |
|
| 954 |
# --- the user's narrowing, on top of the scope --------------------------------------
|
| 955 |
narrow, narrow_params = [], []
|
| 956 |
-
pred = _fs.compile_filter_tree(_clean_tree(filter_tree or [], cols
|
|
|
|
|
|
|
| 957 |
today=today,
|
| 958 |
member_ids=member_ids or None, id_sql=id_sql)
|
| 959 |
if pred is not None:
|
|
@@ -1027,7 +1090,7 @@ def store_field_values(topic, dim, search=None, limit=25):
|
|
| 1027 |
raise ModelError(f"topic {topic!r} has no store binding")
|
| 1028 |
d = (t["store"].get("dims") or {}).get(dim)
|
| 1029 |
if not d:
|
| 1030 |
-
raise
|
| 1031 |
if not d.get("name_col"):
|
| 1032 |
raise ModelError(f"dim {dim!r} has no name column (filter by id)")
|
| 1033 |
s = t["store"]
|
|
|
|
| 71 |
"""A model-file problem (unknown key, bad reference, unparseable expr)."""
|
| 72 |
|
| 73 |
|
| 74 |
+
class UnknownColumnError(ModelError):
|
| 75 |
+
"""A filter/group request named a column the topic does not declare."""
|
| 76 |
+
|
| 77 |
+
def __init__(self, message, column, columns=None):
|
| 78 |
+
super().__init__(message)
|
| 79 |
+
self.column = str(column)
|
| 80 |
+
self.columns = sorted({str(item) for item in (columns or [column])})
|
| 81 |
+
|
| 82 |
+
|
| 83 |
# ---------------------------------------------------------------- loading
|
| 84 |
|
| 85 |
@functools.lru_cache(maxsize=1)
|
|
|
|
| 465 |
_FORMAT_TYPE = {"usd": "currency", "int": "int", "pct": "pct"}
|
| 466 |
|
| 467 |
|
| 468 |
+
def _clean_tree(tree, cols, tolerate=()):
|
| 469 |
"""Run a filter tree through the SAME validator the client's view state goes through.
|
| 470 |
|
| 471 |
`filter_sql`'s documented input contract is "feed me CLEANED trees" β it is faithful to the
|
|
|
|
| 479 |
module with zero imports of its own, so this cannot cycle.
|
| 480 |
"""
|
| 481 |
from aios_grid import (clean_filter_tree, COHORT_FIELD as _COHORT_FIELD,
|
| 482 |
+
VIEW_FIELD as _VIEW_FIELD, FILTER_OPS as _FILTER_OPS,
|
| 483 |
+
COHORT_OPS as _COHORT_OPS, COHORT_OP_ALIASES as _COHORT_ALIASES,
|
| 484 |
+
VIEW_OPS as _VIEW_OPS,
|
| 485 |
MAX_FILTER_DEPTH, MAX_FILTER_NODES, MAX_FILTER_SIBLINGS)
|
| 486 |
|
| 487 |
# REFUSE an over-large tree rather than TRUNCATE it. clean_filter_tree caps siblings per
|
|
|
|
| 556 |
f" β those are resolved to a set of ids by harness.measure_filter, not compiled into "
|
| 557 |
f"this query. Refusing rather than dropping or mis-compiling them, either of which "
|
| 558 |
f"would silently answer a different question under an authoritative count.")
|
| 559 |
+
# The UI cleaner drops unknown columns/operators for stale saved views. On a server query
|
| 560 |
+
# that would silently widen the result, so authoring faults are refused before normalization.
|
| 561 |
+
# `tolerate` covers deliberately narrower row projections.
|
| 562 |
+
tolerated = {str(column) for column in (tolerate or ())}
|
| 563 |
+
known = set(cols) | tolerated | {_COHORT_FIELD, _VIEW_FIELD}
|
| 564 |
+
unknown = []
|
| 565 |
+
bad_ops = []
|
| 566 |
+
|
| 567 |
+
def _inspect(nodes):
|
| 568 |
+
for node in nodes or []:
|
| 569 |
+
if not isinstance(node, dict):
|
| 570 |
+
continue
|
| 571 |
+
if isinstance(node.get('children'), list):
|
| 572 |
+
_inspect(node['children'])
|
| 573 |
+
continue
|
| 574 |
+
column = node.get('colId')
|
| 575 |
+
if column in (None, ''):
|
| 576 |
+
continue
|
| 577 |
+
column = str(column)
|
| 578 |
+
if column not in known:
|
| 579 |
+
unknown.append(column)
|
| 580 |
+
continue
|
| 581 |
+
if tolerated and column in tolerated and column not in cols:
|
| 582 |
+
continue
|
| 583 |
+
op = node.get('op')
|
| 584 |
+
if op in (None, ''):
|
| 585 |
+
continue
|
| 586 |
+
legal = (_COHORT_OPS | set(_COHORT_ALIASES) if column == _COHORT_FIELD
|
| 587 |
+
else _VIEW_OPS if column == _VIEW_FIELD
|
| 588 |
+
else _FILTER_OPS)
|
| 589 |
+
if str(op) not in legal:
|
| 590 |
+
bad_ops.append((column, str(op), sorted(legal)))
|
| 591 |
+
|
| 592 |
+
_inspect(tree)
|
| 593 |
+
if unknown:
|
| 594 |
+
bad = sorted(set(unknown))
|
| 595 |
+
extra = f" (and {bad[1:]})" if len(bad) > 1 else ""
|
| 596 |
+
raise UnknownColumnError(
|
| 597 |
+
f"filter rule names column {bad[0]!r}{extra}, which this topic does not have. "
|
| 598 |
+
f"Refusing rather than dropping the rule, which would silently widen the result.",
|
| 599 |
+
column=bad[0], columns=bad)
|
| 600 |
+
if bad_ops:
|
| 601 |
+
column, op, legal = bad_ops[0]
|
| 602 |
+
raise ModelError(
|
| 603 |
+
f"filter rule on column {column!r} carries operator {op!r}, which is not one this "
|
| 604 |
+
f"filter understands (use: {legal}). Refusing rather than dropping the rule, which "
|
| 605 |
+
f"would silently widen the result.")
|
| 606 |
return clean_filter_tree(tree, set(cols))
|
| 607 |
|
| 608 |
|
|
|
|
| 841 |
gb = [g for g in (group_by or []) if g]
|
| 842 |
for g in gb:
|
| 843 |
if g not in dims:
|
| 844 |
+
raise UnknownColumnError(
|
| 845 |
+
f"group_by {g!r} not a dim of {topic!r} (allowed: {list(dims)})", column=g)
|
| 846 |
d = dims[g]
|
| 847 |
select.append(f"{d['col']} AS {g}_id" if d.get("name_col") else f"{d['col']} AS {g}")
|
| 848 |
group_cols.append(d["col"])
|
|
|
|
| 881 |
where.append(render_scope(s["service_filter"]))
|
| 882 |
for dim_key, vals in (filters or {}).items():
|
| 883 |
if dim_key not in dims:
|
| 884 |
+
raise UnknownColumnError(
|
| 885 |
+
f"filter dim {dim_key!r} not allowed (use: {list(dims)})", column=dim_key)
|
| 886 |
# id dims filter by int; TEXT dims (e.g. city) filter by the value itself β either way
|
| 887 |
# every VALUE stays parameterized (the whitelist covers identifiers only)
|
| 888 |
def _coerce(v):
|
|
|
|
| 1014 |
|
| 1015 |
# --- the user's narrowing, on top of the scope --------------------------------------
|
| 1016 |
narrow, narrow_params = [], []
|
| 1017 |
+
pred = _fs.compile_filter_tree(_clean_tree(filter_tree or [], cols,
|
| 1018 |
+
tolerate=store_columns(topic)),
|
| 1019 |
+
filter_conj, cols,
|
| 1020 |
today=today,
|
| 1021 |
member_ids=member_ids or None, id_sql=id_sql)
|
| 1022 |
if pred is not None:
|
|
|
|
| 1090 |
raise ModelError(f"topic {topic!r} has no store binding")
|
| 1091 |
d = (t["store"].get("dims") or {}).get(dim)
|
| 1092 |
if not d:
|
| 1093 |
+
raise UnknownColumnError(f"unknown dim {dim!r} for topic {topic!r}", column=dim)
|
| 1094 |
if not d.get("name_col"):
|
| 1095 |
raise ModelError(f"dim {dim!r} has no name column (filter by id)")
|
| 1096 |
s = t["store"]
|
platform/model/topics/sales_lines.yml
CHANGED
|
@@ -74,6 +74,14 @@ store:
|
|
| 74 |
# 2,056 customers have a non-agent as agent_ids[0]. Do NOT "fix" it by reading the commission
|
| 75 |
# table, which mixes agents and salespeople.
|
| 76 |
agent: {col: "rp.agent_id", name_col: "ag.name", label: "Agent"}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 77 |
|
| 78 |
ai_context: >
|
| 79 |
The wholesale sales dataset of Royal Imports / Fisch Floral Supply, at order-LINE grain.
|
|
@@ -117,3 +125,7 @@ ai_context: >
|
|
| 117 |
has no address on file β present it as "no state on file", keep it in totals) and duplicate
|
| 118 |
state records exist (two ids can share one name, e.g. New Jersey twice) β list them as the
|
| 119 |
data shows and note the duplication rather than silently merging.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 74 |
# 2,056 customers have a non-agent as agent_ids[0]. Do NOT "fix" it by reading the commission
|
| 75 |
# table, which mixes agents and salespeople.
|
| 76 |
agent: {col: "rp.agent_id", name_col: "ag.name", label: "Agent"}
|
| 77 |
+
# W42-T01: status operands live on the parent order already joined as `o`. These are text
|
| 78 |
+
# codes, so the value and name expressions are intentionally identical; this keeps filtering
|
| 79 |
+
# and grouping on the exact raw Odoo state without inventing a numeric companion.
|
| 80 |
+
invoice_status: {col: "o.invoice_status", name_col: "o.invoice_status",
|
| 81 |
+
label: "Invoice status"}
|
| 82 |
+
# `scope_sql` already limits this to confirmed/locked orders (`sale`/`done`). This dimension
|
| 83 |
+
# distinguishes those states; it must never widen the topic to quotations or cancellations.
|
| 84 |
+
order_state: {col: "o.state", name_col: "o.state", label: "Order state"}
|
| 85 |
|
| 86 |
ai_context: >
|
| 87 |
The wholesale sales dataset of Royal Imports / Fisch Floral Supply, at order-LINE grain.
|
|
|
|
| 125 |
has no address on file β present it as "no state on file", keep it in totals) and duplicate
|
| 126 |
state records exist (two ids can share one name, e.g. New Jersey twice) β list them as the
|
| 127 |
data shows and note the duplication rather than silently merging.
|
| 128 |
+
Invoicing questions use `invoice_status`, inherited from the parent order. Its raw values are
|
| 129 |
+
'invoiced', 'to invoice', 'no', and 'upselling'. `order_state` is limited to 'sale' or 'done'
|
| 130 |
+
because this topic is confirmed-order scope; a missing quotation bucket is not evidence that
|
| 131 |
+
the tenant has no quotations.
|
web/public/sample_customers.json
CHANGED
|
@@ -112,6 +112,7 @@
|
|
| 112 |
"label": "Google Maps",
|
| 113 |
"type": "url",
|
| 114 |
"source": "odoo",
|
|
|
|
| 115 |
"default": true,
|
| 116 |
"description": "A Google Maps link to this customer's address."
|
| 117 |
},
|
|
|
|
| 112 |
"label": "Google Maps",
|
| 113 |
"type": "url",
|
| 114 |
"source": "odoo",
|
| 115 |
+
"valueOverride": "overlay",
|
| 116 |
"default": true,
|
| 117 |
"description": "A Google Maps link to this customer's address."
|
| 118 |
},
|
web/src/automation/AutomationBuilder.tsx
CHANGED
|
@@ -31,7 +31,7 @@
|
|
| 31 |
// AutomationTrigger).
|
| 32 |
// ---------------------------------------------------------------------------
|
| 33 |
import type { ReactNode } from "react";
|
| 34 |
-
import { useEffect, useRef, useState } from "react";
|
| 35 |
|
| 36 |
// β WAVE 30 Β· ITEM 7 (R3 + R4) β connector identity, from the ONE module that owns it. Not a
|
| 37 |
// second copy of two SVGs: the directory, this menu and the trigger picker all answer "which
|
|
@@ -101,6 +101,10 @@ interface Props {
|
|
| 101 |
/** The server's trigger vocabulary (C3). Absent is a state this file states, never fills in. */
|
| 102 |
triggers?: TriggerOption[];
|
| 103 |
catalog: ActionCatalogRow[];
|
|
|
|
|
|
|
|
|
|
|
|
|
| 104 |
vocab?: FlowVocab;
|
| 105 |
tables: UserTable[];
|
| 106 |
voiceAgents?: VoiceAgent[];
|
|
@@ -199,13 +203,6 @@ interface Props {
|
|
| 199 |
* (duplicate names are legal), and the automation still points at neither.
|
| 200 |
*/
|
| 201 |
onTablesChanged: () => Promise<void> | void;
|
| 202 |
-
/**
|
| 203 |
-
* Is there an edit the HEADER's Save still owns? REQUIRED, and it exists so the panel's
|
| 204 |
-
* "All changes saved" stamp can stop being a claim about fields it does not cover β the
|
| 205 |
-
* machine steps' panels moved into Properties this wave and they commit with Save, not on
|
| 206 |
-
* change.
|
| 207 |
-
*/
|
| 208 |
-
dirty: boolean;
|
| 209 |
}
|
| 210 |
|
| 211 |
/*
|
|
@@ -438,6 +435,8 @@ export default function AutomationBuilder({
|
|
| 438 |
onNameCommit,
|
| 439 |
triggers,
|
| 440 |
catalog,
|
|
|
|
|
|
|
| 441 |
vocab,
|
| 442 |
tables,
|
| 443 |
voiceAgents,
|
|
@@ -457,7 +456,6 @@ export default function AutomationBuilder({
|
|
| 457 |
schedules,
|
| 458 |
walkTable,
|
| 459 |
onTablesChanged,
|
| 460 |
-
dirty,
|
| 461 |
}: Props) {
|
| 462 |
const [sel, setSel] = useState<Sel>({ kind: "trigger", id: "" });
|
| 463 |
const [picking, setPicking] = useState(false);
|
|
@@ -948,6 +946,77 @@ export default function AutomationBuilder({
|
|
| 948 |
`verify_steps` exercises the nest, which no amount of JSX here could be tested against. */
|
| 949 |
const menuGroups = groupActions(catalog);
|
| 950 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 951 |
/** ONE action row, so the nested and un-nested lists cannot render differently. */
|
| 952 |
const actionRow = (c: ActionCatalogRow) => (
|
| 953 |
<button
|
|
@@ -1444,43 +1513,52 @@ export default function AutomationBuilder({
|
|
| 1444 |
them, and `clean_actions` refuses the unready ones at the door, so faded is a
|
| 1445 |
wall rather than a decoration. */}
|
| 1446 |
{adding ? (
|
| 1447 |
-
<
|
| 1448 |
{menuGroups.map((g) => (
|
| 1449 |
<div className="autox-menu-group" key={g.key}>
|
| 1450 |
-
<
|
| 1451 |
{/* β WAVE 27 Β· ITEM 33 / C4 β the group's OWN rows first, then one nest per
|
| 1452 |
connector. `<details>` rather than a hand-built disclosure: it IS the
|
| 1453 |
chevron-and-submenu the reference shows, it opens on Enter and Space
|
| 1454 |
without a keydown handler, and it needs no open/closed state of its own
|
| 1455 |
to get wrong. Closed by default β the reference shows collapsed rows,
|
| 1456 |
and a connector nobody is using should cost one line, not six. */}
|
| 1457 |
-
{[...g.rows, ...g.sub].map((entry) => (
|
| 1458 |
-
<
|
| 1459 |
-
|
| 1460 |
-
|
| 1461 |
-
|
| 1462 |
-
|
| 1463 |
-
|
| 1464 |
-
|
| 1465 |
-
|
| 1466 |
-
|
| 1467 |
-
|
| 1468 |
-
|
| 1469 |
-
|
| 1470 |
-
|
| 1471 |
-
|
| 1472 |
-
|
| 1473 |
-
|
| 1474 |
-
|
| 1475 |
-
|
| 1476 |
-
|
| 1477 |
-
|
| 1478 |
-
|
| 1479 |
-
|
| 1480 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1481 |
</div>
|
| 1482 |
))}
|
| 1483 |
-
</
|
| 1484 |
) : null}
|
| 1485 |
</div>
|
| 1486 |
</div>
|
|
@@ -1498,18 +1576,6 @@ export default function AutomationBuilder({
|
|
| 1498 |
>
|
| 1499 |
<div className="auto-panel-head">
|
| 1500 |
{panelTabs}
|
| 1501 |
-
{/*
|
| 1502 |
-
THREE STATES, because this panel now holds two save disciplines. The discrete choices
|
| 1503 |
-
(a trigger, an action, a switch, a branch) persist as they are made; the machine
|
| 1504 |
-
steps' fields, which moved in here with item 5, commit with the header's Save. A
|
| 1505 |
-
two-state stamp had to be wrong about one of them, and "All changes saved" printed
|
| 1506 |
-
over an unsaved column map is the direction that loses work.
|
| 1507 |
-
*/}
|
| 1508 |
-
<span
|
| 1509 |
-
className={"autox-saved" + (busy ? " is-busy" : dirty ? " is-dirty" : "")}
|
| 1510 |
-
>
|
| 1511 |
-
{busy ? "Savingβ¦" : dirty ? "Unsaved changes. Press Save" : "All changes saved"}
|
| 1512 |
-
</span>
|
| 1513 |
</div>
|
| 1514 |
|
| 1515 |
{/*
|
|
|
|
| 31 |
// AutomationTrigger).
|
| 32 |
// ---------------------------------------------------------------------------
|
| 33 |
import type { ReactNode } from "react";
|
| 34 |
+
import { Fragment, useEffect, useRef, useState } from "react";
|
| 35 |
|
| 36 |
// β WAVE 30 Β· ITEM 7 (R3 + R4) β connector identity, from the ONE module that owns it. Not a
|
| 37 |
// second copy of two SVGs: the directory, this menu and the trigger picker all answer "which
|
|
|
|
| 101 |
/** The server's trigger vocabulary (C3). Absent is a state this file states, never fills in. */
|
| 102 |
triggers?: TriggerOption[];
|
| 103 |
catalog: ActionCatalogRow[];
|
| 104 |
+
/** Existing synthetic Field agents, already composed and permission-filtered by the server. */
|
| 105 |
+
fieldAgents: Automation[];
|
| 106 |
+
/** Open one of those existing agents; AI enrichment cannot be authored as a direct action. */
|
| 107 |
+
onOpenFieldAgent: (id: string) => void;
|
| 108 |
vocab?: FlowVocab;
|
| 109 |
tables: UserTable[];
|
| 110 |
voiceAgents?: VoiceAgent[];
|
|
|
|
| 203 |
* (duplicate names are legal), and the automation still points at neither.
|
| 204 |
*/
|
| 205 |
onTablesChanged: () => Promise<void> | void;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 206 |
}
|
| 207 |
|
| 208 |
/*
|
|
|
|
| 435 |
onNameCommit,
|
| 436 |
triggers,
|
| 437 |
catalog,
|
| 438 |
+
fieldAgents,
|
| 439 |
+
onOpenFieldAgent,
|
| 440 |
vocab,
|
| 441 |
tables,
|
| 442 |
voiceAgents,
|
|
|
|
| 456 |
schedules,
|
| 457 |
walkTable,
|
| 458 |
onTablesChanged,
|
|
|
|
| 459 |
}: Props) {
|
| 460 |
const [sel, setSel] = useState<Sel>({ kind: "trigger", id: "" });
|
| 461 |
const [picking, setPicking] = useState(false);
|
|
|
|
| 946 |
`verify_steps` exercises the nest, which no amount of JSX here could be tested against. */
|
| 947 |
const menuGroups = groupActions(catalog);
|
| 948 |
|
| 949 |
+
/*
|
| 950 |
+
* `ai_enrich` deliberately rides the catalog with `menu:false`: it names synthetic steps but
|
| 951 |
+
* the ordinary action door refuses authorship because enrichment belongs to a field. Hiding it
|
| 952 |
+
* from the whole Agent catalog was the bug. This separate consumer uses the row's server-owned
|
| 953 |
+
* label/group/detail and opens only the synthetic Field-agent choices the list route supplied.
|
| 954 |
+
*/
|
| 955 |
+
const fieldAgentCatalog = catalog.find((entry) => entry.kind === "ai_enrich") || null;
|
| 956 |
+
|
| 957 |
+
const fieldAgentChoice = fieldAgentCatalog ? (
|
| 958 |
+
fieldAgentCatalog.ready && fieldAgents.length ? (
|
| 959 |
+
<details className="autox-menu-nest" data-catalog-kind="ai_enrich">
|
| 960 |
+
<summary className="autox-menu-row autox-menu-sum">
|
| 961 |
+
<span
|
| 962 |
+
className={"autox-card-mark"
|
| 963 |
+
+ (hasBrandKind(fieldAgentCatalog.kind) ? " is-brand" : "")}
|
| 964 |
+
>
|
| 965 |
+
<ActionMark kind={fieldAgentCatalog.kind} />
|
| 966 |
+
</span>
|
| 967 |
+
<span className="autox-menu-text">
|
| 968 |
+
<span className="autox-menu-label">{fieldAgentCatalog.label}</span>
|
| 969 |
+
<span className="autox-menu-detail">{fieldAgentCatalog.detail}</span>
|
| 970 |
+
</span>
|
| 971 |
+
</summary>
|
| 972 |
+
{fieldAgents.map((agent) => (
|
| 973 |
+
<button
|
| 974 |
+
key={agent.id}
|
| 975 |
+
type="button"
|
| 976 |
+
className="autox-menu-row"
|
| 977 |
+
onClick={() => {
|
| 978 |
+
setAdding(false);
|
| 979 |
+
onOpenFieldAgent(agent.id);
|
| 980 |
+
}}
|
| 981 |
+
>
|
| 982 |
+
<span
|
| 983 |
+
className={"autox-card-mark"
|
| 984 |
+
+ (hasBrandKind(fieldAgentCatalog.kind) ? " is-brand" : "")}
|
| 985 |
+
>
|
| 986 |
+
<ActionMark kind={fieldAgentCatalog.kind} />
|
| 987 |
+
</span>
|
| 988 |
+
<span className="autox-menu-text">
|
| 989 |
+
<span className="autox-menu-label">{agent.name}</span>
|
| 990 |
+
<span className="autox-menu-detail">Open this field agent</span>
|
| 991 |
+
</span>
|
| 992 |
+
</button>
|
| 993 |
+
))}
|
| 994 |
+
</details>
|
| 995 |
+
) : (
|
| 996 |
+
<button
|
| 997 |
+
type="button"
|
| 998 |
+
className="autox-menu-row is-planned"
|
| 999 |
+
data-catalog-kind="ai_enrich"
|
| 1000 |
+
disabled
|
| 1001 |
+
title="Add an AI field to a database first."
|
| 1002 |
+
>
|
| 1003 |
+
<span
|
| 1004 |
+
className={"autox-card-mark"
|
| 1005 |
+
+ (hasBrandKind(fieldAgentCatalog.kind) ? " is-brand" : "")}
|
| 1006 |
+
>
|
| 1007 |
+
<ActionMark kind={fieldAgentCatalog.kind} />
|
| 1008 |
+
</span>
|
| 1009 |
+
<span className="autox-menu-text">
|
| 1010 |
+
<span className="autox-menu-label">
|
| 1011 |
+
{fieldAgentCatalog.label}
|
| 1012 |
+
<span className="autox-soon">No field agents</span>
|
| 1013 |
+
</span>
|
| 1014 |
+
<span className="autox-menu-detail">Add an AI field to a database first.</span>
|
| 1015 |
+
</span>
|
| 1016 |
+
</button>
|
| 1017 |
+
)
|
| 1018 |
+
) : null;
|
| 1019 |
+
|
| 1020 |
/** ONE action row, so the nested and un-nested lists cannot render differently. */
|
| 1021 |
const actionRow = (c: ActionCatalogRow) => (
|
| 1022 |
<button
|
|
|
|
| 1513 |
them, and `clean_actions` refuses the unready ones at the door, so faded is a
|
| 1514 |
wall rather than a decoration. */}
|
| 1515 |
{adding ? (
|
| 1516 |
+
<section className="autox-menu" aria-label="Action catalog">
|
| 1517 |
{menuGroups.map((g) => (
|
| 1518 |
<div className="autox-menu-group" key={g.key}>
|
| 1519 |
+
<h3 className="autox-menu-head">{g.key}</h3>
|
| 1520 |
{/* β WAVE 27 Β· ITEM 33 / C4 β the group's OWN rows first, then one nest per
|
| 1521 |
connector. `<details>` rather than a hand-built disclosure: it IS the
|
| 1522 |
chevron-and-submenu the reference shows, it opens on Enter and Space
|
| 1523 |
without a keydown handler, and it needs no open/closed state of its own
|
| 1524 |
to get wrong. Closed by default β the reference shows collapsed rows,
|
| 1525 |
and a connector nobody is using should cost one line, not six. */}
|
| 1526 |
+
{[...g.rows, ...g.sub].map((entry) => (
|
| 1527 |
+
<Fragment key={("rows" in entry ? `sub:${entry.key}` : entry.kind)}>
|
| 1528 |
+
{!("rows" in entry) && entry.kind === "voice_agent"
|
| 1529 |
+
&& fieldAgentCatalog?.group === g.key ? fieldAgentChoice : null}
|
| 1530 |
+
{"rows" in entry ? (
|
| 1531 |
+
<details className="autox-menu-nest">
|
| 1532 |
+
<summary className="autox-menu-row autox-menu-sum">
|
| 1533 |
+
{/* β WAVE 30 Β· ITEM 7 / R4 β THE COLLAPSED ROW GETS AN IDENTITY.
|
| 1534 |
+
This is the row the owner clicks before choosing Instagram or
|
| 1535 |
+
TikTok, and until now it was the only row in the menu with
|
| 1536 |
+
nothing on its left: the chevron, then a bare word. The mark is
|
| 1537 |
+
resolved from the connector KEY, so a connector the server adds
|
| 1538 |
+
tomorrow gets a slot for free and simply renders no logo. */}
|
| 1539 |
+
{brandForConnector(entry.key) ? (
|
| 1540 |
+
<span className="autox-card-mark is-brand">
|
| 1541 |
+
{brandForConnector(entry.key)}
|
| 1542 |
+
</span>
|
| 1543 |
+
) : null}
|
| 1544 |
+
<span className="autox-menu-text">
|
| 1545 |
+
<span className="autox-menu-label">{entry.label}</span>
|
| 1546 |
+
<span className="autox-menu-detail">
|
| 1547 |
+
{entry.rows.length} action{entry.rows.length === 1 ? "" : "s"}
|
| 1548 |
+
</span>
|
| 1549 |
+
</span>
|
| 1550 |
+
</summary>
|
| 1551 |
+
{entry.rows.map((c) => actionRow(c))}
|
| 1552 |
+
</details>
|
| 1553 |
+
) : actionRow(entry)}
|
| 1554 |
+
</Fragment>
|
| 1555 |
+
))}
|
| 1556 |
+
{fieldAgentCatalog?.group === g.key
|
| 1557 |
+
&& !g.rows.some((entry) => entry.kind === "voice_agent")
|
| 1558 |
+
? fieldAgentChoice : null}
|
| 1559 |
</div>
|
| 1560 |
))}
|
| 1561 |
+
</section>
|
| 1562 |
) : null}
|
| 1563 |
</div>
|
| 1564 |
</div>
|
|
|
|
| 1576 |
>
|
| 1577 |
<div className="auto-panel-head">
|
| 1578 |
{panelTabs}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1579 |
</div>
|
| 1580 |
|
| 1581 |
{/*
|
web/src/automation/AutomationDetail.tsx
CHANGED
|
@@ -102,6 +102,10 @@ interface Props {
|
|
| 102 |
triggers?: TriggerOption[];
|
| 103 |
/** The ACTION MENU and the builder's ceilings (C4). Same rule: absent is a state, not a gap. */
|
| 104 |
catalog?: ActionCatalogRow[];
|
|
|
|
|
|
|
|
|
|
|
|
|
| 105 |
voiceAgents?: VoiceAgent[];
|
| 106 |
vocab?: FlowVocab;
|
| 107 |
/**
|
|
@@ -198,6 +202,8 @@ export default function AutomationDetail({
|
|
| 198 |
discover,
|
| 199 |
triggers,
|
| 200 |
catalog,
|
|
|
|
|
|
|
| 201 |
voiceAgents,
|
| 202 |
vocab,
|
| 203 |
tick,
|
|
@@ -1557,15 +1563,29 @@ export default function AutomationDetail({
|
|
| 1557 |
The guard is `runBlock`, not `automation.running`: `running` is process state and is
|
| 1558 |
FALSE for the whole 20-30 minute vendor wait, which is precisely the window in which
|
| 1559 |
a second paid search was measured being bought. */}
|
| 1560 |
-
<
|
| 1561 |
-
|
| 1562 |
-
|
| 1563 |
-
|
| 1564 |
-
|
| 1565 |
-
|
| 1566 |
-
|
| 1567 |
-
|
| 1568 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1569 |
<button
|
| 1570 |
type="button"
|
| 1571 |
className="auto-btn is-primary"
|
|
@@ -1749,19 +1769,14 @@ export default function AutomationDetail({
|
|
| 1749 |
name={name}
|
| 1750 |
// β NOT `edit(setName)` β the name has its own immediate write (`commitName`), so
|
| 1751 |
// marking the whole FORM dirty for it would leave `touched` true forever after a
|
| 1752 |
-
// name edit and make the
|
| 1753 |
-
// just saved. `touched`
|
| 1754 |
-
// edited", which is what the stamp below reports.
|
| 1755 |
onNameText={setName}
|
| 1756 |
onNameCommit={() => void commitName()}
|
| 1757 |
-
// β THE PANEL'S STAMP MUST NOT LIE, and item 5 is what made this urgent. "All changes
|
| 1758 |
-
// saved" was honest while Properties held only immediate-write controls; the machine
|
| 1759 |
-
// steps' panels moved in this wave and THOSE commit with the header's Save (url,
|
| 1760 |
-
// extract, the column map, the discovery filters). A stamp promising they are saved,
|
| 1761 |
-
// above the fields that are not, is the same defect as an unsaved name under it.
|
| 1762 |
-
dirty={touched}
|
| 1763 |
{...(triggers ? { triggers } : {})}
|
| 1764 |
catalog={catalog || []}
|
|
|
|
|
|
|
| 1765 |
voiceAgents={voiceAgents}
|
| 1766 |
{...(vocab ? { vocab } : {})}
|
| 1767 |
tables={tables}
|
|
|
|
| 102 |
triggers?: TriggerOption[];
|
| 103 |
/** The ACTION MENU and the builder's ceilings (C4). Same rule: absent is a state, not a gap. */
|
| 104 |
catalog?: ActionCatalogRow[];
|
| 105 |
+
/** Permission-filtered synthetic agents derived from AI fields by the server. */
|
| 106 |
+
fieldAgents: Automation[];
|
| 107 |
+
/** Select one of those existing agents in the shared Agents rail. */
|
| 108 |
+
onOpenFieldAgent: (id: string) => void;
|
| 109 |
voiceAgents?: VoiceAgent[];
|
| 110 |
vocab?: FlowVocab;
|
| 111 |
/**
|
|
|
|
| 202 |
discover,
|
| 203 |
triggers,
|
| 204 |
catalog,
|
| 205 |
+
fieldAgents,
|
| 206 |
+
onOpenFieldAgent,
|
| 207 |
voiceAgents,
|
| 208 |
vocab,
|
| 209 |
tick,
|
|
|
|
| 1563 |
The guard is `runBlock`, not `automation.running`: `running` is process state and is
|
| 1564 |
FALSE for the whole 20-30 minute vendor wait, which is precisely the window in which
|
| 1565 |
a second paid search was measured being bought. */}
|
| 1566 |
+
<span className="auto-run-control">
|
| 1567 |
+
<span
|
| 1568 |
+
className={"autox-saved auto-save-receipt"
|
| 1569 |
+
+ (saving || triggerBusy ? " is-busy" : touched ? " is-dirty" : "")}
|
| 1570 |
+
role="status"
|
| 1571 |
+
aria-live="polite"
|
| 1572 |
+
>
|
| 1573 |
+
{saving || triggerBusy
|
| 1574 |
+
? "Savingβ¦"
|
| 1575 |
+
: touched
|
| 1576 |
+
? "Unsaved changes. Press Save"
|
| 1577 |
+
: "All changes saved"}
|
| 1578 |
+
</span>
|
| 1579 |
+
<button
|
| 1580 |
+
type="button"
|
| 1581 |
+
className="auto-btn"
|
| 1582 |
+
disabled={runState.blocked}
|
| 1583 |
+
title={runState.why || undefined}
|
| 1584 |
+
onClick={() => void start()}
|
| 1585 |
+
>
|
| 1586 |
+
{runState.blocked ? runState.label : "Run now"}
|
| 1587 |
+
</button>
|
| 1588 |
+
</span>
|
| 1589 |
<button
|
| 1590 |
type="button"
|
| 1591 |
className="auto-btn is-primary"
|
|
|
|
| 1769 |
name={name}
|
| 1770 |
// β NOT `edit(setName)` β the name has its own immediate write (`commitName`), so
|
| 1771 |
// marking the whole FORM dirty for it would leave `touched` true forever after a
|
| 1772 |
+
// name edit and make the header receipt say "unsaved changes" about something it had
|
| 1773 |
+
// just saved. `touched` means exactly "a field the header's Save owns was edited".
|
|
|
|
| 1774 |
onNameText={setName}
|
| 1775 |
onNameCommit={() => void commitName()}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1776 |
{...(triggers ? { triggers } : {})}
|
| 1777 |
catalog={catalog || []}
|
| 1778 |
+
fieldAgents={fieldAgents}
|
| 1779 |
+
onOpenFieldAgent={onOpenFieldAgent}
|
| 1780 |
voiceAgents={voiceAgents}
|
| 1781 |
{...(vocab ? { vocab } : {})}
|
| 1782 |
tables={tables}
|
web/src/automation/AutomationSurface.tsx
CHANGED
|
@@ -36,6 +36,7 @@ import {
|
|
| 36 |
liveStepOf,
|
| 37 |
patchAutomation,
|
| 38 |
rememberAutomation,
|
|
|
|
| 39 |
} from "./automationApi";
|
| 40 |
import type { VoiceAgent } from "./voiceAgentTypes";
|
| 41 |
import "../styles/wave44/voice-agent.css";
|
|
@@ -521,6 +522,13 @@ export default function AutomationSurface() {
|
|
| 521 |
}, [openRequest, data, select]);
|
| 522 |
|
| 523 |
const items = data?.automations || [];
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 524 |
const active = items.find((a) => a.id === activeId) || null;
|
| 525 |
const activeVoice = voiceAgents.find((agent) => agent.automationId === activeVoiceId) || null;
|
| 526 |
|
|
@@ -683,7 +691,7 @@ export default function AutomationSurface() {
|
|
| 683 |
);
|
| 684 |
})}
|
| 685 |
{voiceAgents.map((agent) => {
|
| 686 |
-
const isActive = agent.
|
| 687 |
return (
|
| 688 |
<div
|
| 689 |
key={agent.automationId}
|
|
@@ -709,7 +717,7 @@ export default function AutomationSurface() {
|
|
| 709 |
className={"auto-row-switch voice-agent-row-toggle" + (isActive ? " is-on" : "")}
|
| 710 |
disabled
|
| 711 |
aria-pressed={isActive}
|
| 712 |
-
aria-label={`${agent.displayName}: ${voiceStatusLabel(agent.
|
| 713 |
title="Voice activation is controlled on the server."
|
| 714 |
>
|
| 715 |
<span className="auto-row-switch-knob" />
|
|
@@ -778,7 +786,13 @@ export default function AutomationSurface() {
|
|
| 778 |
`Shell.tsx`'s. `fallback={null}`, matching `Lazily`. */}
|
| 779 |
{activeVoice ? (
|
| 780 |
<Suspense fallback={null}>
|
| 781 |
-
<VoiceAgentProperties
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 782 |
</Suspense>
|
| 783 |
) : active ? (
|
| 784 |
<Suspense fallback={null}>
|
|
@@ -801,6 +815,8 @@ export default function AutomationSurface() {
|
|
| 801 |
// `triggers` is: absent must stay absent, so the builder can tell "the server
|
| 802 |
// offered nothing" from "the server offered an empty list".
|
| 803 |
catalog={data?.actionsCatalog}
|
|
|
|
|
|
|
| 804 |
voiceAgents={voiceAgents}
|
| 805 |
vocab={data?.flow}
|
| 806 |
// `?? null` and never `|| {enabled:false}`: an absent tick bit is "the server did
|
|
|
|
| 36 |
liveStepOf,
|
| 37 |
patchAutomation,
|
| 38 |
rememberAutomation,
|
| 39 |
+
replaceVoiceAgent,
|
| 40 |
} from "./automationApi";
|
| 41 |
import type { VoiceAgent } from "./voiceAgentTypes";
|
| 42 |
import "../styles/wave44/voice-agent.css";
|
|
|
|
| 522 |
}, [openRequest, data, select]);
|
| 523 |
|
| 524 |
const items = data?.automations || [];
|
| 525 |
+
/*
|
| 526 |
+
* W44 QA: AI field agents are derived from field definitions, so they cannot be added as
|
| 527 |
+
* ordinary flow actions. The list endpoint already composed and permission-filtered the safe
|
| 528 |
+
* choices as synthetic `field_agent` rows. Pass those rows down instead of inventing a second
|
| 529 |
+
* database/field picker or exposing their encoded ids as user input.
|
| 530 |
+
*/
|
| 531 |
+
const fieldAgents = items.filter((agent) => agent.system === "field_agent");
|
| 532 |
const active = items.find((a) => a.id === activeId) || null;
|
| 533 |
const activeVoice = voiceAgents.find((agent) => agent.automationId === activeVoiceId) || null;
|
| 534 |
|
|
|
|
| 691 |
);
|
| 692 |
})}
|
| 693 |
{voiceAgents.map((agent) => {
|
| 694 |
+
const isActive = agent.lifecycle === "active";
|
| 695 |
return (
|
| 696 |
<div
|
| 697 |
key={agent.automationId}
|
|
|
|
| 717 |
className={"auto-row-switch voice-agent-row-toggle" + (isActive ? " is-on" : "")}
|
| 718 |
disabled
|
| 719 |
aria-pressed={isActive}
|
| 720 |
+
aria-label={`${agent.displayName}: ${voiceStatusLabel(agent.lifecycle)}. Server controlled.`}
|
| 721 |
title="Voice activation is controlled on the server."
|
| 722 |
>
|
| 723 |
<span className="auto-row-switch-knob" />
|
|
|
|
| 786 |
`Shell.tsx`'s. `fallback={null}`, matching `Lazily`. */}
|
| 787 |
{activeVoice ? (
|
| 788 |
<Suspense fallback={null}>
|
| 789 |
+
<VoiceAgentProperties
|
| 790 |
+
key={activeVoice.automationId}
|
| 791 |
+
agent={activeVoice}
|
| 792 |
+
onSaved={(fresh) => {
|
| 793 |
+
setVoiceAgents((current) => replaceVoiceAgent(current, fresh));
|
| 794 |
+
}}
|
| 795 |
+
/>
|
| 796 |
</Suspense>
|
| 797 |
) : active ? (
|
| 798 |
<Suspense fallback={null}>
|
|
|
|
| 815 |
// `triggers` is: absent must stay absent, so the builder can tell "the server
|
| 816 |
// offered nothing" from "the server offered an empty list".
|
| 817 |
catalog={data?.actionsCatalog}
|
| 818 |
+
fieldAgents={fieldAgents}
|
| 819 |
+
onOpenFieldAgent={select}
|
| 820 |
voiceAgents={voiceAgents}
|
| 821 |
vocab={data?.flow}
|
| 822 |
// `?? null` and never `|| {enabled:false}`: an absent tick bit is "the server did
|
web/src/automation/VoiceAgentProperties.tsx
CHANGED
|
@@ -1,17 +1,33 @@
|
|
|
|
|
| 1 |
import { useState } from "react";
|
| 2 |
|
| 3 |
-
import {
|
| 4 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 5 |
|
| 6 |
interface Props {
|
| 7 |
agent: VoiceAgent;
|
|
|
|
| 8 |
}
|
| 9 |
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 15 |
};
|
| 16 |
|
| 17 |
function statusLabel(value: string): string {
|
|
@@ -20,28 +36,150 @@ function statusLabel(value: string): string {
|
|
| 20 |
.replace(/\b\w/g, (letter) => letter.toUpperCase());
|
| 21 |
}
|
| 22 |
|
| 23 |
-
function
|
| 24 |
-
return
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 25 |
}
|
| 26 |
|
| 27 |
-
export default function VoiceAgentProperties({ agent }: Props) {
|
| 28 |
-
const [
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
|
|
|
| 33 |
const [result, setResult] = useState<VoiceHarnessResult | null>(null);
|
| 34 |
const [error, setError] = useState("");
|
|
|
|
|
|
|
| 35 |
const [checking, setChecking] = useState(false);
|
| 36 |
-
const
|
| 37 |
-
|
| 38 |
-
const tables = agent.audienceOptions
|
| 39 |
-
const selectedTable = tables.find((table) => table.key ===
|
| 40 |
const views = selectedTable?.views || [];
|
| 41 |
-
const selectedView = views.find((view) => view.id ===
|
| 42 |
-
const phoneFields =
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 43 |
|
| 44 |
-
const
|
| 45 |
setInput((current) => ({ ...current, [key]: value }));
|
| 46 |
setError("");
|
| 47 |
setResult(null);
|
|
@@ -77,75 +215,244 @@ export default function VoiceAgentProperties({ agent }: Props) {
|
|
| 77 |
<p className="voice-agent-eyebrow">Agent</p>
|
| 78 |
<h1>{agent.displayName}</h1>
|
| 79 |
</div>
|
| 80 |
-
<span
|
| 81 |
-
{
|
|
|
|
|
|
|
|
|
|
| 82 |
</span>
|
| 83 |
</header>
|
| 84 |
|
| 85 |
<div className="voice-agent-grid">
|
| 86 |
-
<section className="voice-agent-section" aria-labelledby="voice-
|
| 87 |
-
<h2 id="voice-
|
| 88 |
<dl className="voice-agent-details">
|
| 89 |
<div>
|
| 90 |
-
<dt>
|
| 91 |
-
<dd>{agent.
|
| 92 |
</div>
|
| 93 |
<div>
|
| 94 |
-
<dt>
|
| 95 |
-
<dd>{agent.
|
| 96 |
</div>
|
| 97 |
<div>
|
| 98 |
-
<dt>
|
| 99 |
-
<dd>{statusLabel(agent.
|
| 100 |
</div>
|
| 101 |
</dl>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 102 |
<button type="button" className="voice-agent-disabled-control" disabled>
|
| 103 |
Voice runs unavailable
|
| 104 |
</button>
|
| 105 |
<p className="voice-agent-note">
|
| 106 |
-
|
| 107 |
-
activates it.
|
| 108 |
</p>
|
| 109 |
</section>
|
| 110 |
|
| 111 |
-
<section className="voice-agent-section" aria-labelledby="voice-
|
| 112 |
-
<h2 id="voice-
|
| 113 |
-
{
|
| 114 |
-
<
|
| 115 |
-
|
| 116 |
-
<
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 122 |
) : (
|
| 123 |
-
<p className="voice-agent-note">No
|
| 124 |
)}
|
| 125 |
-
{agent.capabilities.numberProvisioning === "contact_loopable" ? (
|
| 126 |
-
<p className="voice-agent-contact">
|
| 127 |
-
Number and SIP provisioning: <strong>Contact Loopable</strong>
|
| 128 |
-
</p>
|
| 129 |
-
) : null}
|
| 130 |
</section>
|
| 131 |
</div>
|
| 132 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 133 |
<section className="voice-agent-section" aria-labelledby="voice-bindings-heading">
|
| 134 |
-
<h2 id="voice-bindings-heading">Phone
|
| 135 |
-
{agent.
|
| 136 |
-
<
|
| 137 |
-
|
| 138 |
-
<
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
</
|
| 144 |
-
|
| 145 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 146 |
) : (
|
| 147 |
-
<p className="voice-agent-note">No phone
|
| 148 |
)}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 149 |
</section>
|
| 150 |
|
| 151 |
<section className="voice-agent-section" aria-labelledby="voice-harness-heading">
|
|
@@ -164,13 +471,16 @@ export default function VoiceAgentProperties({ agent }: Props) {
|
|
| 164 |
<select
|
| 165 |
value={input.table}
|
| 166 |
onChange={(event) => {
|
| 167 |
-
setInput(
|
| 168 |
-
setError("");
|
|
|
|
| 169 |
}}
|
| 170 |
-
aria-label="Voice
|
| 171 |
>
|
| 172 |
<option value="">Choose a database</option>
|
| 173 |
-
{tables.map((table) =>
|
|
|
|
|
|
|
| 174 |
</select>
|
| 175 |
</label>
|
| 176 |
<label>
|
|
@@ -178,26 +488,35 @@ export default function VoiceAgentProperties({ agent }: Props) {
|
|
| 178 |
<select
|
| 179 |
value={input.viewId}
|
| 180 |
onChange={(event) => {
|
| 181 |
-
setInput((current) => ({
|
| 182 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 183 |
}}
|
| 184 |
-
aria-label="Voice
|
| 185 |
-
disabled={!
|
| 186 |
>
|
| 187 |
<option value="">Choose a View</option>
|
| 188 |
-
{
|
|
|
|
|
|
|
| 189 |
</select>
|
| 190 |
</label>
|
| 191 |
<label>
|
| 192 |
Phone field
|
| 193 |
<select
|
| 194 |
value={input.phoneField}
|
| 195 |
-
onChange={(event) =>
|
| 196 |
-
aria-label="Voice
|
| 197 |
-
disabled={!
|
| 198 |
>
|
| 199 |
<option value="">Choose a phone field</option>
|
| 200 |
-
{
|
|
|
|
|
|
|
| 201 |
</select>
|
| 202 |
</label>
|
| 203 |
</div>
|
|
|
|
| 1 |
+
/* oxlint-disable react/only-export-components -- pure helpers are executed by the UI contract tests. */
|
| 2 |
import { useState } from "react";
|
| 3 |
|
| 4 |
+
import {
|
| 5 |
+
AutomationError,
|
| 6 |
+
dryRunVoiceAgent,
|
| 7 |
+
patchVoiceAgent,
|
| 8 |
+
} from "./automationApi";
|
| 9 |
+
import type {
|
| 10 |
+
VoiceAgent,
|
| 11 |
+
VoiceAgentDraft,
|
| 12 |
+
VoiceAudienceOption,
|
| 13 |
+
VoiceHarnessInput,
|
| 14 |
+
VoiceHarnessResult,
|
| 15 |
+
} from "./voiceAgentTypes";
|
| 16 |
|
| 17 |
interface Props {
|
| 18 |
agent: VoiceAgent;
|
| 19 |
+
onSaved: (agent: VoiceAgent) => void;
|
| 20 |
}
|
| 21 |
|
| 22 |
+
type PersistVoiceAgent = (voiceId: string, draft: VoiceAgentDraft) => Promise<VoiceAgent>;
|
| 23 |
+
|
| 24 |
+
const READINESS_REASON_LABELS: Record<string, string> = {
|
| 25 |
+
connection: "Connection",
|
| 26 |
+
provider_connection: "Provider connection",
|
| 27 |
+
audience: "Audience",
|
| 28 |
+
knowledge_profile: "Knowledge profile",
|
| 29 |
+
inbound_binding: "Inbound binding",
|
| 30 |
+
activation_gate: "Activation gate",
|
| 31 |
};
|
| 32 |
|
| 33 |
function statusLabel(value: string): string {
|
|
|
|
| 36 |
.replace(/\b\w/g, (letter) => letter.toUpperCase());
|
| 37 |
}
|
| 38 |
|
| 39 |
+
function readinessReasonLabel(value: string): string {
|
| 40 |
+
return READINESS_REASON_LABELS[value] || "Additional setup";
|
| 41 |
+
}
|
| 42 |
+
|
| 43 |
+
export function voiceDraftFromAgent(agent: VoiceAgent): VoiceAgentDraft {
|
| 44 |
+
return {
|
| 45 |
+
portableConfig: { ...agent.portableConfig },
|
| 46 |
+
audience: { ...agent.audience },
|
| 47 |
+
};
|
| 48 |
+
}
|
| 49 |
+
|
| 50 |
+
export function voiceDraftWithTable(
|
| 51 |
+
draft: VoiceAgentDraft,
|
| 52 |
+
tableKey: string
|
| 53 |
+
): VoiceAgentDraft {
|
| 54 |
+
return {
|
| 55 |
+
...draft,
|
| 56 |
+
audience: {
|
| 57 |
+
...draft.audience,
|
| 58 |
+
tableKey,
|
| 59 |
+
viewId: "",
|
| 60 |
+
viewRevision: "",
|
| 61 |
+
phoneFieldKey: "",
|
| 62 |
+
},
|
| 63 |
+
};
|
| 64 |
+
}
|
| 65 |
+
|
| 66 |
+
export function voiceDraftWithView(
|
| 67 |
+
draft: VoiceAgentDraft,
|
| 68 |
+
table: VoiceAudienceOption | undefined,
|
| 69 |
+
viewId: string
|
| 70 |
+
): VoiceAgentDraft {
|
| 71 |
+
const view = table?.views.find((candidate) => candidate.id === viewId);
|
| 72 |
+
return {
|
| 73 |
+
...draft,
|
| 74 |
+
audience: {
|
| 75 |
+
...draft.audience,
|
| 76 |
+
viewId,
|
| 77 |
+
viewRevision: view?.revision || "",
|
| 78 |
+
phoneFieldKey: "",
|
| 79 |
+
},
|
| 80 |
+
};
|
| 81 |
+
}
|
| 82 |
+
|
| 83 |
+
/** Validate against the vocabulary that accompanied this exact DTO, never a client limit table. */
|
| 84 |
+
export function voiceDraftValidationIssue(
|
| 85 |
+
agent: VoiceAgent,
|
| 86 |
+
draft: VoiceAgentDraft
|
| 87 |
+
): string {
|
| 88 |
+
const policyIsOffered = agent.audienceOptions.emptyPolicies.some(
|
| 89 |
+
(option) => option.key === draft.audience.emptyPolicy
|
| 90 |
+
);
|
| 91 |
+
if (!policyIsOffered) {
|
| 92 |
+
return "Choose an empty-value policy currently offered by the server.";
|
| 93 |
+
}
|
| 94 |
+
const ceiling = agent.audienceOptions.maxRecipientsCeiling;
|
| 95 |
+
const maximum = draft.audience.maxRecipients;
|
| 96 |
+
if (!Number.isInteger(maximum) || ceiling < 1 || maximum < 1 || maximum > ceiling) {
|
| 97 |
+
return ceiling > 0
|
| 98 |
+
? `Maximum recipients must be between 1 and ${ceiling}.`
|
| 99 |
+
: "The recipient limit is not available from the server.";
|
| 100 |
+
}
|
| 101 |
+
return "";
|
| 102 |
+
}
|
| 103 |
+
|
| 104 |
+
/** One write, followed by adoption of the exact DTO returned by that write. */
|
| 105 |
+
export async function saveVoiceAgentDraft(
|
| 106 |
+
agent: VoiceAgent,
|
| 107 |
+
draft: VoiceAgentDraft,
|
| 108 |
+
onSaved: (fresh: VoiceAgent) => void,
|
| 109 |
+
persist: PersistVoiceAgent = patchVoiceAgent
|
| 110 |
+
): Promise<VoiceAgent> {
|
| 111 |
+
const issue = voiceDraftValidationIssue(agent, draft);
|
| 112 |
+
if (issue) throw new AutomationError(issue, 400);
|
| 113 |
+
const next = await persist(agent.automationId, draft);
|
| 114 |
+
onSaved(next);
|
| 115 |
+
return next;
|
| 116 |
}
|
| 117 |
|
| 118 |
+
export default function VoiceAgentProperties({ agent, onSaved }: Props) {
|
| 119 |
+
const [draft, setDraft] = useState<VoiceAgentDraft>(() => voiceDraftFromAgent(agent));
|
| 120 |
+
const [input, setInput] = useState<VoiceHarnessInput>(() => ({
|
| 121 |
+
table: agent.audience.tableKey,
|
| 122 |
+
viewId: agent.audience.viewId,
|
| 123 |
+
phoneField: agent.audience.phoneFieldKey,
|
| 124 |
+
}));
|
| 125 |
const [result, setResult] = useState<VoiceHarnessResult | null>(null);
|
| 126 |
const [error, setError] = useState("");
|
| 127 |
+
const [saveError, setSaveError] = useState("");
|
| 128 |
+
const [saveReceipt, setSaveReceipt] = useState("");
|
| 129 |
const [checking, setChecking] = useState(false);
|
| 130 |
+
const [saving, setSaving] = useState(false);
|
| 131 |
+
|
| 132 |
+
const tables = agent.audienceOptions.tables;
|
| 133 |
+
const selectedTable = tables.find((table) => table.key === draft.audience.tableKey);
|
| 134 |
const views = selectedTable?.views || [];
|
| 135 |
+
const selectedView = views.find((view) => view.id === draft.audience.viewId);
|
| 136 |
+
const phoneFields = selectedTable?.phoneFields || [];
|
| 137 |
+
const harnessTable = tables.find((table) => table.key === input.table);
|
| 138 |
+
const harnessViews = harnessTable?.views || [];
|
| 139 |
+
const harnessView = harnessViews.find((view) => view.id === input.viewId);
|
| 140 |
+
const harnessPhoneFields = harnessTable?.phoneFields || [];
|
| 141 |
+
const canCheck = !!input.table.trim() && !!input.viewId.trim() && !!input.phoneField.trim();
|
| 142 |
+
const dirty = JSON.stringify(draft) !== JSON.stringify(voiceDraftFromAgent(agent));
|
| 143 |
+
const emptyPolicies = agent.audienceOptions.emptyPolicies;
|
| 144 |
+
const recipientCeiling = agent.audienceOptions.maxRecipientsCeiling;
|
| 145 |
+
const selectedPolicyIsOffered = emptyPolicies.some(
|
| 146 |
+
(option) => option.key === draft.audience.emptyPolicy
|
| 147 |
+
);
|
| 148 |
+
const validationIssue = voiceDraftValidationIssue(agent, draft);
|
| 149 |
+
const visibleSaveError = saveError || (dirty ? validationIssue : "");
|
| 150 |
+
|
| 151 |
+
const changeDraft = (next: VoiceAgentDraft) => {
|
| 152 |
+
setDraft(next);
|
| 153 |
+
setSaveError("");
|
| 154 |
+
setSaveReceipt("");
|
| 155 |
+
};
|
| 156 |
+
|
| 157 |
+
const saveConfiguration = async () => {
|
| 158 |
+
if (!dirty || validationIssue || saving) return;
|
| 159 |
+
setSaving(true);
|
| 160 |
+
setSaveError("");
|
| 161 |
+
setSaveReceipt("");
|
| 162 |
+
try {
|
| 163 |
+
const next = await saveVoiceAgentDraft(agent, draft, onSaved);
|
| 164 |
+
setDraft(voiceDraftFromAgent(next));
|
| 165 |
+
setInput({
|
| 166 |
+
table: next.audience.tableKey,
|
| 167 |
+
viewId: next.audience.viewId,
|
| 168 |
+
phoneField: next.audience.phoneFieldKey,
|
| 169 |
+
});
|
| 170 |
+
setSaveReceipt("Configuration saved");
|
| 171 |
+
} catch (reason) {
|
| 172 |
+
setSaveError(
|
| 173 |
+
reason instanceof AutomationError
|
| 174 |
+
? reason.message
|
| 175 |
+
: "The Voice configuration could not be saved."
|
| 176 |
+
);
|
| 177 |
+
} finally {
|
| 178 |
+
setSaving(false);
|
| 179 |
+
}
|
| 180 |
+
};
|
| 181 |
|
| 182 |
+
const updateHarnessInput = (key: keyof VoiceHarnessInput, value: string) => {
|
| 183 |
setInput((current) => ({ ...current, [key]: value }));
|
| 184 |
setError("");
|
| 185 |
setResult(null);
|
|
|
|
| 215 |
<p className="voice-agent-eyebrow">Agent</p>
|
| 216 |
<h1>{agent.displayName}</h1>
|
| 217 |
</div>
|
| 218 |
+
<span
|
| 219 |
+
className={`voice-agent-status${agent.readiness.state === "configured" ? " is-ready" : ""}`}
|
| 220 |
+
title="Readiness"
|
| 221 |
+
>
|
| 222 |
+
{statusLabel(agent.readiness.state)}
|
| 223 |
</span>
|
| 224 |
</header>
|
| 225 |
|
| 226 |
<div className="voice-agent-grid">
|
| 227 |
+
<section className="voice-agent-section" aria-labelledby="voice-status-heading">
|
| 228 |
+
<h2 id="voice-status-heading">Status</h2>
|
| 229 |
<dl className="voice-agent-details">
|
| 230 |
<div>
|
| 231 |
+
<dt>Lifecycle</dt>
|
| 232 |
+
<dd>{statusLabel(agent.lifecycle)}</dd>
|
| 233 |
</div>
|
| 234 |
<div>
|
| 235 |
+
<dt>Readiness</dt>
|
| 236 |
+
<dd>{statusLabel(agent.readiness.state)}</dd>
|
| 237 |
</div>
|
| 238 |
<div>
|
| 239 |
+
<dt>Connection</dt>
|
| 240 |
+
<dd>{statusLabel(agent.connectionStatus)}</dd>
|
| 241 |
</div>
|
| 242 |
</dl>
|
| 243 |
+
{agent.readiness.reasons.length ? (
|
| 244 |
+
<ul className="voice-agent-reasons" aria-label="Readiness reasons">
|
| 245 |
+
{agent.readiness.reasons.map((reason) => (
|
| 246 |
+
<li key={reason}>{readinessReasonLabel(reason)}</li>
|
| 247 |
+
))}
|
| 248 |
+
</ul>
|
| 249 |
+
) : (
|
| 250 |
+
<p className="voice-agent-note">No readiness issues reported.</p>
|
| 251 |
+
)}
|
| 252 |
<button type="button" className="voice-agent-disabled-control" disabled>
|
| 253 |
Voice runs unavailable
|
| 254 |
</button>
|
| 255 |
<p className="voice-agent-note">
|
| 256 |
+
Voice stays inactive until Loopable explicitly activates it.
|
|
|
|
| 257 |
</p>
|
| 258 |
</section>
|
| 259 |
|
| 260 |
+
<section className="voice-agent-section" aria-labelledby="voice-knowledge-heading">
|
| 261 |
+
<h2 id="voice-knowledge-heading">Knowledge</h2>
|
| 262 |
+
{agent.knowledgeProfile ? (
|
| 263 |
+
<dl className="voice-agent-details">
|
| 264 |
+
<div>
|
| 265 |
+
<dt>Approval</dt>
|
| 266 |
+
<dd>{statusLabel(agent.knowledgeProfile.approvalState)}</dd>
|
| 267 |
+
</div>
|
| 268 |
+
<div>
|
| 269 |
+
<dt>Version</dt>
|
| 270 |
+
<dd>{agent.knowledgeProfile.version || "Not set"}</dd>
|
| 271 |
+
</div>
|
| 272 |
+
<div>
|
| 273 |
+
<dt>Classification</dt>
|
| 274 |
+
<dd>{agent.knowledgeProfile.classification || "Not set"}</dd>
|
| 275 |
+
</div>
|
| 276 |
+
</dl>
|
| 277 |
) : (
|
| 278 |
+
<p className="voice-agent-note">No knowledge profile is assigned.</p>
|
| 279 |
)}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 280 |
</section>
|
| 281 |
</div>
|
| 282 |
|
| 283 |
+
<section className="voice-agent-section" aria-labelledby="voice-config-heading">
|
| 284 |
+
<div className="voice-agent-section-head">
|
| 285 |
+
<h2 id="voice-config-heading">Configuration</h2>
|
| 286 |
+
<span className="voice-agent-section-state">Draft settings</span>
|
| 287 |
+
</div>
|
| 288 |
+
<div className="voice-agent-config-fields">
|
| 289 |
+
<label className="voice-agent-field is-wide" htmlFor="voice-purpose">
|
| 290 |
+
Purpose
|
| 291 |
+
<textarea
|
| 292 |
+
id="voice-purpose"
|
| 293 |
+
value={draft.portableConfig.purpose}
|
| 294 |
+
onChange={(event) => changeDraft({
|
| 295 |
+
...draft,
|
| 296 |
+
portableConfig: { ...draft.portableConfig, purpose: event.target.value },
|
| 297 |
+
})}
|
| 298 |
+
maxLength={500}
|
| 299 |
+
/>
|
| 300 |
+
</label>
|
| 301 |
+
<label className="voice-agent-field is-wide" htmlFor="voice-callback-policy">
|
| 302 |
+
Callback policy
|
| 303 |
+
<input
|
| 304 |
+
id="voice-callback-policy"
|
| 305 |
+
value={draft.portableConfig.callbackPolicy}
|
| 306 |
+
onChange={(event) => changeDraft({
|
| 307 |
+
...draft,
|
| 308 |
+
portableConfig: { ...draft.portableConfig, callbackPolicy: event.target.value },
|
| 309 |
+
})}
|
| 310 |
+
maxLength={240}
|
| 311 |
+
/>
|
| 312 |
+
</label>
|
| 313 |
+
<label className="voice-agent-field" htmlFor="voice-audience-table">
|
| 314 |
+
Database
|
| 315 |
+
<select
|
| 316 |
+
id="voice-audience-table"
|
| 317 |
+
value={draft.audience.tableKey}
|
| 318 |
+
onChange={(event) => changeDraft(voiceDraftWithTable(draft, event.target.value))}
|
| 319 |
+
>
|
| 320 |
+
<option value="">Choose a database</option>
|
| 321 |
+
{tables.map((table) => (
|
| 322 |
+
<option key={table.key} value={table.key}>{table.label}</option>
|
| 323 |
+
))}
|
| 324 |
+
</select>
|
| 325 |
+
</label>
|
| 326 |
+
<label className="voice-agent-field" htmlFor="voice-audience-view">
|
| 327 |
+
Saved View
|
| 328 |
+
<select
|
| 329 |
+
id="voice-audience-view"
|
| 330 |
+
value={draft.audience.viewId}
|
| 331 |
+
onChange={(event) => changeDraft(
|
| 332 |
+
voiceDraftWithView(draft, selectedTable, event.target.value)
|
| 333 |
+
)}
|
| 334 |
+
disabled={!selectedTable}
|
| 335 |
+
>
|
| 336 |
+
<option value="">Choose a View</option>
|
| 337 |
+
{views.map((view) => (
|
| 338 |
+
<option key={view.id} value={view.id}>{view.label}</option>
|
| 339 |
+
))}
|
| 340 |
+
</select>
|
| 341 |
+
</label>
|
| 342 |
+
<label className="voice-agent-field" htmlFor="voice-audience-phone">
|
| 343 |
+
Phone field
|
| 344 |
+
<select
|
| 345 |
+
id="voice-audience-phone"
|
| 346 |
+
value={draft.audience.phoneFieldKey}
|
| 347 |
+
onChange={(event) => changeDraft({
|
| 348 |
+
...draft,
|
| 349 |
+
audience: { ...draft.audience, phoneFieldKey: event.target.value },
|
| 350 |
+
})}
|
| 351 |
+
disabled={!selectedView}
|
| 352 |
+
>
|
| 353 |
+
<option value="">Choose a phone field</option>
|
| 354 |
+
{phoneFields.map((field) => (
|
| 355 |
+
<option key={field.key} value={field.key}>{field.label}</option>
|
| 356 |
+
))}
|
| 357 |
+
</select>
|
| 358 |
+
</label>
|
| 359 |
+
<label className="voice-agent-field" htmlFor="voice-empty-policy">
|
| 360 |
+
Empty phone values
|
| 361 |
+
<select
|
| 362 |
+
id="voice-empty-policy"
|
| 363 |
+
value={draft.audience.emptyPolicy}
|
| 364 |
+
onChange={(event) => changeDraft({
|
| 365 |
+
...draft,
|
| 366 |
+
audience: {
|
| 367 |
+
...draft.audience,
|
| 368 |
+
emptyPolicy: event.target.value === "refuse" ? "refuse" : "skip",
|
| 369 |
+
},
|
| 370 |
+
})}
|
| 371 |
+
disabled={!emptyPolicies.length}
|
| 372 |
+
>
|
| 373 |
+
{!selectedPolicyIsOffered ? (
|
| 374 |
+
<option value={draft.audience.emptyPolicy} disabled>
|
| 375 |
+
Current policy is unavailable
|
| 376 |
+
</option>
|
| 377 |
+
) : null}
|
| 378 |
+
{emptyPolicies.map((option) => (
|
| 379 |
+
<option key={option.key} value={option.key}>{option.label}</option>
|
| 380 |
+
))}
|
| 381 |
+
</select>
|
| 382 |
+
</label>
|
| 383 |
+
<label className="voice-agent-field" htmlFor="voice-max-recipients">
|
| 384 |
+
Maximum recipients
|
| 385 |
+
<input
|
| 386 |
+
id="voice-max-recipients"
|
| 387 |
+
type="number"
|
| 388 |
+
min={1}
|
| 389 |
+
max={recipientCeiling || undefined}
|
| 390 |
+
step={1}
|
| 391 |
+
value={draft.audience.maxRecipients}
|
| 392 |
+
onChange={(event) => changeDraft({
|
| 393 |
+
...draft,
|
| 394 |
+
audience: {
|
| 395 |
+
...draft.audience,
|
| 396 |
+
maxRecipients: Number(event.target.value),
|
| 397 |
+
},
|
| 398 |
+
})}
|
| 399 |
+
disabled={recipientCeiling < 1}
|
| 400 |
+
aria-describedby="voice-max-recipients-range"
|
| 401 |
+
/>
|
| 402 |
+
<span id="voice-max-recipients-range" className="voice-agent-field-note">
|
| 403 |
+
{recipientCeiling > 0
|
| 404 |
+
? `Allowed range: 1 to ${recipientCeiling}`
|
| 405 |
+
: "Recipient limit unavailable"}
|
| 406 |
+
</span>
|
| 407 |
+
</label>
|
| 408 |
+
<div className="voice-agent-field voice-agent-revision">
|
| 409 |
+
<span>Saved revision</span>
|
| 410 |
+
<output id="voice-view-revision">{draft.audience.viewRevision || "Not set"}</output>
|
| 411 |
+
</div>
|
| 412 |
+
</div>
|
| 413 |
+
<div className="voice-agent-save-row">
|
| 414 |
+
<button
|
| 415 |
+
type="button"
|
| 416 |
+
className="voice-agent-save"
|
| 417 |
+
disabled={!dirty || !!validationIssue || saving}
|
| 418 |
+
onClick={() => void saveConfiguration()}
|
| 419 |
+
>
|
| 420 |
+
{saving ? "Savingβ¦" : "Save configuration"}
|
| 421 |
+
</button>
|
| 422 |
+
<span
|
| 423 |
+
className={`voice-agent-save-state${visibleSaveError ? " is-error" : saveReceipt ? " is-saved" : ""}`}
|
| 424 |
+
role={visibleSaveError ? "alert" : "status"}
|
| 425 |
+
>
|
| 426 |
+
{visibleSaveError || saveReceipt}
|
| 427 |
+
</span>
|
| 428 |
+
</div>
|
| 429 |
+
</section>
|
| 430 |
+
|
| 431 |
<section className="voice-agent-section" aria-labelledby="voice-bindings-heading">
|
| 432 |
+
<h2 id="voice-bindings-heading">Phone binding</h2>
|
| 433 |
+
{agent.phoneBinding ? (
|
| 434 |
+
<dl className="voice-agent-details">
|
| 435 |
+
<div>
|
| 436 |
+
<dt>Number</dt>
|
| 437 |
+
<dd className="voice-agent-number">{agent.phoneBinding.maskedDisplay}</dd>
|
| 438 |
+
</div>
|
| 439 |
+
<div>
|
| 440 |
+
<dt>Inbound</dt>
|
| 441 |
+
<dd>{agent.phoneBinding.routeStatus === "active" ? "Active inbound" : "Inactive"}</dd>
|
| 442 |
+
</div>
|
| 443 |
+
<div>
|
| 444 |
+
<dt>Number state</dt>
|
| 445 |
+
<dd>{statusLabel(agent.phoneBinding.numberStatus)}</dd>
|
| 446 |
+
</div>
|
| 447 |
+
</dl>
|
| 448 |
) : (
|
| 449 |
+
<p className="voice-agent-note">No phone binding is available.</p>
|
| 450 |
)}
|
| 451 |
+
{agent.capabilities.numberProvisioning === "contact_loopable" ? (
|
| 452 |
+
<p className="voice-agent-contact">
|
| 453 |
+
Phone setup: <strong>Contact Loopable</strong>
|
| 454 |
+
</p>
|
| 455 |
+
) : null}
|
| 456 |
</section>
|
| 457 |
|
| 458 |
<section className="voice-agent-section" aria-labelledby="voice-harness-heading">
|
|
|
|
| 471 |
<select
|
| 472 |
value={input.table}
|
| 473 |
onChange={(event) => {
|
| 474 |
+
setInput({ table: event.target.value, viewId: "", phoneField: "" });
|
| 475 |
+
setError("");
|
| 476 |
+
setResult(null);
|
| 477 |
}}
|
| 478 |
+
aria-label="Voice harness database"
|
| 479 |
>
|
| 480 |
<option value="">Choose a database</option>
|
| 481 |
+
{tables.map((table) => (
|
| 482 |
+
<option key={table.key} value={table.key}>{table.label}</option>
|
| 483 |
+
))}
|
| 484 |
</select>
|
| 485 |
</label>
|
| 486 |
<label>
|
|
|
|
| 488 |
<select
|
| 489 |
value={input.viewId}
|
| 490 |
onChange={(event) => {
|
| 491 |
+
setInput((current) => ({
|
| 492 |
+
...current,
|
| 493 |
+
viewId: event.target.value,
|
| 494 |
+
phoneField: "",
|
| 495 |
+
}));
|
| 496 |
+
setError("");
|
| 497 |
+
setResult(null);
|
| 498 |
}}
|
| 499 |
+
aria-label="Voice harness saved View"
|
| 500 |
+
disabled={!harnessTable}
|
| 501 |
>
|
| 502 |
<option value="">Choose a View</option>
|
| 503 |
+
{harnessViews.map((view) => (
|
| 504 |
+
<option key={view.id} value={view.id}>{view.label}</option>
|
| 505 |
+
))}
|
| 506 |
</select>
|
| 507 |
</label>
|
| 508 |
<label>
|
| 509 |
Phone field
|
| 510 |
<select
|
| 511 |
value={input.phoneField}
|
| 512 |
+
onChange={(event) => updateHarnessInput("phoneField", event.target.value)}
|
| 513 |
+
aria-label="Voice harness phone field"
|
| 514 |
+
disabled={!harnessView}
|
| 515 |
>
|
| 516 |
<option value="">Choose a phone field</option>
|
| 517 |
+
{harnessPhoneFields.map((field) => (
|
| 518 |
+
<option key={field.key} value={field.key}>{field.label}</option>
|
| 519 |
+
))}
|
| 520 |
</select>
|
| 521 |
</label>
|
| 522 |
</div>
|
web/src/automation/automationApi.ts
CHANGED
|
@@ -23,7 +23,13 @@ import {
|
|
| 23 |
signal,
|
| 24 |
} from "../apiContract";
|
| 25 |
import type {
|
|
|
|
|
|
|
| 26 |
VoiceAgentList,
|
|
|
|
|
|
|
|
|
|
|
|
|
| 27 |
VoiceHarnessInput,
|
| 28 |
VoiceHarnessResult,
|
| 29 |
} from "./voiceAgentTypes";
|
|
@@ -1020,13 +1026,208 @@ export function listAutomations(abort?: AbortSignal): Promise<AutomationList> {
|
|
| 1020 |
* The Voice control plane has its own narrow browser contract. It is deliberately not folded
|
| 1021 |
* into `/automations`: ordinary Agents and Voice Agent configuration have different safety doors.
|
| 1022 |
*/
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1023 |
export function listVoiceAgents(abort?: AbortSignal): Promise<VoiceAgentList> {
|
| 1024 |
-
return send<
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1025 |
}
|
| 1026 |
|
| 1027 |
/**
|
| 1028 |
-
* Validates only the server-authorized saved View and phone-type field.
|
| 1029 |
-
*
|
| 1030 |
*/
|
| 1031 |
export function dryRunVoiceAgent(
|
| 1032 |
voiceId: string,
|
|
|
|
| 23 |
signal,
|
| 24 |
} from "../apiContract";
|
| 25 |
import type {
|
| 26 |
+
VoiceAgent,
|
| 27 |
+
VoiceAgentDraft,
|
| 28 |
VoiceAgentList,
|
| 29 |
+
VoiceAgentPatchInput,
|
| 30 |
+
VoiceAudience,
|
| 31 |
+
VoiceAudienceOptions,
|
| 32 |
+
VoiceEmptyPolicyOption,
|
| 33 |
VoiceHarnessInput,
|
| 34 |
VoiceHarnessResult,
|
| 35 |
} from "./voiceAgentTypes";
|
|
|
|
| 1026 |
* The Voice control plane has its own narrow browser contract. It is deliberately not folded
|
| 1027 |
* into `/automations`: ordinary Agents and Voice Agent configuration have different safety doors.
|
| 1028 |
*/
|
| 1029 |
+
function voiceRecord(value: unknown): Record<string, unknown> {
|
| 1030 |
+
return value && typeof value === "object" && !Array.isArray(value)
|
| 1031 |
+
? (value as Record<string, unknown>)
|
| 1032 |
+
: {};
|
| 1033 |
+
}
|
| 1034 |
+
|
| 1035 |
+
function voiceText(value: unknown, limit = 500): string {
|
| 1036 |
+
if (typeof value !== "string" && typeof value !== "number") return "";
|
| 1037 |
+
return String(value).trim().slice(0, limit);
|
| 1038 |
+
}
|
| 1039 |
+
|
| 1040 |
+
function voiceWhole(value: unknown, fallback: number): number {
|
| 1041 |
+
const parsed = typeof value === "number" ? value : Number(value);
|
| 1042 |
+
return Number.isFinite(parsed) ? Math.trunc(parsed) : fallback;
|
| 1043 |
+
}
|
| 1044 |
+
|
| 1045 |
+
function voiceMaskedDisplay(value: unknown): string {
|
| 1046 |
+
const display = voiceText(value, 80);
|
| 1047 |
+
const digitCount = (display.match(/\d/g) || []).length;
|
| 1048 |
+
// Treat masking as a phone-shaped grammar, not as the presence of a masking character.
|
| 1049 |
+
// In particular, a lone `x` is common extension notation and must never make raw digits safe.
|
| 1050 |
+
const starOrBulletMask = /^(?:\+\d{1,3}[\s.-]?)?(?:\([*\u2022]{2,4}\)|[*\u2022]{2,4})[\s.-]+[*\u2022]{2,4}[\s.-]+\d{2,6}$/u;
|
| 1051 |
+
const xMask = /^(?:\+\d{1,3}[\s.-]?)?(?:\([xX]{2,4}\)|[xX]{2,4})[\s.-]+[xX]{2,4}[\s.-]+\d{2,6}$/;
|
| 1052 |
+
return digitCount <= 6 && (starOrBulletMask.test(display) || xMask.test(display)) ? display : "";
|
| 1053 |
+
}
|
| 1054 |
+
|
| 1055 |
+
function voiceAudience(value: unknown): VoiceAudience {
|
| 1056 |
+
const row = voiceRecord(value);
|
| 1057 |
+
return {
|
| 1058 |
+
tableKey: voiceText(row.tableKey, 120),
|
| 1059 |
+
viewId: voiceText(row.viewId, 120),
|
| 1060 |
+
viewRevision: voiceText(row.viewRevision, 120),
|
| 1061 |
+
phoneFieldKey: voiceText(row.phoneFieldKey, 120),
|
| 1062 |
+
emptyPolicy: row.emptyPolicy === "refuse" ? "refuse" : "skip",
|
| 1063 |
+
maxRecipients: voiceWhole(row.maxRecipients, 100),
|
| 1064 |
+
};
|
| 1065 |
+
}
|
| 1066 |
+
|
| 1067 |
+
function voiceAudienceOptions(value: unknown): VoiceAudienceOptions {
|
| 1068 |
+
const options = voiceRecord(value);
|
| 1069 |
+
const rawTables = options.tables;
|
| 1070 |
+
const tables = (Array.isArray(rawTables) ? rawTables : []).flatMap((candidate) => {
|
| 1071 |
+
const row = voiceRecord(candidate);
|
| 1072 |
+
const key = voiceText(row.key, 120);
|
| 1073 |
+
if (!key) return [];
|
| 1074 |
+
const rawViews = Array.isArray(row.views) ? row.views : [];
|
| 1075 |
+
const rawFields = Array.isArray(row.phoneFields) ? row.phoneFields : [];
|
| 1076 |
+
const views = rawViews.flatMap((item) => {
|
| 1077 |
+
const view = voiceRecord(item);
|
| 1078 |
+
const id = voiceText(view.id, 120);
|
| 1079 |
+
return id ? [{
|
| 1080 |
+
id,
|
| 1081 |
+
label: voiceText(view.label, 160) || id,
|
| 1082 |
+
revision: voiceText(view.revision, 120),
|
| 1083 |
+
}] : [];
|
| 1084 |
+
});
|
| 1085 |
+
const phoneFields = rawFields.flatMap((item) => {
|
| 1086 |
+
const field = voiceRecord(item);
|
| 1087 |
+
const fieldKey = voiceText(field.key, 120);
|
| 1088 |
+
return fieldKey ? [{
|
| 1089 |
+
key: fieldKey,
|
| 1090 |
+
label: voiceText(field.label, 160) || fieldKey,
|
| 1091 |
+
}] : [];
|
| 1092 |
+
});
|
| 1093 |
+
return [{ key, label: voiceText(row.label, 160) || key, views, phoneFields }];
|
| 1094 |
+
});
|
| 1095 |
+
const seenPolicies = new Set<string>();
|
| 1096 |
+
const rawPolicies = Array.isArray(options.emptyPolicies) ? options.emptyPolicies : [];
|
| 1097 |
+
const emptyPolicies = rawPolicies.flatMap((candidate) => {
|
| 1098 |
+
const row = voiceRecord(candidate);
|
| 1099 |
+
const key = row.key === "skip" || row.key === "refuse" ? row.key : "";
|
| 1100 |
+
const label = voiceText(row.label, 160);
|
| 1101 |
+
if (!key || !label || seenPolicies.has(key)) return [];
|
| 1102 |
+
seenPolicies.add(key);
|
| 1103 |
+
return [{ key, label } as VoiceEmptyPolicyOption];
|
| 1104 |
+
});
|
| 1105 |
+
const parsedCeiling = voiceWhole(options.maxRecipientsCeiling, 0);
|
| 1106 |
+
return {
|
| 1107 |
+
tables,
|
| 1108 |
+
emptyPolicies,
|
| 1109 |
+
maxRecipientsCeiling: parsedCeiling > 0 ? parsedCeiling : 0,
|
| 1110 |
+
};
|
| 1111 |
+
}
|
| 1112 |
+
|
| 1113 |
+
/**
|
| 1114 |
+
* Reduce the server response to the browser's explicit allow-list before React state sees it.
|
| 1115 |
+
* The route may carry server-only compatibility fields; spreading that object here would make a
|
| 1116 |
+
* later JSX autocomplete capable of rendering provider identities or opaque references.
|
| 1117 |
+
*/
|
| 1118 |
+
export function parseVoiceAgent(value: unknown): VoiceAgent | null {
|
| 1119 |
+
const row = voiceRecord(value);
|
| 1120 |
+
const automationId = voiceText(row.automationId, 120);
|
| 1121 |
+
const displayName = voiceText(row.displayName, 120);
|
| 1122 |
+
if (!automationId || !displayName || row.agentType !== "voice") return null;
|
| 1123 |
+
|
| 1124 |
+
const readiness = voiceRecord(row.readiness);
|
| 1125 |
+
const reasons = (Array.isArray(readiness.reasons) ? readiness.reasons : [])
|
| 1126 |
+
.map((reason) => voiceText(reason, 120))
|
| 1127 |
+
.filter(Boolean);
|
| 1128 |
+
const portable = voiceRecord(row.portableConfig);
|
| 1129 |
+
const knowledge = voiceRecord(row.knowledgeProfile);
|
| 1130 |
+
const hasKnowledge = Object.keys(knowledge).length > 0;
|
| 1131 |
+
const binding = voiceRecord(row.phoneBinding);
|
| 1132 |
+
const maskedDisplay = voiceMaskedDisplay(binding.maskedDisplay);
|
| 1133 |
+
const hasBinding = Object.keys(binding).length > 0 && !!maskedDisplay;
|
| 1134 |
+
const capabilities = voiceRecord(row.capabilities);
|
| 1135 |
+
|
| 1136 |
+
const safeAgent: VoiceAgent = {
|
| 1137 |
+
automationId,
|
| 1138 |
+
displayName,
|
| 1139 |
+
agentType: "voice",
|
| 1140 |
+
connectionStatus: voiceText(row.connectionStatus, 80) || "unconfigured",
|
| 1141 |
+
lifecycle: voiceText(row.lifecycle, 80) || "draft",
|
| 1142 |
+
readiness: {
|
| 1143 |
+
state: voiceText(readiness.state, 80) || "needs_attention",
|
| 1144 |
+
reasons,
|
| 1145 |
+
},
|
| 1146 |
+
portableConfig: {
|
| 1147 |
+
purpose: voiceText(portable.purpose, 500),
|
| 1148 |
+
callbackPolicy: voiceText(portable.callbackPolicy, 240),
|
| 1149 |
+
},
|
| 1150 |
+
knowledgeProfile: hasKnowledge ? {
|
| 1151 |
+
version: voiceText(knowledge.version, 80),
|
| 1152 |
+
classification: voiceText(knowledge.classification, 80),
|
| 1153 |
+
approvalState: voiceText(knowledge.approvalState, 80) || "draft",
|
| 1154 |
+
} : null,
|
| 1155 |
+
phoneBinding: hasBinding ? {
|
| 1156 |
+
maskedDisplay,
|
| 1157 |
+
numberStatus: voiceText(binding.numberStatus, 80) || "unconfigured",
|
| 1158 |
+
routeStatus: voiceText(binding.routeStatus, 80) || "inactive",
|
| 1159 |
+
} : null,
|
| 1160 |
+
audience: voiceAudience(row.audience),
|
| 1161 |
+
capabilities: {
|
| 1162 |
+
dryRun: capabilities.dryRun === true,
|
| 1163 |
+
...(capabilities.numberProvisioning === "contact_loopable"
|
| 1164 |
+
? { numberProvisioning: "contact_loopable" as const }
|
| 1165 |
+
: {}),
|
| 1166 |
+
},
|
| 1167 |
+
audienceOptions: voiceAudienceOptions(row.audienceOptions),
|
| 1168 |
+
};
|
| 1169 |
+
return safeAgent;
|
| 1170 |
+
}
|
| 1171 |
+
|
| 1172 |
+
export function parseVoiceAgentList(value: unknown): VoiceAgentList {
|
| 1173 |
+
const rows = voiceRecord(value).voiceAgents;
|
| 1174 |
+
return {
|
| 1175 |
+
voiceAgents: (Array.isArray(rows) ? rows : [])
|
| 1176 |
+
.map(parseVoiceAgent)
|
| 1177 |
+
.filter((row): row is VoiceAgent => row !== null),
|
| 1178 |
+
};
|
| 1179 |
+
}
|
| 1180 |
+
|
| 1181 |
export function listVoiceAgents(abort?: AbortSignal): Promise<VoiceAgentList> {
|
| 1182 |
+
return send<unknown>("/voice-agents", { signal: abort }).then(parseVoiceAgentList);
|
| 1183 |
+
}
|
| 1184 |
+
|
| 1185 |
+
/** Build the complete PATCH body field-by-field. No server DTO or caller extras may hitch a ride. */
|
| 1186 |
+
export function buildVoiceAgentPatch(draft: VoiceAgentDraft): VoiceAgentPatchInput {
|
| 1187 |
+
return {
|
| 1188 |
+
portableConfig: {
|
| 1189 |
+
purpose: voiceText(draft.portableConfig.purpose, 500),
|
| 1190 |
+
callbackPolicy: voiceText(draft.portableConfig.callbackPolicy, 240),
|
| 1191 |
+
},
|
| 1192 |
+
audience: {
|
| 1193 |
+
tableKey: voiceText(draft.audience.tableKey, 120),
|
| 1194 |
+
viewId: voiceText(draft.audience.viewId, 120),
|
| 1195 |
+
viewRevision: voiceText(draft.audience.viewRevision, 120),
|
| 1196 |
+
phoneFieldKey: voiceText(draft.audience.phoneFieldKey, 120),
|
| 1197 |
+
emptyPolicy: draft.audience.emptyPolicy === "refuse" ? "refuse" : "skip",
|
| 1198 |
+
maxRecipients: voiceWhole(draft.audience.maxRecipients, 0),
|
| 1199 |
+
},
|
| 1200 |
+
};
|
| 1201 |
+
}
|
| 1202 |
+
|
| 1203 |
+
export function patchVoiceAgent(
|
| 1204 |
+
voiceId: string,
|
| 1205 |
+
draft: VoiceAgentDraft
|
| 1206 |
+
): Promise<VoiceAgent> {
|
| 1207 |
+
return send<unknown>(`/voice-agents/${encodeURIComponent(voiceId)}`, {
|
| 1208 |
+
method: "PATCH",
|
| 1209 |
+
body: JSON.stringify(buildVoiceAgentPatch(draft)),
|
| 1210 |
+
}).then((payload) => {
|
| 1211 |
+
const next = parseVoiceAgent(voiceRecord(payload).voiceAgent);
|
| 1212 |
+
if (!next) throw new AutomationError("The server returned an invalid Voice agent.", 502);
|
| 1213 |
+
return next;
|
| 1214 |
+
});
|
| 1215 |
+
}
|
| 1216 |
+
|
| 1217 |
+
/** Adopt the exact PATCH receipt; a follow-up list read can only be older than that write. */
|
| 1218 |
+
export function replaceVoiceAgent(current: VoiceAgent[], fresh: VoiceAgent): VoiceAgent[] {
|
| 1219 |
+
let found = false;
|
| 1220 |
+
const next = current.map((agent) => {
|
| 1221 |
+
if (agent.automationId !== fresh.automationId) return agent;
|
| 1222 |
+
found = true;
|
| 1223 |
+
return fresh;
|
| 1224 |
+
});
|
| 1225 |
+
return found ? next : [...next, fresh];
|
| 1226 |
}
|
| 1227 |
|
| 1228 |
/**
|
| 1229 |
+
* Validates only the server-authorized saved View and phone-type field. It cannot dispatch or
|
| 1230 |
+
* mutate provider state; the server returns an explicit no-external-dispatch receipt.
|
| 1231 |
*/
|
| 1232 |
export function dryRunVoiceAgent(
|
| 1233 |
voiceId: string,
|
web/src/automation/voiceAgentTypes.ts
CHANGED
|
@@ -1,27 +1,61 @@
|
|
| 1 |
-
// Browser-safe Voice control-plane shapes. Provider
|
| 2 |
-
//
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3 |
|
| 4 |
export interface VoicePhoneBinding {
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
|
| 8 |
}
|
| 9 |
|
| 10 |
-
export
|
| 11 |
-
|
| 12 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 13 |
|
| 14 |
export interface VoiceCapabilities {
|
| 15 |
dryRun: boolean;
|
| 16 |
-
numberProvisioning: "contact_loopable";
|
| 17 |
-
activation: boolean;
|
| 18 |
}
|
| 19 |
|
| 20 |
export interface VoiceAudienceOption {
|
| 21 |
key: string;
|
| 22 |
label: string;
|
| 23 |
-
views
|
| 24 |
-
phoneFields
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 25 |
}
|
| 26 |
|
| 27 |
export interface VoiceAgent {
|
|
@@ -29,20 +63,29 @@ export interface VoiceAgent {
|
|
| 29 |
displayName: string;
|
| 30 |
agentType: "voice";
|
| 31 |
connectionStatus: string;
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
|
|
|
| 37 |
capabilities: VoiceCapabilities;
|
| 38 |
-
/** Server-composed choices; the browser never invents
|
| 39 |
-
audienceOptions
|
| 40 |
}
|
| 41 |
|
| 42 |
export interface VoiceAgentList {
|
| 43 |
voiceAgents: VoiceAgent[];
|
| 44 |
}
|
| 45 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 46 |
export interface VoiceHarnessInput {
|
| 47 |
table: string;
|
| 48 |
viewId: string;
|
|
|
|
| 1 |
+
// Browser-safe Voice control-plane shapes. Provider identifiers, provider extensions,
|
| 2 |
+
// credentials, knowledge identifiers, SIP/routing material, and raw phone values deliberately
|
| 3 |
+
// have no representation in this client module.
|
| 4 |
+
|
| 5 |
+
export type VoiceEmptyPolicy = "skip" | "refuse";
|
| 6 |
+
|
| 7 |
+
export interface VoicePortableConfig {
|
| 8 |
+
purpose: string;
|
| 9 |
+
callbackPolicy: string;
|
| 10 |
+
}
|
| 11 |
+
|
| 12 |
+
export interface VoiceReadiness {
|
| 13 |
+
state: string;
|
| 14 |
+
reasons: string[];
|
| 15 |
+
}
|
| 16 |
+
|
| 17 |
+
export interface VoiceKnowledgeProfile {
|
| 18 |
+
version: string;
|
| 19 |
+
classification: string;
|
| 20 |
+
approvalState: string;
|
| 21 |
+
}
|
| 22 |
|
| 23 |
export interface VoicePhoneBinding {
|
| 24 |
+
maskedDisplay: string;
|
| 25 |
+
numberStatus: string;
|
| 26 |
+
routeStatus: string;
|
| 27 |
}
|
| 28 |
|
| 29 |
+
export interface VoiceAudience {
|
| 30 |
+
tableKey: string;
|
| 31 |
+
viewId: string;
|
| 32 |
+
viewRevision: string;
|
| 33 |
+
phoneFieldKey: string;
|
| 34 |
+
emptyPolicy: VoiceEmptyPolicy;
|
| 35 |
+
maxRecipients: number;
|
| 36 |
+
}
|
| 37 |
|
| 38 |
export interface VoiceCapabilities {
|
| 39 |
dryRun: boolean;
|
| 40 |
+
numberProvisioning?: "contact_loopable";
|
|
|
|
| 41 |
}
|
| 42 |
|
| 43 |
export interface VoiceAudienceOption {
|
| 44 |
key: string;
|
| 45 |
label: string;
|
| 46 |
+
views: { id: string; label: string; revision: string }[];
|
| 47 |
+
phoneFields: { key: string; label: string }[];
|
| 48 |
+
}
|
| 49 |
+
|
| 50 |
+
export interface VoiceEmptyPolicyOption {
|
| 51 |
+
key: VoiceEmptyPolicy;
|
| 52 |
+
label: string;
|
| 53 |
+
}
|
| 54 |
+
|
| 55 |
+
export interface VoiceAudienceOptions {
|
| 56 |
+
tables: VoiceAudienceOption[];
|
| 57 |
+
emptyPolicies: VoiceEmptyPolicyOption[];
|
| 58 |
+
maxRecipientsCeiling: number;
|
| 59 |
}
|
| 60 |
|
| 61 |
export interface VoiceAgent {
|
|
|
|
| 63 |
displayName: string;
|
| 64 |
agentType: "voice";
|
| 65 |
connectionStatus: string;
|
| 66 |
+
lifecycle: string;
|
| 67 |
+
readiness: VoiceReadiness;
|
| 68 |
+
portableConfig: VoicePortableConfig;
|
| 69 |
+
knowledgeProfile: VoiceKnowledgeProfile | null;
|
| 70 |
+
phoneBinding: VoicePhoneBinding | null;
|
| 71 |
+
audience: VoiceAudience;
|
| 72 |
capabilities: VoiceCapabilities;
|
| 73 |
+
/** Server-composed choices; the browser never invents identifiers, policies, or limits. */
|
| 74 |
+
audienceOptions: VoiceAudienceOptions;
|
| 75 |
}
|
| 76 |
|
| 77 |
export interface VoiceAgentList {
|
| 78 |
voiceAgents: VoiceAgent[];
|
| 79 |
}
|
| 80 |
|
| 81 |
+
/** The complete browser PATCH allow-list. Never construct this by spreading a server DTO. */
|
| 82 |
+
export interface VoiceAgentDraft {
|
| 83 |
+
portableConfig: VoicePortableConfig;
|
| 84 |
+
audience: VoiceAudience;
|
| 85 |
+
}
|
| 86 |
+
|
| 87 |
+
export type VoiceAgentPatchInput = VoiceAgentDraft;
|
| 88 |
+
|
| 89 |
export interface VoiceHarnessInput {
|
| 90 |
table: string;
|
| 91 |
viewId: string;
|
web/src/customer-grid/CatalogView.tsx
CHANGED
|
@@ -31,6 +31,7 @@
|
|
| 31 |
|
| 32 |
import { memo, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
|
| 33 |
import { createPortal } from "react-dom";
|
|
|
|
| 34 |
import {
|
| 35 |
CATALOG_COLS,
|
| 36 |
CATALOG_NAME_MAX,
|
|
@@ -1034,7 +1035,7 @@ export const CatalogView = memo(function CatalogView({
|
|
| 1034 |
// ----------------------------------------------------------------- paint
|
| 1035 |
if (!catalogs.length)
|
| 1036 |
return (
|
| 1037 |
-
<div className="cg-cat cg-cat-blank">
|
| 1038 |
<div className="cg-cat-blank-in">
|
| 1039 |
<CrownMark className="cg-cat-blank-mark" />
|
| 1040 |
<h3>No catalogs yet</h3>
|
|
@@ -1053,7 +1054,7 @@ export const CatalogView = memo(function CatalogView({
|
|
| 1053 |
const used = cat ? codesUsed(cat) : 0;
|
| 1054 |
|
| 1055 |
return (
|
| 1056 |
-
<div className="cg-cat">
|
| 1057 |
{/* ------------------------------------------------------------ rail */}
|
| 1058 |
<aside className="cg-cat-rail">
|
| 1059 |
<div className="cg-cat-rail-head">
|
|
|
|
| 31 |
|
| 32 |
import { memo, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
|
| 33 |
import { createPortal } from "react-dom";
|
| 34 |
+
import { foldNavOnWorkSurface } from "./navFold";
|
| 35 |
import {
|
| 36 |
CATALOG_COLS,
|
| 37 |
CATALOG_NAME_MAX,
|
|
|
|
| 1035 |
// ----------------------------------------------------------------- paint
|
| 1036 |
if (!catalogs.length)
|
| 1037 |
return (
|
| 1038 |
+
<div className="cg-cat cg-cat-blank" onPointerDown={foldNavOnWorkSurface}>
|
| 1039 |
<div className="cg-cat-blank-in">
|
| 1040 |
<CrownMark className="cg-cat-blank-mark" />
|
| 1041 |
<h3>No catalogs yet</h3>
|
|
|
|
| 1054 |
const used = cat ? codesUsed(cat) : 0;
|
| 1055 |
|
| 1056 |
return (
|
| 1057 |
+
<div className="cg-cat" onPointerDown={foldNavOnWorkSurface}>
|
| 1058 |
{/* ------------------------------------------------------------ rail */}
|
| 1059 |
<aside className="cg-cat-rail">
|
| 1060 |
<div className="cg-cat-rail-head">
|
web/src/customer-grid/ColumnMenu.tsx
CHANGED
|
@@ -18,14 +18,17 @@ import { columnDefinitionOffer } from "./display";
|
|
| 18 |
// that must be runnable rather than read back to itself as source text.
|
| 19 |
import { CODE_LANGUAGE_LABELS, CODE_LANGUAGES, CREATABLE_TYPES, choiceOptions, choiceRenames,
|
| 20 |
codeLanguageOf, directionLabel, groupTypePickerRows, isDerivedLink, isMachineOwned,
|
| 21 |
-
|
|
|
|
|
|
|
|
|
|
| 22 |
ROLLUP_REF_OPS, mayEditFieldDefinition } from "./types";
|
| 23 |
-
import type { AggName, Field, FieldFormat, FieldScope, FieldType,
|
| 24 |
-
RollupRefOp, RollupSource, Viewer } from "./types";
|
| 25 |
-
import type { LinkTarget, RollupSourceOffer } from "./apiBridge";
|
| 26 |
import type { WindowSpec } from "./windows";
|
| 27 |
import { normalizeWindow, windowLabel } from "./windows";
|
| 28 |
-
import { WindowPicker } from "../filter-kit";
|
| 29 |
// ββ W41-T29 (R6, contract C2) β the ONE pair of rights predicates plus the copy that says what
|
| 30 |
// they refused, read from the same module the Fields manager reads. C2: no surface re-implements
|
| 31 |
// either test, so this menu asks rather than deriving a second answer of its own.
|
|
@@ -101,7 +104,14 @@ interface FieldConfigExtra {
|
|
| 101 |
geocode?: { addressField: string; country?: string };
|
| 102 |
/** β 2026-08-07 β a `link` column's target. REQUIRED for the type: `_clean_field` returns
|
| 103 |
* None for a link with no bag, so a create without this is a column that never appears. */
|
| 104 |
-
link?: {
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 105 |
/** β 2026-08-07 β a `rollup` column's aggregate. Same requirement, same reason.
|
| 106 |
* β 2026-08-09 β or, INSTEAD, a `source` binding: the read-through kind, which summarises
|
| 107 |
* rows that were never copied into the workspace. The host's `_clean_rollup` reads `source`
|
|
@@ -163,6 +173,8 @@ interface ColumnMenuProps {
|
|
| 163 |
* as it was before this existed. So this prop is what turns the second kind ON, not a flag.
|
| 164 |
*/
|
| 165 |
rollupSourceOffer?: RollupSourceOffer;
|
|
|
|
|
|
|
| 166 |
locked: boolean;
|
| 167 |
/** Product-owned preset fields may still drive view actions, but their schema is immutable. */
|
| 168 |
schemaLocked?: boolean;
|
|
@@ -308,7 +320,7 @@ interface ColumnMenuProps {
|
|
| 308 |
* file and no endpoint unshares a field yet. The half of R6(b) that holds without it is the
|
| 309 |
* REFUSAL: a shared-with-me column loses its Delete row whether or not this handler arrives.
|
| 310 |
*/
|
| 311 |
-
onRemoveFromMine
|
| 312 |
/** ββ Wave-34 (R13) β run this AI enrichment column over many rows.
|
| 313 |
* `scope` is `"blank"` (only cells still empty) or `"always"` (every row the AI
|
| 314 |
* wrote). OPTIONAL for `onDelete`'s reason: a host that has not wired the door shows
|
|
@@ -687,12 +699,14 @@ function optionDrafts(
|
|
| 687 |
|
| 688 |
function optionSettings(
|
| 689 |
drafts: OptionDraft[],
|
| 690 |
-
type: CreateKind
|
| 691 |
-
|
|
|
|
| 692 |
const clean = drafts.map((draft) =>
|
| 693 |
type === "multiselect" ? draft.label.replace(/,/g, " ") : draft.label
|
| 694 |
);
|
| 695 |
-
const
|
|
|
|
| 696 |
const firstByLabel = new Map<string, OptionDraft>();
|
| 697 |
drafts.forEach((draft, index) => {
|
| 698 |
const label = clean[index].trim();
|
|
@@ -708,7 +722,7 @@ function optionSettings(
|
|
| 708 |
if (color && color !== normalizeOptionColor(defaultOptionColor(option)))
|
| 709 |
colors[option] = color;
|
| 710 |
}
|
| 711 |
-
return { options, colors };
|
| 712 |
}
|
| 713 |
|
| 714 |
function optionAppearanceSignature(
|
|
@@ -820,6 +834,7 @@ function OptionsEditor({
|
|
| 820 |
colorCode,
|
| 821 |
onColorCode,
|
| 822 |
type,
|
|
|
|
| 823 |
}: {
|
| 824 |
idPrefix: string;
|
| 825 |
drafts: OptionDraft[];
|
|
@@ -827,10 +842,11 @@ function OptionsEditor({
|
|
| 827 |
colorCode: boolean;
|
| 828 |
onColorCode: (next: boolean) => void;
|
| 829 |
type: CreateKind;
|
|
|
|
| 830 |
}) {
|
| 831 |
const update = (id: string, patch: Partial<OptionDraft>) =>
|
| 832 |
onDrafts(drafts.map((draft) => (draft.id === id ? { ...draft, ...patch } : draft)));
|
| 833 |
-
const settings = optionSettings(drafts, type);
|
| 834 |
return (
|
| 835 |
<div className="cg-options-editor">
|
| 836 |
<div className="cg-options-head">
|
|
@@ -918,6 +934,11 @@ function OptionsEditor({
|
|
| 918 |
{settings.options.length} option{settings.options.length === 1 ? "" : "s"}.
|
| 919 |
{type === "multiselect" && " Commas inside an option are not supported."}
|
| 920 |
</span>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 921 |
</div>
|
| 922 |
);
|
| 923 |
}
|
|
@@ -949,6 +970,8 @@ function ChoicePreview({ field }: { field: Field }) {
|
|
| 949 |
* switch that renders cells.
|
| 950 |
*/
|
| 951 |
type CreateKind = FieldType | "measure" | "geocode";
|
|
|
|
|
|
|
| 952 |
|
| 953 |
/**
|
| 954 |
* ββ W37-T22 (R4 / C7) β the geocode pseudo-kind's picker label, and the address-column families
|
|
@@ -984,10 +1007,12 @@ function TypePicker({
|
|
| 984 |
onPick,
|
| 985 |
offerMeasure,
|
| 986 |
offerGeocode,
|
|
|
|
|
|
|
| 987 |
only,
|
| 988 |
}: {
|
| 989 |
-
value:
|
| 990 |
-
onPick: (k:
|
| 991 |
offerMeasure: boolean;
|
| 992 |
/**
|
| 993 |
* ββ W37-T22 (R4 / C7) β offer the geocode pseudo-kind. REQUIRED, not optional: an optional
|
|
@@ -1005,17 +1030,25 @@ function TypePicker({
|
|
| 1005 |
* "has an address column", which is what W37-T22's `done-when` asks for.
|
| 1006 |
*/
|
| 1007 |
offerGeocode: boolean;
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1008 |
/** Restrict the list (the Edit-field pane passes RETYPE_TYPES β the overlay-editable
|
| 1009 |
* strata a created field may become). Absent = every creatable type. */
|
| 1010 |
only?: readonly FieldType[];
|
| 1011 |
}) {
|
| 1012 |
const [q, setQ] = useState("");
|
| 1013 |
const needle = q.trim().toLowerCase();
|
| 1014 |
-
const
|
| 1015 |
? FIELD_TYPES.filter((r) => (only as readonly string[]).includes(r.value))
|
| 1016 |
: FIELD_TYPES;
|
| 1017 |
-
const
|
|
|
|
| 1018 |
...base,
|
|
|
|
|
|
|
|
|
|
| 1019 |
// C-NAME (item 9, 2026-08-02): "Formula measure (over a period)" -> "Metric". Two words
|
| 1020 |
// of jargon and a parenthetical, replaced by the word people already use for the thing.
|
| 1021 |
// The internal key stays `measure` β see the C-NAME amendment in the wave doc.
|
|
@@ -1087,11 +1120,15 @@ function TypePicker({
|
|
| 1087 |
rather than inventing a glyph no column ever shows (the iconShapes ruling). */}
|
| 1088 |
<FieldTypeIcon
|
| 1089 |
type={
|
| 1090 |
-
r.value === "measure" ? "currency" : r.value === "geocode" ? "text"
|
|
|
|
| 1091 |
}
|
| 1092 |
size={16}
|
| 1093 |
/>
|
| 1094 |
-
<span className="cg-type-label"
|
|
|
|
|
|
|
|
|
|
| 1095 |
</button>
|
| 1096 |
))}
|
| 1097 |
</Fragment>
|
|
@@ -1215,6 +1252,92 @@ function ScopeControl({
|
|
| 1215 |
* time and a nested draft makes every setter a two-level spread, which is where a patcher drops a
|
| 1216 |
* sibling key. `extraFor` does the one nesting at the moment of sending.
|
| 1217 |
*/
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1218 |
interface AiEnrichDraft {
|
| 1219 |
prompt: string;
|
| 1220 |
model: string;
|
|
@@ -1269,6 +1392,8 @@ function ExtraTypeEditor({
|
|
| 1269 |
onLinkSingle,
|
| 1270 |
linkSelectionMode = "manual",
|
| 1271 |
onLinkSelectionMode,
|
|
|
|
|
|
|
| 1272 |
rollupMode = "link",
|
| 1273 |
onRollupMode,
|
| 1274 |
rollupSourceOffer = { topics: [], windows: [] },
|
|
@@ -1337,6 +1462,9 @@ function ExtraTypeEditor({
|
|
| 1337 |
onLinkSingle?: (v: boolean) => void;
|
| 1338 |
linkSelectionMode?: "manual" | "automatic";
|
| 1339 |
onLinkSelectionMode?: (v: "manual" | "automatic") => void;
|
|
|
|
|
|
|
|
|
|
| 1340 |
/** β 2026-08-09 β which KIND of rollup is being built. `"link"` folds workspace rows;
|
| 1341 |
* `"source"` reads through to a governed Odoo topic without copying a row into the store. */
|
| 1342 |
rollupMode?: "link" | "source";
|
|
@@ -1370,7 +1498,7 @@ function ExtraTypeEditor({
|
|
| 1370 |
if (kind === "formula") {
|
| 1371 |
// 2026-07-31 (owner item 2): other FORMULA fields are referencable now β evaluation is
|
| 1372 |
// topological and a cycle is refused at validation, so the old exclusion is gone.
|
| 1373 |
-
const referencable = fields.filter((f) => f.key !== "__proto__");
|
| 1374 |
return (
|
| 1375 |
<>
|
| 1376 |
<label>
|
|
@@ -1627,7 +1755,9 @@ function ExtraTypeEditor({
|
|
| 1627 |
// thing it reads. The schedule and the Run-now button are NOT here β they belong to the
|
| 1628 |
// automation itself, on the Automation surface, because one job can fill a column across
|
| 1629 |
// many records and its cadence is a property of the job, not of the column.
|
| 1630 |
-
const urlish = fields.filter(
|
|
|
|
|
|
|
| 1631 |
const chosen = AUTOMATION_KINDS.find((k) => k.key === automationKind)
|
| 1632 |
?? AUTOMATION_KINDS[0];
|
| 1633 |
return (
|
|
@@ -1685,6 +1815,11 @@ function ExtraTypeEditor({
|
|
| 1685 |
if (kind === "link") {
|
| 1686 |
// β 2026-08-07 β Airtable's "Link to another record", and the whole editor is ONE question:
|
| 1687 |
// which database. The relation itself is then the cell (a set of linked rows).
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1688 |
return (
|
| 1689 |
<>
|
| 1690 |
<label>
|
|
@@ -1694,7 +1829,10 @@ function ExtraTypeEditor({
|
|
| 1694 |
className="cg-input"
|
| 1695 |
value={linkTable}
|
| 1696 |
aria-label="Database to link to"
|
| 1697 |
-
onChange={(event) =>
|
|
|
|
|
|
|
|
|
|
| 1698 |
>
|
| 1699 |
<option value="">Choose a databaseβ¦</option>
|
| 1700 |
{linkTargets.map((t) => (
|
|
@@ -1714,6 +1852,7 @@ function ExtraTypeEditor({
|
|
| 1714 |
className="cg-input"
|
| 1715 |
value={linkSelectionMode}
|
| 1716 |
aria-label="How linked records are selected"
|
|
|
|
| 1717 |
onPointerDown={(event) => event.stopPropagation()}
|
| 1718 |
onChange={(event) => onLinkSelectionMode?.(
|
| 1719 |
event.target.value === "automatic" ? "automatic" : "manual"
|
|
@@ -1723,6 +1862,136 @@ function ExtraTypeEditor({
|
|
| 1723 |
<option value="automatic">Set links automatically</option>
|
| 1724 |
</select>
|
| 1725 |
</label>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1726 |
<label className="cg-cond-line">
|
| 1727 |
<input
|
| 1728 |
type="checkbox"
|
|
@@ -1733,10 +2002,12 @@ function ExtraTypeEditor({
|
|
| 1733 |
/>
|
| 1734 |
<span>Allow only one linked record</span>
|
| 1735 |
</label>
|
| 1736 |
-
|
| 1737 |
-
|
| 1738 |
-
|
| 1739 |
-
|
|
|
|
|
|
|
| 1740 |
</>
|
| 1741 |
);
|
| 1742 |
}
|
|
@@ -1747,10 +2018,10 @@ function ExtraTypeEditor({
|
|
| 1747 |
// WHICH column, folded HOW, and across WHICH records. That last control is the owner's
|
| 1748 |
// headline ("average Views over last N posts") and Airtable cannot express it β its rollup
|
| 1749 |
// conditions filter by predicate, never by rank.
|
| 1750 |
-
const linkFields = fields.filter((f) => f.type === "link");
|
| 1751 |
const chosenLink = linkFields.find((f) => f.key === rollupLink);
|
| 1752 |
const target = linkTargets.find((t) => t.key === chosenLink?.link?.table);
|
| 1753 |
-
const targetFields = target?.fields ?? [];
|
| 1754 |
// β COUNTALL IS THE ONE FUNCTION WITH NO SOURCE COLUMN β it counts linked RECORDS, so the
|
| 1755 |
// field picker would be a control that configures nothing. Airtable's rule, and ours.
|
| 1756 |
const needsField = rollupFn !== "countall";
|
|
@@ -1765,7 +2036,7 @@ function ExtraTypeEditor({
|
|
| 1765 |
onRollupSource?.({ ...rollupSource, ...patch });
|
| 1766 |
// β A join column must hold a SCALAR the group key can equal. Link and rollup columns hold a
|
| 1767 |
// comma-joined id list and a computed value respectively, so neither can ever match.
|
| 1768 |
-
const joinable = fields.filter(
|
| 1769 |
(f) => f.type !== "link" && f.type !== "rollup" && f.key !== "__proto__"
|
| 1770 |
);
|
| 1771 |
const sourceEditor = (
|
|
@@ -1878,6 +2149,9 @@ function ExtraTypeEditor({
|
|
| 1878 |
);
|
| 1879 |
const linkEditor = (
|
| 1880 |
<>
|
|
|
|
|
|
|
|
|
|
| 1881 |
<label>
|
| 1882 |
<span>Through</span>
|
| 1883 |
<select
|
|
@@ -1899,6 +2173,7 @@ function ExtraTypeEditor({
|
|
| 1899 |
link, so add one of those first.
|
| 1900 |
</div>
|
| 1901 |
) : null}
|
|
|
|
| 1902 |
<label>
|
| 1903 |
<span>Fold</span>
|
| 1904 |
<select
|
|
@@ -1913,6 +2188,7 @@ function ExtraTypeEditor({
|
|
| 1913 |
))}
|
| 1914 |
</select>
|
| 1915 |
</label>
|
|
|
|
| 1916 |
{needsField ? (
|
| 1917 |
<label>
|
| 1918 |
<span>Column</span>
|
|
@@ -1971,6 +2247,8 @@ function ExtraTypeEditor({
|
|
| 1971 |
reading what the server does, in sequence. The post-filter list used to sit HERE, above
|
| 1972 |
the window it runs after, which is the one arrangement that teaches the wrong model.
|
| 1973 |
*/}
|
|
|
|
|
|
|
| 1974 |
<RollupConditionList
|
| 1975 |
idPrefix={`${idPrefix}-rollup-where`}
|
| 1976 |
title="Include records"
|
|
@@ -2069,6 +2347,8 @@ function ExtraTypeEditor({
|
|
| 2069 |
targetFields={targetFields}
|
| 2070 |
allowRef
|
| 2071 |
/>
|
|
|
|
|
|
|
| 2072 |
<div className="cg-field-hint">
|
| 2073 |
Computed for you and refreshed as the linked records change β the cell cannot be typed
|
| 2074 |
into.
|
|
@@ -2079,7 +2359,7 @@ function ExtraTypeEditor({
|
|
| 2079 |
// connected source the offer is empty, and a two-way toggle whose second option can never
|
| 2080 |
// work is a control that configures nothing ([[wrong-parent-not-broken-control]]). The link
|
| 2081 |
// editor is then simply what a rollup is, exactly as it was before this existed.
|
| 2082 |
-
if (!sourceTopics.length) return linkEditor;
|
| 2083 |
return (
|
| 2084 |
<>
|
| 2085 |
<label>
|
|
@@ -2113,6 +2393,7 @@ export default function ColumnMenu({
|
|
| 2113 |
fields,
|
| 2114 |
linkTargets = [],
|
| 2115 |
rollupSourceOffer = { topics: [], windows: [] },
|
|
|
|
| 2116 |
geocodable,
|
| 2117 |
locked,
|
| 2118 |
schemaLocked = false,
|
|
@@ -2160,6 +2441,14 @@ export default function ColumnMenu({
|
|
| 2160 |
measures = [],
|
| 2161 |
tableKey,
|
| 2162 |
}: ColumnMenuProps) {
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2163 |
/**
|
| 2164 |
* ββ W40-T24 (owner instruction 18, contract C2) β the pre-set DEFINITION lock, read from the
|
| 2165 |
* one place that states it. `display.ts` carries the whole argument, including the measured
|
|
@@ -2273,7 +2562,7 @@ export default function ColumnMenu({
|
|
| 2273 |
/** C5-AUTOFIELD β the create form's automation config. */
|
| 2274 |
const [automationKind, setAutomationKind] = useState(AUTOMATION_KINDS[0].key);
|
| 2275 |
const [automationUrlField, setAutomationUrlField] = useState(
|
| 2276 |
-
() => fields.find((f) => f.type === "url")?.key ?? ""
|
| 2277 |
);
|
| 2278 |
/**
|
| 2279 |
* β 2026-08-07 β the create form's LINK and ROLLUP configuration.
|
|
@@ -2286,6 +2575,9 @@ export default function ColumnMenu({
|
|
| 2286 |
const [linkTable, setLinkTable] = useState("");
|
| 2287 |
const [linkSingle, setLinkSingle] = useState(false);
|
| 2288 |
const [linkSelectionMode, setLinkSelectionMode] = useState<"manual" | "automatic">("manual");
|
|
|
|
|
|
|
|
|
|
| 2289 |
/** β 2026-08-09 β the read-through half. `rollupMode` decides which bag `extraFor` builds;
|
| 2290 |
* the two are mutually exclusive because the host's `_clean_rollup` returns the `source`
|
| 2291 |
* shape before it ever reads `link`. */
|
|
@@ -2304,6 +2596,24 @@ export default function ColumnMenu({
|
|
| 2304 |
const [rollupWhereConj, setRollupWhereConj] = useState<"and" | "or">("and");
|
| 2305 |
const [rollupConditions, setRollupConditions] = useState<RollupCondition[]>([]);
|
| 2306 |
const [rollupConditionConj, setRollupConditionConj] = useState<"and" | "or">("and");
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2307 |
const [swapTo, setSwapTo] = useState("");
|
| 2308 |
/** The "New field" half of Change-field keeps its own name/options β a half-typed insert
|
| 2309 |
* form must not leak into a swap and vice versa. */
|
|
@@ -2407,19 +2717,23 @@ export default function ColumnMenu({
|
|
| 2407 |
const [editLinkSelectionMode, setEditLinkSelectionMode] = useState<"manual" | "automatic">(
|
| 2408 |
() => field.link?.selectionMode === "automatic" ? "automatic" : "manual"
|
| 2409 |
);
|
|
|
|
|
|
|
|
|
|
| 2410 |
|
| 2411 |
const swapToNewType = swapTo.startsWith(NEW_PREFIX)
|
| 2412 |
? (swapTo.slice(NEW_PREFIX.length) as FieldType)
|
| 2413 |
: null;
|
| 2414 |
|
| 2415 |
-
const createChoice = optionSettings(createOptionDrafts, kind);
|
| 2416 |
const options = createChoice.options;
|
| 2417 |
const swapChoice = swapToNewType
|
| 2418 |
-
? optionSettings(swapOptionDrafts, swapToNewType)
|
| 2419 |
-
: { options: [] as string[], colors: {} as Record<string, string>
|
|
|
|
| 2420 |
const swapNewOptions = swapChoice.options;
|
| 2421 |
/** Owner item 8 β the Edit pane's parsed choices for the drafted type. */
|
| 2422 |
-
const editChoice = optionSettings(editOptionDrafts, editType);
|
| 2423 |
const editOptions = editChoice.options;
|
| 2424 |
|
| 2425 |
// Wave-5 item 9, amended 2026-07-31 (owner item 2) β live formula validation for BOTH
|
|
@@ -2466,7 +2780,9 @@ export default function ColumnMenu({
|
|
| 2466 |
* permanently unable to run.
|
| 2467 |
*/
|
| 2468 |
const addressFields = useMemo(
|
| 2469 |
-
() => fields.filter(
|
|
|
|
|
|
|
| 2470 |
[fields]
|
| 2471 |
);
|
| 2472 |
const offerGeocode = geocodable && addressFields.length > 0;
|
|
@@ -2483,6 +2799,7 @@ export default function ColumnMenu({
|
|
| 2483 |
// unparseable formula would be a permanently blank column, refused here rather than shipped.
|
| 2484 |
const canCreate =
|
| 2485 |
effectiveLabel.trim() !== "" &&
|
|
|
|
| 2486 |
(kind !== "measure" || !!chosenMeasure) &&
|
| 2487 |
// ββ W37-T22 (R4 / C7) β a geocode column with no address column to read is a column no run
|
| 2488 |
// can ever fill: the identical argument the `automation` URL-column rule below makes, and the
|
|
@@ -2503,7 +2820,7 @@ export default function ColumnMenu({
|
|
| 2503 |
// `ai_enrich` column with no prompt, so creating one without this gate produces a column that
|
| 2504 |
// is named, configured and simply absent on the next read.
|
| 2505 |
(kind !== "ai_enrich" || aiEnrich.prompt.trim() !== "") &&
|
| 2506 |
-
(kind !== "link" || linkTable !== "") &&
|
| 2507 |
(kind !== "rollup" || (rollupMode === "source"
|
| 2508 |
// β 2026-08-09 β the read-through bag. ALL FOUR keys are required by `_clean_rollup`
|
| 2509 |
// (`if not (topic and measure and group_by and on): return None`), and `on` is the one a
|
|
@@ -2522,7 +2839,8 @@ export default function ColumnMenu({
|
|
| 2522 |
t: CreateKind,
|
| 2523 |
src: string,
|
| 2524 |
starCount: number,
|
| 2525 |
-
lang: string
|
|
|
|
| 2526 |
): FieldConfigExtra | undefined => {
|
| 2527 |
if (t === "formula") return { formula: src.trim() };
|
| 2528 |
if (t === "rating") return { max: starCount };
|
|
@@ -2564,8 +2882,12 @@ export default function ColumnMenu({
|
|
| 2564 |
// picks records). The DERIVED mode is the automation's, spawned with its join declared β
|
| 2565 |
// offering "join on a column of the other table" here would be a second, harder mental
|
| 2566 |
// model for the same button.
|
| 2567 |
-
if (t === "link")
|
| 2568 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2569 |
if (t === "rollup" && rollupMode === "source")
|
| 2570 |
// β THE SOURCE BAG TRAVELS ALONE. `_clean_rollup` reads `source` first and returns
|
| 2571 |
// immediately, so sending `link`/`fn` alongside it would ship keys the store drops β
|
|
@@ -2660,7 +2982,7 @@ export default function ColumnMenu({
|
|
| 2660 |
onCreate(clean, kind, position === "end" ? null : field.key, position,
|
| 2661 |
needsOptions(kind) ? options : undefined, undefined,
|
| 2662 |
withScope({
|
| 2663 |
-
...extraFor(kind, formulaText, maxValue, codeLanguage),
|
| 2664 |
...optionExtraFor(kind, createChoice.colors, createColorCode),
|
| 2665 |
}));
|
| 2666 |
onClose();
|
|
@@ -2669,6 +2991,7 @@ export default function ColumnMenu({
|
|
| 2669 |
const canCreateSwap =
|
| 2670 |
swapToNewType != null &&
|
| 2671 |
swapLabel.trim() !== "" &&
|
|
|
|
| 2672 |
(swapToNewType !== "formula" || swapFormulaCheck.ok) &&
|
| 2673 |
// ββ Wave-34 (R13) β the SAME completeness gate `canCreate` carries, on this door too.
|
| 2674 |
//
|
|
@@ -2691,7 +3014,7 @@ export default function ColumnMenu({
|
|
| 2691 |
swapToNewType,
|
| 2692 |
needsOptions(swapToNewType) ? swapNewOptions : undefined,
|
| 2693 |
withScope({
|
| 2694 |
-
...extraFor(swapToNewType, swapFormulaText, swapMaxValue, swapCodeLanguage),
|
| 2695 |
...optionExtraFor(swapToNewType, swapChoice.colors, swapColorCode),
|
| 2696 |
})
|
| 2697 |
);
|
|
@@ -2750,7 +3073,8 @@ export default function ColumnMenu({
|
|
| 2750 |
// and silently drop the half-finished type change beside it.
|
| 2751 |
const editBlocked =
|
| 2752 |
(editRetypeTouched && !editRetypeValid) ||
|
| 2753 |
-
(editFormulaTouched && !editFormulaCheck.ok)
|
|
|
|
| 2754 |
// Item 21 (2026-08-02) β the PERIOD moved into this pane, so its dirty-check has to be
|
| 2755 |
// computed before the pane's save gate rather than beside the menu's own button. Same three
|
| 2756 |
// lines, hoisted: `canSaveEdit` reads `periodChanged`, and a `const` read before its
|
|
@@ -2802,7 +3126,9 @@ export default function ColumnMenu({
|
|
| 2802 |
? JSON.stringify(editRollup) !== JSON.stringify(field.rollup ?? {})
|
| 2803 |
: editLinkTable !== (field.link?.table ?? "") ||
|
| 2804 |
editLinkSingle !== (field.link?.single === true) ||
|
| 2805 |
-
editLinkSelectionMode !== (field.link?.selectionMode === "automatic" ? "automatic" : "manual")
|
|
|
|
|
|
|
| 2806 |
const canSaveEdit =
|
| 2807 |
/**
|
| 2808 |
* β W41-T31 β THE DESCRIPTION-ONLY PANE'S WHOLE SAVE CONDITION, and it is one dirty flag
|
|
@@ -2828,7 +3154,8 @@ export default function ColumnMenu({
|
|
| 2828 |
(editType !== "ai_enrich" || aiEnrich.prompt.trim() !== "") &&
|
| 2829 |
(editingRelational
|
| 2830 |
? (editRollupValid && (editRelationalTouched || editNameDirty || editNoteDirty) &&
|
| 2831 |
-
(field.type !== "link" ||
|
|
|
|
| 2832 |
: (editNameDirty || editRetypeTouched || editFormulaTouched ||
|
| 2833 |
(canPeriod && periodChanged) || editNoteDirty)));
|
| 2834 |
/**
|
|
@@ -2867,6 +3194,7 @@ export default function ColumnMenu({
|
|
| 2867 |
*/
|
| 2868 |
if (!canEditDescription &&
|
| 2869 |
editingRelational && onFieldConfig && (editRelationalTouched || editNameDirty)) {
|
|
|
|
| 2870 |
// β THE WHOLE BAG, EVERY SAVE. `_clean_rollup` is a pure cleaner over what it receives β
|
| 2871 |
// it does not merge with the stored bag β so a partial patch is a REBUILD, and an omitted
|
| 2872 |
// `limit` would silently become "no limit" rather than "unchanged".
|
|
@@ -2876,7 +3204,14 @@ export default function ColumnMenu({
|
|
| 2876 |
? { rollup: editRollup as Record<string, unknown> }
|
| 2877 |
: { link: { table: editLinkTable,
|
| 2878 |
selectionMode: editLinkSelectionMode,
|
| 2879 |
-
...(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2880 |
});
|
| 2881 |
if (editNoteDirty) onNote(note);
|
| 2882 |
onClose();
|
|
@@ -2959,7 +3294,7 @@ export default function ColumnMenu({
|
|
| 2959 |
* would contain; `swapOffered` is whether the picker exists at all, and it is read twice (the
|
| 2960 |
* control itself, and the focus fallback that has to know whether the control is there).
|
| 2961 |
*/
|
| 2962 |
-
const swapOptions = fields.filter((f) => f.key !== field.key);
|
| 2963 |
const presetSwap = swapOptions.filter((f) => f.source === "odoo" && !f.custom);
|
| 2964 |
const yourSwap = swapOptions.filter((f) => !(f.source === "odoo" && !f.custom));
|
| 2965 |
const swapOffered = offer.swap && swapOptions.length > 0;
|
|
@@ -3091,7 +3426,7 @@ export default function ColumnMenu({
|
|
| 3091 |
onAccept={(proposal: FieldProposal) => {
|
| 3092 |
setLabel(proposal.label);
|
| 3093 |
setLabelTouched(true);
|
| 3094 |
-
|
| 3095 |
if (proposal.options && proposal.options.length)
|
| 3096 |
setCreateOptionDrafts(optionDrafts(proposal.options));
|
| 3097 |
setAskAgent(false);
|
|
@@ -3128,10 +3463,12 @@ export default function ColumnMenu({
|
|
| 3128 |
rows, Airtable-style. The measure row appears exactly when the host offers
|
| 3129 |
measures β the same availability rule as the filter's measure conditions. */}
|
| 3130 |
<TypePicker
|
| 3131 |
-
value={kind}
|
| 3132 |
-
onPick={
|
| 3133 |
offerMeasure={measures.length > 0}
|
| 3134 |
offerGeocode={offerGeocode}
|
|
|
|
|
|
|
| 3135 |
/>
|
| 3136 |
</div>
|
| 3137 |
{kind === "measure" && (
|
|
@@ -3236,6 +3573,14 @@ export default function ColumnMenu({
|
|
| 3236 |
onLinkSingle={setLinkSingle}
|
| 3237 |
linkSelectionMode={linkSelectionMode}
|
| 3238 |
onLinkSelectionMode={setLinkSelectionMode}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3239 |
rollupMode={rollupMode}
|
| 3240 |
onRollupMode={setRollupMode}
|
| 3241 |
rollupSourceOffer={rollupSourceOffer}
|
|
@@ -3280,6 +3625,7 @@ export default function ColumnMenu({
|
|
| 3280 |
colorCode={createColorCode}
|
| 3281 |
onColorCode={setCreateColorCode}
|
| 3282 |
type={kind}
|
|
|
|
| 3283 |
/>
|
| 3284 |
)}
|
| 3285 |
{kind === "user" && (
|
|
@@ -3529,6 +3875,14 @@ export default function ColumnMenu({
|
|
| 3529 |
onLinkSingle={setEditLinkSingle}
|
| 3530 |
linkSelectionMode={editLinkSelectionMode}
|
| 3531 |
onLinkSelectionMode={setEditLinkSelectionMode}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3532 |
rollupSourceOffer={rollupSourceOffer}
|
| 3533 |
rollupMode={editRollup.source ? "source" : "link"}
|
| 3534 |
// β A MODE SWITCH REPLACES THE BAG, it does not merge into it. `_clean_rollup`
|
|
@@ -3614,6 +3968,8 @@ export default function ColumnMenu({
|
|
| 3614 |
value={editType}
|
| 3615 |
onPick={(k) => setEditType(k as FieldType)}
|
| 3616 |
offerMeasure={false}
|
|
|
|
|
|
|
| 3617 |
offerGeocode={
|
| 3618 |
/* β FALSE ON PURPOSE, and stated rather than omitted: this is the RETYPE
|
| 3619 |
picker, and a geocode column is not a type an existing column can BECOME.
|
|
@@ -3709,6 +4065,7 @@ export default function ColumnMenu({
|
|
| 3709 |
colorCode={editColorCode}
|
| 3710 |
onColorCode={setEditColorCode}
|
| 3711 |
type={editType}
|
|
|
|
| 3712 |
/>
|
| 3713 |
)}
|
| 3714 |
{editType !== field.type && (
|
|
@@ -3881,6 +4238,7 @@ export default function ColumnMenu({
|
|
| 3881 |
colorCode={swapColorCode}
|
| 3882 |
onColorCode={setSwapColorCode}
|
| 3883 |
type={swapToNewType}
|
|
|
|
| 3884 |
/>
|
| 3885 |
)}
|
| 3886 |
{swapToNewType === "user" && (
|
|
@@ -4375,7 +4733,7 @@ export default function ColumnMenu({
|
|
| 4375 |
<div className="cg-menu-sep" role="separator" aria-hidden />
|
| 4376 |
|
| 4377 |
{/* Group 3 β sort. Direction wording stays the shipped per-type directionLabel. */}
|
| 4378 |
-
{onSort && <>
|
| 4379 |
<button type="button" onClick={() => { onSort("asc"); onClose(); }}>
|
| 4380 |
<MenuLabel
|
| 4381 |
icon="sortAsc"
|
|
@@ -4403,7 +4761,7 @@ export default function ColumnMenu({
|
|
| 4403 |
column itself (offered only while the host serves measures, the same
|
| 4404 |
availability rule as measure conditions). Everything else keeps the plain
|
| 4405 |
filterable check. */}
|
| 4406 |
-
{onFilterBy && (field.filterable !== false ||
|
| 4407 |
(field.measure != null && measures.length > 0)) && (
|
| 4408 |
<button type="button" onClick={() => { onFilterBy(); onClose(); }}>
|
| 4409 |
<MenuLabel icon="filter" text="Filter by this field" />
|
|
|
|
| 18 |
// that must be runnable rather than read back to itself as source text.
|
| 19 |
import { CODE_LANGUAGE_LABELS, CODE_LANGUAGES, CREATABLE_TYPES, choiceOptions, choiceRenames,
|
| 20 |
codeLanguageOf, directionLabel, groupTypePickerRows, isDerivedLink, isMachineOwned,
|
| 21 |
+
isOfferableField, isProfileField, offerableCreateKind, parseOptions, ratingMax,
|
| 22 |
+
ROLLUP_FN_LABELS, ROLLUP_FNS, ROLLUP_PRESET_FNS, ROLLUP_PRESETS, rollupPresetOf,
|
| 23 |
+
serverOptionLimit,
|
| 24 |
+
filterTreeConj, filterTreeNodes, offerableFields, TYPE_DESCRIPTIONS,
|
| 25 |
ROLLUP_REF_OPS, mayEditFieldDefinition } from "./types";
|
| 26 |
+
import type { AggName, Conjunction, Field, FieldFormat, FieldScope, FieldType, FilterNode, Measure,
|
| 27 |
+
RollupCondition, RollupFn, RollupPreset, RollupRefOp, RollupSource, Viewer } from "./types";
|
| 28 |
+
import type { HopTopic, HopTopicOffer, LinkTarget, RollupSourceOffer } from "./apiBridge";
|
| 29 |
import type { WindowSpec } from "./windows";
|
| 30 |
import { normalizeWindow, windowLabel } from "./windows";
|
| 31 |
+
import { FilterBuilderPanel, WindowPicker } from "../filter-kit";
|
| 32 |
// ββ W41-T29 (R6, contract C2) β the ONE pair of rights predicates plus the copy that says what
|
| 33 |
// they refused, read from the same module the Fields manager reads. C2: no surface re-implements
|
| 34 |
// either test, so this menu asks rather than deriving a second answer of its own.
|
|
|
|
| 104 |
geocode?: { addressField: string; country?: string };
|
| 105 |
/** β 2026-08-07 β a `link` column's target. REQUIRED for the type: `_clean_field` returns
|
| 106 |
* None for a link with no bag, so a create without this is a column that never appears. */
|
| 107 |
+
link?: {
|
| 108 |
+
table: string;
|
| 109 |
+
on?: string;
|
| 110 |
+
from?: string;
|
| 111 |
+
single?: boolean;
|
| 112 |
+
selectionMode?: "manual" | "automatic";
|
| 113 |
+
via?: HopViaBag;
|
| 114 |
+
};
|
| 115 |
/** β 2026-08-07 β a `rollup` column's aggregate. Same requirement, same reason.
|
| 116 |
* β 2026-08-09 β or, INSTEAD, a `source` binding: the read-through kind, which summarises
|
| 117 |
* rows that were never copied into the workspace. The host's `_clean_rollup` reads `source`
|
|
|
|
| 173 |
* as it was before this existed. So this prop is what turns the second kind ON, not a flag.
|
| 174 |
*/
|
| 175 |
rollupSourceOffer?: RollupSourceOffer;
|
| 176 |
+
/** Dedicated typed offer from GET /grid/hop-topics; never derived from rollup sources. */
|
| 177 |
+
hopTopicOffer?: HopTopicOffer;
|
| 178 |
locked: boolean;
|
| 179 |
/** Product-owned preset fields may still drive view actions, but their schema is immutable. */
|
| 180 |
schemaLocked?: boolean;
|
|
|
|
| 320 |
* file and no endpoint unshares a field yet. The half of R6(b) that holds without it is the
|
| 321 |
* REFUSAL: a shared-with-me column loses its Delete row whether or not this handler arrives.
|
| 322 |
*/
|
| 323 |
+
onRemoveFromMine: () => void;
|
| 324 |
/** ββ Wave-34 (R13) β run this AI enrichment column over many rows.
|
| 325 |
* `scope` is `"blank"` (only cells still empty) or `"always"` (every row the AI
|
| 326 |
* wrote). OPTIONAL for `onDelete`'s reason: a host that has not wired the door shows
|
|
|
|
| 699 |
|
| 700 |
function optionSettings(
|
| 701 |
drafts: OptionDraft[],
|
| 702 |
+
type: CreateKind,
|
| 703 |
+
maxOptions: number | null
|
| 704 |
+
): { options: string[]; colors: Record<string, string>; capMessage: string | null } {
|
| 705 |
const clean = drafts.map((draft) =>
|
| 706 |
type === "multiselect" ? draft.label.replace(/,/g, " ") : draft.label
|
| 707 |
);
|
| 708 |
+
const parsed = parseOptions(clean.join("\n"), maxOptions);
|
| 709 |
+
const options = parsed.options;
|
| 710 |
const firstByLabel = new Map<string, OptionDraft>();
|
| 711 |
drafts.forEach((draft, index) => {
|
| 712 |
const label = clean[index].trim();
|
|
|
|
| 722 |
if (color && color !== normalizeOptionColor(defaultOptionColor(option)))
|
| 723 |
colors[option] = color;
|
| 724 |
}
|
| 725 |
+
return { options, colors, capMessage: parsed.message };
|
| 726 |
}
|
| 727 |
|
| 728 |
function optionAppearanceSignature(
|
|
|
|
| 834 |
colorCode,
|
| 835 |
onColorCode,
|
| 836 |
type,
|
| 837 |
+
maxOptions,
|
| 838 |
}: {
|
| 839 |
idPrefix: string;
|
| 840 |
drafts: OptionDraft[];
|
|
|
|
| 842 |
colorCode: boolean;
|
| 843 |
onColorCode: (next: boolean) => void;
|
| 844 |
type: CreateKind;
|
| 845 |
+
maxOptions: number | null;
|
| 846 |
}) {
|
| 847 |
const update = (id: string, patch: Partial<OptionDraft>) =>
|
| 848 |
onDrafts(drafts.map((draft) => (draft.id === id ? { ...draft, ...patch } : draft)));
|
| 849 |
+
const settings = optionSettings(drafts, type, maxOptions);
|
| 850 |
return (
|
| 851 |
<div className="cg-options-editor">
|
| 852 |
<div className="cg-options-head">
|
|
|
|
| 934 |
{settings.options.length} option{settings.options.length === 1 ? "" : "s"}.
|
| 935 |
{type === "multiselect" && " Commas inside an option are not supported."}
|
| 936 |
</span>
|
| 937 |
+
{settings.capMessage && (
|
| 938 |
+
<span className="cg-field-hint is-refusal" role="alert">
|
| 939 |
+
{settings.capMessage}
|
| 940 |
+
</span>
|
| 941 |
+
)}
|
| 942 |
</div>
|
| 943 |
);
|
| 944 |
}
|
|
|
|
| 970 |
* switch that renders cells.
|
| 971 |
*/
|
| 972 |
type CreateKind = FieldType | "measure" | "geocode";
|
| 973 |
+
type PickerKind = CreateKind | RollupPreset;
|
| 974 |
+
const PRESET_LABELS: Record<RollupPreset, string> = { count: "Count", lookup: "Lookup" };
|
| 975 |
|
| 976 |
/**
|
| 977 |
* ββ W37-T22 (R4 / C7) β the geocode pseudo-kind's picker label, and the address-column families
|
|
|
|
| 1007 |
onPick,
|
| 1008 |
offerMeasure,
|
| 1009 |
offerGeocode,
|
| 1010 |
+
offerPresets,
|
| 1011 |
+
isUserTable,
|
| 1012 |
only,
|
| 1013 |
}: {
|
| 1014 |
+
value: PickerKind;
|
| 1015 |
+
onPick: (k: PickerKind) => void;
|
| 1016 |
offerMeasure: boolean;
|
| 1017 |
/**
|
| 1018 |
* ββ W37-T22 (R4 / C7) β offer the geocode pseudo-kind. REQUIRED, not optional: an optional
|
|
|
|
| 1030 |
* "has an address column", which is what W37-T22's `done-when` asks for.
|
| 1031 |
*/
|
| 1032 |
offerGeocode: boolean;
|
| 1033 |
+
/** Presets author a rollup bag and are create-only, never retype options. */
|
| 1034 |
+
offerPresets: boolean;
|
| 1035 |
+
/** Runtime database surfaces withhold create kinds their server refuses. */
|
| 1036 |
+
isUserTable: boolean;
|
| 1037 |
/** Restrict the list (the Edit-field pane passes RETYPE_TYPES β the overlay-editable
|
| 1038 |
* strata a created field may become). Absent = every creatable type. */
|
| 1039 |
only?: readonly FieldType[];
|
| 1040 |
}) {
|
| 1041 |
const [q, setQ] = useState("");
|
| 1042 |
const needle = q.trim().toLowerCase();
|
| 1043 |
+
const offerable = only
|
| 1044 |
? FIELD_TYPES.filter((r) => (only as readonly string[]).includes(r.value))
|
| 1045 |
: FIELD_TYPES;
|
| 1046 |
+
const base = offerable.filter((row) => offerableCreateKind(row.value, isUserTable));
|
| 1047 |
+
const rows: { value: PickerKind; label: string }[] = [
|
| 1048 |
...base,
|
| 1049 |
+
...(offerPresets
|
| 1050 |
+
? ROLLUP_PRESETS.map((preset) => ({ value: preset, label: PRESET_LABELS[preset] }))
|
| 1051 |
+
: []),
|
| 1052 |
// C-NAME (item 9, 2026-08-02): "Formula measure (over a period)" -> "Metric". Two words
|
| 1053 |
// of jargon and a parenthetical, replaced by the word people already use for the thing.
|
| 1054 |
// The internal key stays `measure` β see the C-NAME amendment in the wave doc.
|
|
|
|
| 1120 |
rather than inventing a glyph no column ever shows (the iconShapes ruling). */}
|
| 1121 |
<FieldTypeIcon
|
| 1122 |
type={
|
| 1123 |
+
r.value === "measure" ? "currency" : r.value === "geocode" ? "text"
|
| 1124 |
+
: r.value === "count" || r.value === "lookup" ? "rollup" : r.value
|
| 1125 |
}
|
| 1126 |
size={16}
|
| 1127 |
/>
|
| 1128 |
+
<span className="cg-type-label" style={{ whiteSpace: "normal" }}>
|
| 1129 |
+
<span>{r.label}</span>
|
| 1130 |
+
<span className="cg-field-hint">{TYPE_DESCRIPTIONS[r.value]}</span>
|
| 1131 |
+
</span>
|
| 1132 |
</button>
|
| 1133 |
))}
|
| 1134 |
</Fragment>
|
|
|
|
| 1252 |
* time and a nested draft makes every setter a two-level spread, which is where a patcher drops a
|
| 1253 |
* sibling key. `extraFor` does the one nesting at the moment of sending.
|
| 1254 |
*/
|
| 1255 |
+
// W42-T08: the governed semantic hop optionally carried by a Link field.
|
| 1256 |
+
export interface HopViaBag {
|
| 1257 |
+
topic: string;
|
| 1258 |
+
source_dim: string;
|
| 1259 |
+
target_dim: string;
|
| 1260 |
+
target_key: string;
|
| 1261 |
+
scope_key: string;
|
| 1262 |
+
measure: string;
|
| 1263 |
+
filter: FilterNode[];
|
| 1264 |
+
filterConj: Conjunction;
|
| 1265 |
+
window: string;
|
| 1266 |
+
}
|
| 1267 |
+
|
| 1268 |
+
export interface HopDraft {
|
| 1269 |
+
topic: string;
|
| 1270 |
+
sourceDim: string;
|
| 1271 |
+
targetDim: string;
|
| 1272 |
+
targetKey: string;
|
| 1273 |
+
measure: string;
|
| 1274 |
+
filter: FilterNode[];
|
| 1275 |
+
filterConj: Conjunction;
|
| 1276 |
+
window: string;
|
| 1277 |
+
scopeKey: string;
|
| 1278 |
+
}
|
| 1279 |
+
|
| 1280 |
+
export const HOP_WINDOW_ALL = "all_time";
|
| 1281 |
+
|
| 1282 |
+
export const emptyHopDraft = (): HopDraft => ({
|
| 1283 |
+
topic: "", sourceDim: "", targetDim: "", targetKey: "", measure: "",
|
| 1284 |
+
filter: [], filterConj: "and", window: HOP_WINDOW_ALL, scopeKey: "",
|
| 1285 |
+
});
|
| 1286 |
+
|
| 1287 |
+
interface HopOffer {
|
| 1288 |
+
topics: HopTopic[];
|
| 1289 |
+
windows: { key: string; label: string }[];
|
| 1290 |
+
scopeKey: string;
|
| 1291 |
+
draft: HopDraft;
|
| 1292 |
+
onDraft: (patch: Partial<HopDraft>) => void;
|
| 1293 |
+
}
|
| 1294 |
+
|
| 1295 |
+
export function hopVia(
|
| 1296 |
+
draft: HopDraft | null | undefined,
|
| 1297 |
+
scopeKey: string
|
| 1298 |
+
): HopViaBag | null {
|
| 1299 |
+
if (!draft) return null;
|
| 1300 |
+
const topic = draft.topic.trim();
|
| 1301 |
+
const sourceDim = draft.sourceDim.trim();
|
| 1302 |
+
const targetDim = draft.targetDim.trim();
|
| 1303 |
+
const targetKey = draft.targetKey.trim();
|
| 1304 |
+
const measure = draft.measure.trim();
|
| 1305 |
+
const scope = (draft.scopeKey || scopeKey || "").trim();
|
| 1306 |
+
if (!topic || !sourceDim || !targetDim || !targetKey || !measure || !scope) return null;
|
| 1307 |
+
return {
|
| 1308 |
+
topic,
|
| 1309 |
+
source_dim: sourceDim,
|
| 1310 |
+
target_dim: targetDim,
|
| 1311 |
+
target_key: targetKey,
|
| 1312 |
+
scope_key: scope,
|
| 1313 |
+
measure,
|
| 1314 |
+
filter: draft.filter,
|
| 1315 |
+
filterConj: draft.filterConj,
|
| 1316 |
+
window: draft.window || HOP_WINDOW_ALL,
|
| 1317 |
+
};
|
| 1318 |
+
}
|
| 1319 |
+
|
| 1320 |
+
export const hopIncomplete = (draft: HopDraft | null | undefined, scopeKey: string): boolean =>
|
| 1321 |
+
!!draft && draft.topic.trim() !== "" && hopVia(draft, scopeKey) === null;
|
| 1322 |
+
|
| 1323 |
+
export function hopDraftFrom(link: unknown): HopDraft {
|
| 1324 |
+
const via = (link as { via?: Record<string, unknown> } | null | undefined)?.via;
|
| 1325 |
+
const draft = emptyHopDraft();
|
| 1326 |
+
if (!via || typeof via !== "object") return draft;
|
| 1327 |
+
const text = (value: unknown) => (typeof value === "string" ? value : "");
|
| 1328 |
+
return {
|
| 1329 |
+
topic: text(via.topic),
|
| 1330 |
+
sourceDim: text(via.source_dim),
|
| 1331 |
+
targetDim: text(via.target_dim),
|
| 1332 |
+
targetKey: text(via.target_key),
|
| 1333 |
+
measure: text(via.measure),
|
| 1334 |
+
filter: Array.isArray(via.filter) ? (via.filter as FilterNode[]) : [],
|
| 1335 |
+
filterConj: via.filterConj === "or" ? "or" : "and",
|
| 1336 |
+
window: text(via.window) || HOP_WINDOW_ALL,
|
| 1337 |
+
scopeKey: text(via.scope_key),
|
| 1338 |
+
};
|
| 1339 |
+
}
|
| 1340 |
+
|
| 1341 |
interface AiEnrichDraft {
|
| 1342 |
prompt: string;
|
| 1343 |
model: string;
|
|
|
|
| 1392 |
onLinkSingle,
|
| 1393 |
linkSelectionMode = "manual",
|
| 1394 |
onLinkSelectionMode,
|
| 1395 |
+
hop = null,
|
| 1396 |
+
rollupPreset = null,
|
| 1397 |
rollupMode = "link",
|
| 1398 |
onRollupMode,
|
| 1399 |
rollupSourceOffer = { topics: [], windows: [] },
|
|
|
|
| 1462 |
onLinkSingle?: (v: boolean) => void;
|
| 1463 |
linkSelectionMode?: "manual" | "automatic";
|
| 1464 |
onLinkSelectionMode?: (v: "manual" | "automatic") => void;
|
| 1465 |
+
hop?: HopOffer | null;
|
| 1466 |
+
/** Count/Lookup presets reopen in their reduced editor only when the stored bag is exact. */
|
| 1467 |
+
rollupPreset?: RollupPreset | null;
|
| 1468 |
/** β 2026-08-09 β which KIND of rollup is being built. `"link"` folds workspace rows;
|
| 1469 |
* `"source"` reads through to a governed Odoo topic without copying a row into the store. */
|
| 1470 |
rollupMode?: "link" | "source";
|
|
|
|
| 1498 |
if (kind === "formula") {
|
| 1499 |
// 2026-07-31 (owner item 2): other FORMULA fields are referencable now β evaluation is
|
| 1500 |
// topological and a cycle is refused at validation, so the old exclusion is gone.
|
| 1501 |
+
const referencable = offerableFields(fields).filter((f) => f.key !== "__proto__");
|
| 1502 |
return (
|
| 1503 |
<>
|
| 1504 |
<label>
|
|
|
|
| 1755 |
// thing it reads. The schedule and the Run-now button are NOT here β they belong to the
|
| 1756 |
// automation itself, on the Automation surface, because one job can fill a column across
|
| 1757 |
// many records and its cadence is a property of the job, not of the column.
|
| 1758 |
+
const urlish = offerableFields(fields).filter(
|
| 1759 |
+
(f) => f.type === "url" || f.type === "text"
|
| 1760 |
+
);
|
| 1761 |
const chosen = AUTOMATION_KINDS.find((k) => k.key === automationKind)
|
| 1762 |
?? AUTOMATION_KINDS[0];
|
| 1763 |
return (
|
|
|
|
| 1815 |
if (kind === "link") {
|
| 1816 |
// β 2026-08-07 β Airtable's "Link to another record", and the whole editor is ONE question:
|
| 1817 |
// which database. The relation itself is then the cell (a set of linked rows).
|
| 1818 |
+
const hopTopic = hop?.topics.find((topic) => topic.key === hop.draft.topic);
|
| 1819 |
+
const hopTargetFields = linkTargets.find((target) => target.key === linkTable)?.fields
|
| 1820 |
+
.filter((candidate) => candidate.type !== "link" && candidate.type !== "rollup") ?? [];
|
| 1821 |
+
const hopWindow = hop?.draft.window || HOP_WINDOW_ALL;
|
| 1822 |
+
const hopWindowOffered = !!hop?.windows.some((candidate) => candidate.key === hopWindow);
|
| 1823 |
return (
|
| 1824 |
<>
|
| 1825 |
<label>
|
|
|
|
| 1829 |
className="cg-input"
|
| 1830 |
value={linkTable}
|
| 1831 |
aria-label="Database to link to"
|
| 1832 |
+
onChange={(event) => {
|
| 1833 |
+
onLinkTable?.(event.target.value);
|
| 1834 |
+
hop?.onDraft({ targetKey: "" });
|
| 1835 |
+
}}
|
| 1836 |
>
|
| 1837 |
<option value="">Choose a databaseβ¦</option>
|
| 1838 |
{linkTargets.map((t) => (
|
|
|
|
| 1852 |
className="cg-input"
|
| 1853 |
value={linkSelectionMode}
|
| 1854 |
aria-label="How linked records are selected"
|
| 1855 |
+
disabled={!!hop?.draft.topic}
|
| 1856 |
onPointerDown={(event) => event.stopPropagation()}
|
| 1857 |
onChange={(event) => onLinkSelectionMode?.(
|
| 1858 |
event.target.value === "automatic" ? "automatic" : "manual"
|
|
|
|
| 1862 |
<option value="automatic">Set links automatically</option>
|
| 1863 |
</select>
|
| 1864 |
</label>
|
| 1865 |
+
{hop ? (
|
| 1866 |
+
<div className="cg-hop">
|
| 1867 |
+
<label className="cg-hop-question">
|
| 1868 |
+
<span>Through</span>
|
| 1869 |
+
<select
|
| 1870 |
+
id={`${idPrefix}-hop-topic`}
|
| 1871 |
+
className="cg-input"
|
| 1872 |
+
value={hop.draft.topic}
|
| 1873 |
+
aria-label="Data to travel through"
|
| 1874 |
+
onChange={(event) => {
|
| 1875 |
+
const topic = event.target.value;
|
| 1876 |
+
onLinkSelectionMode?.(topic ? "automatic" : "manual");
|
| 1877 |
+
hop.onDraft({
|
| 1878 |
+
topic,
|
| 1879 |
+
sourceDim: "",
|
| 1880 |
+
targetDim: "",
|
| 1881 |
+
measure: "",
|
| 1882 |
+
filter: [],
|
| 1883 |
+
filterConj: "and",
|
| 1884 |
+
});
|
| 1885 |
+
}}
|
| 1886 |
+
>
|
| 1887 |
+
<option value="">Nothing, link the records directly</option>
|
| 1888 |
+
{hop.topics.map((topic) => (
|
| 1889 |
+
<option key={topic.key} value={topic.key}>{topic.label}</option>
|
| 1890 |
+
))}
|
| 1891 |
+
</select>
|
| 1892 |
+
</label>
|
| 1893 |
+
{hop.topics.length === 0 ? (
|
| 1894 |
+
<div className="cg-field-hint">No governed data is available to travel through.</div>
|
| 1895 |
+
) : null}
|
| 1896 |
+
{hopTopic ? (
|
| 1897 |
+
<div className="cg-hop-body">
|
| 1898 |
+
<label>
|
| 1899 |
+
<span>Matched from</span>
|
| 1900 |
+
<select
|
| 1901 |
+
id={`${idPrefix}-hop-source-dim`}
|
| 1902 |
+
className="cg-input"
|
| 1903 |
+
value={hop.draft.sourceDim}
|
| 1904 |
+
aria-label="What names a row of this database"
|
| 1905 |
+
onChange={(event) => hop.onDraft({ sourceDim: event.target.value })}
|
| 1906 |
+
>
|
| 1907 |
+
<option value="">Choose the starting match</option>
|
| 1908 |
+
{hopTopic.dims.map((dim) => (
|
| 1909 |
+
<option key={dim.key} value={dim.key}>{dim.label}</option>
|
| 1910 |
+
))}
|
| 1911 |
+
</select>
|
| 1912 |
+
</label>
|
| 1913 |
+
<label>
|
| 1914 |
+
<span>Matched to</span>
|
| 1915 |
+
<select
|
| 1916 |
+
id={`${idPrefix}-hop-target-dim`}
|
| 1917 |
+
className="cg-input"
|
| 1918 |
+
value={hop.draft.targetDim}
|
| 1919 |
+
aria-label="What names a row of the other database"
|
| 1920 |
+
onChange={(event) => hop.onDraft({ targetDim: event.target.value })}
|
| 1921 |
+
>
|
| 1922 |
+
<option value="">Choose the destination match</option>
|
| 1923 |
+
{hopTopic.dims.map((dim) => (
|
| 1924 |
+
<option key={dim.key} value={dim.key}>{dim.label}</option>
|
| 1925 |
+
))}
|
| 1926 |
+
</select>
|
| 1927 |
+
</label>
|
| 1928 |
+
<label>
|
| 1929 |
+
<span>Column over there</span>
|
| 1930 |
+
<select
|
| 1931 |
+
id={`${idPrefix}-hop-target-key`}
|
| 1932 |
+
className="cg-input"
|
| 1933 |
+
value={hop.draft.targetKey}
|
| 1934 |
+
aria-label="Column in the other database holding that value"
|
| 1935 |
+
onChange={(event) => hop.onDraft({ targetKey: event.target.value })}
|
| 1936 |
+
>
|
| 1937 |
+
<option value="">Choose the destination column</option>
|
| 1938 |
+
{hopTargetFields.map((candidate) => (
|
| 1939 |
+
<option key={candidate.key} value={candidate.key}>{candidate.label}</option>
|
| 1940 |
+
))}
|
| 1941 |
+
</select>
|
| 1942 |
+
</label>
|
| 1943 |
+
<label>
|
| 1944 |
+
<span>Measure</span>
|
| 1945 |
+
<select
|
| 1946 |
+
id={`${idPrefix}-hop-measure`}
|
| 1947 |
+
className="cg-input"
|
| 1948 |
+
value={hop.draft.measure}
|
| 1949 |
+
aria-label="Measure"
|
| 1950 |
+
onChange={(event) => hop.onDraft({ measure: event.target.value })}
|
| 1951 |
+
>
|
| 1952 |
+
<option value="">Choose a measure</option>
|
| 1953 |
+
{hopTopic.measures.map((measure) => (
|
| 1954 |
+
<option key={measure.key} value={measure.key}>{measure.label}</option>
|
| 1955 |
+
))}
|
| 1956 |
+
</select>
|
| 1957 |
+
</label>
|
| 1958 |
+
{hop.windows.length > 0 ? (
|
| 1959 |
+
<label>
|
| 1960 |
+
<span>Over</span>
|
| 1961 |
+
<select
|
| 1962 |
+
id={`${idPrefix}-hop-window`}
|
| 1963 |
+
className="cg-input"
|
| 1964 |
+
value={hopWindow}
|
| 1965 |
+
aria-label="Date window"
|
| 1966 |
+
onChange={(event) => hop.onDraft({ window: event.target.value })}
|
| 1967 |
+
>
|
| 1968 |
+
{hopWindowOffered ? null : <option value={hopWindow}>{hopWindow}</option>}
|
| 1969 |
+
{hop.windows.map((candidate) => (
|
| 1970 |
+
<option key={candidate.key} value={candidate.key}>{candidate.label}</option>
|
| 1971 |
+
))}
|
| 1972 |
+
</select>
|
| 1973 |
+
</label>
|
| 1974 |
+
) : null}
|
| 1975 |
+
<div className="cg-hop-filter">
|
| 1976 |
+
<span className="cg-type-title">Keep only</span>
|
| 1977 |
+
<FilterBuilderPanel
|
| 1978 |
+
fields={hopTopic.dims}
|
| 1979 |
+
filters={{ conj: hop.draft.filterConj, nodes: hop.draft.filter }}
|
| 1980 |
+
onChange={(next) => hop.onDraft({
|
| 1981 |
+
filter: filterTreeNodes(next),
|
| 1982 |
+
filterConj: filterTreeConj(next),
|
| 1983 |
+
})}
|
| 1984 |
+
/>
|
| 1985 |
+
</div>
|
| 1986 |
+
{(hop.draft.scopeKey || hop.scopeKey).trim() === "" ? (
|
| 1987 |
+
<div className="cg-field-hint">
|
| 1988 |
+
This database has no usable starting scope, so the hop cannot be saved.
|
| 1989 |
+
</div>
|
| 1990 |
+
) : null}
|
| 1991 |
+
</div>
|
| 1992 |
+
) : null}
|
| 1993 |
+
</div>
|
| 1994 |
+
) : null}
|
| 1995 |
<label className="cg-cond-line">
|
| 1996 |
<input
|
| 1997 |
type="checkbox"
|
|
|
|
| 2002 |
/>
|
| 2003 |
<span>Allow only one linked record</span>
|
| 2004 |
</label>
|
| 2005 |
+
{hop?.draft.topic ? null : (
|
| 2006 |
+
<div className="cg-field-hint">
|
| 2007 |
+
A cell here holds the records you pick. Add a Rollup column afterwards to summarise a
|
| 2008 |
+
column of those records β an average, a total, a count.
|
| 2009 |
+
</div>
|
| 2010 |
+
)}
|
| 2011 |
</>
|
| 2012 |
);
|
| 2013 |
}
|
|
|
|
| 2018 |
// WHICH column, folded HOW, and across WHICH records. That last control is the owner's
|
| 2019 |
// headline ("average Views over last N posts") and Airtable cannot express it β its rollup
|
| 2020 |
// conditions filter by predicate, never by rank.
|
| 2021 |
+
const linkFields = offerableFields(fields).filter((f) => f.type === "link");
|
| 2022 |
const chosenLink = linkFields.find((f) => f.key === rollupLink);
|
| 2023 |
const target = linkTargets.find((t) => t.key === chosenLink?.link?.table);
|
| 2024 |
+
const targetFields = offerableFields(target?.fields ?? []);
|
| 2025 |
// β COUNTALL IS THE ONE FUNCTION WITH NO SOURCE COLUMN β it counts linked RECORDS, so the
|
| 2026 |
// field picker would be a control that configures nothing. Airtable's rule, and ours.
|
| 2027 |
const needsField = rollupFn !== "countall";
|
|
|
|
| 2036 |
onRollupSource?.({ ...rollupSource, ...patch });
|
| 2037 |
// β A join column must hold a SCALAR the group key can equal. Link and rollup columns hold a
|
| 2038 |
// comma-joined id list and a computed value respectively, so neither can ever match.
|
| 2039 |
+
const joinable = offerableFields(fields).filter(
|
| 2040 |
(f) => f.type !== "link" && f.type !== "rollup" && f.key !== "__proto__"
|
| 2041 |
);
|
| 2042 |
const sourceEditor = (
|
|
|
|
| 2149 |
);
|
| 2150 |
const linkEditor = (
|
| 2151 |
<>
|
| 2152 |
+
{rollupPreset ? (
|
| 2153 |
+
<div className="cg-field-hint">{TYPE_DESCRIPTIONS[rollupPreset]}</div>
|
| 2154 |
+
) : null}
|
| 2155 |
<label>
|
| 2156 |
<span>Through</span>
|
| 2157 |
<select
|
|
|
|
| 2173 |
link, so add one of those first.
|
| 2174 |
</div>
|
| 2175 |
) : null}
|
| 2176 |
+
{rollupPreset ? null : (
|
| 2177 |
<label>
|
| 2178 |
<span>Fold</span>
|
| 2179 |
<select
|
|
|
|
| 2188 |
))}
|
| 2189 |
</select>
|
| 2190 |
</label>
|
| 2191 |
+
)}
|
| 2192 |
{needsField ? (
|
| 2193 |
<label>
|
| 2194 |
<span>Column</span>
|
|
|
|
| 2247 |
reading what the server does, in sequence. The post-filter list used to sit HERE, above
|
| 2248 |
the window it runs after, which is the one arrangement that teaches the wrong model.
|
| 2249 |
*/}
|
| 2250 |
+
{rollupPreset ? null : (
|
| 2251 |
+
<>
|
| 2252 |
<RollupConditionList
|
| 2253 |
idPrefix={`${idPrefix}-rollup-where`}
|
| 2254 |
title="Include records"
|
|
|
|
| 2347 |
targetFields={targetFields}
|
| 2348 |
allowRef
|
| 2349 |
/>
|
| 2350 |
+
</>
|
| 2351 |
+
)}
|
| 2352 |
<div className="cg-field-hint">
|
| 2353 |
Computed for you and refreshed as the linked records change β the cell cannot be typed
|
| 2354 |
into.
|
|
|
|
| 2359 |
// connected source the offer is empty, and a two-way toggle whose second option can never
|
| 2360 |
// work is a control that configures nothing ([[wrong-parent-not-broken-control]]). The link
|
| 2361 |
// editor is then simply what a rollup is, exactly as it was before this existed.
|
| 2362 |
+
if (rollupPreset || !sourceTopics.length) return linkEditor;
|
| 2363 |
return (
|
| 2364 |
<>
|
| 2365 |
<label>
|
|
|
|
| 2393 |
fields,
|
| 2394 |
linkTargets = [],
|
| 2395 |
rollupSourceOffer = { topics: [], windows: [] },
|
| 2396 |
+
hopTopicOffer = { topics: [], windows: [], omissions: [] },
|
| 2397 |
geocodable,
|
| 2398 |
locked,
|
| 2399 |
schemaLocked = false,
|
|
|
|
| 2441 |
measures = [],
|
| 2442 |
tableKey,
|
| 2443 |
}: ColumnMenuProps) {
|
| 2444 |
+
const optionLimit = serverOptionLimit(fields);
|
| 2445 |
+
const fieldOfferable = isOfferableField(field);
|
| 2446 |
+
const hopScopeKey = tableKey === "customer_data"
|
| 2447 |
+
? "customer"
|
| 2448 |
+
: tableKey === "product_data"
|
| 2449 |
+
? "product"
|
| 2450 |
+
: tableKey ?? "";
|
| 2451 |
+
const hopTopics: HopTopic[] = hopTopicOffer.topics;
|
| 2452 |
/**
|
| 2453 |
* ββ W40-T24 (owner instruction 18, contract C2) β the pre-set DEFINITION lock, read from the
|
| 2454 |
* one place that states it. `display.ts` carries the whole argument, including the measured
|
|
|
|
| 2562 |
/** C5-AUTOFIELD β the create form's automation config. */
|
| 2563 |
const [automationKind, setAutomationKind] = useState(AUTOMATION_KINDS[0].key);
|
| 2564 |
const [automationUrlField, setAutomationUrlField] = useState(
|
| 2565 |
+
() => offerableFields(fields).find((f) => f.type === "url")?.key ?? ""
|
| 2566 |
);
|
| 2567 |
/**
|
| 2568 |
* β 2026-08-07 β the create form's LINK and ROLLUP configuration.
|
|
|
|
| 2575 |
const [linkTable, setLinkTable] = useState("");
|
| 2576 |
const [linkSingle, setLinkSingle] = useState(false);
|
| 2577 |
const [linkSelectionMode, setLinkSelectionMode] = useState<"manual" | "automatic">("manual");
|
| 2578 |
+
const [hopDraft, setHopDraft] = useState<HopDraft>(emptyHopDraft);
|
| 2579 |
+
const patchHopDraft = (patch: Partial<HopDraft>) =>
|
| 2580 |
+
setHopDraft((current) => ({ ...current, ...patch }));
|
| 2581 |
/** β 2026-08-09 β the read-through half. `rollupMode` decides which bag `extraFor` builds;
|
| 2582 |
* the two are mutually exclusive because the host's `_clean_rollup` returns the `source`
|
| 2583 |
* shape before it ever reads `link`. */
|
|
|
|
| 2596 |
const [rollupWhereConj, setRollupWhereConj] = useState<"and" | "or">("and");
|
| 2597 |
const [rollupConditions, setRollupConditions] = useState<RollupCondition[]>([]);
|
| 2598 |
const [rollupConditionConj, setRollupConditionConj] = useState<"and" | "or">("and");
|
| 2599 |
+
const [rollupPreset, setRollupPreset] = useState<RollupPreset | null>(null);
|
| 2600 |
+
const pickKind = (picked: PickerKind) => {
|
| 2601 |
+
const preset = picked === "count" || picked === "lookup" ? picked : null;
|
| 2602 |
+
setRollupPreset(preset);
|
| 2603 |
+
if (!preset) {
|
| 2604 |
+
setKind(picked as CreateKind);
|
| 2605 |
+
return;
|
| 2606 |
+
}
|
| 2607 |
+
setKind("rollup");
|
| 2608 |
+
setRollupMode("link");
|
| 2609 |
+
setRollupFn(ROLLUP_PRESET_FNS[preset]);
|
| 2610 |
+
if (preset === "count") setRollupField("");
|
| 2611 |
+
setRollupLimit(0);
|
| 2612 |
+
setRollupSortBy("");
|
| 2613 |
+
setRollupDistinctBy("");
|
| 2614 |
+
setRollupWhere([]);
|
| 2615 |
+
setRollupConditions([]);
|
| 2616 |
+
};
|
| 2617 |
const [swapTo, setSwapTo] = useState("");
|
| 2618 |
/** The "New field" half of Change-field keeps its own name/options β a half-typed insert
|
| 2619 |
* form must not leak into a swap and vice versa. */
|
|
|
|
| 2717 |
const [editLinkSelectionMode, setEditLinkSelectionMode] = useState<"manual" | "automatic">(
|
| 2718 |
() => field.link?.selectionMode === "automatic" ? "automatic" : "manual"
|
| 2719 |
);
|
| 2720 |
+
const [editHopDraft, setEditHopDraft] = useState<HopDraft>(() => hopDraftFrom(field.link));
|
| 2721 |
+
const patchEditHopDraft = (patch: Partial<HopDraft>) =>
|
| 2722 |
+
setEditHopDraft((current) => ({ ...current, ...patch }));
|
| 2723 |
|
| 2724 |
const swapToNewType = swapTo.startsWith(NEW_PREFIX)
|
| 2725 |
? (swapTo.slice(NEW_PREFIX.length) as FieldType)
|
| 2726 |
: null;
|
| 2727 |
|
| 2728 |
+
const createChoice = optionSettings(createOptionDrafts, kind, optionLimit);
|
| 2729 |
const options = createChoice.options;
|
| 2730 |
const swapChoice = swapToNewType
|
| 2731 |
+
? optionSettings(swapOptionDrafts, swapToNewType, optionLimit)
|
| 2732 |
+
: { options: [] as string[], colors: {} as Record<string, string>,
|
| 2733 |
+
capMessage: null as string | null };
|
| 2734 |
const swapNewOptions = swapChoice.options;
|
| 2735 |
/** Owner item 8 β the Edit pane's parsed choices for the drafted type. */
|
| 2736 |
+
const editChoice = optionSettings(editOptionDrafts, editType, optionLimit);
|
| 2737 |
const editOptions = editChoice.options;
|
| 2738 |
|
| 2739 |
// Wave-5 item 9, amended 2026-07-31 (owner item 2) β live formula validation for BOTH
|
|
|
|
| 2780 |
* permanently unable to run.
|
| 2781 |
*/
|
| 2782 |
const addressFields = useMemo(
|
| 2783 |
+
() => offerableFields(fields).filter(
|
| 2784 |
+
(f) => (GEOCODE_ADDRESS_TYPES as readonly string[]).includes(f.type)
|
| 2785 |
+
),
|
| 2786 |
[fields]
|
| 2787 |
);
|
| 2788 |
const offerGeocode = geocodable && addressFields.length > 0;
|
|
|
|
| 2799 |
// unparseable formula would be a permanently blank column, refused here rather than shipped.
|
| 2800 |
const canCreate =
|
| 2801 |
effectiveLabel.trim() !== "" &&
|
| 2802 |
+
(!needsOptions(kind) || createChoice.capMessage === null) &&
|
| 2803 |
(kind !== "measure" || !!chosenMeasure) &&
|
| 2804 |
// ββ W37-T22 (R4 / C7) β a geocode column with no address column to read is a column no run
|
| 2805 |
// can ever fill: the identical argument the `automation` URL-column rule below makes, and the
|
|
|
|
| 2820 |
// `ai_enrich` column with no prompt, so creating one without this gate produces a column that
|
| 2821 |
// is named, configured and simply absent on the next read.
|
| 2822 |
(kind !== "ai_enrich" || aiEnrich.prompt.trim() !== "") &&
|
| 2823 |
+
(kind !== "link" || (linkTable !== "" && !hopIncomplete(hopDraft, hopScopeKey))) &&
|
| 2824 |
(kind !== "rollup" || (rollupMode === "source"
|
| 2825 |
// β 2026-08-09 β the read-through bag. ALL FOUR keys are required by `_clean_rollup`
|
| 2826 |
// (`if not (topic and measure and group_by and on): return None`), and `on` is the one a
|
|
|
|
| 2839 |
t: CreateKind,
|
| 2840 |
src: string,
|
| 2841 |
starCount: number,
|
| 2842 |
+
lang: string,
|
| 2843 |
+
hopSource: HopDraft | null
|
| 2844 |
): FieldConfigExtra | undefined => {
|
| 2845 |
if (t === "formula") return { formula: src.trim() };
|
| 2846 |
if (t === "rating") return { max: starCount };
|
|
|
|
| 2882 |
// picks records). The DERIVED mode is the automation's, spawned with its join declared β
|
| 2883 |
// offering "join on a column of the other table" here would be a second, harder mental
|
| 2884 |
// model for the same button.
|
| 2885 |
+
if (t === "link") {
|
| 2886 |
+
const via = hopVia(hopSource, hopScopeKey);
|
| 2887 |
+
return { link: { table: linkTable, selectionMode: linkSelectionMode,
|
| 2888 |
+
...(linkSingle ? { single: true } : {}),
|
| 2889 |
+
...(via ? { from: "pid", on: via.target_key, via } : {}) } };
|
| 2890 |
+
}
|
| 2891 |
if (t === "rollup" && rollupMode === "source")
|
| 2892 |
// β THE SOURCE BAG TRAVELS ALONE. `_clean_rollup` reads `source` first and returns
|
| 2893 |
// immediately, so sending `link`/`fn` alongside it would ship keys the store drops β
|
|
|
|
| 2982 |
onCreate(clean, kind, position === "end" ? null : field.key, position,
|
| 2983 |
needsOptions(kind) ? options : undefined, undefined,
|
| 2984 |
withScope({
|
| 2985 |
+
...extraFor(kind, formulaText, maxValue, codeLanguage, hopDraft),
|
| 2986 |
...optionExtraFor(kind, createChoice.colors, createColorCode),
|
| 2987 |
}));
|
| 2988 |
onClose();
|
|
|
|
| 2991 |
const canCreateSwap =
|
| 2992 |
swapToNewType != null &&
|
| 2993 |
swapLabel.trim() !== "" &&
|
| 2994 |
+
(!needsOptions(swapToNewType) || swapChoice.capMessage === null) &&
|
| 2995 |
(swapToNewType !== "formula" || swapFormulaCheck.ok) &&
|
| 2996 |
// ββ Wave-34 (R13) β the SAME completeness gate `canCreate` carries, on this door too.
|
| 2997 |
//
|
|
|
|
| 3014 |
swapToNewType,
|
| 3015 |
needsOptions(swapToNewType) ? swapNewOptions : undefined,
|
| 3016 |
withScope({
|
| 3017 |
+
...extraFor(swapToNewType, swapFormulaText, swapMaxValue, swapCodeLanguage, null),
|
| 3018 |
...optionExtraFor(swapToNewType, swapChoice.colors, swapColorCode),
|
| 3019 |
})
|
| 3020 |
);
|
|
|
|
| 3073 |
// and silently drop the half-finished type change beside it.
|
| 3074 |
const editBlocked =
|
| 3075 |
(editRetypeTouched && !editRetypeValid) ||
|
| 3076 |
+
(editFormulaTouched && !editFormulaCheck.ok) ||
|
| 3077 |
+
(needsOptions(editType) && editChoice.capMessage !== null);
|
| 3078 |
// Item 21 (2026-08-02) β the PERIOD moved into this pane, so its dirty-check has to be
|
| 3079 |
// computed before the pane's save gate rather than beside the menu's own button. Same three
|
| 3080 |
// lines, hoisted: `canSaveEdit` reads `periodChanged`, and a `const` read before its
|
|
|
|
| 3126 |
? JSON.stringify(editRollup) !== JSON.stringify(field.rollup ?? {})
|
| 3127 |
: editLinkTable !== (field.link?.table ?? "") ||
|
| 3128 |
editLinkSingle !== (field.link?.single === true) ||
|
| 3129 |
+
editLinkSelectionMode !== (field.link?.selectionMode === "automatic" ? "automatic" : "manual") ||
|
| 3130 |
+
JSON.stringify(hopVia(editHopDraft, hopScopeKey)) !==
|
| 3131 |
+
JSON.stringify(hopVia(hopDraftFrom(field.link), hopScopeKey)));
|
| 3132 |
const canSaveEdit =
|
| 3133 |
/**
|
| 3134 |
* β W41-T31 β THE DESCRIPTION-ONLY PANE'S WHOLE SAVE CONDITION, and it is one dirty flag
|
|
|
|
| 3154 |
(editType !== "ai_enrich" || aiEnrich.prompt.trim() !== "") &&
|
| 3155 |
(editingRelational
|
| 3156 |
? (editRollupValid && (editRelationalTouched || editNameDirty || editNoteDirty) &&
|
| 3157 |
+
(field.type !== "link" ||
|
| 3158 |
+
(editLinkTable !== "" && !hopIncomplete(editHopDraft, hopScopeKey))))
|
| 3159 |
: (editNameDirty || editRetypeTouched || editFormulaTouched ||
|
| 3160 |
(canPeriod && periodChanged) || editNoteDirty)));
|
| 3161 |
/**
|
|
|
|
| 3194 |
*/
|
| 3195 |
if (!canEditDescription &&
|
| 3196 |
editingRelational && onFieldConfig && (editRelationalTouched || editNameDirty)) {
|
| 3197 |
+
const editVia = hopVia(editHopDraft, hopScopeKey);
|
| 3198 |
// β THE WHOLE BAG, EVERY SAVE. `_clean_rollup` is a pure cleaner over what it receives β
|
| 3199 |
// it does not merge with the stored bag β so a partial patch is a REBUILD, and an omitted
|
| 3200 |
// `limit` would silently become "no limit" rather than "unchanged".
|
|
|
|
| 3204 |
? { rollup: editRollup as Record<string, unknown> }
|
| 3205 |
: { link: { table: editLinkTable,
|
| 3206 |
selectionMode: editLinkSelectionMode,
|
| 3207 |
+
...(field.link?.on
|
| 3208 |
+
? { on: field.link.on }
|
| 3209 |
+
: editVia ? { on: editVia.target_key } : {}),
|
| 3210 |
+
...(field.link?.from
|
| 3211 |
+
? { from: field.link.from }
|
| 3212 |
+
: editVia ? { from: "pid" } : {}),
|
| 3213 |
+
...(editLinkSingle ? { single: true } : {}),
|
| 3214 |
+
...(editVia ? { via: editVia } : {}) } }),
|
| 3215 |
});
|
| 3216 |
if (editNoteDirty) onNote(note);
|
| 3217 |
onClose();
|
|
|
|
| 3294 |
* would contain; `swapOffered` is whether the picker exists at all, and it is read twice (the
|
| 3295 |
* control itself, and the focus fallback that has to know whether the control is there).
|
| 3296 |
*/
|
| 3297 |
+
const swapOptions = offerableFields(fields).filter((f) => f.key !== field.key);
|
| 3298 |
const presetSwap = swapOptions.filter((f) => f.source === "odoo" && !f.custom);
|
| 3299 |
const yourSwap = swapOptions.filter((f) => !(f.source === "odoo" && !f.custom));
|
| 3300 |
const swapOffered = offer.swap && swapOptions.length > 0;
|
|
|
|
| 3426 |
onAccept={(proposal: FieldProposal) => {
|
| 3427 |
setLabel(proposal.label);
|
| 3428 |
setLabelTouched(true);
|
| 3429 |
+
pickKind(proposal.kind);
|
| 3430 |
if (proposal.options && proposal.options.length)
|
| 3431 |
setCreateOptionDrafts(optionDrafts(proposal.options));
|
| 3432 |
setAskAgent(false);
|
|
|
|
| 3463 |
rows, Airtable-style. The measure row appears exactly when the host offers
|
| 3464 |
measures β the same availability rule as the filter's measure conditions. */}
|
| 3465 |
<TypePicker
|
| 3466 |
+
value={rollupPreset ?? kind}
|
| 3467 |
+
onPick={pickKind}
|
| 3468 |
offerMeasure={measures.length > 0}
|
| 3469 |
offerGeocode={offerGeocode}
|
| 3470 |
+
offerPresets
|
| 3471 |
+
isUserTable={isUserTable}
|
| 3472 |
/>
|
| 3473 |
</div>
|
| 3474 |
{kind === "measure" && (
|
|
|
|
| 3573 |
onLinkSingle={setLinkSingle}
|
| 3574 |
linkSelectionMode={linkSelectionMode}
|
| 3575 |
onLinkSelectionMode={setLinkSelectionMode}
|
| 3576 |
+
hop={{
|
| 3577 |
+
topics: hopTopics,
|
| 3578 |
+
windows: hopTopicOffer.windows,
|
| 3579 |
+
scopeKey: hopScopeKey,
|
| 3580 |
+
draft: hopDraft,
|
| 3581 |
+
onDraft: patchHopDraft,
|
| 3582 |
+
}}
|
| 3583 |
+
rollupPreset={rollupPreset}
|
| 3584 |
rollupMode={rollupMode}
|
| 3585 |
onRollupMode={setRollupMode}
|
| 3586 |
rollupSourceOffer={rollupSourceOffer}
|
|
|
|
| 3625 |
colorCode={createColorCode}
|
| 3626 |
onColorCode={setCreateColorCode}
|
| 3627 |
type={kind}
|
| 3628 |
+
maxOptions={optionLimit}
|
| 3629 |
/>
|
| 3630 |
)}
|
| 3631 |
{kind === "user" && (
|
|
|
|
| 3875 |
onLinkSingle={setEditLinkSingle}
|
| 3876 |
linkSelectionMode={editLinkSelectionMode}
|
| 3877 |
onLinkSelectionMode={setEditLinkSelectionMode}
|
| 3878 |
+
hop={{
|
| 3879 |
+
topics: hopTopics,
|
| 3880 |
+
windows: hopTopicOffer.windows,
|
| 3881 |
+
scopeKey: hopScopeKey,
|
| 3882 |
+
draft: editHopDraft,
|
| 3883 |
+
onDraft: patchEditHopDraft,
|
| 3884 |
+
}}
|
| 3885 |
+
rollupPreset={rollupPresetOf(editRollup)}
|
| 3886 |
rollupSourceOffer={rollupSourceOffer}
|
| 3887 |
rollupMode={editRollup.source ? "source" : "link"}
|
| 3888 |
// β A MODE SWITCH REPLACES THE BAG, it does not merge into it. `_clean_rollup`
|
|
|
|
| 3968 |
value={editType}
|
| 3969 |
onPick={(k) => setEditType(k as FieldType)}
|
| 3970 |
offerMeasure={false}
|
| 3971 |
+
offerPresets={false}
|
| 3972 |
+
isUserTable={isUserTable}
|
| 3973 |
offerGeocode={
|
| 3974 |
/* β FALSE ON PURPOSE, and stated rather than omitted: this is the RETYPE
|
| 3975 |
picker, and a geocode column is not a type an existing column can BECOME.
|
|
|
|
| 4065 |
colorCode={editColorCode}
|
| 4066 |
onColorCode={setEditColorCode}
|
| 4067 |
type={editType}
|
| 4068 |
+
maxOptions={optionLimit}
|
| 4069 |
/>
|
| 4070 |
)}
|
| 4071 |
{editType !== field.type && (
|
|
|
|
| 4238 |
colorCode={swapColorCode}
|
| 4239 |
onColorCode={setSwapColorCode}
|
| 4240 |
type={swapToNewType}
|
| 4241 |
+
maxOptions={optionLimit}
|
| 4242 |
/>
|
| 4243 |
)}
|
| 4244 |
{swapToNewType === "user" && (
|
|
|
|
| 4733 |
<div className="cg-menu-sep" role="separator" aria-hidden />
|
| 4734 |
|
| 4735 |
{/* Group 3 β sort. Direction wording stays the shipped per-type directionLabel. */}
|
| 4736 |
+
{onSort && fieldOfferable && <>
|
| 4737 |
<button type="button" onClick={() => { onSort("asc"); onClose(); }}>
|
| 4738 |
<MenuLabel
|
| 4739 |
icon="sortAsc"
|
|
|
|
| 4761 |
column itself (offered only while the host serves measures, the same
|
| 4762 |
availability rule as measure conditions). Everything else keeps the plain
|
| 4763 |
filterable check. */}
|
| 4764 |
+
{onFilterBy && fieldOfferable && (field.filterable !== false ||
|
| 4765 |
(field.measure != null && measures.length > 0)) && (
|
| 4766 |
<button type="button" onClick={() => { onFilterBy(); onClose(); }}>
|
| 4767 |
<MenuLabel icon="filter" text="Filter by this field" />
|
web/src/customer-grid/CustomerGrid.tsx
CHANGED
|
@@ -7,6 +7,7 @@ import {
|
|
| 7 |
useRef,
|
| 8 |
useState,
|
| 9 |
} from "react";
|
|
|
|
| 10 |
import { DataEditor, GridCellKind } from "@glideapps/glide-data-grid";
|
| 11 |
import type {
|
| 12 |
CellClickedEventArgs,
|
|
@@ -94,9 +95,9 @@ import { API_V1, CREDENTIALS, NAV_MINIMIZE_EVENT, ROWS_STALE_EVENT, TOAST_EVENT,
|
|
| 94 |
from "../apiContract";
|
| 95 |
import type { ViewOpenDetail } from "../apiContract";
|
| 96 |
import { addTableField, addTableRow, clearTopicRowsCache, deleteRouteOrderField, deleteTableField,
|
| 97 |
-
deleteTableRow, dropTableRowsCache, fetchLinkTargets, refusalMessage,
|
| 98 |
-
fetchRollupSources, patchRouteOrderField, patchTableField, enrichField } from "./apiBridge";
|
| 99 |
-
import type { LinkTarget, RollupSourceOffer } from "./apiBridge";
|
| 100 |
import SelectFromFile from "./SelectFromFile";
|
| 101 |
import ImportDialog from "./ImportDialog";
|
| 102 |
import { FormInterface } from "./FormInterface";
|
|
@@ -107,7 +108,7 @@ import type { CellChange, UndoBook, UndoEntry, UndoRow, UndoValue } from "./undo
|
|
| 107 |
import { buildXlsxWorkbook, exportFilename, groupingApplies, runExport, toExportGroups, triggerDownload } from "./export";
|
| 108 |
import type { ExportFormat, ExportGrouping } from "./export";
|
| 109 |
import { dataPathHash } from "./dataPath";
|
| 110 |
-
import type { DataPath } from "./dataPath";
|
| 111 |
import "../styles/wave44/data-workspace.css";
|
| 112 |
// owner item 3 (2026-08-03) β a time-series view exports its SHEET, not the rows under it.
|
| 113 |
import { buildTsCsv, tsSheetToTable } from "./timeSeriesData";
|
|
@@ -140,6 +141,7 @@ import type { RouteSourceView } from "./MapView";
|
|
| 140 |
/* βββ W18-C CATALOG βββ (owner item 4, contract C6) */
|
| 141 |
import { CatalogView } from "./CatalogView";
|
| 142 |
import { GalleryView, TimelineView } from "./GalleryTimelineViews";
|
|
|
|
| 143 |
import { CATALOG_CODE_FIELD } from "./catalogData";
|
| 144 |
import type { CatalogSpec } from "./types";
|
| 145 |
/* βββ end W18-C CATALOG βββ */
|
|
@@ -173,6 +175,7 @@ import { ALL_VIEW_ID, MAX_CALENDAR_METRICS, allViewName,
|
|
| 173 |
measureColumnIndex, ratingMax, ruleColumnKeys,
|
| 174 |
shouldAdoptEmbeddedSelection,
|
| 175 |
tableMode, uniqueDisplayName,
|
|
|
|
| 176 |
/* β W41-T38 β the rail's OWN name resolver, so a collision test compares what the reader
|
| 177 |
actually sees. The rail has always drawn `viewDisplayName(view)`; `renameView` was testing
|
| 178 |
`view.name`, and for the default view those two are different strings. */
|
|
@@ -184,7 +187,7 @@ import { ALL_VIEW_ID, MAX_CALENDAR_METRICS, allViewName,
|
|
| 184 |
and only consumed here, because W41-T43 (this file) and W41-T44 (`RecordDetail.tsx`) open the
|
| 185 |
same feature through other doors and neither of them may edit `types.ts`. */
|
| 186 |
import { buildPivotRequest, cleanSecondaryView, emptyViewConfig, PIVOT_PATH, PIVOT_WINDOW_LABELS,
|
| 187 |
-
pivotResponse, relationalTargets } from "./types";
|
| 188 |
import type {
|
| 189 |
DisplayMode,
|
| 190 |
DisplaySpec,
|
|
@@ -195,6 +198,7 @@ import type {
|
|
| 195 |
FilterNode,
|
| 196 |
FilterRule,
|
| 197 |
PivotResponse,
|
|
|
|
| 198 |
PivotWindow,
|
| 199 |
Row,
|
| 200 |
RowHeightMode,
|
|
@@ -514,6 +518,7 @@ type PivotState =
|
|
| 514 |
| { status: "idle" }
|
| 515 |
| { status: "loading" }
|
| 516 |
| { status: "absent" }
|
|
|
|
| 517 |
| { status: "ok"; answer: PivotResponse };
|
| 518 |
|
| 519 |
/**
|
|
@@ -691,6 +696,177 @@ function withColorField(config: ViewConfig, key: string): ViewConfig {
|
|
| 691 |
return { ...config, colorBy: key || null, display: cleanDisplay(display) };
|
| 692 |
}
|
| 693 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 694 |
function readLocal(storageKey: string): LocalWorkspace | null {
|
| 695 |
try {
|
| 696 |
const raw = localStorage.getItem(`aios-grid:${storageKey}`);
|
|
@@ -987,7 +1163,15 @@ interface CustomerGridProps {
|
|
| 987 |
scope?: SurfaceScope;
|
| 988 |
/** Shell-owned Data workspace location; grid resolves its view/field, never the global rail. */
|
| 989 |
dataPath?: DataPath;
|
| 990 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 991 |
/** A Query-owned immutable artefact. `scope` remains the renderer's mapped data scope. */
|
| 992 |
queryBinding?: QueryVirtualBinding;
|
| 993 |
/** Read-only Grid view embedded in a linked-record modal. It keeps the standard
|
|
@@ -999,6 +1183,25 @@ interface CustomerGridProps {
|
|
| 999 |
embeddedSelectable?: boolean;
|
| 1000 |
embeddedSelectedIds?: readonly number[];
|
| 1001 |
onEmbeddedSelectionChange?: (recordIds: number[]) => void;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1002 |
}
|
| 1003 |
|
| 1004 |
interface LinkGridModalProps {
|
|
@@ -1007,12 +1210,13 @@ interface LinkGridModalProps {
|
|
| 1007 |
recordIds: readonly number[];
|
| 1008 |
editable?: boolean;
|
| 1009 |
single?: boolean;
|
|
|
|
| 1010 |
onSave?: (recordIds: number[]) => void;
|
| 1011 |
onClose: () => void;
|
| 1012 |
}
|
| 1013 |
|
| 1014 |
function LinkGridModal({ label, table, recordIds, editable = false, single = false,
|
| 1015 |
-
onSave, onClose }: LinkGridModalProps) {
|
| 1016 |
const panelRef = useRef<HTMLDivElement>(null);
|
| 1017 |
const [selectedIds, setSelectedIds] = useState<number[]>(() => [...recordIds]);
|
| 1018 |
const changeSelectedIds = useCallback((ids: number[]) => {
|
|
@@ -1064,6 +1268,7 @@ function LinkGridModal({ label, table, recordIds, editable = false, single = fal
|
|
| 1064 |
scope={table}
|
| 1065 |
embedded
|
| 1066 |
embeddedRecordIds={editable ? undefined : recordIds}
|
|
|
|
| 1067 |
embeddedSelectable={editable}
|
| 1068 |
embeddedSelectedIds={selectedIds}
|
| 1069 |
onEmbeddedSelectionChange={changeSelectedIds}
|
|
@@ -1135,13 +1340,22 @@ function CustomerGrid(props: CustomerGridProps = {}) {
|
|
| 1135 |
function CustomerGridSurface({
|
| 1136 |
scope = "customer",
|
| 1137 |
dataPath,
|
| 1138 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1139 |
queryBinding,
|
| 1140 |
embedded = false,
|
| 1141 |
embeddedRecordIds,
|
| 1142 |
embeddedSelectable = false,
|
| 1143 |
embeddedSelectedIds = [],
|
| 1144 |
onEmbeddedSelectionChange,
|
|
|
|
| 1145 |
}: CustomerGridProps = {}) {
|
| 1146 |
const isQueryPreview = queryBinding !== undefined;
|
| 1147 |
/**
|
|
@@ -1208,16 +1422,19 @@ function CustomerGridSurface({
|
|
| 1208 |
*/
|
| 1209 |
const [pendingRows, setPendingRows] = useState<Row[]>([]);
|
| 1210 |
const rawRows = useMemo(() => {
|
| 1211 |
-
const
|
| 1212 |
? fetchedRows.filter((row) => new Set(embeddedRecordIds).has(row.pid))
|
| 1213 |
: fetchedRows;
|
|
|
|
|
|
|
|
|
|
| 1214 |
if (!pendingRows.length) return base;
|
| 1215 |
const known = new Set(base.map((r) => r.pid));
|
| 1216 |
const extra = pendingRows.filter((r) => !known.has(r.pid));
|
| 1217 |
return extra.length ? [...base, ...extra] : base;
|
| 1218 |
// The scalar key keeps this stable when a caller reconstructs the same id list.
|
| 1219 |
// eslint-disable-next-line react-hooks/exhaustive-deps
|
| 1220 |
-
}, [fetchedRows, embeddedIdsKey, pendingRows]);
|
| 1221 |
useEffect(() => {
|
| 1222 |
// β PRUNED AGAINST THE FETCHED PAYLOAD, not against `rawRows` β `rawRows` contains the
|
| 1223 |
// pending rows, so it can never report that one has been absorbed. Pruning against the
|
|
@@ -2013,6 +2230,19 @@ function CustomerGridSurface({
|
|
| 2013 |
const isUserTable = !embedded && scope.startsWith("ut_");
|
| 2014 |
const recordsMutable = payload?.recordsMutable !== false;
|
| 2015 |
const canMutateRecords = isUserTable && recordsMutable;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2016 |
/**
|
| 2017 |
* β 2026-08-07 β the databases a `link` column may point at, fetched when the column menu
|
| 2018 |
* OPENS rather than on every render of the grid.
|
|
@@ -2073,6 +2303,25 @@ function CustomerGridSurface({
|
|
| 2073 |
live = false;
|
| 2074 |
};
|
| 2075 |
}, [columnMenu, plusMenu]);
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2076 |
/**
|
| 2077 |
* β WAVE 27 Β· OWNER ITEM 22 β the values the ACTIVE VIEW forces on a new record.
|
| 2078 |
*
|
|
@@ -2265,6 +2514,12 @@ function CustomerGridSurface({
|
|
| 2265 |
useEffect(() => {
|
| 2266 |
if (displayMode !== "map") setRoutePanelOpen(false);
|
| 2267 |
}, [displayMode]);
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2268 |
|
| 2269 |
// βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 2270 |
// ββ WAVE 30 Β· W30-T42 (contract C2) β PAGING A READ-THROUGH GRID.
|
|
@@ -4314,7 +4569,7 @@ function CustomerGridSurface({
|
|
| 4314 |
if (!row) return;
|
| 4315 |
// Owner item 10: clicking into the cells is "I am working now" β the frame folds its
|
| 4316 |
// navigation rail to the slim strip (a no-op in the embed; the shell listens).
|
| 4317 |
-
|
| 4318 |
if (row.kind === "group-header") {
|
| 4319 |
event.preventDefault();
|
| 4320 |
setCollapsed((current) => {
|
|
@@ -4377,7 +4632,7 @@ function CustomerGridSurface({
|
|
| 4377 |
// The large modal mounts the same Grid surface over exactly these pids, so its standard
|
| 4378 |
// search, Filters, Sort, Fields, and column menus keep working for every database kind.
|
| 4379 |
if (row.kind === "data" && field?.type === "link" && field.link?.table) {
|
| 4380 |
-
if (field.link.table
|
| 4381 |
event.preventDefault();
|
| 4382 |
setActiveCell(cell[0], cell[1]);
|
| 4383 |
setLinkAt({ pid: row.record.pid, fieldKey: field.key });
|
|
@@ -4452,10 +4707,10 @@ function CustomerGridSurface({
|
|
| 4452 |
const row = displayRows[cell[1]];
|
| 4453 |
const column = visibleCols[cell[0]];
|
| 4454 |
const field = column ? fieldByKey.get(column.id!) : undefined;
|
| 4455 |
-
if (row?.kind === "data" && field
|
| 4456 |
setDetailPid(row.record.pid);
|
| 4457 |
},
|
| 4458 |
-
[displayRows, visibleCols, fieldByKey]
|
| 4459 |
);
|
| 4460 |
const onCellEdited = useCallback(
|
| 4461 |
(cell: Item, value: EditableGridCell) => {
|
|
@@ -6356,17 +6611,7 @@ function CustomerGridSurface({
|
|
| 6356 |
const f = fieldByKey.get(key);
|
| 6357 |
if (!f?.custom || key === lockedKey) return;
|
| 6358 |
setFields((current) => current.filter((item) => item.key !== key));
|
| 6359 |
-
|
| 6360 |
-
delete nextWidths[key];
|
| 6361 |
-
updateConfig({
|
| 6362 |
-
...config,
|
| 6363 |
-
order: order.filter((k) => k !== key),
|
| 6364 |
-
visible: [...visible].filter((k) => k !== key),
|
| 6365 |
-
widths: nextWidths,
|
| 6366 |
-
sorts: (config.sorts ?? []).filter((s) => s.colId !== key),
|
| 6367 |
-
groupBy: config.groupBy === key ? null : config.groupBy,
|
| 6368 |
-
colorBy: config.colorBy === key ? null : config.colorBy,
|
| 6369 |
-
});
|
| 6370 |
stampFieldDelete(key);
|
| 6371 |
emitHostEvent({ id: eventId("fielddel"), type: "field_delete", key });
|
| 6372 |
},
|
|
@@ -6409,17 +6654,7 @@ function CustomerGridSurface({
|
|
| 6409 |
void deleteRouteOrderField(key).then((ok) => {
|
| 6410 |
if (!ok) return; // the bridge has already said why
|
| 6411 |
setFields((current) => current.filter((item) => item.key !== key));
|
| 6412 |
-
|
| 6413 |
-
delete nextWidths[key];
|
| 6414 |
-
updateConfig({
|
| 6415 |
-
...config,
|
| 6416 |
-
order: order.filter((k) => k !== key),
|
| 6417 |
-
visible: [...visible].filter((k) => k !== key),
|
| 6418 |
-
widths: nextWidths,
|
| 6419 |
-
sorts: (config.sorts ?? []).filter((s) => s.colId !== key),
|
| 6420 |
-
groupBy: config.groupBy === key ? null : config.groupBy,
|
| 6421 |
-
colorBy: config.colorBy === key ? null : config.colorBy,
|
| 6422 |
-
});
|
| 6423 |
// β AND THE ROWS CACHE, for the reason `revealRouteField` states above: the values went
|
| 6424 |
// with the definition (`shared_overlay.drop_field` scrubs the cells), so a refetch served
|
| 6425 |
// from the pre-delete window would repaint the numbers of a column that no longer exists.
|
|
@@ -6471,17 +6706,7 @@ function CustomerGridSurface({
|
|
| 6471 |
void deleteTableField(scope, key).then((ok) => {
|
| 6472 |
if (!ok) return; // the bridge has already said why
|
| 6473 |
setFields((current) => current.filter((item) => item.key !== key));
|
| 6474 |
-
|
| 6475 |
-
delete nextWidths[key];
|
| 6476 |
-
updateConfig({
|
| 6477 |
-
...config,
|
| 6478 |
-
order: order.filter((k) => k !== key),
|
| 6479 |
-
visible: [...visible].filter((k) => k !== key),
|
| 6480 |
-
widths: nextWidths,
|
| 6481 |
-
sorts: (config.sorts ?? []).filter((s) => s.colId !== key),
|
| 6482 |
-
groupBy: config.groupBy === key ? null : config.groupBy,
|
| 6483 |
-
colorBy: config.colorBy === key ? null : config.colorBy,
|
| 6484 |
-
});
|
| 6485 |
signal(WORKSPACE_STALE_EVENT);
|
| 6486 |
signal(ROWS_STALE_EVENT);
|
| 6487 |
});
|
|
@@ -7382,7 +7607,9 @@ function CustomerGridSurface({
|
|
| 7382 |
});
|
| 7383 |
if (!live) return;
|
| 7384 |
if (!res.ok) {
|
| 7385 |
-
|
|
|
|
|
|
|
| 7386 |
return;
|
| 7387 |
}
|
| 7388 |
const answer = pivotResponse(await res.json().catch(() => null));
|
|
@@ -7443,7 +7670,7 @@ function CustomerGridSurface({
|
|
| 7443 |
// Cohort mode's toolbar control (rendered by Toolbar via the `cohortAction` slot; the popover
|
| 7444 |
// it opens is with the other overlays at the bottom). Disabled without an active cohort β
|
| 7445 |
// zero cohorts is the host page's near-empty state, not this button's error to explain.
|
| 7446 |
-
const cohortAction = cohortMode ? (
|
| 7447 |
<button
|
| 7448 |
type="button"
|
| 7449 |
className="cg-tb-btn cg-tb-addcust"
|
|
@@ -7565,6 +7792,9 @@ function CustomerGridSurface({
|
|
| 7565 |
?? (linkField && linkRow ? linkRow[linkField.key] : "")
|
| 7566 |
?? ""
|
| 7567 |
);
|
|
|
|
|
|
|
|
|
|
| 7568 |
const linkedRecordIds = [...new Set(
|
| 7569 |
linkValue.split(",").map((part) => Number(part.trim())).filter(
|
| 7570 |
(pid) => Number.isInteger(pid) && pid > 0
|
|
@@ -7674,7 +7904,9 @@ function CustomerGridSurface({
|
|
| 7674 |
|
| 7675 |
const pivotOn = !!secondary;
|
| 7676 |
const pivotAnswer = pivot.status === "ok" ? pivot.answer : null;
|
| 7677 |
-
const pivotRefusal =
|
|
|
|
|
|
|
| 7678 |
/**
|
| 7679 |
* β W41-T43 β THE SAVED PIVOT NAMES A LINK COLUMN THIS READER WAS NOT SERVED. No request went
|
| 7680 |
* out (`pivotRequestBody` is empty), so `pivot` stays `idle` and every other branch below is
|
|
@@ -7762,7 +7994,14 @@ function CustomerGridSurface({
|
|
| 7762 |
*/
|
| 7763 |
const secondaryToolbar = pivotOn && pivotServed && secondary ? (
|
| 7764 |
<Toolbar
|
|
|
|
| 7765 |
nouns={pivotTarget?.label ?? "records"}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 7766 |
sourceLabel={topic.nouns}
|
| 7767 |
fields={pivotFields}
|
| 7768 |
visible={pivotVisible}
|
|
@@ -7844,6 +8083,15 @@ function CustomerGridSurface({
|
|
| 7844 |
`QueryPage`. */}
|
| 7845 |
{!hideViews && (
|
| 7846 |
<ViewSidebar
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 7847 |
/* ββ W36-T05 (owner item 6 Β· R3 Β· R14) β the View agent, and the ONE class that
|
| 7848 |
folds the main rail. β `null` when closed, never a hidden node: `index.css` folds
|
| 7849 |
on `.shell-root:has(.cg-agent-panel)`, and `:has()` matches what EXISTS. */
|
|
@@ -8219,20 +8467,15 @@ function CustomerGridSurface({
|
|
| 8219 |
) : null
|
| 8220 |
)}
|
| 8221 |
<main className="cg-main">
|
| 8222 |
-
{dataPath && (
|
| 8223 |
-
<nav className="cg-data-path" aria-label="Data path">
|
| 8224 |
-
<span>Data</span>
|
| 8225 |
-
<span aria-hidden>βΊ</span>
|
| 8226 |
-
<span>{dataLabel ?? topic.key}</span>
|
| 8227 |
-
<span aria-hidden>βΊ</span>
|
| 8228 |
-
<span>{viewDisplayName(views.find((view) => view.id === activeViewId) ?? {
|
| 8229 |
-
id: activeViewId,
|
| 8230 |
-
name: activeViewId,
|
| 8231 |
-
})}</span>
|
| 8232 |
-
</nav>
|
| 8233 |
-
)}
|
| 8234 |
<Toolbar
|
|
|
|
| 8235 |
nouns={topic.nouns}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 8236 |
// Item 12 (C-LOCK) β the banner's copy. β BOTH fields are omitted when this reader
|
| 8237 |
// cannot see the locked set, and that omission is the SIGNAL, not an oversight: it
|
| 8238 |
// is what selects RECORD's second sentence ("locked to a set you cannot see").
|
|
@@ -8313,6 +8556,17 @@ function CustomerGridSurface({
|
|
| 8313 |
signal(TOAST_EVENT, "These sorts are locked. Copy this View to change them.");
|
| 8314 |
return;
|
| 8315 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 8316 |
updateConfig({ ...config, sorts });
|
| 8317 |
}}
|
| 8318 |
sortsLocked={activeSortsLocked}
|
|
@@ -8384,11 +8638,10 @@ function CustomerGridSurface({
|
|
| 8384 |
onToggleRoute={() => setRoutePanelOpen((open) => !open)}
|
| 8385 |
/>
|
| 8386 |
)}
|
| 8387 |
-
{/* ββ WAVE 42 Β· W42-T19 (owner instruction 11) β CALENDAR'S SECOND ROW
|
| 8388 |
-
|
| 8389 |
-
|
| 8390 |
-
|
| 8391 |
-
guard shape as `MapSettings` directly above, which is the pattern the owner named. */}
|
| 8392 |
{displayMode === "calendar" && !pivotOn && (
|
| 8393 |
<CalendarSettings
|
| 8394 |
dateField={calendarField}
|
|
@@ -8622,7 +8875,7 @@ function CustomerGridSurface({
|
|
| 8622 |
* a record that then appears twice while scrolling, which reads as duplicated data
|
| 8623 |
* rather than as a layout bug.
|
| 8624 |
*/
|
| 8625 |
-
freezeTrailingRows={
|
| 8626 |
rowHeight={rowHeight}
|
| 8627 |
headerHeight={36}
|
| 8628 |
rowMarkers="both"
|
|
@@ -9101,6 +9354,11 @@ function CustomerGridSurface({
|
|
| 9101 |
activeView={routeSourceView}
|
| 9102 |
tableKey={topic.key}
|
| 9103 |
onManagedRouteViewState={applyManagedRouteViewState}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 9104 |
/* β OWNER ITEM 9 β the route's "Add a record" search reaches PAST the view's own
|
| 9105 |
filter, so it is handed `scopedRows`: the book after the row wall (`allowed_pids`
|
| 9106 |
plus the business-unit scope) and before `useVisibleRows` applies filters, search
|
|
@@ -9319,7 +9577,7 @@ function CustomerGridSurface({
|
|
| 9319 |
: `Delete ${selectedPids.size === 1 ? "record" : "records"}`}
|
| 9320 |
</button>
|
| 9321 |
)}
|
| 9322 |
-
{cohortMode ? (
|
| 9323 |
// Item 2c: on the Cohort page the selection EDITS MEMBERSHIP of the fixed set β
|
| 9324 |
// "Remove from cohort" replaces "Add to cohort". Direct (no popover): the
|
| 9325 |
// checked set is explicit, the button says what it does, and re-adding is one
|
|
@@ -9352,13 +9610,13 @@ function CustomerGridSurface({
|
|
| 9352 |
>
|
| 9353 |
Add to cohort
|
| 9354 |
</button>
|
| 9355 |
-
)}
|
| 9356 |
{/* β Owner item 9 β the counterpart, and it renders ONLY when it can do
|
| 9357 |
something: the checked rows have to be in a cohort this viewer may edit for
|
| 9358 |
"Remove from cohortβ¦" to mean anything. Same bar, same selection, opposite
|
| 9359 |
direction β the ellipsis says a picker follows, because unlike cohort mode
|
| 9360 |
the target is not implied by where you are standing. */}
|
| 9361 |
-
{!cohortMode && removableLists.length > 0 && (
|
| 9362 |
<button
|
| 9363 |
type="button"
|
| 9364 |
className="cg-btn cg-selbar-remove-pick"
|
|
@@ -9472,6 +9730,7 @@ function CustomerGridSurface({
|
|
| 9472 |
*/
|
| 9473 |
linkTargets={linkTargets}
|
| 9474 |
rollupSourceOffer={rollupSourceOffer}
|
|
|
|
| 9475 |
locked={menuField.key === lockedKey}
|
| 9476 |
schemaLocked={isSchemaLocked(menuField)}
|
| 9477 |
/* ββ W40-T24 β the menu's `columnDefinitionOffer` (display.ts) needs the same stratum
|
|
@@ -9696,6 +9955,10 @@ function CustomerGridSurface({
|
|
| 9696 |
}
|
| 9697 |
: undefined
|
| 9698 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
| 9699 |
onDuplicate={
|
| 9700 |
// Creatable strata only β a base Odoo field offers no Duplicate (contract).
|
| 9701 |
menuField.custom && !menuField.shared ? () => duplicateField(menuField) : undefined
|
|
@@ -9727,7 +9990,18 @@ function CustomerGridSurface({
|
|
| 9727 |
onSort={
|
| 9728 |
activeSortsLocked
|
| 9729 |
? undefined
|
| 9730 |
-
: (dir) =>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 9731 |
}
|
| 9732 |
onClearSort={
|
| 9733 |
activeSortsLocked
|
|
@@ -9797,6 +10071,7 @@ function CustomerGridSurface({
|
|
| 9797 |
field={fieldByKey.get(lockedKey)!}
|
| 9798 |
fields={fields}
|
| 9799 |
locked
|
|
|
|
| 9800 |
viewer={viewer}
|
| 9801 |
sortedDir={null}
|
| 9802 |
isFiltered={false}
|
|
@@ -9807,6 +10082,10 @@ function CustomerGridSurface({
|
|
| 9807 |
onNote={() => undefined}
|
| 9808 |
onHide={() => undefined}
|
| 9809 |
onCreate={createField}
|
|
|
|
|
|
|
|
|
|
|
|
|
| 9810 |
/* The SAME answer as the sibling instance above, stated rather than defaulted: this is
|
| 9811 |
the "+" menu and it creates through the identical `createField`, so a different value
|
| 9812 |
here would mean one door offers the kind and its twin does not. The note above the
|
|
@@ -9838,6 +10117,7 @@ function CustomerGridSurface({
|
|
| 9838 |
// either way. See the sibling's note for why self-links are offered now.
|
| 9839 |
linkTargets={linkTargets}
|
| 9840 |
rollupSourceOffer={rollupSourceOffer}
|
|
|
|
| 9841 |
/>
|
| 9842 |
)}
|
| 9843 |
|
|
@@ -9877,7 +10157,7 @@ function CustomerGridSurface({
|
|
| 9877 |
|
| 9878 |
{/* The selection bar's cohort picker: existing cohorts, or a new one by name. Mirrors the
|
| 9879 |
view menu's Add-to-list surface so the two ways of building a cohort read identically. */}
|
| 9880 |
-
{selAddOpen && selAddRef.current && selectedPids.size > 0 && (
|
| 9881 |
<AnchoredOverlay
|
| 9882 |
anchor={selAddRef.current}
|
| 9883 |
className="cg-pop cg-add-list-pop"
|
|
@@ -9966,7 +10246,7 @@ function CustomerGridSurface({
|
|
| 9966 |
</AnchoredOverlay>
|
| 9967 |
)}
|
| 9968 |
|
| 9969 |
-
{selRemoveOpen && selRemoveRef.current && removableLists.length > 0 && (
|
| 9970 |
<AnchoredOverlay
|
| 9971 |
anchor={selRemoveRef.current}
|
| 9972 |
className="cg-pop cg-add-list-pop"
|
|
@@ -10002,7 +10282,7 @@ function CustomerGridSurface({
|
|
| 10002 |
once. Candidates exclude current members; picks ACCUMULATE across searches, so the
|
| 10003 |
confirm button carries the running total. The 50-row render cap is stated beside the
|
| 10004 |
list β nothing silently truncated. */}
|
| 10005 |
-
{cohortMode && addCustOpen && addCustRef.current && activeCohortId && (
|
| 10006 |
<AnchoredOverlay
|
| 10007 |
anchor={addCustRef.current}
|
| 10008 |
className="cg-pop cg-addcust-pop"
|
|
@@ -10099,13 +10379,14 @@ function CustomerGridSurface({
|
|
| 10099 |
onClose={closeJson}
|
| 10100 |
/>
|
| 10101 |
)}
|
| 10102 |
-
{linkField
|
| 10103 |
<LinkGridModal
|
| 10104 |
label={linkField.label}
|
| 10105 |
-
table={
|
| 10106 |
recordIds={linkedRecordIds}
|
| 10107 |
editable={canEditField(linkField) && !isDerivedLink(linkField)}
|
| 10108 |
-
single={linkField.link.single === true}
|
|
|
|
| 10109 |
onSave={(ids) => patchAndRecord(
|
| 10110 |
linkAt.pid,
|
| 10111 |
{ [linkField.key]: ids.join(",") },
|
|
|
|
| 7 |
useRef,
|
| 8 |
useState,
|
| 9 |
} from "react";
|
| 10 |
+
import type { ReactNode } from "react";
|
| 11 |
import { DataEditor, GridCellKind } from "@glideapps/glide-data-grid";
|
| 12 |
import type {
|
| 13 |
CellClickedEventArgs,
|
|
|
|
| 95 |
from "../apiContract";
|
| 96 |
import type { ViewOpenDetail } from "../apiContract";
|
| 97 |
import { addTableField, addTableRow, clearTopicRowsCache, deleteRouteOrderField, deleteTableField,
|
| 98 |
+
deleteTableFields, deleteTableRow, dropTableRowsCache, fetchLinkTargets, refusalMessage,
|
| 99 |
+
fetchHopTopics, fetchRollupSources, patchRouteOrderField, patchTableField, enrichField } from "./apiBridge";
|
| 100 |
+
import type { FieldDeleteResult, HopTopicOffer, LinkTarget, RollupSourceOffer } from "./apiBridge";
|
| 101 |
import SelectFromFile from "./SelectFromFile";
|
| 102 |
import ImportDialog from "./ImportDialog";
|
| 103 |
import { FormInterface } from "./FormInterface";
|
|
|
|
| 108 |
import { buildXlsxWorkbook, exportFilename, groupingApplies, runExport, toExportGroups, triggerDownload } from "./export";
|
| 109 |
import type { ExportFormat, ExportGrouping } from "./export";
|
| 110 |
import { dataPathHash } from "./dataPath";
|
| 111 |
+
import type { DataDatabase, DataDatabaseFolder, DataPath } from "./dataPath";
|
| 112 |
import "../styles/wave44/data-workspace.css";
|
| 113 |
// owner item 3 (2026-08-03) β a time-series view exports its SHEET, not the rows under it.
|
| 114 |
import { buildTsCsv, tsSheetToTable } from "./timeSeriesData";
|
|
|
|
| 141 |
/* βββ W18-C CATALOG βββ (owner item 4, contract C6) */
|
| 142 |
import { CatalogView } from "./CatalogView";
|
| 143 |
import { GalleryView, TimelineView } from "./GalleryTimelineViews";
|
| 144 |
+
import { foldGridCell } from "./navFold";
|
| 145 |
import { CATALOG_CODE_FIELD } from "./catalogData";
|
| 146 |
import type { CatalogSpec } from "./types";
|
| 147 |
/* βββ end W18-C CATALOG βββ */
|
|
|
|
| 175 |
measureColumnIndex, ratingMax, ruleColumnKeys,
|
| 176 |
shouldAdoptEmbeddedSelection,
|
| 177 |
tableMode, uniqueDisplayName,
|
| 178 |
+
routeSortRefusal,
|
| 179 |
/* β W41-T38 β the rail's OWN name resolver, so a collision test compares what the reader
|
| 180 |
actually sees. The rail has always drawn `viewDisplayName(view)`; `renameView` was testing
|
| 181 |
`view.name`, and for the default view those two are different strings. */
|
|
|
|
| 187 |
and only consumed here, because W41-T43 (this file) and W41-T44 (`RecordDetail.tsx`) open the
|
| 188 |
same feature through other doors and neither of them may edit `types.ts`. */
|
| 189 |
import { buildPivotRequest, cleanSecondaryView, emptyViewConfig, PIVOT_PATH, PIVOT_WINDOW_LABELS,
|
| 190 |
+
pivotRefusalFromBody, pivotResponse, relationalTargets } from "./types";
|
| 191 |
import type {
|
| 192 |
DisplayMode,
|
| 193 |
DisplaySpec,
|
|
|
|
| 198 |
FilterNode,
|
| 199 |
FilterRule,
|
| 200 |
PivotResponse,
|
| 201 |
+
PivotRefusal,
|
| 202 |
PivotWindow,
|
| 203 |
Row,
|
| 204 |
RowHeightMode,
|
|
|
|
| 518 |
| { status: "idle" }
|
| 519 |
| { status: "loading" }
|
| 520 |
| { status: "absent" }
|
| 521 |
+
| { status: "refused"; refusal: PivotRefusal }
|
| 522 |
| { status: "ok"; answer: PivotResponse };
|
| 523 |
|
| 524 |
/**
|
|
|
|
| 696 |
return { ...config, colorBy: key || null, display: cleanDisplay(display) };
|
| 697 |
}
|
| 698 |
|
| 699 |
+
/** Atomically scrub every view reference to the fields the server actually removed. */
|
| 700 |
+
export function configWithoutFields(
|
| 701 |
+
config: ViewConfig,
|
| 702 |
+
removed: readonly string[],
|
| 703 |
+
): ViewConfig {
|
| 704 |
+
const gone = new Set(removed.filter((key) => typeof key === "string" && key !== ""));
|
| 705 |
+
if (gone.size === 0) return config;
|
| 706 |
+
const widths = { ...(config.widths ?? {}) };
|
| 707 |
+
for (const key of gone) delete widths[key];
|
| 708 |
+
const next: ViewConfig = {
|
| 709 |
+
...config,
|
| 710 |
+
order: (config.order ?? []).filter((key) => !gone.has(key)),
|
| 711 |
+
visible: (config.visible ?? []).filter((key) => !gone.has(key)),
|
| 712 |
+
widths,
|
| 713 |
+
sorts: (config.sorts ?? []).filter((sort) => !gone.has(sort.colId)),
|
| 714 |
+
groupBy: config.groupBy && gone.has(config.groupBy) ? null : config.groupBy,
|
| 715 |
+
colorBy: config.colorBy && gone.has(config.colorBy) ? null : config.colorBy,
|
| 716 |
+
};
|
| 717 |
+
const spec = next.display;
|
| 718 |
+
if (spec?.colorField && gone.has(spec.colorField)) {
|
| 719 |
+
const display: DisplaySpec = { ...spec };
|
| 720 |
+
delete display.colorField;
|
| 721 |
+
next.display = cleanDisplay(display);
|
| 722 |
+
}
|
| 723 |
+
return next;
|
| 724 |
+
}
|
| 725 |
+
|
| 726 |
+
export type FieldDeleteDoor = "overlay" | "definition" | "route";
|
| 727 |
+
|
| 728 |
+
export function fieldDeleteDoor(
|
| 729 |
+
field: Field | undefined,
|
| 730 |
+
opts: { isUserTable: boolean; lockedKey: string },
|
| 731 |
+
): FieldDeleteDoor | null {
|
| 732 |
+
if (!field || field.key === opts.lockedKey) return null;
|
| 733 |
+
if (field.custom && !field.shared) return "overlay";
|
| 734 |
+
if (opts.isUserTable && !field.custom &&
|
| 735 |
+
(field.type === "link" || field.type === "rollup" || field.type === "formula")) {
|
| 736 |
+
return "definition";
|
| 737 |
+
}
|
| 738 |
+
if (field.shared && field.kind === "route_order") return "route";
|
| 739 |
+
return null;
|
| 740 |
+
}
|
| 741 |
+
|
| 742 |
+
export interface FieldBulkDoorDeps {
|
| 743 |
+
config: ViewConfig;
|
| 744 |
+
updateConfig: (next: ViewConfig) => void;
|
| 745 |
+
order: string[];
|
| 746 |
+
visible: Set<string>;
|
| 747 |
+
lockedKey: string;
|
| 748 |
+
fieldByKey: Map<string, Field>;
|
| 749 |
+
isUserTable: boolean;
|
| 750 |
+
scope: string;
|
| 751 |
+
rowsPath: string;
|
| 752 |
+
setFields: (update: (current: Field[]) => Field[]) => void;
|
| 753 |
+
stampFieldDelete: (key: string) => void;
|
| 754 |
+
}
|
| 755 |
+
|
| 756 |
+
export interface FieldBulkDoors {
|
| 757 |
+
onSetFieldsHidden: (keys: string[], hidden: boolean) => void;
|
| 758 |
+
onShareFields: (keys: string[]) => void;
|
| 759 |
+
onReassignFields: (keys: string[]) => void;
|
| 760 |
+
onDeleteFields: (keys: string[]) => void;
|
| 761 |
+
onRemoveField: (key: string) => void;
|
| 762 |
+
}
|
| 763 |
+
|
| 764 |
+
function reportFieldDeleteRefusals(
|
| 765 |
+
results: readonly FieldDeleteResult[],
|
| 766 |
+
fieldByKey: Map<string, Field>,
|
| 767 |
+
): void {
|
| 768 |
+
const refused = results.filter((item) => item.status === "refused");
|
| 769 |
+
if (refused.length === 0) return;
|
| 770 |
+
const explained = refused.find((item) =>
|
| 771 |
+
typeof item.reason === "string" && item.reason.trim().length > 0);
|
| 772 |
+
if (!explained) {
|
| 773 |
+
signal(TOAST_EVENT, refused.length === 1
|
| 774 |
+
? "That column was left alone, and the server gave no reason."
|
| 775 |
+
: `${refused.length} of those columns were left alone, and the server gave no reason.`);
|
| 776 |
+
return;
|
| 777 |
+
}
|
| 778 |
+
const label = fieldByKey.get(explained.key)?.label ?? explained.key;
|
| 779 |
+
signal(TOAST_EVENT, refused.length === 1
|
| 780 |
+
? `${label} was left alone. ${explained.reason}`
|
| 781 |
+
: `${refused.length} of those columns were left alone. ${label}: ${explained.reason}`);
|
| 782 |
+
}
|
| 783 |
+
|
| 784 |
+
export function useFieldBulkDoors(deps: FieldBulkDoorDeps): FieldBulkDoors {
|
| 785 |
+
const { config, updateConfig, order, visible, lockedKey, fieldByKey, isUserTable, scope,
|
| 786 |
+
rowsPath, setFields, stampFieldDelete } = deps;
|
| 787 |
+
const onSetFieldsHidden = useCallback((keys: string[], hidden: boolean) => {
|
| 788 |
+
const next = new Set(visible);
|
| 789 |
+
for (const key of keys) {
|
| 790 |
+
if (hidden) {
|
| 791 |
+
if (key !== lockedKey) next.delete(key);
|
| 792 |
+
} else next.add(key);
|
| 793 |
+
}
|
| 794 |
+
updateConfig({ ...config, visible: [...new Set([lockedKey, ...next])] });
|
| 795 |
+
}, [config, lockedKey, updateConfig, visible]);
|
| 796 |
+
|
| 797 |
+
const onDeleteFields = useCallback((keys: string[]) => {
|
| 798 |
+
const overlay: string[] = [];
|
| 799 |
+
const definition: string[] = [];
|
| 800 |
+
const route: string[] = [];
|
| 801 |
+
const noDoor: string[] = [];
|
| 802 |
+
for (const key of keys) {
|
| 803 |
+
const door = fieldDeleteDoor(fieldByKey.get(key), { isUserTable, lockedKey });
|
| 804 |
+
if (door === "overlay") overlay.push(key);
|
| 805 |
+
else if (door === "definition") definition.push(key);
|
| 806 |
+
else if (door === "route") route.push(key);
|
| 807 |
+
else noDoor.push(key);
|
| 808 |
+
}
|
| 809 |
+
void (async () => {
|
| 810 |
+
const gone = [...overlay];
|
| 811 |
+
let touchedServer = false;
|
| 812 |
+
let unreadableAnswer = false;
|
| 813 |
+
if (definition.length > 0) {
|
| 814 |
+
const outcome = await deleteTableFields(scope, definition);
|
| 815 |
+
gone.push(...outcome.deleted);
|
| 816 |
+
touchedServer = outcome.deleted.length > 0;
|
| 817 |
+
unreadableAnswer = outcome.unreadable;
|
| 818 |
+
reportFieldDeleteRefusals(outcome.results, fieldByKey);
|
| 819 |
+
}
|
| 820 |
+
for (const key of route) {
|
| 821 |
+
// Route fields retain their dedicated lifecycle wall; execute serially so refusal toasts
|
| 822 |
+
// do not race each other into one slot.
|
| 823 |
+
// eslint-disable-next-line no-await-in-loop
|
| 824 |
+
const ok = await deleteRouteOrderField(key);
|
| 825 |
+
if (ok) {
|
| 826 |
+
gone.push(key);
|
| 827 |
+
touchedServer = true;
|
| 828 |
+
}
|
| 829 |
+
}
|
| 830 |
+
if (noDoor.length > 0) {
|
| 831 |
+
signal(TOAST_EVENT, noDoor.length === 1
|
| 832 |
+
? "One of those columns cannot be deleted here, so it was left alone."
|
| 833 |
+
: `${noDoor.length} of those columns cannot be deleted here, so they were left alone.`);
|
| 834 |
+
}
|
| 835 |
+
if (gone.length > 0) {
|
| 836 |
+
const goneSet = new Set(gone);
|
| 837 |
+
setFields((current) => current.filter((item) => !goneSet.has(item.key)));
|
| 838 |
+
updateConfig(configWithoutFields({ ...config, order, visible: [...visible] }, gone));
|
| 839 |
+
for (const key of overlay) {
|
| 840 |
+
stampFieldDelete(key);
|
| 841 |
+
emitHostEvent({ id: eventId("fielddel"), type: "field_delete", key });
|
| 842 |
+
}
|
| 843 |
+
}
|
| 844 |
+
if (touchedServer || unreadableAnswer) {
|
| 845 |
+
clearTopicRowsCache(rowsPath);
|
| 846 |
+
signal(WORKSPACE_STALE_EVENT);
|
| 847 |
+
signal(ROWS_STALE_EVENT);
|
| 848 |
+
}
|
| 849 |
+
})();
|
| 850 |
+
}, [config, fieldByKey, isUserTable, lockedKey, order, rowsPath, scope, setFields,
|
| 851 |
+
stampFieldDelete, updateConfig, visible]);
|
| 852 |
+
|
| 853 |
+
const onShareFields = useCallback((keys: string[]) => {
|
| 854 |
+
if (keys.length > 0) signal(TOAST_EVENT,
|
| 855 |
+
"Sharing several fields in one go is not available yet, so share them one at a time from each column's own menu.");
|
| 856 |
+
}, []);
|
| 857 |
+
const onReassignFields = useCallback((keys: string[]) => {
|
| 858 |
+
if (keys.length > 0) signal(TOAST_EVENT,
|
| 859 |
+
"Handing several fields to a new owner in one go is not available yet, so change the owner one column at a time from its share panel.");
|
| 860 |
+
}, []);
|
| 861 |
+
const onRemoveField = useCallback((key: string) => {
|
| 862 |
+
if (key) signal(TOAST_EVENT,
|
| 863 |
+
"Taking a shared field off your own list is not available yet, so hide it or ask the person who owns it to withdraw it.");
|
| 864 |
+
}, []);
|
| 865 |
+
return useMemo(() => ({ onSetFieldsHidden, onShareFields, onReassignFields,
|
| 866 |
+
onDeleteFields, onRemoveField }),
|
| 867 |
+
[onDeleteFields, onReassignFields, onRemoveField, onSetFieldsHidden, onShareFields]);
|
| 868 |
+
}
|
| 869 |
+
|
| 870 |
function readLocal(storageKey: string): LocalWorkspace | null {
|
| 871 |
try {
|
| 872 |
const raw = localStorage.getItem(`aios-grid:${storageKey}`);
|
|
|
|
| 1163 |
scope?: SurfaceScope;
|
| 1164 |
/** Shell-owned Data workspace location; grid resolves its view/field, never the global rail. */
|
| 1165 |
dataPath?: DataPath;
|
| 1166 |
+
databases?: readonly DataDatabase[];
|
| 1167 |
+
activeDatabaseKey?: string;
|
| 1168 |
+
databaseFolders?: readonly DataDatabaseFolder[];
|
| 1169 |
+
onSelectDatabase?: (key: string) => void;
|
| 1170 |
+
onDatabaseMove?: (key: string, folderId: string | null) => void;
|
| 1171 |
+
onDatabaseFolderRename?: (folderId: string, name: string) => void;
|
| 1172 |
+
onDatabaseFolderDelete?: (folderId: string) => void;
|
| 1173 |
+
renderDatabaseActions?: (database: DataDatabase) => ReactNode;
|
| 1174 |
+
databaseCreateControl?: ReactNode;
|
| 1175 |
/** A Query-owned immutable artefact. `scope` remains the renderer's mapped data scope. */
|
| 1176 |
queryBinding?: QueryVirtualBinding;
|
| 1177 |
/** Read-only Grid view embedded in a linked-record modal. It keeps the standard
|
|
|
|
| 1183 |
embeddedSelectable?: boolean;
|
| 1184 |
embeddedSelectedIds?: readonly number[];
|
| 1185 |
onEmbeddedSelectionChange?: (recordIds: number[]) => void;
|
| 1186 |
+
/** Source record withheld from an editable picker over its own database. */
|
| 1187 |
+
embeddedExcludeRecordId?: number;
|
| 1188 |
+
}
|
| 1189 |
+
|
| 1190 |
+
/** Exact client mirror of core.user_tables.is_linkable_target. */
|
| 1191 |
+
const LINKABLE_MODULE_KEYS = ["customer_data", "product_data"] as const;
|
| 1192 |
+
|
| 1193 |
+
export function isLinkableTarget(table: unknown): boolean {
|
| 1194 |
+
if (typeof table !== "string") return false;
|
| 1195 |
+
if (table.startsWith("ut_") && table.length > 3) return true;
|
| 1196 |
+
return (LINKABLE_MODULE_KEYS as readonly string[]).includes(table);
|
| 1197 |
+
}
|
| 1198 |
+
|
| 1199 |
+
/** Resolve storage keys to renderer scopes without treating an arbitrary key as a scope. */
|
| 1200 |
+
export function scopeForLinkTable(table: unknown): SurfaceScope | undefined {
|
| 1201 |
+
if (!isLinkableTarget(table)) return undefined;
|
| 1202 |
+
if (table === "customer_data") return "customer";
|
| 1203 |
+
if (table === "product_data") return "product";
|
| 1204 |
+
return table as `ut_${string}`;
|
| 1205 |
}
|
| 1206 |
|
| 1207 |
interface LinkGridModalProps {
|
|
|
|
| 1210 |
recordIds: readonly number[];
|
| 1211 |
editable?: boolean;
|
| 1212 |
single?: boolean;
|
| 1213 |
+
excludeRecordId?: number;
|
| 1214 |
onSave?: (recordIds: number[]) => void;
|
| 1215 |
onClose: () => void;
|
| 1216 |
}
|
| 1217 |
|
| 1218 |
function LinkGridModal({ label, table, recordIds, editable = false, single = false,
|
| 1219 |
+
excludeRecordId, onSave, onClose }: LinkGridModalProps) {
|
| 1220 |
const panelRef = useRef<HTMLDivElement>(null);
|
| 1221 |
const [selectedIds, setSelectedIds] = useState<number[]>(() => [...recordIds]);
|
| 1222 |
const changeSelectedIds = useCallback((ids: number[]) => {
|
|
|
|
| 1268 |
scope={table}
|
| 1269 |
embedded
|
| 1270 |
embeddedRecordIds={editable ? undefined : recordIds}
|
| 1271 |
+
embeddedExcludeRecordId={editable ? excludeRecordId : undefined}
|
| 1272 |
embeddedSelectable={editable}
|
| 1273 |
embeddedSelectedIds={selectedIds}
|
| 1274 |
onEmbeddedSelectionChange={changeSelectedIds}
|
|
|
|
| 1340 |
function CustomerGridSurface({
|
| 1341 |
scope = "customer",
|
| 1342 |
dataPath,
|
| 1343 |
+
databases,
|
| 1344 |
+
activeDatabaseKey,
|
| 1345 |
+
databaseFolders,
|
| 1346 |
+
onSelectDatabase,
|
| 1347 |
+
onDatabaseMove,
|
| 1348 |
+
onDatabaseFolderRename,
|
| 1349 |
+
onDatabaseFolderDelete,
|
| 1350 |
+
renderDatabaseActions,
|
| 1351 |
+
databaseCreateControl,
|
| 1352 |
queryBinding,
|
| 1353 |
embedded = false,
|
| 1354 |
embeddedRecordIds,
|
| 1355 |
embeddedSelectable = false,
|
| 1356 |
embeddedSelectedIds = [],
|
| 1357 |
onEmbeddedSelectionChange,
|
| 1358 |
+
embeddedExcludeRecordId,
|
| 1359 |
}: CustomerGridProps = {}) {
|
| 1360 |
const isQueryPreview = queryBinding !== undefined;
|
| 1361 |
/**
|
|
|
|
| 1422 |
*/
|
| 1423 |
const [pendingRows, setPendingRows] = useState<Row[]>([]);
|
| 1424 |
const rawRows = useMemo(() => {
|
| 1425 |
+
const projected = embeddedRecordIds
|
| 1426 |
? fetchedRows.filter((row) => new Set(embeddedRecordIds).has(row.pid))
|
| 1427 |
: fetchedRows;
|
| 1428 |
+
const base = embeddedExcludeRecordId !== undefined
|
| 1429 |
+
? projected.filter((row) => row.pid !== embeddedExcludeRecordId)
|
| 1430 |
+
: projected;
|
| 1431 |
if (!pendingRows.length) return base;
|
| 1432 |
const known = new Set(base.map((r) => r.pid));
|
| 1433 |
const extra = pendingRows.filter((r) => !known.has(r.pid));
|
| 1434 |
return extra.length ? [...base, ...extra] : base;
|
| 1435 |
// The scalar key keeps this stable when a caller reconstructs the same id list.
|
| 1436 |
// eslint-disable-next-line react-hooks/exhaustive-deps
|
| 1437 |
+
}, [fetchedRows, embeddedIdsKey, embeddedExcludeRecordId, pendingRows]);
|
| 1438 |
useEffect(() => {
|
| 1439 |
// β PRUNED AGAINST THE FETCHED PAYLOAD, not against `rawRows` β `rawRows` contains the
|
| 1440 |
// pending rows, so it can never report that one has been absorbed. Pruning against the
|
|
|
|
| 2230 |
const isUserTable = !embedded && scope.startsWith("ut_");
|
| 2231 |
const recordsMutable = payload?.recordsMutable !== false;
|
| 2232 |
const canMutateRecords = isUserTable && recordsMutable;
|
| 2233 |
+
const fieldBulkDoors = useFieldBulkDoors({
|
| 2234 |
+
config,
|
| 2235 |
+
updateConfig,
|
| 2236 |
+
order,
|
| 2237 |
+
visible,
|
| 2238 |
+
lockedKey,
|
| 2239 |
+
fieldByKey,
|
| 2240 |
+
isUserTable,
|
| 2241 |
+
scope,
|
| 2242 |
+
rowsPath: topic.rowsPath,
|
| 2243 |
+
setFields,
|
| 2244 |
+
stampFieldDelete,
|
| 2245 |
+
});
|
| 2246 |
/**
|
| 2247 |
* β 2026-08-07 β the databases a `link` column may point at, fetched when the column menu
|
| 2248 |
* OPENS rather than on every render of the grid.
|
|
|
|
| 2303 |
live = false;
|
| 2304 |
};
|
| 2305 |
}, [columnMenu, plusMenu]);
|
| 2306 |
+
/**
|
| 2307 |
+
* The hop editor has a separate server vocabulary from source rollups. In particular its
|
| 2308 |
+
* dimensions publish date and number types used by the operator picker, so deriving it from
|
| 2309 |
+
* /tables/rollup-sources (and repainting everything as text) is a functional data loss.
|
| 2310 |
+
*/
|
| 2311 |
+
const [hopTopicOffer, setHopTopicOffer] =
|
| 2312 |
+
useState<HopTopicOffer>({ topics: [], windows: [], omissions: [] });
|
| 2313 |
+
const hopOfferAsked = useRef(false);
|
| 2314 |
+
useEffect(() => {
|
| 2315 |
+
if ((!columnMenu && !plusMenu) || hopOfferAsked.current) return;
|
| 2316 |
+
hopOfferAsked.current = true;
|
| 2317 |
+
let live = true;
|
| 2318 |
+
void fetchHopTopics().then((offer) => {
|
| 2319 |
+
if (live) setHopTopicOffer(offer);
|
| 2320 |
+
});
|
| 2321 |
+
return () => {
|
| 2322 |
+
live = false;
|
| 2323 |
+
};
|
| 2324 |
+
}, [columnMenu, plusMenu]);
|
| 2325 |
/**
|
| 2326 |
* β WAVE 27 Β· OWNER ITEM 22 β the values the ACTIVE VIEW forces on a new record.
|
| 2327 |
*
|
|
|
|
| 2514 |
useEffect(() => {
|
| 2515 |
if (displayMode !== "map") setRoutePanelOpen(false);
|
| 2516 |
}, [displayMode]);
|
| 2517 |
+
useEffect(() => {
|
| 2518 |
+
if (!routePanelOpen) return;
|
| 2519 |
+
setSelAddOpen(false);
|
| 2520 |
+
setSelRemoveOpen(false);
|
| 2521 |
+
setAddCustOpen(false);
|
| 2522 |
+
}, [routePanelOpen]);
|
| 2523 |
|
| 2524 |
// βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 2525 |
// ββ WAVE 30 Β· W30-T42 (contract C2) β PAGING A READ-THROUGH GRID.
|
|
|
|
| 4569 |
if (!row) return;
|
| 4570 |
// Owner item 10: clicking into the cells is "I am working now" β the frame folds its
|
| 4571 |
// navigation rail to the slim strip (a no-op in the embed; the shell listens).
|
| 4572 |
+
foldGridCell();
|
| 4573 |
if (row.kind === "group-header") {
|
| 4574 |
event.preventDefault();
|
| 4575 |
setCollapsed((current) => {
|
|
|
|
| 4632 |
// The large modal mounts the same Grid surface over exactly these pids, so its standard
|
| 4633 |
// search, Filters, Sort, Fields, and column menus keep working for every database kind.
|
| 4634 |
if (row.kind === "data" && field?.type === "link" && field.link?.table) {
|
| 4635 |
+
if (isLinkableTarget(field.link.table)) {
|
| 4636 |
event.preventDefault();
|
| 4637 |
setActiveCell(cell[0], cell[1]);
|
| 4638 |
setLinkAt({ pid: row.record.pid, fieldKey: field.key });
|
|
|
|
| 4707 |
const row = displayRows[cell[1]];
|
| 4708 |
const column = visibleCols[cell[0]];
|
| 4709 |
const field = column ? fieldByKey.get(column.id!) : undefined;
|
| 4710 |
+
if (row?.kind === "data" && field && !canEditField(field))
|
| 4711 |
setDetailPid(row.record.pid);
|
| 4712 |
},
|
| 4713 |
+
[displayRows, visibleCols, fieldByKey, canEditField]
|
| 4714 |
);
|
| 4715 |
const onCellEdited = useCallback(
|
| 4716 |
(cell: Item, value: EditableGridCell) => {
|
|
|
|
| 6611 |
const f = fieldByKey.get(key);
|
| 6612 |
if (!f?.custom || key === lockedKey) return;
|
| 6613 |
setFields((current) => current.filter((item) => item.key !== key));
|
| 6614 |
+
updateConfig(configWithoutFields({ ...config, order, visible: [...visible] }, [key]));
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 6615 |
stampFieldDelete(key);
|
| 6616 |
emitHostEvent({ id: eventId("fielddel"), type: "field_delete", key });
|
| 6617 |
},
|
|
|
|
| 6654 |
void deleteRouteOrderField(key).then((ok) => {
|
| 6655 |
if (!ok) return; // the bridge has already said why
|
| 6656 |
setFields((current) => current.filter((item) => item.key !== key));
|
| 6657 |
+
updateConfig(configWithoutFields({ ...config, order, visible: [...visible] }, [key]));
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 6658 |
// β AND THE ROWS CACHE, for the reason `revealRouteField` states above: the values went
|
| 6659 |
// with the definition (`shared_overlay.drop_field` scrubs the cells), so a refetch served
|
| 6660 |
// from the pre-delete window would repaint the numbers of a column that no longer exists.
|
|
|
|
| 6706 |
void deleteTableField(scope, key).then((ok) => {
|
| 6707 |
if (!ok) return; // the bridge has already said why
|
| 6708 |
setFields((current) => current.filter((item) => item.key !== key));
|
| 6709 |
+
updateConfig(configWithoutFields({ ...config, order, visible: [...visible] }, [key]));
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 6710 |
signal(WORKSPACE_STALE_EVENT);
|
| 6711 |
signal(ROWS_STALE_EVENT);
|
| 6712 |
});
|
|
|
|
| 7607 |
});
|
| 7608 |
if (!live) return;
|
| 7609 |
if (!res.ok) {
|
| 7610 |
+
const refusal = pivotRefusalFromBody(await res.json().catch(() => null));
|
| 7611 |
+
if (!live) return;
|
| 7612 |
+
setPivot(refusal ? { status: "refused", refusal } : { status: "absent" });
|
| 7613 |
return;
|
| 7614 |
}
|
| 7615 |
const answer = pivotResponse(await res.json().catch(() => null));
|
|
|
|
| 7670 |
// Cohort mode's toolbar control (rendered by Toolbar via the `cohortAction` slot; the popover
|
| 7671 |
// it opens is with the other overlays at the bottom). Disabled without an active cohort β
|
| 7672 |
// zero cohorts is the host page's near-empty state, not this button's error to explain.
|
| 7673 |
+
const cohortAction = cohortMode && !routePanelOpen ? (
|
| 7674 |
<button
|
| 7675 |
type="button"
|
| 7676 |
className="cg-tb-btn cg-tb-addcust"
|
|
|
|
| 7792 |
?? (linkField && linkRow ? linkRow[linkField.key] : "")
|
| 7793 |
?? ""
|
| 7794 |
);
|
| 7795 |
+
const linkTargetScope = linkField?.type === "link"
|
| 7796 |
+
? scopeForLinkTable(linkField.link?.table)
|
| 7797 |
+
: undefined;
|
| 7798 |
const linkedRecordIds = [...new Set(
|
| 7799 |
linkValue.split(",").map((part) => Number(part.trim())).filter(
|
| 7800 |
(pid) => Number.isInteger(pid) && pid > 0
|
|
|
|
| 7904 |
|
| 7905 |
const pivotOn = !!secondary;
|
| 7906 |
const pivotAnswer = pivot.status === "ok" ? pivot.answer : null;
|
| 7907 |
+
const pivotRefusal = pivot.status === "refused"
|
| 7908 |
+
? pivot.refusal
|
| 7909 |
+
: pivotAnswer?.refusal ?? null;
|
| 7910 |
/**
|
| 7911 |
* β W41-T43 β THE SAVED PIVOT NAMES A LINK COLUMN THIS READER WAS NOT SERVED. No request went
|
| 7912 |
* out (`pivotRequestBody` is empty), so `pivot` stays `idle` and every other branch below is
|
|
|
|
| 7994 |
*/
|
| 7995 |
const secondaryToolbar = pivotOn && pivotServed && secondary ? (
|
| 7996 |
<Toolbar
|
| 7997 |
+
manager={true}
|
| 7998 |
nouns={pivotTarget?.label ?? "records"}
|
| 7999 |
+
viewer={viewer}
|
| 8000 |
+
onSetFieldsHidden={null}
|
| 8001 |
+
onShareFields={null}
|
| 8002 |
+
onReassignFields={null}
|
| 8003 |
+
onDeleteFields={null}
|
| 8004 |
+
onRemoveField={null}
|
| 8005 |
sourceLabel={topic.nouns}
|
| 8006 |
fields={pivotFields}
|
| 8007 |
visible={pivotVisible}
|
|
|
|
| 8083 |
`QueryPage`. */}
|
| 8084 |
{!hideViews && (
|
| 8085 |
<ViewSidebar
|
| 8086 |
+
databases={databases}
|
| 8087 |
+
activeDatabaseKey={activeDatabaseKey}
|
| 8088 |
+
databaseFolders={databaseFolders}
|
| 8089 |
+
onSelectDatabase={onSelectDatabase}
|
| 8090 |
+
onDatabaseMove={onDatabaseMove}
|
| 8091 |
+
onDatabaseFolderRename={onDatabaseFolderRename}
|
| 8092 |
+
onDatabaseFolderDelete={onDatabaseFolderDelete}
|
| 8093 |
+
renderDatabaseActions={renderDatabaseActions}
|
| 8094 |
+
databaseCreateControl={databaseCreateControl}
|
| 8095 |
/* ββ W36-T05 (owner item 6 Β· R3 Β· R14) β the View agent, and the ONE class that
|
| 8096 |
folds the main rail. β `null` when closed, never a hidden node: `index.css` folds
|
| 8097 |
on `.shell-root:has(.cg-agent-panel)`, and `:has()` matches what EXISTS. */
|
|
|
|
| 8467 |
) : null
|
| 8468 |
)}
|
| 8469 |
<main className="cg-main">
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 8470 |
<Toolbar
|
| 8471 |
+
manager={true}
|
| 8472 |
nouns={topic.nouns}
|
| 8473 |
+
viewer={viewer}
|
| 8474 |
+
onSetFieldsHidden={fieldBulkDoors.onSetFieldsHidden}
|
| 8475 |
+
onShareFields={fieldBulkDoors.onShareFields}
|
| 8476 |
+
onReassignFields={fieldBulkDoors.onReassignFields}
|
| 8477 |
+
onDeleteFields={fieldBulkDoors.onDeleteFields}
|
| 8478 |
+
onRemoveField={fieldBulkDoors.onRemoveField}
|
| 8479 |
// Item 12 (C-LOCK) β the banner's copy. β BOTH fields are omitted when this reader
|
| 8480 |
// cannot see the locked set, and that omission is the SIGNAL, not an oversight: it
|
| 8481 |
// is what selects RECORD's second sentence ("locked to a set you cannot see").
|
|
|
|
| 8556 |
signal(TOAST_EVENT, "These sorts are locked. Copy this View to change them.");
|
| 8557 |
return;
|
| 8558 |
}
|
| 8559 |
+
const refusal = sorts
|
| 8560 |
+
.map((sort) => routeSortRefusal(
|
| 8561 |
+
sort.colId,
|
| 8562 |
+
{ nodes: config.filters, conj: config.filterConj },
|
| 8563 |
+
fields,
|
| 8564 |
+
))
|
| 8565 |
+
.find((message): message is string => message !== null);
|
| 8566 |
+
if (refusal) {
|
| 8567 |
+
signal(TOAST_EVENT, refusal);
|
| 8568 |
+
return;
|
| 8569 |
+
}
|
| 8570 |
updateConfig({ ...config, sorts });
|
| 8571 |
}}
|
| 8572 |
sortsLocked={activeSortsLocked}
|
|
|
|
| 8638 |
onToggleRoute={() => setRoutePanelOpen((open) => !open)}
|
| 8639 |
/>
|
| 8640 |
)}
|
| 8641 |
+
{/* ββ WAVE 42 Β· W42-T19 (owner instruction 11) β CALENDAR'S SECOND ROW. The real
|
| 8642 |
+
`CalendarSettings` render stays in the same position and guard shape as `MapSettings`:
|
| 8643 |
+
after the primary Toolbar, before the grid. The primary mode trigger therefore stays
|
| 8644 |
+
on row one while Calendar's date, Day cells, and Totals controls live here. */}
|
|
|
|
| 8645 |
{displayMode === "calendar" && !pivotOn && (
|
| 8646 |
<CalendarSettings
|
| 8647 |
dateField={calendarField}
|
|
|
|
| 8875 |
* a record that then appears twice while scrolling, which reads as duplicated data
|
| 8876 |
* rather than as a layout bug.
|
| 8877 |
*/
|
| 8878 |
+
freezeTrailingRows={totalsRowShown ? 1 : 0}
|
| 8879 |
rowHeight={rowHeight}
|
| 8880 |
headerHeight={36}
|
| 8881 |
rowMarkers="both"
|
|
|
|
| 9354 |
activeView={routeSourceView}
|
| 9355 |
tableKey={topic.key}
|
| 9356 |
onManagedRouteViewState={applyManagedRouteViewState}
|
| 9357 |
+
onZoneChanged={() => {
|
| 9358 |
+
clearTopicRowsCache(topic.rowsPath);
|
| 9359 |
+
dropTableRowsCache(topic.key);
|
| 9360 |
+
signal(ROWS_STALE_EVENT);
|
| 9361 |
+
}}
|
| 9362 |
/* β OWNER ITEM 9 β the route's "Add a record" search reaches PAST the view's own
|
| 9363 |
filter, so it is handed `scopedRows`: the book after the row wall (`allowed_pids`
|
| 9364 |
plus the business-unit scope) and before `useVisibleRows` applies filters, search
|
|
|
|
| 9577 |
: `Delete ${selectedPids.size === 1 ? "record" : "records"}`}
|
| 9578 |
</button>
|
| 9579 |
)}
|
| 9580 |
+
{!routePanelOpen && (cohortMode ? (
|
| 9581 |
// Item 2c: on the Cohort page the selection EDITS MEMBERSHIP of the fixed set β
|
| 9582 |
// "Remove from cohort" replaces "Add to cohort". Direct (no popover): the
|
| 9583 |
// checked set is explicit, the button says what it does, and re-adding is one
|
|
|
|
| 9610 |
>
|
| 9611 |
Add to cohort
|
| 9612 |
</button>
|
| 9613 |
+
))}
|
| 9614 |
{/* β Owner item 9 β the counterpart, and it renders ONLY when it can do
|
| 9615 |
something: the checked rows have to be in a cohort this viewer may edit for
|
| 9616 |
"Remove from cohortβ¦" to mean anything. Same bar, same selection, opposite
|
| 9617 |
direction β the ellipsis says a picker follows, because unlike cohort mode
|
| 9618 |
the target is not implied by where you are standing. */}
|
| 9619 |
+
{!routePanelOpen && !cohortMode && removableLists.length > 0 && (
|
| 9620 |
<button
|
| 9621 |
type="button"
|
| 9622 |
className="cg-btn cg-selbar-remove-pick"
|
|
|
|
| 9730 |
*/
|
| 9731 |
linkTargets={linkTargets}
|
| 9732 |
rollupSourceOffer={rollupSourceOffer}
|
| 9733 |
+
hopTopicOffer={hopTopicOffer}
|
| 9734 |
locked={menuField.key === lockedKey}
|
| 9735 |
schemaLocked={isSchemaLocked(menuField)}
|
| 9736 |
/* ββ W40-T24 β the menu's `columnDefinitionOffer` (display.ts) needs the same stratum
|
|
|
|
| 9955 |
}
|
| 9956 |
: undefined
|
| 9957 |
}
|
| 9958 |
+
onRemoveFromMine={() => {
|
| 9959 |
+
fieldBulkDoors.onRemoveField(menuField.key);
|
| 9960 |
+
setColumnMenu(null);
|
| 9961 |
+
}}
|
| 9962 |
onDuplicate={
|
| 9963 |
// Creatable strata only β a base Odoo field offers no Duplicate (contract).
|
| 9964 |
menuField.custom && !menuField.shared ? () => duplicateField(menuField) : undefined
|
|
|
|
| 9990 |
onSort={
|
| 9991 |
activeSortsLocked
|
| 9992 |
? undefined
|
| 9993 |
+
: (dir) => {
|
| 9994 |
+
const refusal = routeSortRefusal(
|
| 9995 |
+
menuField.key,
|
| 9996 |
+
{ nodes: config.filters, conj: config.filterConj },
|
| 9997 |
+
fields,
|
| 9998 |
+
);
|
| 9999 |
+
if (refusal) {
|
| 10000 |
+
signal(TOAST_EVENT, refusal);
|
| 10001 |
+
return;
|
| 10002 |
+
}
|
| 10003 |
+
updateConfig({ ...config, sorts: [{ colId: menuField.key, dir }] });
|
| 10004 |
+
}
|
| 10005 |
}
|
| 10006 |
onClearSort={
|
| 10007 |
activeSortsLocked
|
|
|
|
| 10071 |
field={fieldByKey.get(lockedKey)!}
|
| 10072 |
fields={fields}
|
| 10073 |
locked
|
| 10074 |
+
isUserTable={isUserTable}
|
| 10075 |
viewer={viewer}
|
| 10076 |
sortedDir={null}
|
| 10077 |
isFiltered={false}
|
|
|
|
| 10082 |
onNote={() => undefined}
|
| 10083 |
onHide={() => undefined}
|
| 10084 |
onCreate={createField}
|
| 10085 |
+
onRemoveFromMine={() => {
|
| 10086 |
+
fieldBulkDoors.onRemoveField(lockedKey);
|
| 10087 |
+
setPlusMenu(null);
|
| 10088 |
+
}}
|
| 10089 |
/* The SAME answer as the sibling instance above, stated rather than defaulted: this is
|
| 10090 |
the "+" menu and it creates through the identical `createField`, so a different value
|
| 10091 |
here would mean one door offers the kind and its twin does not. The note above the
|
|
|
|
| 10117 |
// either way. See the sibling's note for why self-links are offered now.
|
| 10118 |
linkTargets={linkTargets}
|
| 10119 |
rollupSourceOffer={rollupSourceOffer}
|
| 10120 |
+
hopTopicOffer={hopTopicOffer}
|
| 10121 |
/>
|
| 10122 |
)}
|
| 10123 |
|
|
|
|
| 10157 |
|
| 10158 |
{/* The selection bar's cohort picker: existing cohorts, or a new one by name. Mirrors the
|
| 10159 |
view menu's Add-to-list surface so the two ways of building a cohort read identically. */}
|
| 10160 |
+
{!routePanelOpen && selAddOpen && selAddRef.current && selectedPids.size > 0 && (
|
| 10161 |
<AnchoredOverlay
|
| 10162 |
anchor={selAddRef.current}
|
| 10163 |
className="cg-pop cg-add-list-pop"
|
|
|
|
| 10246 |
</AnchoredOverlay>
|
| 10247 |
)}
|
| 10248 |
|
| 10249 |
+
{!routePanelOpen && selRemoveOpen && selRemoveRef.current && removableLists.length > 0 && (
|
| 10250 |
<AnchoredOverlay
|
| 10251 |
anchor={selRemoveRef.current}
|
| 10252 |
className="cg-pop cg-add-list-pop"
|
|
|
|
| 10282 |
once. Candidates exclude current members; picks ACCUMULATE across searches, so the
|
| 10283 |
confirm button carries the running total. The 50-row render cap is stated beside the
|
| 10284 |
list β nothing silently truncated. */}
|
| 10285 |
+
{!routePanelOpen && cohortMode && addCustOpen && addCustRef.current && activeCohortId && (
|
| 10286 |
<AnchoredOverlay
|
| 10287 |
anchor={addCustRef.current}
|
| 10288 |
className="cg-pop cg-addcust-pop"
|
|
|
|
| 10379 |
onClose={closeJson}
|
| 10380 |
/>
|
| 10381 |
)}
|
| 10382 |
+
{linkField && linkTargetScope && linkAt && (
|
| 10383 |
<LinkGridModal
|
| 10384 |
label={linkField.label}
|
| 10385 |
+
table={linkTargetScope}
|
| 10386 |
recordIds={linkedRecordIds}
|
| 10387 |
editable={canEditField(linkField) && !isDerivedLink(linkField)}
|
| 10388 |
+
single={linkField.link?.single === true}
|
| 10389 |
+
excludeRecordId={linkTargetScope === scope ? linkAt.pid : undefined}
|
| 10390 |
onSave={(ids) => patchAndRecord(
|
| 10391 |
linkAt.pid,
|
| 10392 |
{ [linkField.key]: ids.join(",") },
|
web/src/customer-grid/FieldProperties.tsx
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
|
|
| 1 |
import type { Field } from "./types";
|
| 2 |
|
| 3 |
/** C3's server-owned field facts are intentionally read, never inferred client-side. */
|
|
@@ -6,7 +7,6 @@ type ContractField = Field & {
|
|
| 6 |
valueAuthority?: string;
|
| 7 |
scope?: string;
|
| 8 |
deletionLocked?: boolean;
|
| 9 |
-
limits?: { maxOptions?: number };
|
| 10 |
};
|
| 11 |
|
| 12 |
const unknown = "Not provided";
|
|
@@ -33,10 +33,10 @@ export function FieldProperties({ field }: { field: Field }) {
|
|
| 33 |
<dt>Deletion lock</dt>
|
| 34 |
<dd>{contract.deletionLocked ? "Locked" : "Not locked"}</dd>
|
| 35 |
</div>
|
| 36 |
-
{typeof
|
| 37 |
<div>
|
| 38 |
<dt>Maximum options</dt>
|
| 39 |
-
<dd>{
|
| 40 |
</div>
|
| 41 |
)}
|
| 42 |
</dl>
|
|
|
|
| 1 |
+
import { isPickType } from "./types";
|
| 2 |
import type { Field } from "./types";
|
| 3 |
|
| 4 |
/** C3's server-owned field facts are intentionally read, never inferred client-side. */
|
|
|
|
| 7 |
valueAuthority?: string;
|
| 8 |
scope?: string;
|
| 9 |
deletionLocked?: boolean;
|
|
|
|
| 10 |
};
|
| 11 |
|
| 12 |
const unknown = "Not provided";
|
|
|
|
| 33 |
<dt>Deletion lock</dt>
|
| 34 |
<dd>{contract.deletionLocked ? "Locked" : "Not locked"}</dd>
|
| 35 |
</div>
|
| 36 |
+
{isPickType(field.type) && typeof field.limits?.maxOptions === "number" && (
|
| 37 |
<div>
|
| 38 |
<dt>Maximum options</dt>
|
| 39 |
+
<dd>{field.limits.maxOptions}</dd>
|
| 40 |
</div>
|
| 41 |
)}
|
| 42 |
</dl>
|
web/src/customer-grid/FormInterface.tsx
CHANGED
|
@@ -26,6 +26,7 @@ import { useCallback, useEffect, useMemo, useState } from "react";
|
|
| 26 |
import { API_V1, CREDENTIALS } from "../apiContract";
|
| 27 |
import type { Field, FieldType, FormSpec } from "./types";
|
| 28 |
import { TYPE_LABELS } from "./iconShapes";
|
|
|
|
| 29 |
import "./FormInterface.css";
|
| 30 |
|
| 31 |
/**
|
|
@@ -226,7 +227,7 @@ export function FormInterface({
|
|
| 226 |
// ---- the states that are not a form -------------------------------------------------------
|
| 227 |
if (!viewId) {
|
| 228 |
return (
|
| 229 |
-
<div className="cg-form-empty">
|
| 230 |
A form belongs to a saved view. Save this view first, then build the form on it.
|
| 231 |
</div>
|
| 232 |
);
|
|
@@ -236,7 +237,7 @@ export function FormInterface({
|
|
| 236 |
// (a locked one accepts no new records, so a form could only ever collect refusals), while
|
| 237 |
// `readOnlyReason` is about the VIEWER's grant.
|
| 238 |
return (
|
| 239 |
-
<div className="cg-form-empty">
|
| 240 |
This database does not accept new records, so a form has nowhere to put an answer.
|
| 241 |
</div>
|
| 242 |
);
|
|
@@ -245,7 +246,7 @@ export function FormInterface({
|
|
| 245 |
const diverged = spec === null && (link.stored?.fields ?? 0) > 0;
|
| 246 |
|
| 247 |
return (
|
| 248 |
-
<div className="cg-form-build">
|
| 249 |
<div className="cg-form-pane">
|
| 250 |
<h2 className="cg-form-h">Form</h2>
|
| 251 |
{!canEdit && readOnlyReason && <p className="cg-form-note">{readOnlyReason}</p>}
|
|
|
|
| 26 |
import { API_V1, CREDENTIALS } from "../apiContract";
|
| 27 |
import type { Field, FieldType, FormSpec } from "./types";
|
| 28 |
import { TYPE_LABELS } from "./iconShapes";
|
| 29 |
+
import { foldNavOnWorkSurface } from "./navFold";
|
| 30 |
import "./FormInterface.css";
|
| 31 |
|
| 32 |
/**
|
|
|
|
| 227 |
// ---- the states that are not a form -------------------------------------------------------
|
| 228 |
if (!viewId) {
|
| 229 |
return (
|
| 230 |
+
<div className="cg-form-empty" onPointerDown={foldNavOnWorkSurface}>
|
| 231 |
A form belongs to a saved view. Save this view first, then build the form on it.
|
| 232 |
</div>
|
| 233 |
);
|
|
|
|
| 237 |
// (a locked one accepts no new records, so a form could only ever collect refusals), while
|
| 238 |
// `readOnlyReason` is about the VIEWER's grant.
|
| 239 |
return (
|
| 240 |
+
<div className="cg-form-empty" onPointerDown={foldNavOnWorkSurface}>
|
| 241 |
This database does not accept new records, so a form has nowhere to put an answer.
|
| 242 |
</div>
|
| 243 |
);
|
|
|
|
| 246 |
const diverged = spec === null && (link.stored?.fields ?? 0) > 0;
|
| 247 |
|
| 248 |
return (
|
| 249 |
+
<div className="cg-form-build" onPointerDown={foldNavOnWorkSurface}>
|
| 250 |
<div className="cg-form-pane">
|
| 251 |
<h2 className="cg-form-h">Form</h2>
|
| 252 |
{!canEdit && readOnlyReason && <p className="cg-form-note">{readOnlyReason}</p>}
|
web/src/customer-grid/MapView.tsx
CHANGED
|
@@ -94,8 +94,19 @@ import {
|
|
| 94 |
import type { GeoStop, Pt, RouteStamp, View } from "./mapProjection";
|
| 95 |
import { LP_INK, LP_MAP_SELECTED, LP_PURPLE, LP_PURPLE_DEEP } from "./theme";
|
| 96 |
import { RouteNav } from "./RouteNav";
|
| 97 |
-
import {
|
| 98 |
-
import
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 99 |
import "./map.css";
|
| 100 |
|
| 101 |
/**
|
|
@@ -348,41 +359,14 @@ export function translateZoneGeometry(
|
|
| 348 |
|
| 349 |
/** C3's durable map-domain DTO. Zones are not generic fields: geometry, visibility and the
|
| 350 |
* membership snapshot only make sense to this projection. */
|
| 351 |
-
|
| 352 |
-
id: string;
|
| 353 |
-
name: string;
|
| 354 |
-
color: string;
|
| 355 |
-
geometryGeoJson: ZoneGeometry;
|
| 356 |
-
visible: boolean;
|
| 357 |
-
geographicField: string;
|
| 358 |
-
memberships: number[];
|
| 359 |
-
/** C1 Zone membership is polygon OR ZIP; the server recomputes the union. */
|
| 360 |
-
zipCodes?: string[];
|
| 361 |
-
createdBy?: string;
|
| 362 |
-
createdAt?: string;
|
| 363 |
-
}
|
| 364 |
|
| 365 |
interface ZoneMove {
|
| 366 |
zone: MapZone;
|
|
|
|
| 367 |
start: Pt;
|
| 368 |
}
|
| 369 |
|
| 370 |
-
interface RouteDelivery {
|
| 371 |
-
id: string;
|
| 372 |
-
name: string;
|
| 373 |
-
recipient: string;
|
| 374 |
-
schedule: { cron?: string; enabled?: boolean };
|
| 375 |
-
snapshot: {
|
| 376 |
-
sourceViewId: string;
|
| 377 |
-
sourceViewRevision: string;
|
| 378 |
-
sourceViewName: string;
|
| 379 |
-
timezone: string;
|
| 380 |
-
routeField: string;
|
| 381 |
-
orderedStopIds: number[];
|
| 382 |
-
mapsPerLink: number;
|
| 383 |
-
};
|
| 384 |
-
}
|
| 385 |
-
|
| 386 |
/** Immutable provenance supplied by the host grid for a scheduled route snapshot. */
|
| 387 |
export interface RouteSourceView {
|
| 388 |
id: string;
|
|
@@ -438,6 +422,7 @@ export function MapView({
|
|
| 438 |
activeView,
|
| 439 |
tableKey,
|
| 440 |
onManagedRouteViewState,
|
|
|
|
| 441 |
}: {
|
| 442 |
/** DISTINCT data rows from the full pipeline, overlay edits layered β the
|
| 443 |
* calendar/kanban contract, verbatim. */
|
|
@@ -481,6 +466,9 @@ export function MapView({
|
|
| 481 |
tableKey: string;
|
| 482 |
/** C2 handoff: the server alone returns the managed route-membership clause. */
|
| 483 |
onManagedRouteViewState?: (viewState: Record<string, unknown>) => void;
|
|
|
|
|
|
|
|
|
|
| 484 |
/**
|
| 485 |
* ββ OWNER ITEM 9 β THE WHOLE BOOK, so a stop can be added that the VIEW filtered out.
|
| 486 |
*
|
|
@@ -543,12 +531,21 @@ export function MapView({
|
|
| 543 |
const [zones, setZones] = useState<MapZone[] | null>(null);
|
| 544 |
/** C2 named-route read model. Legacy route-order columns remain compatibility only. */
|
| 545 |
const [namedRoutes, setNamedRoutes] = useState<MapRouteDto[]>([]);
|
|
|
|
|
|
|
| 546 |
const [selectedRouteIds, setSelectedRouteIds] = useState<ReadonlySet<string>>(new Set());
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 547 |
const [managedRouteViewState, setManagedRouteViewState] = useState<Record<string, unknown> | null>(null);
|
| 548 |
const [routeSelectionWarning, setRouteSelectionWarning] = useState<string | null>(null);
|
| 549 |
const [activeZoneIds, setActiveZoneIds] = useState<ReadonlySet<string>>(new Set());
|
| 550 |
-
const [zoneChooserOpen, setZoneChooserOpen] = useState(false);
|
| 551 |
const [zoneNavigatorOpen, setZoneNavigatorOpen] = useState(false);
|
|
|
|
| 552 |
const [zoneEditorId, setZoneEditorId] = useState("");
|
| 553 |
const [zoneName, setZoneName] = useState("");
|
| 554 |
const [zoneColor, setZoneColor] = useState(ZONE_COLOR_CHOICES[0].value);
|
|
@@ -560,9 +557,29 @@ export function MapView({
|
|
| 560 |
const [zoneGeometryDraft, setZoneGeometryDraft] = useState<{ id: string; geometry: ZoneGeometry } | null>(null);
|
| 561 |
const [zoneBusy, setZoneBusy] = useState(false);
|
| 562 |
const [zoneErr, setZoneErr] = useState<string | null>(null);
|
|
|
|
| 563 |
const mapNavigator = mapNavigatorMode(routePanelOpen, zoneNavigatorOpen);
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 564 |
useEffect(() => {
|
| 565 |
-
if (routePanelOpen)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 566 |
}, [routePanelOpen]);
|
| 567 |
/**
|
| 568 |
* W37-T36 β the ROAD answer, which is the half arithmetic cannot produce.
|
|
@@ -617,14 +634,11 @@ export function MapView({
|
|
| 617 |
const [routeEditNote, setRouteEditNote] = useState("");
|
| 618 |
const [routeEditBusy, setRouteEditBusy] = useState(false);
|
| 619 |
const [routeEditErr, setRouteEditErr] = useState<string | null>(null);
|
| 620 |
-
/**
|
| 621 |
-
|
|
|
|
| 622 |
const [routeCopyMsg, setRouteCopyMsg] = useState<string | null>(null);
|
| 623 |
-
const [
|
| 624 |
-
const [routeScheduleBusy, setRouteScheduleBusy] = useState(false);
|
| 625 |
-
const [routeScheduleMsg, setRouteScheduleMsg] = useState<string | null>(null);
|
| 626 |
-
const [routeScheduleErr, setRouteScheduleErr] = useState<string | null>(null);
|
| 627 |
-
const [routeDeliveries, setRouteDeliveries] = useState<RouteDelivery[] | null>(null);
|
| 628 |
/** Which saved column a save writes to. `""` = a new field, named in the prompt below. */
|
| 629 |
const [saveTarget, setSaveTarget] = useState("");
|
| 630 |
/**
|
|
@@ -642,7 +656,7 @@ export function MapView({
|
|
| 642 |
* wall, reported as `mine`). Collapsing them into one control would either offer a Save that
|
| 643 |
* earns a 403 or hide a route the person is allowed to read.
|
| 644 |
*/
|
| 645 |
-
const [
|
| 646 |
const [openErr, setOpenErr] = useState<string | null>(null);
|
| 647 |
/**
|
| 648 |
* ββ OWNER ITEM 5 (2026-08-23) β THE NAME IS ASKED FOR, AND ITS DEFAULT COMES FROM THE SERVER.
|
|
@@ -845,7 +859,7 @@ export function MapView({
|
|
| 845 |
|
| 846 |
const loadZones = useCallback(async () => {
|
| 847 |
try {
|
| 848 |
-
const res = await fetch(
|
| 849 |
credentials: "same-origin",
|
| 850 |
});
|
| 851 |
const body = res.ok ? await res.json().catch(() => null) : null;
|
|
@@ -859,14 +873,17 @@ export function MapView({
|
|
| 859 |
() => [...new Set(rows.map((row) => row.pid))].sort((a, b) => a - b).join(","),
|
| 860 |
[rows]
|
| 861 |
);
|
| 862 |
-
|
| 863 |
-
|
| 864 |
-
|
| 865 |
-
|
| 866 |
-
|
| 867 |
-
.catch(() =>
|
| 868 |
-
|
|
|
|
|
|
|
| 869 |
}, [visibleRoutePids]);
|
|
|
|
| 870 |
useEffect(() => {
|
| 871 |
// A managed clause belongs to one saved View. Never carry it into another View's authored state.
|
| 872 |
setManagedRouteViewState(null);
|
|
@@ -944,11 +961,132 @@ export function MapView({
|
|
| 944 |
if (res.status === 409 && body?.error?.code === "no_route_stop") return "This route has no matching stop to move.";
|
| 945 |
if (!res.ok) return body?.error?.message || "The stop order could not be changed.";
|
| 946 |
const routeUpdate = body?.route as MapRouteDto | undefined;
|
| 947 |
-
if (routeUpdate) setNamedRoutes((current) => current.map((item) => item.id === routeUpdate.id
|
|
|
|
|
|
|
| 948 |
return null;
|
| 949 |
} catch { return "The stop order could not be changed."; }
|
| 950 |
}, []);
|
| 951 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 952 |
const activeZones = useMemo(
|
| 953 |
() => (zones || []).filter((zone) => zone.visible && activeZoneIds.has(zone.id)),
|
| 954 |
[zones, activeZoneIds]
|
|
@@ -972,14 +1110,143 @@ export function MapView({
|
|
| 972 |
});
|
| 973 |
const body = await res.json().catch(() => null);
|
| 974 |
if (!res.ok) return body?.error?.message || "The Route could not be created.";
|
| 975 |
-
if (body?.route)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 976 |
return null;
|
| 977 |
} catch { return "The Route could not be created."; }
|
| 978 |
-
}, [activeView]);
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 979 |
const zoneEditor = useMemo(
|
| 980 |
() => (zones || []).find((zone) => zone.id === zoneEditorId) || null,
|
| 981 |
[zones, zoneEditorId]
|
| 982 |
);
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 983 |
/**
|
| 984 |
* Zone visibility is a checkbox chooser, not a ctrl-click native multi-select. A toggle also
|
| 985 |
* immediately projects the Zone's durable membership onto the grid selection; removing one
|
|
@@ -999,26 +1266,21 @@ export function MapView({
|
|
| 999 |
else for (const pid of zone.memberships || []) if (!stillHeld.has(pid)) selection.delete(pid);
|
| 1000 |
onSelectPids([...selection], "replace");
|
| 1001 |
setActiveZoneIds(next);
|
| 1002 |
-
if (checked) {
|
| 1003 |
-
setZoneEditorId(zone.id);
|
| 1004 |
-
setZoneName(zone.name);
|
| 1005 |
-
setZoneColor(zone.color);
|
| 1006 |
-
setZoneGeographicField(zone.geographicField || "");
|
| 1007 |
-
setZoneZipCodes((zone.zipCodes || []).join(", "));
|
| 1008 |
-
}
|
| 1009 |
}, [activeZoneIds, zones, selectedPids, onSelectPids]);
|
| 1010 |
const zonePolygons = useMemo(() => activeZones.flatMap((zone) => {
|
| 1011 |
const geometry = zoneGeometryDraft?.id === zone.id
|
| 1012 |
? zoneGeometryDraft.geometry
|
| 1013 |
: zone.geometryGeoJson;
|
| 1014 |
-
|
|
|
|
| 1015 |
? [geometry.coordinates as number[][][]]
|
| 1016 |
-
: geometry
|
| 1017 |
? geometry.coordinates as number[][][][]
|
| 1018 |
: [];
|
| 1019 |
return polygons.flatMap((polygon, polygonIndex) => polygon.map((ring, ringIndex) => ({
|
| 1020 |
key: `${zone.id}:${polygonIndex}:${ringIndex}`,
|
| 1021 |
zone,
|
|
|
|
| 1022 |
points: ring
|
| 1023 |
.filter((pair) => Array.isArray(pair) && Number.isFinite(pair[0]) && Number.isFinite(pair[1]))
|
| 1024 |
.map((pair) => project(pair[0], pair[1])),
|
|
@@ -1043,29 +1305,36 @@ export function MapView({
|
|
| 1043 |
}, [drawnZoneGeometry, points, selectedPids]);
|
| 1044 |
|
| 1045 |
const saveZone = useCallback(async (existing?: MapZone) => {
|
| 1046 |
-
const geometryGeoJson = selectionZoneGeometry();
|
| 1047 |
const name = zoneName.trim() || existing?.name || "";
|
| 1048 |
-
|
| 1049 |
-
|
|
|
|
| 1050 |
return;
|
| 1051 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1052 |
setZoneBusy(true);
|
| 1053 |
setZoneErr(null);
|
| 1054 |
try {
|
| 1055 |
-
const res = await fetch(existing ?
|
| 1056 |
method: existing ? "PATCH" : "POST",
|
| 1057 |
credentials: "same-origin",
|
| 1058 |
headers: { "Content-Type": "application/json" },
|
| 1059 |
-
body: JSON.stringify({
|
| 1060 |
-
tableKey,
|
| 1061 |
name,
|
| 1062 |
color: zoneColor || existing?.color || ZONE_COLOR_CHOICES[0].value,
|
| 1063 |
geometryGeoJson,
|
| 1064 |
visible: existing?.visible ?? true,
|
| 1065 |
geographicField: zoneGeographicField,
|
| 1066 |
-
zipCodes
|
| 1067 |
-
memberships
|
| 1068 |
-
}),
|
| 1069 |
});
|
| 1070 |
const body = await res.json().catch(() => null);
|
| 1071 |
if (!res.ok) {
|
|
@@ -1078,7 +1347,15 @@ export function MapView({
|
|
| 1078 |
const without = (current || []).filter((zone) => zone.id !== saved.id);
|
| 1079 |
return [...without, saved].sort((a, b) => a.name.localeCompare(b.name));
|
| 1080 |
});
|
| 1081 |
-
setActiveZoneIds((current) =>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1082 |
}
|
| 1083 |
setDrawnZoneGeometry(null);
|
| 1084 |
setZoneName("");
|
|
@@ -1087,17 +1364,19 @@ export function MapView({
|
|
| 1087 |
} finally {
|
| 1088 |
setZoneBusy(false);
|
| 1089 |
}
|
| 1090 |
-
}, [selectionZoneGeometry, zoneName, zoneColor, zoneGeographicField,
|
|
|
|
|
|
|
| 1091 |
|
| 1092 |
const setZoneVisible = useCallback(async (zone: MapZone, visible: boolean) => {
|
| 1093 |
setZoneBusy(true);
|
| 1094 |
setZoneErr(null);
|
| 1095 |
try {
|
| 1096 |
-
const res = await fetch(
|
| 1097 |
method: "PATCH",
|
| 1098 |
credentials: "same-origin",
|
| 1099 |
headers: { "Content-Type": "application/json" },
|
| 1100 |
-
body: JSON.stringify(
|
| 1101 |
});
|
| 1102 |
const body = await res.json().catch(() => null);
|
| 1103 |
if (!res.ok) {
|
|
@@ -1105,24 +1384,30 @@ export function MapView({
|
|
| 1105 |
return;
|
| 1106 |
}
|
| 1107 |
const saved = body?.zone as MapZone | undefined;
|
| 1108 |
-
if (saved)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1109 |
} catch {
|
| 1110 |
setZoneErr("The Zone visibility could not be updated.");
|
| 1111 |
} finally {
|
| 1112 |
setZoneBusy(false);
|
| 1113 |
}
|
| 1114 |
-
}, [tableKey]);
|
| 1115 |
|
| 1116 |
/** Persist a direct boundary drag without re-deriving membership from the current selection. */
|
| 1117 |
const persistZoneGeometry = useCallback(async (zone: MapZone, geometryGeoJson: ZoneGeometry) => {
|
| 1118 |
setZoneBusy(true);
|
| 1119 |
setZoneErr(null);
|
| 1120 |
try {
|
| 1121 |
-
const res = await fetch(
|
| 1122 |
method: "PATCH",
|
| 1123 |
credentials: "same-origin",
|
| 1124 |
headers: { "Content-Type": "application/json" },
|
| 1125 |
-
body: JSON.stringify(
|
|
|
|
|
|
|
| 1126 |
});
|
| 1127 |
const body = await res.json().catch(() => null);
|
| 1128 |
if (!res.ok) {
|
|
@@ -1130,13 +1415,50 @@ export function MapView({
|
|
| 1130 |
return;
|
| 1131 |
}
|
| 1132 |
const saved = body?.zone as MapZone | undefined;
|
| 1133 |
-
if (saved)
|
|
|
|
|
|
|
|
|
|
| 1134 |
} catch {
|
| 1135 |
setZoneErr("The Zone boundary could not be saved.");
|
| 1136 |
} finally {
|
| 1137 |
setZoneBusy(false);
|
| 1138 |
}
|
| 1139 |
-
}, [tableKey]);
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1140 |
|
| 1141 |
// The fit is the INITIAL view, not the projection (see mapProjection.ts).
|
| 1142 |
const fit = useMemo(
|
|
@@ -1292,6 +1614,27 @@ export function MapView({
|
|
| 1292 |
[]
|
| 1293 |
);
|
| 1294 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1295 |
/** Selected pins that can actually be routed, in a STABLE order (by pid) β
|
| 1296 |
* a Set's iteration order must not be what decides a route. */
|
| 1297 |
const customerRoutable = useMemo(
|
|
@@ -1579,13 +1922,16 @@ export function MapView({
|
|
| 1579 |
}
|
| 1580 |
}, []);
|
| 1581 |
|
| 1582 |
-
const loadRouteDeliveries = useCallback(async () => {
|
| 1583 |
try {
|
| 1584 |
-
const res = await fetch(
|
|
|
|
|
|
|
|
|
|
| 1585 |
const body = res.ok ? await res.json().catch(() => null) : null;
|
| 1586 |
-
|
| 1587 |
} catch {
|
| 1588 |
-
|
| 1589 |
}
|
| 1590 |
}, []);
|
| 1591 |
|
|
@@ -1598,8 +1944,13 @@ export function MapView({
|
|
| 1598 |
if ((routePanelOpen || routeOn) && routeCols === null) void loadRouteCols();
|
| 1599 |
}, [routePanelOpen, routeOn, routeCols, loadRouteCols]);
|
| 1600 |
useEffect(() => {
|
| 1601 |
-
|
| 1602 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1603 |
|
| 1604 |
const updateRouteDetails = useCallback(async () => {
|
| 1605 |
if (!routeEditKey || !routeEditName.trim()) return;
|
|
@@ -1643,58 +1994,35 @@ export function MapView({
|
|
| 1643 |
}
|
| 1644 |
}, [plan]);
|
| 1645 |
|
| 1646 |
-
const
|
| 1647 |
-
|
| 1648 |
-
|
| 1649 |
-
|
| 1650 |
-
|
| 1651 |
-
|
| 1652 |
-
|
| 1653 |
-
|
| 1654 |
-
|
| 1655 |
-
|
| 1656 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1657 |
try {
|
| 1658 |
-
const
|
| 1659 |
-
|
| 1660 |
-
method: "
|
| 1661 |
-
|
| 1662 |
-
headers: { "Content-Type": "application/json" },
|
| 1663 |
-
body: JSON.stringify({
|
| 1664 |
-
name: openedRoute
|
| 1665 |
-
? `${(routeCols || []).find((route) => route.key === openedRoute)?.label || "Route"} delivery`
|
| 1666 |
-
: "Scheduled route",
|
| 1667 |
-
recipient: routeRecipient.trim(),
|
| 1668 |
-
schedule: { cron: "0 8 * * *", enabled: true },
|
| 1669 |
-
routeSnapshot: {
|
| 1670 |
-
// This route's stop ids are frozen below. The View config is only a compare guard:
|
| 1671 |
-
// the API resolves this saved View and mints the durable revision itself.
|
| 1672 |
-
sourceViewId: activeView.id,
|
| 1673 |
-
sourceViewConfig: activeView.config,
|
| 1674 |
-
sourceViewName: activeView.name,
|
| 1675 |
-
timezone,
|
| 1676 |
-
routeField: saveTarget || openedRoute,
|
| 1677 |
-
orderedStopIds,
|
| 1678 |
-
mapsPerLink,
|
| 1679 |
-
},
|
| 1680 |
-
}),
|
| 1681 |
-
});
|
| 1682 |
const body = await res.json().catch(() => null);
|
| 1683 |
-
if (!res.ok)
|
| 1684 |
-
|
| 1685 |
-
|
| 1686 |
-
}
|
| 1687 |
-
setRouteScheduleMsg(`Scheduled ${orderedStopIds.length.toLocaleString()} frozen stops to ${routeRecipient.trim()} each day at 08:00.`);
|
| 1688 |
-
setRouteDeliveries((current) => {
|
| 1689 |
-
const delivery = body?.delivery as RouteDelivery | undefined;
|
| 1690 |
-
return delivery ? [...(current || []), delivery] : current;
|
| 1691 |
-
});
|
| 1692 |
} catch {
|
| 1693 |
-
|
| 1694 |
-
} finally {
|
| 1695 |
-
setRouteScheduleBusy(false);
|
| 1696 |
}
|
| 1697 |
-
}, [
|
| 1698 |
|
| 1699 |
/**
|
| 1700 |
* ββ OWNER, 2026-08-23 β **OPEN A SAVED ROUTE AND SEE IT ON THE MAP.**
|
|
@@ -2050,10 +2378,10 @@ export function MapView({
|
|
| 2050 |
// hooks live until route-order columns are retired server-side; none renders a second Route UI.
|
| 2051 |
void [
|
| 2052 |
formatDuration, ROUTE_STOP_CAP, RecordPicker, setRoundTrip, setDepot, setTravelMode, travelModes,
|
| 2053 |
-
roadBusy, roadErr, routeEditBusy, routeEditErr,
|
| 2054 |
-
|
| 2055 |
saveBusy, saveMsg, saveErr, selectFilteredRouteRecords, unroutable, unroutableNames,
|
| 2056 |
-
updateRouteDetails, copyRouteLinks,
|
| 2057 |
orderStale, removeStop, addRecord, addableRecords, moveStop,
|
| 2058 |
];
|
| 2059 |
|
|
@@ -2235,7 +2563,7 @@ export function MapView({
|
|
| 2235 |
const current = unproject(fromScreen({ x, y }, view));
|
| 2236 |
setZoneGeometryDraft({
|
| 2237 |
id: zoneMove.zone.id,
|
| 2238 |
-
geometry: translateZoneGeometry(zoneMove.
|
| 2239 |
lon: current.lon - origin.lon,
|
| 2240 |
lat: current.lat - origin.lat,
|
| 2241 |
}),
|
|
@@ -2340,6 +2668,19 @@ export function MapView({
|
|
| 2340 |
[onSelectPids, selectedPids]
|
| 2341 |
);
|
| 2342 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2343 |
const onPointerUp = useCallback(
|
| 2344 |
(e: ReactPointerEvent<SVGSVGElement>) => {
|
| 2345 |
if (zoneMove) {
|
|
@@ -2544,8 +2885,25 @@ export function MapView({
|
|
| 2544 |
</span>
|
| 2545 |
)}
|
| 2546 |
{zones !== null && (
|
| 2547 |
-
<button
|
| 2548 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2549 |
</button>
|
| 2550 |
)}
|
| 2551 |
{/* βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
|
@@ -2568,12 +2926,63 @@ export function MapView({
|
|
| 2568 |
<aside id="cg-route-popover" className="cg-route-popover cg-route-nav-panel cg-route-index" aria-label="Routes">
|
| 2569 |
<RouteNav
|
| 2570 |
routes={namedRoutes}
|
|
|
|
| 2571 |
selectedIds={selectedRouteIds}
|
|
|
|
| 2572 |
sources={routeSources}
|
|
|
|
|
|
|
|
|
|
| 2573 |
onToggle={(route) => void toggleNamedRoute(route)}
|
|
|
|
|
|
|
| 2574 |
onCreate={createNamedRoute}
|
| 2575 |
onMoveToOrder={moveNamedRouteStop}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2576 |
/>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2577 |
{routeSelectionWarning && (
|
| 2578 |
<span className="cg-w44-route-warning" role="status">{routeSelectionWarning}</span>
|
| 2579 |
)}
|
|
@@ -2585,145 +2994,143 @@ export function MapView({
|
|
| 2585 |
</aside>
|
| 2586 |
)}
|
| 2587 |
{geoControl}
|
| 2588 |
-
{zones !== null && mapNavigator === "zones" && (
|
| 2589 |
-
<aside className="cg-route-popover cg-route-nav-panel cg-zone-nav" aria-label="Zone
|
| 2590 |
-
<div className="cg-route-popover-head">
|
| 2591 |
-
|
| 2592 |
-
|
| 2593 |
-
|
| 2594 |
-
|
| 2595 |
-
|
| 2596 |
-
|
| 2597 |
-
|
| 2598 |
-
|
| 2599 |
-
|
| 2600 |
-
|
| 2601 |
-
</button>
|
| 2602 |
-
{zoneChooserOpen && (
|
| 2603 |
-
<div id="cg-map-zone-choices" className="cg-map-zone-choices" role="group" aria-label="Visible map Zones">
|
| 2604 |
-
{(zones || []).length === 0 ? (
|
| 2605 |
-
<span className="cg-map-zone-empty">No Zones yet.</span>
|
| 2606 |
-
) : (zones || []).map((zone) => (
|
| 2607 |
-
<label className="cg-map-zone-choice" key={zone.id}>
|
| 2608 |
<input
|
| 2609 |
type="checkbox"
|
| 2610 |
checked={activeZoneIds.has(zone.id)}
|
|
|
|
| 2611 |
onChange={(event) => toggleZone(zone, event.target.checked)}
|
| 2612 |
/>
|
| 2613 |
<span className="cg-map-zone-swatch" style={{ backgroundColor: zone.color }} aria-hidden="true" />
|
| 2614 |
<span>{zone.visible ? zone.name : `${zone.name} (hidden)`}</span>
|
| 2615 |
</label>
|
| 2616 |
-
|
| 2617 |
-
|
| 2618 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2619 |
</div>
|
| 2620 |
-
|
| 2621 |
-
|
| 2622 |
-
|
| 2623 |
-
|
| 2624 |
-
|
| 2625 |
-
|
| 2626 |
-
|
| 2627 |
-
|
| 2628 |
-
|
| 2629 |
-
|
| 2630 |
-
|
| 2631 |
-
|
| 2632 |
-
|
| 2633 |
-
|
| 2634 |
-
|
| 2635 |
-
|
| 2636 |
-
|
| 2637 |
-
|
| 2638 |
-
|
| 2639 |
-
{zoneEditor.visible ? "Hide Zone" : "Show Zone"}
|
| 2640 |
-
</button>
|
| 2641 |
-
)}
|
| 2642 |
-
<label className="cg-map-zone-control">
|
| 2643 |
-
Geography
|
| 2644 |
-
<select
|
| 2645 |
-
className="cg-route-select"
|
| 2646 |
-
value={zoneGeographicField}
|
| 2647 |
-
aria-label="Geographic field"
|
| 2648 |
-
onChange={(event) => {
|
| 2649 |
-
setZoneGeographicField(event.target.value);
|
| 2650 |
-
setZoneGeographicValue("");
|
| 2651 |
-
}}
|
| 2652 |
-
>
|
| 2653 |
-
<option value="">Choose a geographic field</option>
|
| 2654 |
-
{geographicFields.map((key) => <option key={key} value={key}>{key}</option>)}
|
| 2655 |
-
</select>
|
| 2656 |
-
</label>
|
| 2657 |
-
{zoneGeographicField && (
|
| 2658 |
<label className="cg-map-zone-control">
|
| 2659 |
-
|
| 2660 |
<select
|
| 2661 |
className="cg-route-select"
|
| 2662 |
-
value={
|
| 2663 |
-
aria-label="Geographic
|
| 2664 |
onChange={(event) => {
|
| 2665 |
-
|
| 2666 |
-
setZoneGeographicValue(
|
| 2667 |
-
if (value) {
|
| 2668 |
-
onSelectPids(
|
| 2669 |
-
mapRows.filter((row) => String(row[zoneGeographicField] ?? "").trim() === value).map((row) => row.pid),
|
| 2670 |
-
"replace"
|
| 2671 |
-
);
|
| 2672 |
-
}
|
| 2673 |
}}
|
| 2674 |
>
|
| 2675 |
-
<option value="">Choose a
|
| 2676 |
-
{
|
| 2677 |
</select>
|
| 2678 |
</label>
|
| 2679 |
-
|
| 2680 |
-
|
| 2681 |
-
|
| 2682 |
-
|
| 2683 |
-
|
| 2684 |
-
|
| 2685 |
-
|
| 2686 |
-
|
| 2687 |
-
|
| 2688 |
-
|
| 2689 |
-
|
| 2690 |
-
|
| 2691 |
-
|
| 2692 |
-
|
| 2693 |
-
|
| 2694 |
-
|
| 2695 |
-
|
| 2696 |
-
|
| 2697 |
-
|
| 2698 |
-
|
| 2699 |
-
|
| 2700 |
-
|
| 2701 |
-
|
| 2702 |
-
|
| 2703 |
-
|
| 2704 |
-
|
| 2705 |
-
|
| 2706 |
-
|
| 2707 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2708 |
>
|
| 2709 |
-
{
|
| 2710 |
-
|
| 2711 |
-
|
| 2712 |
-
|
| 2713 |
-
|
| 2714 |
-
|
| 2715 |
-
|
| 2716 |
-
|
| 2717 |
-
|
| 2718 |
-
|
| 2719 |
-
|
| 2720 |
-
|
| 2721 |
-
: "Save a Zone around the selected records"}
|
| 2722 |
-
>
|
| 2723 |
-
{zoneBusy ? "Saving Zone" : zoneEditor ? "Update Zone" : "Save Zone"}
|
| 2724 |
-
</button>
|
| 2725 |
-
{zoneErr && <span className="cg-cal-nodate">{zoneErr}</span>}
|
| 2726 |
-
</div>
|
| 2727 |
</aside>
|
| 2728 |
)}
|
| 2729 |
{/* Every gesture the map has, named. `alt` (add to the selection rather
|
|
@@ -2732,7 +3139,13 @@ export function MapView({
|
|
| 2732 |
knew about. It needs shift too β alt alone still pans. */}
|
| 2733 |
<span className="cg-map-hint">
|
| 2734 |
Scroll to zoom Β· drag to pan Β· {lassoTool ? "shift-drag to lasso" : "shift-drag to select"}{" "}
|
| 2735 |
-
Β· shift-alt-drag to extend the selection Β·
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2736 |
pin to add or remove it from the selection
|
| 2737 |
</span>
|
| 2738 |
</div>
|
|
@@ -2742,7 +3155,7 @@ export function MapView({
|
|
| 2742 |
role="group"
|
| 2743 |
aria-label="Map canvas. Arrow keys pan, plus and minus zoom, square brackets rotate, zero fits to data and faces north."
|
| 2744 |
onKeyDown={onFrameKeyDown}
|
| 2745 |
-
onPointerDown={() => signal(NAV_MINIMIZE_EVENT)}
|
| 2746 |
>
|
| 2747 |
<svg
|
| 2748 |
ref={setSvgEl}
|
|
@@ -2838,6 +3251,7 @@ export function MapView({
|
|
| 2838 |
svg?.setPointerCapture(event.pointerId);
|
| 2839 |
setZoneMove({
|
| 2840 |
zone: ring.zone,
|
|
|
|
| 2841 |
start: localPoint(event.clientX, event.clientY),
|
| 2842 |
});
|
| 2843 |
}}
|
|
@@ -2923,7 +3337,7 @@ export function MapView({
|
|
| 2923 |
// hint bar above is the SIGHTED half of this same disclosure. It said "Click to
|
| 2924 |
// select, double click to open." until R10 made that false.
|
| 2925 |
// Policed by `verify_ui.py::pin_label_states_the_gesture`.
|
| 2926 |
-
aria-label={
|
| 2927 |
onMouseEnter={() => setHoverPid(p.pid)}
|
| 2928 |
onMouseLeave={() => setHoverPid((h) => (h === p.pid ? null : h))}
|
| 2929 |
onFocus={() => setHoverPid(p.pid)}
|
|
@@ -2941,6 +3355,10 @@ export function MapView({
|
|
| 2941 |
pinSelect(p.pid, true);
|
| 2942 |
return;
|
| 2943 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2944 |
// ββ W41-T48 (owner instruction 22) β OPENING A RECORD FOLDS THE RAIL, ON
|
| 2945 |
// THE MAP EXACTLY AS IN THE GRID. `CustomerGrid.tsx::onCellClicked` raises
|
| 2946 |
// this on every cell click; the map was the one surface that opened a record
|
|
@@ -2975,6 +3393,7 @@ export function MapView({
|
|
| 2975 |
onDoubleClick={(e) => {
|
| 2976 |
if (movedRef.current) return;
|
| 2977 |
e.preventDefault();
|
|
|
|
| 2978 |
onOpen(p.pid);
|
| 2979 |
}}
|
| 2980 |
onKeyDown={(e) => {
|
|
@@ -2986,6 +3405,10 @@ export function MapView({
|
|
| 2986 |
// disambiguate, so the guard the pointer needs would only be superstition.
|
| 2987 |
if (e.key === "Enter") {
|
| 2988 |
e.preventDefault();
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2989 |
// W41-T48 β the keyboard mirror of the plain click, so it folds the rail
|
| 2990 |
// for the same reason. β `!e.repeat` is this path's `e.detail <= 1`: a HELD
|
| 2991 |
// Enter auto-repeats keydown for as long as the finger is down, and every
|
|
|
|
| 94 |
import type { GeoStop, Pt, RouteStamp, View } from "./mapProjection";
|
| 95 |
import { LP_INK, LP_MAP_SELECTED, LP_PURPLE, LP_PURPLE_DEEP } from "./theme";
|
| 96 |
import { RouteNav } from "./RouteNav";
|
| 97 |
+
import { normalizedRouteMapLinks } from "./routeLinks";
|
| 98 |
+
import {
|
| 99 |
+
requestRouteDelivery,
|
| 100 |
+
usesNormalizedCustomerZones,
|
| 101 |
+
zoneCollectionPath,
|
| 102 |
+
zoneItemPath,
|
| 103 |
+
zoneMutationPayload,
|
| 104 |
+
} from "./routeZoneApi";
|
| 105 |
+
import { mapNavigatorMode, normalizedZoneZipCodes, routeSourceStopIds, toggleRouteSelection, zoneMembershipPids } from "./routeZoneTypes";
|
| 106 |
+
import type {
|
| 107 |
+
MapRouteDto, MapRouteFolderDto, MapRouteSource, MapRouteUpdate, MapZoneDto,
|
| 108 |
+
RouteDeliveryDto, RouteDeliveryRequest, RouteSelectionRequest, RouteSelectionResponse,
|
| 109 |
+
} from "./routeZoneTypes";
|
| 110 |
import "./map.css";
|
| 111 |
|
| 112 |
/**
|
|
|
|
| 359 |
|
| 360 |
/** C3's durable map-domain DTO. Zones are not generic fields: geometry, visibility and the
|
| 361 |
* membership snapshot only make sense to this projection. */
|
| 362 |
+
type MapZone = MapZoneDto;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 363 |
|
| 364 |
interface ZoneMove {
|
| 365 |
zone: MapZone;
|
| 366 |
+
geometry: ZoneGeometry;
|
| 367 |
start: Pt;
|
| 368 |
}
|
| 369 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 370 |
/** Immutable provenance supplied by the host grid for a scheduled route snapshot. */
|
| 371 |
export interface RouteSourceView {
|
| 372 |
id: string;
|
|
|
|
| 422 |
activeView,
|
| 423 |
tableKey,
|
| 424 |
onManagedRouteViewState,
|
| 425 |
+
onZoneChanged,
|
| 426 |
}: {
|
| 427 |
/** DISTINCT data rows from the full pipeline, overlay edits layered β the
|
| 428 |
* calendar/kanban contract, verbatim. */
|
|
|
|
| 466 |
tableKey: string;
|
| 467 |
/** C2 handoff: the server alone returns the managed route-membership clause. */
|
| 468 |
onManagedRouteViewState?: (viewState: Record<string, unknown>) => void;
|
| 469 |
+
/** Customer Zones also project into the read-only grid field, so a successful normalized
|
| 470 |
+
* mutation invalidates the host row payload instead of leaving that projection stale. */
|
| 471 |
+
onZoneChanged?: () => void;
|
| 472 |
/**
|
| 473 |
* ββ OWNER ITEM 9 β THE WHOLE BOOK, so a stop can be added that the VIEW filtered out.
|
| 474 |
*
|
|
|
|
| 531 |
const [zones, setZones] = useState<MapZone[] | null>(null);
|
| 532 |
/** C2 named-route read model. Legacy route-order columns remain compatibility only. */
|
| 533 |
const [namedRoutes, setNamedRoutes] = useState<MapRouteDto[]>([]);
|
| 534 |
+
const [routeFolders, setRouteFolders] = useState<MapRouteFolderDto[]>([]);
|
| 535 |
+
const [createdRoute, setCreatedRoute] = useState<MapRouteDto | null>(null);
|
| 536 |
const [selectedRouteIds, setSelectedRouteIds] = useState<ReadonlySet<string>>(new Set());
|
| 537 |
+
/** The Route detail is the only pin-edit target. Route selection never chooses it implicitly. */
|
| 538 |
+
const [activeRouteId, setActiveRouteId] = useState<string | null>(null);
|
| 539 |
+
const [routePinPrompt, setRoutePinPrompt] = useState<{
|
| 540 |
+
routeId: string; customerPid: number; title: string; present: boolean;
|
| 541 |
+
} | null>(null);
|
| 542 |
+
const [routePinNotice, setRoutePinNotice] = useState<string | null>(null);
|
| 543 |
+
const [routePinBusy, setRoutePinBusy] = useState(false);
|
| 544 |
const [managedRouteViewState, setManagedRouteViewState] = useState<Record<string, unknown> | null>(null);
|
| 545 |
const [routeSelectionWarning, setRouteSelectionWarning] = useState<string | null>(null);
|
| 546 |
const [activeZoneIds, setActiveZoneIds] = useState<ReadonlySet<string>>(new Set());
|
|
|
|
| 547 |
const [zoneNavigatorOpen, setZoneNavigatorOpen] = useState(false);
|
| 548 |
+
const [zoneEditorOpen, setZoneEditorOpen] = useState(false);
|
| 549 |
const [zoneEditorId, setZoneEditorId] = useState("");
|
| 550 |
const [zoneName, setZoneName] = useState("");
|
| 551 |
const [zoneColor, setZoneColor] = useState(ZONE_COLOR_CHOICES[0].value);
|
|
|
|
| 557 |
const [zoneGeometryDraft, setZoneGeometryDraft] = useState<{ id: string; geometry: ZoneGeometry } | null>(null);
|
| 558 |
const [zoneBusy, setZoneBusy] = useState(false);
|
| 559 |
const [zoneErr, setZoneErr] = useState<string | null>(null);
|
| 560 |
+
const normalizedCustomerZones = usesNormalizedCustomerZones(tableKey);
|
| 561 |
const mapNavigator = mapNavigatorMode(routePanelOpen, zoneNavigatorOpen);
|
| 562 |
+
const activeNamedRoute = useMemo(
|
| 563 |
+
() => activeRouteId ? namedRoutes.find((route) => route.id === activeRouteId) || null : null,
|
| 564 |
+
[activeRouteId, namedRoutes]
|
| 565 |
+
);
|
| 566 |
+
useEffect(() => {
|
| 567 |
+
setRoutePinPrompt(null);
|
| 568 |
+
setRoutePinNotice(null);
|
| 569 |
+
}, [activeRouteId]);
|
| 570 |
+
useEffect(() => {
|
| 571 |
+
if (activeRouteId && !activeNamedRoute) setActiveRouteId(null);
|
| 572 |
+
}, [activeNamedRoute, activeRouteId]);
|
| 573 |
useEffect(() => {
|
| 574 |
+
if (routePanelOpen) {
|
| 575 |
+
setZoneNavigatorOpen(false);
|
| 576 |
+
setZoneEditorOpen(false);
|
| 577 |
+
return;
|
| 578 |
+
}
|
| 579 |
+
setActiveRouteId(null);
|
| 580 |
+
setRoutePinPrompt(null);
|
| 581 |
+
setRoutePinNotice(null);
|
| 582 |
+
setRoutePinBusy(false);
|
| 583 |
}, [routePanelOpen]);
|
| 584 |
/**
|
| 585 |
* W37-T36 β the ROAD answer, which is the half arithmetic cannot produce.
|
|
|
|
| 634 |
const [routeEditNote, setRouteEditNote] = useState("");
|
| 635 |
const [routeEditBusy, setRouteEditBusy] = useState(false);
|
| 636 |
const [routeEditErr, setRouteEditErr] = useState<string | null>(null);
|
| 637 |
+
/** The legacy on-map planner still chunks a preview at ten stops. Scheduled normalized Routes
|
| 638 |
+
* own their independently editable 2-10 choice inside RouteNav. */
|
| 639 |
+
const mapsPerLink = 10;
|
| 640 |
const [routeCopyMsg, setRouteCopyMsg] = useState<string | null>(null);
|
| 641 |
+
const [routeDeliveries, setRouteDeliveries] = useState<RouteDeliveryDto[] | null>(null);
|
|
|
|
|
|
|
|
|
|
|
|
|
| 642 |
/** Which saved column a save writes to. `""` = a new field, named in the prompt below. */
|
| 643 |
const [saveTarget, setSaveTarget] = useState("");
|
| 644 |
/**
|
|
|
|
| 656 |
* wall, reported as `mine`). Collapsing them into one control would either offer a Save that
|
| 657 |
* earns a 403 or hide a route the person is allowed to read.
|
| 658 |
*/
|
| 659 |
+
const [, setOpenedRoute] = useState("");
|
| 660 |
const [openErr, setOpenErr] = useState<string | null>(null);
|
| 661 |
/**
|
| 662 |
* ββ OWNER ITEM 5 (2026-08-23) β THE NAME IS ASKED FOR, AND ITS DEFAULT COMES FROM THE SERVER.
|
|
|
|
| 859 |
|
| 860 |
const loadZones = useCallback(async () => {
|
| 861 |
try {
|
| 862 |
+
const res = await fetch(zoneCollectionPath(tableKey), {
|
| 863 |
credentials: "same-origin",
|
| 864 |
});
|
| 865 |
const body = res.ok ? await res.json().catch(() => null) : null;
|
|
|
|
| 873 |
() => [...new Set(rows.map((row) => row.pid))].sort((a, b) => a - b).join(","),
|
| 874 |
[rows]
|
| 875 |
);
|
| 876 |
+
const loadNamedRoutes = useCallback(async () => {
|
| 877 |
+
try {
|
| 878 |
+
const res = await fetch(`/api/v1/customers/routes?visiblePids=${encodeURIComponent(visibleRoutePids)}`, {
|
| 879 |
+
credentials: "same-origin",
|
| 880 |
+
});
|
| 881 |
+
const body = res.ok ? await res.json().catch(() => null) : null;
|
| 882 |
+
if (Array.isArray(body?.routes)) setNamedRoutes(body.routes);
|
| 883 |
+
if (Array.isArray(body?.folders)) setRouteFolders(body.folders);
|
| 884 |
+
} catch { /* Keep the last honest Route navigation when a refresh is temporarily unavailable. */ }
|
| 885 |
}, [visibleRoutePids]);
|
| 886 |
+
useEffect(() => { void loadNamedRoutes(); }, [loadNamedRoutes, routePanelOpen]);
|
| 887 |
useEffect(() => {
|
| 888 |
// A managed clause belongs to one saved View. Never carry it into another View's authored state.
|
| 889 |
setManagedRouteViewState(null);
|
|
|
|
| 961 |
if (res.status === 409 && body?.error?.code === "no_route_stop") return "This route has no matching stop to move.";
|
| 962 |
if (!res.ok) return body?.error?.message || "The stop order could not be changed.";
|
| 963 |
const routeUpdate = body?.route as MapRouteDto | undefined;
|
| 964 |
+
if (routeUpdate) setNamedRoutes((current) => current.map((item) => item.id === routeUpdate.id
|
| 965 |
+
? { ...item, ...routeUpdate, folderId: item.folderId, navOrder: item.navOrder }
|
| 966 |
+
: item));
|
| 967 |
return null;
|
| 968 |
} catch { return "The stop order could not be changed."; }
|
| 969 |
}, []);
|
| 970 |
|
| 971 |
+
const updateNamedRoute = useCallback(async (
|
| 972 |
+
route: MapRouteDto, patch: MapRouteUpdate
|
| 973 |
+
): Promise<string | null> => {
|
| 974 |
+
if (!route.permission.canEdit || route.compatibility === "legacy-route-order")
|
| 975 |
+
return "This Route is read-only.";
|
| 976 |
+
try {
|
| 977 |
+
const res = await fetch(`/api/v1/customers/routes/${encodeURIComponent(route.id)}`, {
|
| 978 |
+
method: "PATCH", credentials: "same-origin", headers: { "Content-Type": "application/json" },
|
| 979 |
+
body: JSON.stringify(patch),
|
| 980 |
+
});
|
| 981 |
+
const body = await res.json().catch(() => null);
|
| 982 |
+
if (!res.ok) return body?.error?.message || body?.detail?.message || "The Route could not be updated.";
|
| 983 |
+
const routeUpdate = body?.route as MapRouteDto | undefined;
|
| 984 |
+
if (!routeUpdate) return "The Route update returned no Route.";
|
| 985 |
+
setNamedRoutes((current) => current.map((item) => item.id === routeUpdate.id
|
| 986 |
+
? { ...item, ...routeUpdate, folderId: item.folderId, navOrder: item.navOrder }
|
| 987 |
+
: item));
|
| 988 |
+
return null;
|
| 989 |
+
} catch { return "The Route could not be updated."; }
|
| 990 |
+
}, []);
|
| 991 |
+
|
| 992 |
+
const deleteNamedRoute = useCallback(async (route: MapRouteDto): Promise<string | null> => {
|
| 993 |
+
if (!route.permission.canEdit || route.compatibility === "legacy-route-order")
|
| 994 |
+
return "This Route is read-only.";
|
| 995 |
+
try {
|
| 996 |
+
const res = await fetch(`/api/v1/customers/routes/${encodeURIComponent(route.id)}`, {
|
| 997 |
+
method: "DELETE", credentials: "same-origin",
|
| 998 |
+
});
|
| 999 |
+
const body = await res.json().catch(() => null);
|
| 1000 |
+
if (!res.ok) return body?.error?.message || body?.detail?.message || "The Route could not be deleted.";
|
| 1001 |
+
|
| 1002 |
+
const nextSelected = new Set(selectedRouteIds);
|
| 1003 |
+
const removedSelection = nextSelected.delete(route.id);
|
| 1004 |
+
setNamedRoutes((current) => current.filter((item) => item.id !== route.id));
|
| 1005 |
+
setCreatedRoute((current) => current?.id === route.id ? null : current);
|
| 1006 |
+
setSelectedRouteIds(nextSelected);
|
| 1007 |
+
if (activeRouteId === route.id) setActiveRouteId(null);
|
| 1008 |
+
setRoutePinPrompt(null);
|
| 1009 |
+
setRoutePinNotice(null);
|
| 1010 |
+
|
| 1011 |
+
if (removedSelection && activeView) {
|
| 1012 |
+
try {
|
| 1013 |
+
const selectionRes = await fetch("/api/v1/customers/routes/selection", {
|
| 1014 |
+
method: "POST", credentials: "same-origin", headers: { "Content-Type": "application/json" },
|
| 1015 |
+
body: JSON.stringify({
|
| 1016 |
+
routeIds: [...nextSelected],
|
| 1017 |
+
viewState: managedRouteViewState || (activeView.config as unknown as Record<string, unknown>),
|
| 1018 |
+
} satisfies RouteSelectionRequest),
|
| 1019 |
+
});
|
| 1020 |
+
const selectionBody = await selectionRes.json().catch(() => null) as RouteSelectionResponse | null;
|
| 1021 |
+
if (!selectionRes.ok || selectionBody?.managedBy !== "loopable" || !selectionBody.viewState)
|
| 1022 |
+
throw new Error("managed selection refusal");
|
| 1023 |
+
setManagedRouteViewState(selectionBody.viewState);
|
| 1024 |
+
onManagedRouteViewState?.(selectionBody.viewState);
|
| 1025 |
+
setRouteSelectionWarning(null);
|
| 1026 |
+
} catch {
|
| 1027 |
+
setRouteSelectionWarning("The Route was deleted, but its View inclusion could not be cleared.");
|
| 1028 |
+
}
|
| 1029 |
+
}
|
| 1030 |
+
return null;
|
| 1031 |
+
} catch { return "The Route could not be deleted."; }
|
| 1032 |
+
}, [activeRouteId, activeView, managedRouteViewState, onManagedRouteViewState, selectedRouteIds]);
|
| 1033 |
+
|
| 1034 |
+
const requestRoutePinMembership = useCallback((customerPid: number, title: string) => {
|
| 1035 |
+
setRoutePinNotice(null);
|
| 1036 |
+
if (!activeNamedRoute) {
|
| 1037 |
+
setRoutePinPrompt(null);
|
| 1038 |
+
setRoutePinNotice("Open a route first.");
|
| 1039 |
+
return;
|
| 1040 |
+
}
|
| 1041 |
+
if (!activeNamedRoute.permission.canEdit || activeNamedRoute.compatibility === "legacy-route-order") {
|
| 1042 |
+
setRoutePinPrompt(null);
|
| 1043 |
+
setRoutePinNotice("This Route is read-only.");
|
| 1044 |
+
return;
|
| 1045 |
+
}
|
| 1046 |
+
const isMember = activeNamedRoute.visibleStopIds.includes(customerPid);
|
| 1047 |
+
setRoutePinPrompt({
|
| 1048 |
+
routeId: activeNamedRoute.id,
|
| 1049 |
+
customerPid,
|
| 1050 |
+
title: title || `Record ${customerPid}`,
|
| 1051 |
+
present: !isMember,
|
| 1052 |
+
});
|
| 1053 |
+
}, [activeNamedRoute]);
|
| 1054 |
+
|
| 1055 |
+
const confirmRoutePinMembership = useCallback(async () => {
|
| 1056 |
+
const prompt = routePinPrompt;
|
| 1057 |
+
if (!prompt || routePinBusy) return;
|
| 1058 |
+
setRoutePinBusy(true);
|
| 1059 |
+
setRoutePinNotice(null);
|
| 1060 |
+
try {
|
| 1061 |
+
const res = await fetch(
|
| 1062 |
+
`/api/v1/customers/routes/${encodeURIComponent(prompt.routeId)}/stops/membership`,
|
| 1063 |
+
{
|
| 1064 |
+
method: "POST", credentials: "same-origin", headers: { "Content-Type": "application/json" },
|
| 1065 |
+
body: JSON.stringify({ customerPid: prompt.customerPid, present: prompt.present }),
|
| 1066 |
+
}
|
| 1067 |
+
);
|
| 1068 |
+
const body = await res.json().catch(() => null);
|
| 1069 |
+
if (!res.ok) {
|
| 1070 |
+
setRoutePinNotice(body?.error?.message || body?.detail?.message || "The Route stop could not be changed.");
|
| 1071 |
+
return;
|
| 1072 |
+
}
|
| 1073 |
+
const routeUpdate = body?.route as MapRouteDto | undefined;
|
| 1074 |
+
if (!routeUpdate) {
|
| 1075 |
+
setRoutePinNotice("The Route stop update returned no Route.");
|
| 1076 |
+
return;
|
| 1077 |
+
}
|
| 1078 |
+
setNamedRoutes((current) => current.map((item) => item.id === routeUpdate.id
|
| 1079 |
+
? { ...item, ...routeUpdate, folderId: item.folderId, navOrder: item.navOrder }
|
| 1080 |
+
: item));
|
| 1081 |
+
setRoutePinPrompt(null);
|
| 1082 |
+
setRoutePinNotice(`${prompt.title} was ${prompt.present ? "added to" : "removed from"} ${routeUpdate.name}.`);
|
| 1083 |
+
} catch {
|
| 1084 |
+
setRoutePinNotice("The Route stop could not be changed.");
|
| 1085 |
+
} finally {
|
| 1086 |
+
setRoutePinBusy(false);
|
| 1087 |
+
}
|
| 1088 |
+
}, [routePinBusy, routePinPrompt]);
|
| 1089 |
+
|
| 1090 |
const activeZones = useMemo(
|
| 1091 |
() => (zones || []).filter((zone) => zone.visible && activeZoneIds.has(zone.id)),
|
| 1092 |
[zones, activeZoneIds]
|
|
|
|
| 1110 |
});
|
| 1111 |
const body = await res.json().catch(() => null);
|
| 1112 |
if (!res.ok) return body?.error?.message || "The Route could not be created.";
|
| 1113 |
+
if (body?.route) {
|
| 1114 |
+
setNamedRoutes((current) => [...current, body.route].sort((a, b) => a.navOrder - b.navOrder));
|
| 1115 |
+
setCreatedRoute(body.route as MapRouteDto);
|
| 1116 |
+
await loadNamedRoutes();
|
| 1117 |
+
}
|
| 1118 |
return null;
|
| 1119 |
} catch { return "The Route could not be created."; }
|
| 1120 |
+
}, [activeView, loadNamedRoutes]);
|
| 1121 |
+
const duplicateNamedRoute = useCallback(async (route: MapRouteDto): Promise<string | null> => {
|
| 1122 |
+
try {
|
| 1123 |
+
const res = await fetch(`/api/v1/customers/routes/${encodeURIComponent(route.id)}/duplicate`, {
|
| 1124 |
+
method: "POST", credentials: "same-origin", headers: { "Content-Type": "application/json" },
|
| 1125 |
+
body: JSON.stringify({ name: `${route.name} copy` }),
|
| 1126 |
+
});
|
| 1127 |
+
const body = await res.json().catch(() => null);
|
| 1128 |
+
if (!res.ok) return body?.error?.message || body?.detail?.message || "The Route could not be duplicated.";
|
| 1129 |
+
if (!body?.route) return "The duplicate returned no Route.";
|
| 1130 |
+
setNamedRoutes((current) => [...current, body.route].sort((a, b) => a.navOrder - b.navOrder));
|
| 1131 |
+
setCreatedRoute(body.route as MapRouteDto);
|
| 1132 |
+
await loadNamedRoutes();
|
| 1133 |
+
return null;
|
| 1134 |
+
} catch { return "The Route could not be duplicated."; }
|
| 1135 |
+
}, [loadNamedRoutes]);
|
| 1136 |
+
const shareNamedRoute = useCallback(async (route: MapRouteDto): Promise<string | null> => {
|
| 1137 |
+
if (!route.permission.canEdit || route.compatibility === "legacy-route-order")
|
| 1138 |
+
return "Only the Route owner can share this Route.";
|
| 1139 |
+
try {
|
| 1140 |
+
const res = await fetch(`/api/v1/customers/routes/${encodeURIComponent(route.id)}/share-ready`, {
|
| 1141 |
+
method: "POST", credentials: "same-origin",
|
| 1142 |
+
});
|
| 1143 |
+
const body = await res.json().catch(() => null);
|
| 1144 |
+
if (!res.ok) return body?.error?.message || body?.detail?.message || "Sharing could not be opened.";
|
| 1145 |
+
window.dispatchEvent(new CustomEvent("aios:share-open", {
|
| 1146 |
+
detail: { kind: body?.kind || "field", id: body?.id || route.shareId, label: body?.label || route.name },
|
| 1147 |
+
}));
|
| 1148 |
+
return null;
|
| 1149 |
+
} catch { return "Sharing could not be opened."; }
|
| 1150 |
+
}, []);
|
| 1151 |
+
const moveNamedRoute = useCallback(async (route: MapRouteDto, folderId: string | null): Promise<string | null> => {
|
| 1152 |
+
try {
|
| 1153 |
+
const res = await fetch(`/api/v1/customers/routes/${encodeURIComponent(route.id)}/folder`, {
|
| 1154 |
+
method: "PATCH", credentials: "same-origin", headers: { "Content-Type": "application/json" },
|
| 1155 |
+
body: JSON.stringify({ folderId }),
|
| 1156 |
+
});
|
| 1157 |
+
const body = await res.json().catch(() => null);
|
| 1158 |
+
if (!res.ok) return body?.error?.message || body?.detail?.message || "The Route could not be moved.";
|
| 1159 |
+
if (body?.route) setNamedRoutes((current) => current.map((item) => item.id === route.id ? body.route : item));
|
| 1160 |
+
if (Array.isArray(body?.folders)) setRouteFolders(body.folders);
|
| 1161 |
+
return null;
|
| 1162 |
+
} catch { return "The Route could not be moved."; }
|
| 1163 |
+
}, []);
|
| 1164 |
+
const reorderNamedRoutes = useCallback(async (order: string[]): Promise<string | null> => {
|
| 1165 |
+
try {
|
| 1166 |
+
const res = await fetch("/api/v1/customers/routes/reorder", {
|
| 1167 |
+
method: "POST", credentials: "same-origin", headers: { "Content-Type": "application/json" },
|
| 1168 |
+
body: JSON.stringify({ order }),
|
| 1169 |
+
});
|
| 1170 |
+
const body = await res.json().catch(() => null);
|
| 1171 |
+
if (!res.ok) return body?.error?.message || body?.detail?.message || "The Route order could not be saved.";
|
| 1172 |
+
await loadNamedRoutes();
|
| 1173 |
+
return null;
|
| 1174 |
+
} catch { return "The Route order could not be saved."; }
|
| 1175 |
+
}, [loadNamedRoutes]);
|
| 1176 |
+
const createNamedRouteFolder = useCallback(async (name: string, parent: string | null): Promise<string | null> => {
|
| 1177 |
+
try {
|
| 1178 |
+
const res = await fetch("/api/v1/customers/route-folders", {
|
| 1179 |
+
method: "POST", credentials: "same-origin", headers: { "Content-Type": "application/json" },
|
| 1180 |
+
body: JSON.stringify({ name, parent }),
|
| 1181 |
+
});
|
| 1182 |
+
const body = await res.json().catch(() => null);
|
| 1183 |
+
if (!res.ok) return body?.error?.message || body?.detail?.message || "The folder could not be created.";
|
| 1184 |
+
if (Array.isArray(body?.folders)) setRouteFolders(body.folders);
|
| 1185 |
+
return null;
|
| 1186 |
+
} catch { return "The folder could not be created."; }
|
| 1187 |
+
}, []);
|
| 1188 |
+
const updateNamedRouteFolder = useCallback(async (
|
| 1189 |
+
folder: MapRouteFolderDto, patch: { name?: string; parent?: string | null }
|
| 1190 |
+
): Promise<string | null> => {
|
| 1191 |
+
try {
|
| 1192 |
+
const res = await fetch(`/api/v1/customers/route-folders/${encodeURIComponent(folder.id)}`, {
|
| 1193 |
+
method: "PATCH", credentials: "same-origin", headers: { "Content-Type": "application/json" },
|
| 1194 |
+
body: JSON.stringify(patch),
|
| 1195 |
+
});
|
| 1196 |
+
const body = await res.json().catch(() => null);
|
| 1197 |
+
if (!res.ok) return body?.error?.message || body?.detail?.message || "The folder could not be updated.";
|
| 1198 |
+
if (Array.isArray(body?.folders)) setRouteFolders(body.folders);
|
| 1199 |
+
return null;
|
| 1200 |
+
} catch { return "The folder could not be updated."; }
|
| 1201 |
+
}, []);
|
| 1202 |
+
const deleteNamedRouteFolder = useCallback(async (folder: MapRouteFolderDto): Promise<string | null> => {
|
| 1203 |
+
try {
|
| 1204 |
+
const res = await fetch(`/api/v1/customers/route-folders/${encodeURIComponent(folder.id)}`, {
|
| 1205 |
+
method: "DELETE", credentials: "same-origin",
|
| 1206 |
+
});
|
| 1207 |
+
const body = await res.json().catch(() => null);
|
| 1208 |
+
if (!res.ok) return body?.error?.message || body?.detail?.message || "The folder could not be deleted.";
|
| 1209 |
+
if (Array.isArray(body?.folders)) setRouteFolders(body.folders);
|
| 1210 |
+
await loadNamedRoutes();
|
| 1211 |
+
return null;
|
| 1212 |
+
} catch { return "The folder could not be deleted."; }
|
| 1213 |
+
}, [loadNamedRoutes]);
|
| 1214 |
+
const reorderNamedRouteFolders = useCallback(async (order: string[]): Promise<string | null> => {
|
| 1215 |
+
try {
|
| 1216 |
+
const res = await fetch("/api/v1/customers/route-folders/reorder", {
|
| 1217 |
+
method: "POST", credentials: "same-origin", headers: { "Content-Type": "application/json" },
|
| 1218 |
+
body: JSON.stringify({ order }),
|
| 1219 |
+
});
|
| 1220 |
+
const body = await res.json().catch(() => null);
|
| 1221 |
+
if (!res.ok) return body?.error?.message || body?.detail?.message || "The folder order could not be saved.";
|
| 1222 |
+
await loadNamedRoutes();
|
| 1223 |
+
return null;
|
| 1224 |
+
} catch { return "The folder order could not be saved."; }
|
| 1225 |
+
}, [loadNamedRoutes]);
|
| 1226 |
const zoneEditor = useMemo(
|
| 1227 |
() => (zones || []).find((zone) => zone.id === zoneEditorId) || null,
|
| 1228 |
[zones, zoneEditorId]
|
| 1229 |
);
|
| 1230 |
+
const beginNewZone = useCallback(() => {
|
| 1231 |
+
setZoneEditorId("");
|
| 1232 |
+
setZoneName("");
|
| 1233 |
+
setZoneColor(ZONE_COLOR_CHOICES[0].value);
|
| 1234 |
+
setZoneZipCodes("");
|
| 1235 |
+
setDrawnZoneGeometry(null);
|
| 1236 |
+
setZoneErr(null);
|
| 1237 |
+
setZoneEditorOpen(true);
|
| 1238 |
+
}, []);
|
| 1239 |
+
const beginEditZone = useCallback((zone: MapZone) => {
|
| 1240 |
+
setZoneEditorId(zone.id);
|
| 1241 |
+
setZoneName(zone.name);
|
| 1242 |
+
setZoneColor(zone.color);
|
| 1243 |
+
setZoneGeographicField(zone.geographicField || "");
|
| 1244 |
+
setZoneGeographicValue("");
|
| 1245 |
+
setZoneZipCodes((zone.zipCodes || []).join(", "));
|
| 1246 |
+
setDrawnZoneGeometry(null);
|
| 1247 |
+
setZoneErr(null);
|
| 1248 |
+
setZoneEditorOpen(true);
|
| 1249 |
+
}, []);
|
| 1250 |
/**
|
| 1251 |
* Zone visibility is a checkbox chooser, not a ctrl-click native multi-select. A toggle also
|
| 1252 |
* immediately projects the Zone's durable membership onto the grid selection; removing one
|
|
|
|
| 1266 |
else for (const pid of zone.memberships || []) if (!stillHeld.has(pid)) selection.delete(pid);
|
| 1267 |
onSelectPids([...selection], "replace");
|
| 1268 |
setActiveZoneIds(next);
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1269 |
}, [activeZoneIds, zones, selectedPids, onSelectPids]);
|
| 1270 |
const zonePolygons = useMemo(() => activeZones.flatMap((zone) => {
|
| 1271 |
const geometry = zoneGeometryDraft?.id === zone.id
|
| 1272 |
? zoneGeometryDraft.geometry
|
| 1273 |
: zone.geometryGeoJson;
|
| 1274 |
+
if (!geometry) return [];
|
| 1275 |
+
const polygons = geometry.type === "Polygon"
|
| 1276 |
? [geometry.coordinates as number[][][]]
|
| 1277 |
+
: geometry.type === "MultiPolygon"
|
| 1278 |
? geometry.coordinates as number[][][][]
|
| 1279 |
: [];
|
| 1280 |
return polygons.flatMap((polygon, polygonIndex) => polygon.map((ring, ringIndex) => ({
|
| 1281 |
key: `${zone.id}:${polygonIndex}:${ringIndex}`,
|
| 1282 |
zone,
|
| 1283 |
+
geometry,
|
| 1284 |
points: ring
|
| 1285 |
.filter((pair) => Array.isArray(pair) && Number.isFinite(pair[0]) && Number.isFinite(pair[1]))
|
| 1286 |
.map((pair) => project(pair[0], pair[1])),
|
|
|
|
| 1305 |
}, [drawnZoneGeometry, points, selectedPids]);
|
| 1306 |
|
| 1307 |
const saveZone = useCallback(async (existing?: MapZone) => {
|
| 1308 |
+
const geometryGeoJson = drawnZoneGeometry || existing?.geometryGeoJson || selectionZoneGeometry();
|
| 1309 |
const name = zoneName.trim() || existing?.name || "";
|
| 1310 |
+
const zipCodes = normalizedZoneZipCodes(zoneZipCodes);
|
| 1311 |
+
if (!name || (!geometryGeoJson && zipCodes.length === 0)) {
|
| 1312 |
+
setZoneErr("Name a Zone and add a boundary or at least one ZIP code.");
|
| 1313 |
return;
|
| 1314 |
}
|
| 1315 |
+
if (normalizedCustomerZones && !existing && !activeView?.id) {
|
| 1316 |
+
setZoneErr("Open a saved View before creating a Customer Zone.");
|
| 1317 |
+
return;
|
| 1318 |
+
}
|
| 1319 |
+
const memberships = zoneMembershipPids(
|
| 1320 |
+
selectedPids, allRows || mapRows, zipCodes, zoneGeographicField
|
| 1321 |
+
);
|
| 1322 |
setZoneBusy(true);
|
| 1323 |
setZoneErr(null);
|
| 1324 |
try {
|
| 1325 |
+
const res = await fetch(existing ? zoneItemPath(tableKey, existing.id) : zoneCollectionPath(tableKey), {
|
| 1326 |
method: existing ? "PATCH" : "POST",
|
| 1327 |
credentials: "same-origin",
|
| 1328 |
headers: { "Content-Type": "application/json" },
|
| 1329 |
+
body: JSON.stringify(zoneMutationPayload(tableKey, existing?.sourceViewId || activeView?.id || null, {
|
|
|
|
| 1330 |
name,
|
| 1331 |
color: zoneColor || existing?.color || ZONE_COLOR_CHOICES[0].value,
|
| 1332 |
geometryGeoJson,
|
| 1333 |
visible: existing?.visible ?? true,
|
| 1334 |
geographicField: zoneGeographicField,
|
| 1335 |
+
zipCodes,
|
| 1336 |
+
memberships,
|
| 1337 |
+
})),
|
| 1338 |
});
|
| 1339 |
const body = await res.json().catch(() => null);
|
| 1340 |
if (!res.ok) {
|
|
|
|
| 1347 |
const without = (current || []).filter((zone) => zone.id !== saved.id);
|
| 1348 |
return [...without, saved].sort((a, b) => a.name.localeCompare(b.name));
|
| 1349 |
});
|
| 1350 |
+
setActiveZoneIds((current) => {
|
| 1351 |
+
const next = new Set(current);
|
| 1352 |
+
if (saved.visible) next.add(saved.id);
|
| 1353 |
+
else next.delete(saved.id);
|
| 1354 |
+
return next;
|
| 1355 |
+
});
|
| 1356 |
+
setZoneEditorId(saved.id);
|
| 1357 |
+
setZoneEditorOpen(false);
|
| 1358 |
+
if (normalizedCustomerZones) onZoneChanged?.();
|
| 1359 |
}
|
| 1360 |
setDrawnZoneGeometry(null);
|
| 1361 |
setZoneName("");
|
|
|
|
| 1364 |
} finally {
|
| 1365 |
setZoneBusy(false);
|
| 1366 |
}
|
| 1367 |
+
}, [drawnZoneGeometry, selectionZoneGeometry, zoneName, zoneColor, zoneGeographicField,
|
| 1368 |
+
zoneZipCodes, selectedPids, allRows, mapRows, tableKey, normalizedCustomerZones,
|
| 1369 |
+
activeView?.id, onZoneChanged]);
|
| 1370 |
|
| 1371 |
const setZoneVisible = useCallback(async (zone: MapZone, visible: boolean) => {
|
| 1372 |
setZoneBusy(true);
|
| 1373 |
setZoneErr(null);
|
| 1374 |
try {
|
| 1375 |
+
const res = await fetch(zoneItemPath(tableKey, zone.id), {
|
| 1376 |
method: "PATCH",
|
| 1377 |
credentials: "same-origin",
|
| 1378 |
headers: { "Content-Type": "application/json" },
|
| 1379 |
+
body: JSON.stringify(zoneMutationPayload(tableKey, zone.sourceViewId || activeView?.id || null, { visible })),
|
| 1380 |
});
|
| 1381 |
const body = await res.json().catch(() => null);
|
| 1382 |
if (!res.ok) {
|
|
|
|
| 1384 |
return;
|
| 1385 |
}
|
| 1386 |
const saved = body?.zone as MapZone | undefined;
|
| 1387 |
+
if (saved) {
|
| 1388 |
+
setZones((current) => (current || []).map((item) => item.id === saved.id ? saved : item));
|
| 1389 |
+
if (!saved.visible && activeZoneIds.has(saved.id)) toggleZone(zone, false);
|
| 1390 |
+
if (normalizedCustomerZones) onZoneChanged?.();
|
| 1391 |
+
}
|
| 1392 |
} catch {
|
| 1393 |
setZoneErr("The Zone visibility could not be updated.");
|
| 1394 |
} finally {
|
| 1395 |
setZoneBusy(false);
|
| 1396 |
}
|
| 1397 |
+
}, [tableKey, activeZoneIds, toggleZone, activeView?.id, normalizedCustomerZones, onZoneChanged]);
|
| 1398 |
|
| 1399 |
/** Persist a direct boundary drag without re-deriving membership from the current selection. */
|
| 1400 |
const persistZoneGeometry = useCallback(async (zone: MapZone, geometryGeoJson: ZoneGeometry) => {
|
| 1401 |
setZoneBusy(true);
|
| 1402 |
setZoneErr(null);
|
| 1403 |
try {
|
| 1404 |
+
const res = await fetch(zoneItemPath(tableKey, zone.id), {
|
| 1405 |
method: "PATCH",
|
| 1406 |
credentials: "same-origin",
|
| 1407 |
headers: { "Content-Type": "application/json" },
|
| 1408 |
+
body: JSON.stringify(zoneMutationPayload(
|
| 1409 |
+
tableKey, zone.sourceViewId || activeView?.id || null, { geometryGeoJson },
|
| 1410 |
+
)),
|
| 1411 |
});
|
| 1412 |
const body = await res.json().catch(() => null);
|
| 1413 |
if (!res.ok) {
|
|
|
|
| 1415 |
return;
|
| 1416 |
}
|
| 1417 |
const saved = body?.zone as MapZone | undefined;
|
| 1418 |
+
if (saved) {
|
| 1419 |
+
setZones((current) => (current || []).map((item) => item.id === saved.id ? saved : item));
|
| 1420 |
+
if (normalizedCustomerZones) onZoneChanged?.();
|
| 1421 |
+
}
|
| 1422 |
} catch {
|
| 1423 |
setZoneErr("The Zone boundary could not be saved.");
|
| 1424 |
} finally {
|
| 1425 |
setZoneBusy(false);
|
| 1426 |
}
|
| 1427 |
+
}, [tableKey, activeView?.id, normalizedCustomerZones, onZoneChanged]);
|
| 1428 |
+
|
| 1429 |
+
const deleteZone = useCallback(async (zone: MapZone) => {
|
| 1430 |
+
setZoneBusy(true);
|
| 1431 |
+
setZoneErr(null);
|
| 1432 |
+
try {
|
| 1433 |
+
const generic = !normalizedCustomerZones;
|
| 1434 |
+
const res = await fetch(zoneItemPath(tableKey, zone.id), {
|
| 1435 |
+
method: "DELETE",
|
| 1436 |
+
credentials: "same-origin",
|
| 1437 |
+
...(generic ? {
|
| 1438 |
+
headers: { "Content-Type": "application/json" },
|
| 1439 |
+
body: JSON.stringify({ tableKey }),
|
| 1440 |
+
} : {}),
|
| 1441 |
+
});
|
| 1442 |
+
const body = await res.json().catch(() => null);
|
| 1443 |
+
if (!res.ok) {
|
| 1444 |
+
setZoneErr(body?.error?.message || body?.detail?.message || "The Zone could not be deleted.");
|
| 1445 |
+
return;
|
| 1446 |
+
}
|
| 1447 |
+
setZones((current) => (current || []).filter((item) => item.id !== zone.id));
|
| 1448 |
+
setActiveZoneIds((current) => {
|
| 1449 |
+
const next = new Set(current);
|
| 1450 |
+
next.delete(zone.id);
|
| 1451 |
+
return next;
|
| 1452 |
+
});
|
| 1453 |
+
setZoneEditorId("");
|
| 1454 |
+
setZoneEditorOpen(false);
|
| 1455 |
+
if (normalizedCustomerZones) onZoneChanged?.();
|
| 1456 |
+
} catch {
|
| 1457 |
+
setZoneErr("The Zone could not be deleted.");
|
| 1458 |
+
} finally {
|
| 1459 |
+
setZoneBusy(false);
|
| 1460 |
+
}
|
| 1461 |
+
}, [normalizedCustomerZones, onZoneChanged, tableKey]);
|
| 1462 |
|
| 1463 |
// The fit is the INITIAL view, not the projection (see mapProjection.ts).
|
| 1464 |
const fit = useMemo(
|
|
|
|
| 1614 |
[]
|
| 1615 |
);
|
| 1616 |
|
| 1617 |
+
const activeRouteMaps = useMemo(() => {
|
| 1618 |
+
if (!activeNamedRoute) return { links: [], missingStopIds: [], refusal: null };
|
| 1619 |
+
const wanted = new Set(activeNamedRoute.visibleStopIds);
|
| 1620 |
+
const located = [] as { pid: number; lat: number; lon: number }[];
|
| 1621 |
+
for (const row of (allRows?.length ? allRows : mapRows)) {
|
| 1622 |
+
if (!wanted.has(row.pid)) continue;
|
| 1623 |
+
const at = coordField
|
| 1624 |
+
? parseLatLon(row[coordField.key])
|
| 1625 |
+
: (() => {
|
| 1626 |
+
const lat = coord(row.lat);
|
| 1627 |
+
const lon = coord(row.lon);
|
| 1628 |
+
return lat == null || lon == null || !isPlottable(lat, lon) ? null : { lat, lon };
|
| 1629 |
+
})();
|
| 1630 |
+
if (at) located.push({ pid: row.pid, lat: at.lat, lon: at.lon });
|
| 1631 |
+
}
|
| 1632 |
+
return normalizedRouteMapLinks(activeNamedRoute.visibleStopIds, located, coarsePointer);
|
| 1633 |
+
}, [activeNamedRoute, allRows, coarsePointer, coordField, mapRows]);
|
| 1634 |
+
const activeRouteMapsRefusal = activeRouteMaps.missingStopIds.length
|
| 1635 |
+
? `${activeRouteMaps.missingStopIds.length.toLocaleString()} Route stop${activeRouteMaps.missingStopIds.length === 1 ? " has" : "s have"} no map location. Add coordinates before opening Maps links.`
|
| 1636 |
+
: activeRouteMaps.refusal;
|
| 1637 |
+
|
| 1638 |
/** Selected pins that can actually be routed, in a STABLE order (by pid) β
|
| 1639 |
* a Set's iteration order must not be what decides a route. */
|
| 1640 |
const customerRoutable = useMemo(
|
|
|
|
| 1922 |
}
|
| 1923 |
}, []);
|
| 1924 |
|
| 1925 |
+
const loadRouteDeliveries = useCallback(async (routeId: string): Promise<RouteDeliveryDto[]> => {
|
| 1926 |
try {
|
| 1927 |
+
const res = await fetch(
|
| 1928 |
+
`/api/v1/customers/routes/${encodeURIComponent(routeId)}/deliveries`,
|
| 1929 |
+
{ credentials: "same-origin" },
|
| 1930 |
+
);
|
| 1931 |
const body = res.ok ? await res.json().catch(() => null) : null;
|
| 1932 |
+
return Array.isArray(body?.deliveries) ? body.deliveries : [];
|
| 1933 |
} catch {
|
| 1934 |
+
return [];
|
| 1935 |
}
|
| 1936 |
}, []);
|
| 1937 |
|
|
|
|
| 1944 |
if ((routePanelOpen || routeOn) && routeCols === null) void loadRouteCols();
|
| 1945 |
}, [routePanelOpen, routeOn, routeCols, loadRouteCols]);
|
| 1946 |
useEffect(() => {
|
| 1947 |
+
let current = true;
|
| 1948 |
+
setRouteDeliveries(null);
|
| 1949 |
+
if (routePanelOpen && activeRouteId) void loadRouteDeliveries(activeRouteId).then((deliveries) => {
|
| 1950 |
+
if (current) setRouteDeliveries(deliveries);
|
| 1951 |
+
});
|
| 1952 |
+
return () => { current = false; };
|
| 1953 |
+
}, [activeRouteId, loadRouteDeliveries, routePanelOpen]);
|
| 1954 |
|
| 1955 |
const updateRouteDetails = useCallback(async () => {
|
| 1956 |
if (!routeEditKey || !routeEditName.trim()) return;
|
|
|
|
| 1994 |
}
|
| 1995 |
}, [plan]);
|
| 1996 |
|
| 1997 |
+
const scheduleNamedRouteDelivery = useCallback(async (
|
| 1998 |
+
route: MapRouteDto,
|
| 1999 |
+
request: RouteDeliveryRequest,
|
| 2000 |
+
): Promise<string | null> => {
|
| 2001 |
+
const result = await requestRouteDelivery(route.id, request);
|
| 2002 |
+
if (result.error || !result.delivery) return result.error || "The Route delivery was not saved.";
|
| 2003 |
+
setRouteDeliveries((current) => [...(current || []).filter(
|
| 2004 |
+
(delivery) => delivery.id !== result.delivery!.id
|
| 2005 |
+
), result.delivery!]);
|
| 2006 |
+
return null;
|
| 2007 |
+
}, []);
|
| 2008 |
+
|
| 2009 |
+
const deleteNamedRouteDelivery = useCallback(async (
|
| 2010 |
+
route: MapRouteDto,
|
| 2011 |
+
delivery: RouteDeliveryDto,
|
| 2012 |
+
): Promise<string | null> => {
|
| 2013 |
try {
|
| 2014 |
+
const res = await fetch(
|
| 2015 |
+
`/api/v1/customers/routes/${encodeURIComponent(route.id)}/deliveries/${encodeURIComponent(delivery.id)}`,
|
| 2016 |
+
{ method: "DELETE", credentials: "same-origin" },
|
| 2017 |
+
);
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2018 |
const body = await res.json().catch(() => null);
|
| 2019 |
+
if (!res.ok) return body?.error?.message || body?.detail?.message || "The Route delivery could not be removed.";
|
| 2020 |
+
setRouteDeliveries((current) => (current || []).filter((item) => item.id !== delivery.id));
|
| 2021 |
+
return null;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2022 |
} catch {
|
| 2023 |
+
return "The Route delivery could not be removed.";
|
|
|
|
|
|
|
| 2024 |
}
|
| 2025 |
+
}, []);
|
| 2026 |
|
| 2027 |
/**
|
| 2028 |
* ββ OWNER, 2026-08-23 β **OPEN A SAVED ROUTE AND SEE IT ON THE MAP.**
|
|
|
|
| 2378 |
// hooks live until route-order columns are retired server-side; none renders a second Route UI.
|
| 2379 |
void [
|
| 2380 |
formatDuration, ROUTE_STOP_CAP, RecordPicker, setRoundTrip, setDepot, setTravelMode, travelModes,
|
| 2381 |
+
roadBusy, roadErr, routeEditBusy, routeEditErr, routeCopyMsg,
|
| 2382 |
+
openErr, naming, nameDraft, setNameDraft,
|
| 2383 |
saveBusy, saveMsg, saveErr, selectFilteredRouteRecords, unroutable, unroutableNames,
|
| 2384 |
+
updateRouteDetails, copyRouteLinks, openSavedRoute, saveRouteOrder,
|
| 2385 |
orderStale, removeStop, addRecord, addableRecords, moveStop,
|
| 2386 |
];
|
| 2387 |
|
|
|
|
| 2563 |
const current = unproject(fromScreen({ x, y }, view));
|
| 2564 |
setZoneGeometryDraft({
|
| 2565 |
id: zoneMove.zone.id,
|
| 2566 |
+
geometry: translateZoneGeometry(zoneMove.geometry, {
|
| 2567 |
lon: current.lon - origin.lon,
|
| 2568 |
lat: current.lat - origin.lat,
|
| 2569 |
}),
|
|
|
|
| 2668 |
[onSelectPids, selectedPids]
|
| 2669 |
);
|
| 2670 |
|
| 2671 |
+
const pinAriaLabel = useCallback((point: MapPoint) => {
|
| 2672 |
+
const title = point.title || "Untitled record";
|
| 2673 |
+
const selectionHint = "Shift-click or press Space to select.";
|
| 2674 |
+
if (!routePanelOpen)
|
| 2675 |
+
return `${title}. Click or press Enter to open the record. ${selectionHint}`;
|
| 2676 |
+
if (!activeNamedRoute)
|
| 2677 |
+
return `${title}. Routes are open. Open a route first. ${selectionHint}`;
|
| 2678 |
+
if (!activeNamedRoute.permission.canEdit || activeNamedRoute.compatibility === "legacy-route-order")
|
| 2679 |
+
return `${title}. ${activeNamedRoute.name} is read-only. ${selectionHint}`;
|
| 2680 |
+
const action = activeNamedRoute.visibleStopIds.includes(point.pid) ? "remove" : "add";
|
| 2681 |
+
return `${title}. Plain click or Enter asks to ${action} this stop ${action === "add" ? "to" : "from"} ${activeNamedRoute.name}. ${selectionHint}`;
|
| 2682 |
+
}, [activeNamedRoute, routePanelOpen]);
|
| 2683 |
+
|
| 2684 |
const onPointerUp = useCallback(
|
| 2685 |
(e: ReactPointerEvent<SVGSVGElement>) => {
|
| 2686 |
if (zoneMove) {
|
|
|
|
| 2885 |
</span>
|
| 2886 |
)}
|
| 2887 |
{zones !== null && (
|
| 2888 |
+
<button
|
| 2889 |
+
type="button"
|
| 2890 |
+
className="cg-btn cg-map-zone-trigger"
|
| 2891 |
+
disabled={mapNavigator === "routes"}
|
| 2892 |
+
aria-expanded={mapNavigator === "zones"}
|
| 2893 |
+
aria-controls="cg-zone-popover"
|
| 2894 |
+
aria-haspopup="dialog"
|
| 2895 |
+
aria-label="Choose Zones"
|
| 2896 |
+
onClick={() => {
|
| 2897 |
+
setZoneNavigatorOpen((open) => {
|
| 2898 |
+
const next = !open;
|
| 2899 |
+
if (next) setZoneEditorOpen(false);
|
| 2900 |
+
return next;
|
| 2901 |
+
});
|
| 2902 |
+
}}
|
| 2903 |
+
title={mapNavigator === "routes" ? "Close Routes before choosing Zones" : "Choose Zones"}
|
| 2904 |
+
>
|
| 2905 |
+
Zone{activeZoneIds.size ? ` (${activeZoneIds.size.toLocaleString()})` : ""}
|
| 2906 |
+
<svg viewBox="0 0 12 8" aria-hidden="true"><path d="m2 2 4 4 4-4" /></svg>
|
| 2907 |
</button>
|
| 2908 |
)}
|
| 2909 |
{/* βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
|
|
|
| 2926 |
<aside id="cg-route-popover" className="cg-route-popover cg-route-nav-panel cg-route-index" aria-label="Routes">
|
| 2927 |
<RouteNav
|
| 2928 |
routes={namedRoutes}
|
| 2929 |
+
folders={routeFolders}
|
| 2930 |
selectedIds={selectedRouteIds}
|
| 2931 |
+
activeRouteId={activeRouteId}
|
| 2932 |
sources={routeSources}
|
| 2933 |
+
storageKey={tableKey}
|
| 2934 |
+
createdRoute={createdRoute}
|
| 2935 |
+
onCreatedDismiss={() => setCreatedRoute(null)}
|
| 2936 |
onToggle={(route) => void toggleNamedRoute(route)}
|
| 2937 |
+
onActiveRouteChange={setActiveRouteId}
|
| 2938 |
+
onOpenRecord={onOpen}
|
| 2939 |
onCreate={createNamedRoute}
|
| 2940 |
onMoveToOrder={moveNamedRouteStop}
|
| 2941 |
+
onUpdate={updateNamedRoute}
|
| 2942 |
+
onDuplicate={duplicateNamedRoute}
|
| 2943 |
+
onDelete={deleteNamedRoute}
|
| 2944 |
+
onShare={shareNamedRoute}
|
| 2945 |
+
onRouteMove={moveNamedRoute}
|
| 2946 |
+
onRouteReorder={reorderNamedRoutes}
|
| 2947 |
+
onFolderCreate={createNamedRouteFolder}
|
| 2948 |
+
onFolderUpdate={updateNamedRouteFolder}
|
| 2949 |
+
onFolderDelete={deleteNamedRouteFolder}
|
| 2950 |
+
onFolderReorder={reorderNamedRouteFolders}
|
| 2951 |
+
filteredRecordCount={rows.length}
|
| 2952 |
+
onSelectFiltered={selectFilteredRouteRecords}
|
| 2953 |
+
onCreateStart={() => setSaveTarget("")}
|
| 2954 |
+
mapLinks={activeRouteMaps.links}
|
| 2955 |
+
mapLinkRefusal={activeRouteMapsRefusal}
|
| 2956 |
+
deliveries={routeDeliveries}
|
| 2957 |
+
onSchedule={scheduleNamedRouteDelivery}
|
| 2958 |
+
onDeleteDelivery={deleteNamedRouteDelivery}
|
| 2959 |
/>
|
| 2960 |
+
{routePinPrompt && (
|
| 2961 |
+
<div
|
| 2962 |
+
className="cg-w44-route-prompt"
|
| 2963 |
+
role="dialog"
|
| 2964 |
+
aria-label={`${routePinPrompt.present ? "Add" : "Remove"} Route stop`}
|
| 2965 |
+
aria-describedby="cg-route-pin-prompt-copy"
|
| 2966 |
+
>
|
| 2967 |
+
<p id="cg-route-pin-prompt-copy">
|
| 2968 |
+
{routePinPrompt.present ? "Add" : "Remove"} {routePinPrompt.title}{" "}
|
| 2969 |
+
{routePinPrompt.present ? "to" : "from"} {activeNamedRoute?.name || "this Route"}?
|
| 2970 |
+
</p>
|
| 2971 |
+
<div className="cg-form-actions">
|
| 2972 |
+
<button type="button" className="cg-btn cg-btn--primary" disabled={routePinBusy}
|
| 2973 |
+
onClick={() => void confirmRoutePinMembership()}>
|
| 2974 |
+
Confirm {routePinPrompt.present ? "add" : "remove"}
|
| 2975 |
+
</button>
|
| 2976 |
+
<button type="button" className="cg-btn" disabled={routePinBusy}
|
| 2977 |
+
onClick={() => setRoutePinPrompt(null)}>
|
| 2978 |
+
Cancel
|
| 2979 |
+
</button>
|
| 2980 |
+
</div>
|
| 2981 |
+
</div>
|
| 2982 |
+
)}
|
| 2983 |
+
{routePinNotice && (
|
| 2984 |
+
<span className="cg-w44-route-warning" role="status">{routePinNotice}</span>
|
| 2985 |
+
)}
|
| 2986 |
{routeSelectionWarning && (
|
| 2987 |
<span className="cg-w44-route-warning" role="status">{routeSelectionWarning}</span>
|
| 2988 |
)}
|
|
|
|
| 2994 |
</aside>
|
| 2995 |
)}
|
| 2996 |
{geoControl}
|
| 2997 |
+
{zones !== null && mapNavigator === "zones" && !zoneEditorOpen && (
|
| 2998 |
+
<aside id="cg-zone-popover" className="cg-route-popover cg-route-nav-panel cg-zone-nav" aria-label="Zone chooser">
|
| 2999 |
+
<div className="cg-route-popover-head">
|
| 3000 |
+
<button type="button" className="cg-route-index-back" onClick={() => setZoneNavigatorOpen(false)}>Back</button>
|
| 3001 |
+
<span className="cg-views-title">Zones</span>
|
| 3002 |
+
</div>
|
| 3003 |
+
<div className="cg-map-zones" role="group" aria-label="Choose visible Zones">
|
| 3004 |
+
<div id="cg-map-zone-choices" className="cg-map-zone-choices" role="group" aria-label="Visible map Zones">
|
| 3005 |
+
{(zones || []).length === 0 ? (
|
| 3006 |
+
<span className="cg-map-zone-empty">No Zones yet.</span>
|
| 3007 |
+
) : (zones || []).map((zone) => (
|
| 3008 |
+
<div className="cg-map-zone-option" key={zone.id}>
|
| 3009 |
+
<label className="cg-map-zone-choice">
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3010 |
<input
|
| 3011 |
type="checkbox"
|
| 3012 |
checked={activeZoneIds.has(zone.id)}
|
| 3013 |
+
disabled={!zone.visible}
|
| 3014 |
onChange={(event) => toggleZone(zone, event.target.checked)}
|
| 3015 |
/>
|
| 3016 |
<span className="cg-map-zone-swatch" style={{ backgroundColor: zone.color }} aria-hidden="true" />
|
| 3017 |
<span>{zone.visible ? zone.name : `${zone.name} (hidden)`}</span>
|
| 3018 |
</label>
|
| 3019 |
+
<button type="button" className="cg-map-zone-edit"
|
| 3020 |
+
disabled={normalizedCustomerZones && !zone.permission?.canEdit}
|
| 3021 |
+
onClick={() => beginEditZone(zone)} aria-label={`Edit ${zone.name}`}>
|
| 3022 |
+
Edit
|
| 3023 |
+
</button>
|
| 3024 |
+
</div>
|
| 3025 |
+
))}
|
| 3026 |
+
</div>
|
| 3027 |
+
<button type="button" className="cg-btn cg-btn--primary" onClick={beginNewZone}>New Zone</button>
|
| 3028 |
</div>
|
| 3029 |
+
</aside>
|
| 3030 |
+
)}
|
| 3031 |
+
{zones !== null && mapNavigator === "zones" && zoneEditorOpen && (
|
| 3032 |
+
<aside id="cg-zone-popover" className="cg-route-popover cg-route-nav-panel cg-zone-nav" aria-label={zoneEditor ? `Edit ${zoneEditor.name}` : "Create Zone"}>
|
| 3033 |
+
<div className="cg-route-popover-head">
|
| 3034 |
+
<button type="button" className="cg-route-index-back" onClick={() => { setZoneErr(null); setZoneEditorOpen(false); }}>Back to Zones</button>
|
| 3035 |
+
<span className="cg-views-title">{zoneEditor ? "Edit Zone" : "New Zone"}</span>
|
| 3036 |
+
</div>
|
| 3037 |
+
<div className="cg-map-zones cg-map-zone-editor">
|
| 3038 |
+
{zoneEditor && (
|
| 3039 |
+
<button
|
| 3040 |
+
type="button"
|
| 3041 |
+
className="cg-btn"
|
| 3042 |
+
disabled={zoneBusy || (normalizedCustomerZones && !zoneEditor.permission?.canEdit)}
|
| 3043 |
+
onClick={() => void setZoneVisible(zoneEditor, !zoneEditor.visible)}
|
| 3044 |
+
>
|
| 3045 |
+
{zoneEditor.visible ? "Hide Zone" : "Show Zone"}
|
| 3046 |
+
</button>
|
| 3047 |
+
)}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3048 |
<label className="cg-map-zone-control">
|
| 3049 |
+
Geography
|
| 3050 |
<select
|
| 3051 |
className="cg-route-select"
|
| 3052 |
+
value={zoneGeographicField}
|
| 3053 |
+
aria-label="Geographic field"
|
| 3054 |
onChange={(event) => {
|
| 3055 |
+
setZoneGeographicField(event.target.value);
|
| 3056 |
+
setZoneGeographicValue("");
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3057 |
}}
|
| 3058 |
>
|
| 3059 |
+
<option value="">Choose a geographic field</option>
|
| 3060 |
+
{geographicFields.map((key) => <option key={key} value={key}>{key}</option>)}
|
| 3061 |
</select>
|
| 3062 |
</label>
|
| 3063 |
+
{zoneGeographicField && (
|
| 3064 |
+
<label className="cg-map-zone-control">
|
| 3065 |
+
Group
|
| 3066 |
+
<select
|
| 3067 |
+
className="cg-route-select"
|
| 3068 |
+
value={zoneGeographicValue}
|
| 3069 |
+
aria-label="Geographic group"
|
| 3070 |
+
onChange={(event) => {
|
| 3071 |
+
const value = event.target.value;
|
| 3072 |
+
setZoneGeographicValue(value);
|
| 3073 |
+
if (value) {
|
| 3074 |
+
onSelectPids(
|
| 3075 |
+
mapRows.filter((row) => String(row[zoneGeographicField] ?? "").trim() === value).map((row) => row.pid),
|
| 3076 |
+
"replace"
|
| 3077 |
+
);
|
| 3078 |
+
}
|
| 3079 |
+
}}
|
| 3080 |
+
>
|
| 3081 |
+
<option value="">Choose a group</option>
|
| 3082 |
+
{geographicValues.map((value) => <option key={value} value={value}>{value}</option>)}
|
| 3083 |
+
</select>
|
| 3084 |
+
</label>
|
| 3085 |
+
)}
|
| 3086 |
+
<label className="cg-map-zone-control">
|
| 3087 |
+
ZIP codes
|
| 3088 |
+
<input
|
| 3089 |
+
className="cg-input"
|
| 3090 |
+
value={zoneZipCodes}
|
| 3091 |
+
aria-label="Zone ZIP codes"
|
| 3092 |
+
placeholder="75201, 75202"
|
| 3093 |
+
onChange={(event) => setZoneZipCodes(event.target.value)}
|
| 3094 |
+
/>
|
| 3095 |
+
</label>
|
| 3096 |
+
<label className="cg-map-zone-control">
|
| 3097 |
+
Zone name
|
| 3098 |
+
<input
|
| 3099 |
+
className="cg-input"
|
| 3100 |
+
value={zoneName}
|
| 3101 |
+
maxLength={120}
|
| 3102 |
+
aria-label="Zone name"
|
| 3103 |
+
placeholder="Name this Zone"
|
| 3104 |
+
onChange={(event) => setZoneName(event.target.value)}
|
| 3105 |
+
/>
|
| 3106 |
+
</label>
|
| 3107 |
+
<label className="cg-map-zone-control">
|
| 3108 |
+
Color
|
| 3109 |
+
<select className="cg-route-select" value={zoneColor} aria-label="Zone color" onChange={(event) => setZoneColor(event.target.value)}>
|
| 3110 |
+
{ZONE_COLOR_CHOICES.map((choice) => <option key={choice.value} value={choice.value}>{choice.label}</option>)}
|
| 3111 |
+
</select>
|
| 3112 |
+
</label>
|
| 3113 |
+
<button
|
| 3114 |
+
type="button"
|
| 3115 |
+
className="cg-btn cg-btn--primary"
|
| 3116 |
+
disabled={zoneBusy || (normalizedCustomerZones && !!zoneEditor && !zoneEditor.permission?.canEdit)}
|
| 3117 |
+
onClick={() => void saveZone(zoneEditor || undefined)}
|
| 3118 |
+
title={drawnZoneGeometry
|
| 3119 |
+
? (zoneEditor ? "Replace this Zone boundary with the drawn shape" : "Save the drawn Zone")
|
| 3120 |
+
: zoneEditor ? "Save Zone details" : "Save a Zone around the selected records"}
|
| 3121 |
>
|
| 3122 |
+
{zoneBusy ? "Saving Zone" : zoneEditor ? "Update Zone" : "Save Zone"}
|
| 3123 |
+
</button>
|
| 3124 |
+
{zoneEditor && (!normalizedCustomerZones || zoneEditor.permission?.canDelete) && (
|
| 3125 |
+
<button type="button" className="cg-btn cg-btn--danger" disabled={zoneBusy}
|
| 3126 |
+
onClick={() => {
|
| 3127 |
+
if (window.confirm(`Delete ${zoneEditor.name}?`)) void deleteZone(zoneEditor);
|
| 3128 |
+
}}>
|
| 3129 |
+
Delete Zone
|
| 3130 |
+
</button>
|
| 3131 |
+
)}
|
| 3132 |
+
{zoneErr && <span className="cg-cal-nodate" role="status">{zoneErr}</span>}
|
| 3133 |
+
</div>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3134 |
</aside>
|
| 3135 |
)}
|
| 3136 |
{/* Every gesture the map has, named. `alt` (add to the selection rather
|
|
|
|
| 3139 |
knew about. It needs shift too β alt alone still pans. */}
|
| 3140 |
<span className="cg-map-hint">
|
| 3141 |
Scroll to zoom Β· drag to pan Β· {lassoTool ? "shift-drag to lasso" : "shift-drag to select"}{" "}
|
| 3142 |
+
Β· shift-alt-drag to extend the selection Β· {routePanelOpen
|
| 3143 |
+
? activeNamedRoute
|
| 3144 |
+
? activeNamedRoute.permission.canEdit && activeNamedRoute.compatibility !== "legacy-route-order"
|
| 3145 |
+
? `click or press Enter on a pin to ask to add or remove it from ${activeNamedRoute.name}`
|
| 3146 |
+
: `${activeNamedRoute.name} is read-only; plain click or Enter does not open a record`
|
| 3147 |
+
: "open a route first; plain click or Enter does not open a record"
|
| 3148 |
+
: "click or press Enter on a pin to open the record"} Β· shift-click or press Space on a
|
| 3149 |
pin to add or remove it from the selection
|
| 3150 |
</span>
|
| 3151 |
</div>
|
|
|
|
| 3155 |
role="group"
|
| 3156 |
aria-label="Map canvas. Arrow keys pan, plus and minus zoom, square brackets rotate, zero fits to data and faces north."
|
| 3157 |
onKeyDown={onFrameKeyDown}
|
| 3158 |
+
onPointerDown={() => { if (!routePanelOpen) signal(NAV_MINIMIZE_EVENT); }}
|
| 3159 |
>
|
| 3160 |
<svg
|
| 3161 |
ref={setSvgEl}
|
|
|
|
| 3251 |
svg?.setPointerCapture(event.pointerId);
|
| 3252 |
setZoneMove({
|
| 3253 |
zone: ring.zone,
|
| 3254 |
+
geometry: ring.geometry,
|
| 3255 |
start: localPoint(event.clientX, event.clientY),
|
| 3256 |
});
|
| 3257 |
}}
|
|
|
|
| 3337 |
// hint bar above is the SIGHTED half of this same disclosure. It said "Click to
|
| 3338 |
// select, double click to open." until R10 made that false.
|
| 3339 |
// Policed by `verify_ui.py::pin_label_states_the_gesture`.
|
| 3340 |
+
aria-label={pinAriaLabel(p)}
|
| 3341 |
onMouseEnter={() => setHoverPid(p.pid)}
|
| 3342 |
onMouseLeave={() => setHoverPid((h) => (h === p.pid ? null : h))}
|
| 3343 |
onFocus={() => setHoverPid(p.pid)}
|
|
|
|
| 3355 |
pinSelect(p.pid, true);
|
| 3356 |
return;
|
| 3357 |
}
|
| 3358 |
+
if (routePanelOpen) {
|
| 3359 |
+
requestRoutePinMembership(p.pid, p.title);
|
| 3360 |
+
return;
|
| 3361 |
+
}
|
| 3362 |
// ββ W41-T48 (owner instruction 22) β OPENING A RECORD FOLDS THE RAIL, ON
|
| 3363 |
// THE MAP EXACTLY AS IN THE GRID. `CustomerGrid.tsx::onCellClicked` raises
|
| 3364 |
// this on every cell click; the map was the one surface that opened a record
|
|
|
|
| 3393 |
onDoubleClick={(e) => {
|
| 3394 |
if (movedRef.current) return;
|
| 3395 |
e.preventDefault();
|
| 3396 |
+
if (routePanelOpen) return;
|
| 3397 |
onOpen(p.pid);
|
| 3398 |
}}
|
| 3399 |
onKeyDown={(e) => {
|
|
|
|
| 3405 |
// disambiguate, so the guard the pointer needs would only be superstition.
|
| 3406 |
if (e.key === "Enter") {
|
| 3407 |
e.preventDefault();
|
| 3408 |
+
if (routePanelOpen) {
|
| 3409 |
+
if (!e.repeat) requestRoutePinMembership(p.pid, p.title);
|
| 3410 |
+
return;
|
| 3411 |
+
}
|
| 3412 |
// W41-T48 β the keyboard mirror of the plain click, so it folds the rail
|
| 3413 |
// for the same reason. β `!e.repeat` is this path's `e.detail <= 1`: a HELD
|
| 3414 |
// Enter auto-repeats keydown for as long as the finger is down, and every
|
web/src/customer-grid/RecordDetail.tsx
CHANGED
|
@@ -1627,7 +1627,7 @@ export default function RecordDetail({
|
|
| 1627 |
<section className="cg-detail-section cg-detail-relsec">
|
| 1628 |
<h3 className="cg-detail-sechead">
|
| 1629 |
{relTargets.length === 0 ? (
|
| 1630 |
-
<span>
|
| 1631 |
) : (
|
| 1632 |
<button
|
| 1633 |
type="button"
|
|
@@ -1635,7 +1635,7 @@ export default function RecordDetail({
|
|
| 1635 |
aria-expanded={relOpen}
|
| 1636 |
onClick={() => setRelOpen((open) => !open)}
|
| 1637 |
>
|
| 1638 |
-
|
| 1639 |
</button>
|
| 1640 |
)}
|
| 1641 |
<span className="cg-detail-seccount">
|
|
|
|
| 1627 |
<section className="cg-detail-section cg-detail-relsec">
|
| 1628 |
<h3 className="cg-detail-sechead">
|
| 1629 |
{relTargets.length === 0 ? (
|
| 1630 |
+
<span>Related</span>
|
| 1631 |
) : (
|
| 1632 |
<button
|
| 1633 |
type="button"
|
|
|
|
| 1635 |
aria-expanded={relOpen}
|
| 1636 |
onClick={() => setRelOpen((open) => !open)}
|
| 1637 |
>
|
| 1638 |
+
Related
|
| 1639 |
</button>
|
| 1640 |
)}
|
| 1641 |
<span className="cg-detail-seccount">
|
web/src/customer-grid/RouteNav.tsx
CHANGED
|
@@ -1,44 +1,555 @@
|
|
| 1 |
-
import { useState } from "react";
|
|
|
|
|
|
|
|
|
|
| 2 |
import { boundedGoogleMapsUrl } from "./routeZoneTypes";
|
| 3 |
-
import type {
|
|
|
|
|
|
|
|
|
|
|
|
|
| 4 |
|
| 5 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 6 |
routes: MapRouteDto[];
|
|
|
|
| 7 |
selectedIds: ReadonlySet<string>;
|
|
|
|
| 8 |
sources: MapRouteSource[];
|
|
|
|
|
|
|
|
|
|
| 9 |
onToggle: (route: MapRouteDto) => void;
|
| 10 |
-
|
| 11 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 12 |
}) {
|
| 13 |
-
const
|
|
|
|
|
|
|
|
|
|
|
|
|
| 14 |
const [creating, setCreating] = useState(false);
|
|
|
|
| 15 |
const [name, setName] = useState("");
|
|
|
|
| 16 |
const [sourceId, setSourceId] = useState<MapRouteSource["id"]>("selection");
|
| 17 |
const [error, setError] = useState<string | null>(null);
|
| 18 |
-
const [
|
| 19 |
-
const
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 20 |
const source = sources.find((item) => item.id === sourceId) || sources[0];
|
| 21 |
const mapsUrl = boundedGoogleMapsUrl(route?.mapsUrl);
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 22 |
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 44 |
}
|
|
|
|
| 1 |
+
import { useEffect, useMemo, useState } from "react";
|
| 2 |
+
import { folderPath, levelAt, resolveStoredPath } from "./dataPath";
|
| 3 |
+
import type { NormalizedRouteMapLink } from "./routeLinks";
|
| 4 |
+
import { submitRouteStopMove } from "./routeStopMove";
|
| 5 |
import { boundedGoogleMapsUrl } from "./routeZoneTypes";
|
| 6 |
+
import type {
|
| 7 |
+
MapRouteDto, MapRouteFolderDto, MapRouteSource, MapRouteUpdate,
|
| 8 |
+
RouteDeliveryDto, RouteDeliveryRequest,
|
| 9 |
+
} from "./routeZoneTypes";
|
| 10 |
+
import "../styles/wave42/route-nav.css";
|
| 11 |
|
| 12 |
+
type Result = Promise<string | null>;
|
| 13 |
+
|
| 14 |
+
export function RouteNav({ routes, folders, selectedIds, activeRouteId, sources, storageKey,
|
| 15 |
+
createdRoute, onCreatedDismiss, onToggle, onActiveRouteChange, onOpenRecord, onCreate,
|
| 16 |
+
onMoveToOrder, onUpdate, onDuplicate, onDelete, onShare, onRouteMove, onRouteReorder,
|
| 17 |
+
onFolderCreate, onFolderUpdate, onFolderDelete, onFolderReorder, filteredRecordCount,
|
| 18 |
+
onSelectFiltered, onCreateStart, mapLinks, mapLinkRefusal, deliveries, onSchedule,
|
| 19 |
+
onDeleteDelivery }: {
|
| 20 |
routes: MapRouteDto[];
|
| 21 |
+
folders: MapRouteFolderDto[];
|
| 22 |
selectedIds: ReadonlySet<string>;
|
| 23 |
+
activeRouteId: string | null;
|
| 24 |
sources: MapRouteSource[];
|
| 25 |
+
storageKey: string;
|
| 26 |
+
createdRoute: MapRouteDto | null;
|
| 27 |
+
onCreatedDismiss: () => void;
|
| 28 |
onToggle: (route: MapRouteDto) => void;
|
| 29 |
+
onActiveRouteChange: (routeId: string | null) => void;
|
| 30 |
+
onOpenRecord: (pid: number) => void;
|
| 31 |
+
onCreate: (name: string, source: MapRouteSource) => Result;
|
| 32 |
+
onMoveToOrder: (route: MapRouteDto, customerPid: number, order: number) => Result;
|
| 33 |
+
onUpdate: (route: MapRouteDto, patch: MapRouteUpdate) => Result;
|
| 34 |
+
onDuplicate: (route: MapRouteDto) => Result;
|
| 35 |
+
onDelete: (route: MapRouteDto) => Promise<string | null>;
|
| 36 |
+
onShare: (route: MapRouteDto) => Result;
|
| 37 |
+
onRouteMove: (route: MapRouteDto, folderId: string | null) => Result;
|
| 38 |
+
onRouteReorder: (order: string[]) => Result;
|
| 39 |
+
onFolderCreate: (name: string, parent: string | null) => Result;
|
| 40 |
+
onFolderUpdate: (folder: MapRouteFolderDto, patch: { name?: string; parent?: string | null }) => Result;
|
| 41 |
+
onFolderDelete: (folder: MapRouteFolderDto) => Result;
|
| 42 |
+
onFolderReorder: (order: string[]) => Result;
|
| 43 |
+
filteredRecordCount: number;
|
| 44 |
+
onSelectFiltered: () => void;
|
| 45 |
+
onCreateStart: () => void;
|
| 46 |
+
mapLinks: NormalizedRouteMapLink[];
|
| 47 |
+
mapLinkRefusal: string | null;
|
| 48 |
+
deliveries: RouteDeliveryDto[] | null;
|
| 49 |
+
onSchedule: (route: MapRouteDto, request: RouteDeliveryRequest) => Result;
|
| 50 |
+
onDeleteDelivery: (route: MapRouteDto, delivery: RouteDeliveryDto) => Result;
|
| 51 |
}) {
|
| 52 |
+
const routePathKey = `aios-routes-at-${storageKey}`;
|
| 53 |
+
const [at, setAt] = useState<string | null>(() => {
|
| 54 |
+
if (typeof window === "undefined") return null;
|
| 55 |
+
try { return window.localStorage.getItem(routePathKey); } catch { return null; }
|
| 56 |
+
});
|
| 57 |
const [creating, setCreating] = useState(false);
|
| 58 |
+
const [creatingFolder, setCreatingFolder] = useState(false);
|
| 59 |
const [name, setName] = useState("");
|
| 60 |
+
const [folderName, setFolderName] = useState("");
|
| 61 |
const [sourceId, setSourceId] = useState<MapRouteSource["id"]>("selection");
|
| 62 |
const [error, setError] = useState<string | null>(null);
|
| 63 |
+
const [orderDrafts, setOrderDrafts] = useState<Record<number, string>>({});
|
| 64 |
+
const [orderErrors, setOrderErrors] = useState<Record<number, string>>({});
|
| 65 |
+
const [editName, setEditName] = useState("");
|
| 66 |
+
const [editMapsUrl, setEditMapsUrl] = useState("");
|
| 67 |
+
const [deleteConfirm, setDeleteConfirm] = useState(false);
|
| 68 |
+
const [menuId, setMenuId] = useState<string | null>(null);
|
| 69 |
+
const [renameId, setRenameId] = useState<string | null>(null);
|
| 70 |
+
const [renameDraft, setRenameDraft] = useState("");
|
| 71 |
+
const [busy, setBusy] = useState(false);
|
| 72 |
+
const [deliveryRecipient, setDeliveryRecipient] = useState("");
|
| 73 |
+
const [deliveryMapsPerLink, setDeliveryMapsPerLink] = useState(10);
|
| 74 |
+
const [deliveryNotice, setDeliveryNotice] = useState<string | null>(null);
|
| 75 |
+
const [deliveryError, setDeliveryError] = useState<string | null>(null);
|
| 76 |
+
const [deliveryBusy, setDeliveryBusy] = useState(false);
|
| 77 |
+
const [mapCopyNotice, setMapCopyNotice] = useState<string | null>(null);
|
| 78 |
+
const [mapCopyError, setMapCopyError] = useState<string | null>(null);
|
| 79 |
+
const route = activeRouteId ? routes.find((item) => item.id === activeRouteId) : null;
|
| 80 |
const source = sources.find((item) => item.id === sourceId) || sources[0];
|
| 81 |
const mapsUrl = boundedGoogleMapsUrl(route?.mapsUrl);
|
| 82 |
+
const knownFolders = useMemo(() => new Set(folders.map((folder) => folder.id)), [folders]);
|
| 83 |
+
const validAt = resolveStoredPath(at, knownFolders);
|
| 84 |
+
const level = useMemo(
|
| 85 |
+
() => levelAt(validAt, folders, routes, (item) => item.folderId),
|
| 86 |
+
[folders, routes, validAt]
|
| 87 |
+
);
|
| 88 |
+
const crumbs = useMemo(() => folderPath(validAt, folders), [folders, validAt]);
|
| 89 |
+
const deliveryTimezone = useMemo(() => {
|
| 90 |
+
try { return Intl.DateTimeFormat().resolvedOptions().timeZone || "UTC"; }
|
| 91 |
+
catch { return "UTC"; }
|
| 92 |
+
}, []);
|
| 93 |
+
|
| 94 |
+
const navigate = (folderId: string | null) => {
|
| 95 |
+
setAt(folderId);
|
| 96 |
+
setMenuId(null);
|
| 97 |
+
setError(null);
|
| 98 |
+
try {
|
| 99 |
+
if (folderId) window.localStorage.setItem(routePathKey, folderId);
|
| 100 |
+
else window.localStorage.removeItem(routePathKey);
|
| 101 |
+
} catch { /* Navigation remains usable when storage is unavailable. */ }
|
| 102 |
+
};
|
| 103 |
+
|
| 104 |
+
useEffect(() => {
|
| 105 |
+
if (at && !validAt) navigate(null);
|
| 106 |
+
// `navigate` deliberately remains a local action; validity is the only reactive input.
|
| 107 |
+
// eslint-disable-next-line react-hooks/exhaustive-deps
|
| 108 |
+
}, [at, validAt]);
|
| 109 |
+
useEffect(() => {
|
| 110 |
+
setEditName(route?.name || "");
|
| 111 |
+
setEditMapsUrl(route?.mapsUrl || "");
|
| 112 |
+
setOrderDrafts({});
|
| 113 |
+
setOrderErrors({});
|
| 114 |
+
setDeleteConfirm(false);
|
| 115 |
+
setError(null);
|
| 116 |
+
setDeliveryNotice(null);
|
| 117 |
+
setDeliveryError(null);
|
| 118 |
+
setMapCopyNotice(null);
|
| 119 |
+
setMapCopyError(null);
|
| 120 |
+
}, [route?.id, route?.mapsUrl, route?.name]);
|
| 121 |
+
|
| 122 |
+
const copyMapLinks = () => {
|
| 123 |
+
setMapCopyNotice(null);
|
| 124 |
+
setMapCopyError(null);
|
| 125 |
+
const clipboard = typeof navigator === "undefined" ? null : navigator.clipboard;
|
| 126 |
+
if (!mapLinks.length || !clipboard?.writeText) {
|
| 127 |
+
setMapCopyError("Maps links could not be copied in this browser.");
|
| 128 |
+
return;
|
| 129 |
+
}
|
| 130 |
+
void clipboard.writeText(mapLinks.map((link) => link.url).join("\n"))
|
| 131 |
+
.then(() => setMapCopyNotice(
|
| 132 |
+
`${mapLinks.length.toLocaleString()} Maps link${mapLinks.length === 1 ? "" : "s"} copied.`
|
| 133 |
+
))
|
| 134 |
+
.catch(() => setMapCopyError("Maps links could not be copied. Open each link instead."));
|
| 135 |
+
};
|
| 136 |
+
|
| 137 |
+
const scheduleDelivery = (target: MapRouteDto) => {
|
| 138 |
+
const recipient = deliveryRecipient.trim();
|
| 139 |
+
if (!recipient) {
|
| 140 |
+
setDeliveryError("Choose an active Inbox recipient.");
|
| 141 |
+
return;
|
| 142 |
+
}
|
| 143 |
+
setDeliveryBusy(true);
|
| 144 |
+
setDeliveryError(null);
|
| 145 |
+
setDeliveryNotice(null);
|
| 146 |
+
void onSchedule(target, {
|
| 147 |
+
recipient,
|
| 148 |
+
timezone: deliveryTimezone,
|
| 149 |
+
mapsPerLink: deliveryMapsPerLink,
|
| 150 |
+
}).then((message) => {
|
| 151 |
+
if (message) setDeliveryError(message);
|
| 152 |
+
else setDeliveryNotice(`${target.name} will be delivered to ${recipient} daily at 08:00.`);
|
| 153 |
+
}).finally(() => setDeliveryBusy(false));
|
| 154 |
+
};
|
| 155 |
+
|
| 156 |
+
const removeDelivery = (target: MapRouteDto, delivery: RouteDeliveryDto) => {
|
| 157 |
+
setDeliveryBusy(true);
|
| 158 |
+
setDeliveryError(null);
|
| 159 |
+
setDeliveryNotice(null);
|
| 160 |
+
void onDeleteDelivery(target, delivery).then((message) => {
|
| 161 |
+
if (message) setDeliveryError(message);
|
| 162 |
+
else setDeliveryNotice(`${delivery.name} was removed.`);
|
| 163 |
+
}).finally(() => setDeliveryBusy(false));
|
| 164 |
+
};
|
| 165 |
+
|
| 166 |
+
const finish = (operation: Result) => {
|
| 167 |
+
setBusy(true);
|
| 168 |
+
void operation.then(setError).finally(() => setBusy(false));
|
| 169 |
+
};
|
| 170 |
+
const commitStopMove = (target: MapRouteDto, pid: number, raw: string) => {
|
| 171 |
+
setBusy(true);
|
| 172 |
+
setOrderErrors((current) => {
|
| 173 |
+
const next = { ...current };
|
| 174 |
+
delete next[pid];
|
| 175 |
+
return next;
|
| 176 |
+
});
|
| 177 |
+
void submitRouteStopMove(target, pid, raw, onMoveToOrder).then((result) => {
|
| 178 |
+
if (result.error) {
|
| 179 |
+
const message = result.error;
|
| 180 |
+
setOrderErrors((current) => ({ ...current, [pid]: message }));
|
| 181 |
+
return;
|
| 182 |
+
}
|
| 183 |
+
setOrderDrafts((current) => {
|
| 184 |
+
const next = { ...current };
|
| 185 |
+
delete next[pid];
|
| 186 |
+
return next;
|
| 187 |
+
});
|
| 188 |
+
setOrderErrors((current) => {
|
| 189 |
+
const next = { ...current };
|
| 190 |
+
delete next[pid];
|
| 191 |
+
return next;
|
| 192 |
+
});
|
| 193 |
+
}).finally(() => setBusy(false));
|
| 194 |
+
};
|
| 195 |
+
const swap = (ids: string[], id: string, delta: number) => {
|
| 196 |
+
const index = ids.indexOf(id);
|
| 197 |
+
const other = index + delta;
|
| 198 |
+
if (index < 0 || other < 0 || other >= ids.length) return null;
|
| 199 |
+
const next = [...ids];
|
| 200 |
+
[next[index], next[other]] = [next[other], next[index]];
|
| 201 |
+
return next;
|
| 202 |
+
};
|
| 203 |
+
|
| 204 |
+
if (route) {
|
| 205 |
+
const canEdit = route.permission.canEdit && route.compatibility !== "legacy-route-order";
|
| 206 |
+
return (
|
| 207 |
+
<section className="cg-w44-route-nav" aria-label={`${route.name} route`}>
|
| 208 |
+
<button type="button" className="cg-w44-route-back" onClick={() => onActiveRouteChange(null)}>
|
| 209 |
+
Back to routes
|
| 210 |
+
</button>
|
| 211 |
+
<div className="cg-w44-route-title">
|
| 212 |
+
<i style={{ backgroundColor: route.color }} aria-hidden="true" />
|
| 213 |
+
{route.number}. {route.name}
|
| 214 |
+
</div>
|
| 215 |
+
<p className="cg-w44-route-meta">
|
| 216 |
+
{route.shared ? `Shared by ${route.owner || "another user"}` : route.sharedOut ? "Shared with others" : "Private"}
|
| 217 |
+
</p>
|
| 218 |
+
{route.visibleStopIds.length ? (
|
| 219 |
+
<ol className="cg-w44-route-stops">
|
| 220 |
+
{route.visibleStopIds.map((pid, index) => (
|
| 221 |
+
<li key={pid}>
|
| 222 |
+
<button type="button" className="cg-w44-route-stop-open"
|
| 223 |
+
aria-label={`Open stop ${index + 1} record`} onClick={() => onOpenRecord(pid)}>
|
| 224 |
+
Stop {index + 1}
|
| 225 |
+
</button>
|
| 226 |
+
{canEdit && (
|
| 227 |
+
<span className="cg-w44-route-stop-actions">
|
| 228 |
+
<button type="button" className="cg-w44-route-step" disabled={busy || index === 0}
|
| 229 |
+
aria-label={`Move stop ${index + 1} earlier`}
|
| 230 |
+
title="Move earlier" onClick={() => commitStopMove(route, pid, String(index))}>
|
| 231 |
+
<svg viewBox="0 0 16 16" aria-hidden="true"><path d="M10 3 5 8l5 5" /></svg>
|
| 232 |
+
</button>
|
| 233 |
+
<label className="cg-w44-route-position"><span>Position</span>
|
| 234 |
+
<input className="cg-w44-route-order" type="text" inputMode="numeric" pattern="[0-9]*"
|
| 235 |
+
disabled={busy}
|
| 236 |
+
value={orderDrafts[pid] ?? String(index + 1)}
|
| 237 |
+
aria-invalid={orderErrors[pid] ? true : undefined}
|
| 238 |
+
aria-describedby={orderErrors[pid] ? `cg-route-order-error-${pid}` : undefined}
|
| 239 |
+
onFocus={(event) => event.currentTarget.select()}
|
| 240 |
+
onChange={(event) => {
|
| 241 |
+
const raw = event.target.value;
|
| 242 |
+
setOrderDrafts((current) => ({ ...current, [pid]: raw }));
|
| 243 |
+
setOrderErrors((current) => {
|
| 244 |
+
const next = { ...current };
|
| 245 |
+
delete next[pid];
|
| 246 |
+
return next;
|
| 247 |
+
});
|
| 248 |
+
}}
|
| 249 |
+
onKeyDown={(event) => {
|
| 250 |
+
if (event.key === "Enter") {
|
| 251 |
+
event.preventDefault();
|
| 252 |
+
commitStopMove(route, pid, event.currentTarget.value);
|
| 253 |
+
} else if (event.key === "Escape") {
|
| 254 |
+
event.preventDefault();
|
| 255 |
+
setOrderDrafts((current) => {
|
| 256 |
+
const next = { ...current };
|
| 257 |
+
delete next[pid];
|
| 258 |
+
return next;
|
| 259 |
+
});
|
| 260 |
+
setOrderErrors((current) => {
|
| 261 |
+
const next = { ...current };
|
| 262 |
+
delete next[pid];
|
| 263 |
+
return next;
|
| 264 |
+
});
|
| 265 |
+
}
|
| 266 |
+
}} />
|
| 267 |
+
</label>
|
| 268 |
+
<button type="button" className="cg-w44-route-position-apply" disabled={busy}
|
| 269 |
+
onClick={() => commitStopMove(route, pid, orderDrafts[pid] ?? String(index + 1))}>
|
| 270 |
+
Move
|
| 271 |
+
</button>
|
| 272 |
+
<button type="button" className="cg-w44-route-step"
|
| 273 |
+
disabled={busy || index === route.visibleStopIds.length - 1}
|
| 274 |
+
aria-label={`Move stop ${index + 1} later`}
|
| 275 |
+
title="Move later" onClick={() => commitStopMove(route, pid, String(index + 2))}>
|
| 276 |
+
<svg viewBox="0 0 16 16" aria-hidden="true"><path d="m6 3 5 5-5 5" /></svg>
|
| 277 |
+
</button>
|
| 278 |
+
</span>
|
| 279 |
+
)}
|
| 280 |
+
{orderErrors[pid] && <span id={`cg-route-order-error-${pid}`}
|
| 281 |
+
className="cg-w44-route-order-error" role="alert">{orderErrors[pid]}</span>}
|
| 282 |
+
</li>
|
| 283 |
+
))}
|
| 284 |
+
</ol>
|
| 285 |
+
) : <p className="cg-w44-route-empty">No stops yet. Add customers from a route source.</p>}
|
| 286 |
+
{mapsUrl && <a className="cg-w44-route-maps" href={mapsUrl} target="_blank" rel="noopener noreferrer">Open Maps</a>}
|
| 287 |
+
{route.mapsUrl && !mapsUrl && <span className="cg-w44-route-empty">Maps link is unavailable.</span>}
|
| 288 |
+
<section className="cg-w44-route-map-links" aria-labelledby="cg-route-map-links-title">
|
| 289 |
+
<div>
|
| 290 |
+
<h3 id="cg-route-map-links-title">Google Maps</h3>
|
| 291 |
+
<p>Current ordered Route stops, split into links of at most 10 stops.</p>
|
| 292 |
+
</div>
|
| 293 |
+
{mapLinkRefusal ? (
|
| 294 |
+
<span className="cg-w44-route-warning" role="alert">{mapLinkRefusal}</span>
|
| 295 |
+
) : mapLinks.length ? <>
|
| 296 |
+
<ol>
|
| 297 |
+
{mapLinks.map((link) => (
|
| 298 |
+
<li key={`${link.index}:${link.start}:${link.end}`}>
|
| 299 |
+
<a href={link.url} target="_blank" rel="noopener noreferrer">
|
| 300 |
+
Link {link.index} - Stops {link.start + 1} to {link.end}
|
| 301 |
+
</a>
|
| 302 |
+
<small>{link.stopIds.length.toLocaleString()} stops</small>
|
| 303 |
+
</li>
|
| 304 |
+
))}
|
| 305 |
+
</ol>
|
| 306 |
+
<button type="button" className="cg-route-copy-links" onClick={copyMapLinks}>
|
| 307 |
+
Copy Maps links
|
| 308 |
+
</button>
|
| 309 |
+
</> : (
|
| 310 |
+
<span className="cg-w44-route-empty">Add at least two located stops to open this Route in Maps.</span>
|
| 311 |
+
)}
|
| 312 |
+
{mapCopyNotice && <span className="cg-w44-route-empty" role="status">{mapCopyNotice}</span>}
|
| 313 |
+
{mapCopyError && <span className="cg-w44-route-warning" role="alert">{mapCopyError}</span>}
|
| 314 |
+
</section>
|
| 315 |
+
{canEdit ? (
|
| 316 |
+
<div className="cg-w44-route-edit" aria-label="Edit Route">
|
| 317 |
+
<label className="cg-w44-route-label">Route name
|
| 318 |
+
<input className="cg-input" value={editName} maxLength={120} onChange={(event) => setEditName(event.target.value)} />
|
| 319 |
+
</label>
|
| 320 |
+
<label className="cg-w44-route-label">Google Maps URL
|
| 321 |
+
<input className="cg-input" type="url" value={editMapsUrl} maxLength={2048}
|
| 322 |
+
placeholder="https://www.google.com/maps/..." onChange={(event) => setEditMapsUrl(event.target.value)} />
|
| 323 |
+
</label>
|
| 324 |
+
<div className="cg-form-actions">
|
| 325 |
+
<button type="button" className="cg-btn cg-btn--primary" disabled={busy || !editName.trim()}
|
| 326 |
+
onClick={() => finish(onUpdate(route, { name: editName.trim(), mapsUrl: editMapsUrl.trim() }))}>
|
| 327 |
+
Save Route
|
| 328 |
+
</button>
|
| 329 |
+
<button type="button" className="cg-btn" disabled={busy} onClick={() => finish(onShare(route))}>Share</button>
|
| 330 |
+
<button type="button" className="cg-btn" disabled={busy} onClick={() => setDeleteConfirm(true)}>Delete Route</button>
|
| 331 |
+
</div>
|
| 332 |
+
{deleteConfirm && (
|
| 333 |
+
<div role="alertdialog" aria-label={`Delete ${route.name} Route`} aria-describedby="cg-route-delete-copy">
|
| 334 |
+
<p id="cg-route-delete-copy">Delete this Route and its saved stop order?</p>
|
| 335 |
+
<div className="cg-form-actions">
|
| 336 |
+
<button type="button" className="cg-btn cg-btn--danger" disabled={busy}
|
| 337 |
+
onClick={() => { setBusy(true); void onDelete(route).then((message) => {
|
| 338 |
+
setError(message); if (!message) onActiveRouteChange(null);
|
| 339 |
+
}).finally(() => setBusy(false)); }}>Confirm delete</button>
|
| 340 |
+
<button type="button" className="cg-btn" disabled={busy} onClick={() => setDeleteConfirm(false)}>Cancel</button>
|
| 341 |
+
</div>
|
| 342 |
+
</div>
|
| 343 |
+
)}
|
| 344 |
+
</div>
|
| 345 |
+
) : <p className="cg-w44-route-empty">{route.compatibility === "legacy-route-order"
|
| 346 |
+
? "This legacy Route is read-only." : "Only the owner and an editor of the source View can change this Route."}</p>}
|
| 347 |
+
{canEdit && (
|
| 348 |
+
<section className="cg-w44-route-delivery" aria-labelledby="cg-route-delivery-title">
|
| 349 |
+
<div>
|
| 350 |
+
<h3 id="cg-route-delivery-title">Daily delivery</h3>
|
| 351 |
+
<p>Freeze this Route now and send it to Inbox each day at 08:00 ({deliveryTimezone}).</p>
|
| 352 |
+
</div>
|
| 353 |
+
<label className="cg-w44-route-label">Inbox recipient
|
| 354 |
+
<input className="cg-input" value={deliveryRecipient} autoComplete="username"
|
| 355 |
+
placeholder="Account username" onChange={(event) => setDeliveryRecipient(event.target.value)} />
|
| 356 |
+
</label>
|
| 357 |
+
<label className="cg-w44-route-label">Stops per Maps link
|
| 358 |
+
<input className="cg-input" type="number" min={2} max={10} value={deliveryMapsPerLink}
|
| 359 |
+
onChange={(event) => setDeliveryMapsPerLink(
|
| 360 |
+
Math.max(2, Math.min(10, Number(event.target.value) || 2))
|
| 361 |
+
)} />
|
| 362 |
+
</label>
|
| 363 |
+
<button type="button" className="cg-btn cg-btn--primary"
|
| 364 |
+
disabled={deliveryBusy || route.visibleStopIds.length < 2 || !deliveryRecipient.trim()}
|
| 365 |
+
onClick={() => scheduleDelivery(route)}>
|
| 366 |
+
{deliveryBusy ? "Scheduling" : "Schedule delivery"}
|
| 367 |
+
</button>
|
| 368 |
+
{route.visibleStopIds.length < 2 && (
|
| 369 |
+
<span className="cg-w44-route-empty">Add at least two stops before scheduling.</span>
|
| 370 |
+
)}
|
| 371 |
+
<div className="cg-w44-route-delivery-list" aria-label="Existing Route deliveries">
|
| 372 |
+
{deliveries === null ? (
|
| 373 |
+
<span className="cg-w44-route-empty">Loading deliveries.</span>
|
| 374 |
+
) : deliveries.length === 0 ? (
|
| 375 |
+
<span className="cg-w44-route-empty">No deliveries scheduled.</span>
|
| 376 |
+
) : (
|
| 377 |
+
<ul>
|
| 378 |
+
{deliveries.map((delivery) => (
|
| 379 |
+
<li key={delivery.id}>
|
| 380 |
+
<div className="cg-w44-route-delivery-audit">
|
| 381 |
+
<strong>{delivery.name}</strong>
|
| 382 |
+
<dl>
|
| 383 |
+
<div><dt>Source View</dt><dd>{delivery.snapshot.sourceViewName} <code>{delivery.snapshot.sourceViewId}</code></dd></div>
|
| 384 |
+
<div><dt>Pinned revision</dt><dd><code>{delivery.snapshot.sourceViewRevision}</code></dd></div>
|
| 385 |
+
<div><dt>Schedule</dt><dd>{delivery.schedule.cron || "Not scheduled"} - {delivery.schedule.enabled === false ? "Paused" : "Active"}</dd></div>
|
| 386 |
+
<div><dt>Timezone</dt><dd>{delivery.snapshot.timezone}</dd></div>
|
| 387 |
+
<div><dt>Recipient</dt><dd>{delivery.recipient}</dd></div>
|
| 388 |
+
<div><dt>Ordered stop IDs</dt><dd><code>{delivery.snapshot.orderedStopIds.join(", ")}</code></dd></div>
|
| 389 |
+
<div><dt>Maps link cap</dt><dd>{delivery.snapshot.mapsPerLink} stops per link</dd></div>
|
| 390 |
+
</dl>
|
| 391 |
+
</div>
|
| 392 |
+
<button type="button" className="cg-btn" disabled={deliveryBusy}
|
| 393 |
+
aria-label={`Remove ${delivery.name}`} onClick={() => removeDelivery(route, delivery)}>
|
| 394 |
+
Remove
|
| 395 |
+
</button>
|
| 396 |
+
</li>
|
| 397 |
+
))}
|
| 398 |
+
</ul>
|
| 399 |
+
)}
|
| 400 |
+
</div>
|
| 401 |
+
{deliveryNotice && <span className="cg-w44-route-empty" role="status">{deliveryNotice}</span>}
|
| 402 |
+
{deliveryError && <span className="cg-w44-route-warning" role="alert">{deliveryError}</span>}
|
| 403 |
+
</section>
|
| 404 |
+
)}
|
| 405 |
+
{error && <span className="cg-w44-route-empty" role="status">{error}</span>}
|
| 406 |
+
</section>
|
| 407 |
+
);
|
| 408 |
+
}
|
| 409 |
+
|
| 410 |
+
if (creating) {
|
| 411 |
+
return (
|
| 412 |
+
<section className="cg-w44-route-nav" aria-label="Create route">
|
| 413 |
+
<button type="button" className="cg-w44-route-back" onClick={() => setCreating(false)}>Back to routes</button>
|
| 414 |
+
<label className="cg-w44-route-label">Route name
|
| 415 |
+
<input className="cg-input" value={name} maxLength={120} onChange={(event) => setName(event.target.value)} />
|
| 416 |
+
</label>
|
| 417 |
+
<fieldset className="cg-w44-route-sources"><legend>Route source</legend>
|
| 418 |
+
{sources.map((item) => <label key={item.id}><input type="radio" name="route-source"
|
| 419 |
+
checked={sourceId === item.id} onChange={() => setSourceId(item.id)} />
|
| 420 |
+
{item.label} ({item.pids.length.toLocaleString()})</label>)}
|
| 421 |
+
</fieldset>
|
| 422 |
+
<button type="button" className="cg-btn cg-btn--primary" disabled={busy || !name.trim() || !source || source.pids.length === 0}
|
| 423 |
+
onClick={() => { if (!source) return; setBusy(true); void onCreate(name.trim(), source).then((message) => {
|
| 424 |
+
setError(message); if (!message) { setName(""); setCreating(false); }
|
| 425 |
+
}).finally(() => setBusy(false)); }}>Create route</button>
|
| 426 |
+
{error && <span className="cg-w44-route-empty" role="status">{error}</span>}
|
| 427 |
+
</section>
|
| 428 |
+
);
|
| 429 |
+
}
|
| 430 |
|
| 431 |
+
const routeIds = level.leaves.map((item) => item.id);
|
| 432 |
+
const folderIds = level.folders.map((item) => item.id);
|
| 433 |
+
return (
|
| 434 |
+
<section className="cg-w44-route-nav" aria-label="Named routes">
|
| 435 |
+
<div className="cg-w44-route-head">
|
| 436 |
+
<div className="cg-w44-route-title">Routes</div>
|
| 437 |
+
<button type="button" className="cg-w44-route-detail" onClick={() => {
|
| 438 |
+
setError(null); onCreateStart(); setCreating(true);
|
| 439 |
+
}}>Create route</button>
|
| 440 |
+
</div>
|
| 441 |
+
<button type="button" className="cg-w44-route-filtered" disabled={filteredRecordCount === 0}
|
| 442 |
+
onClick={onSelectFiltered}>
|
| 443 |
+
Select all {filteredRecordCount.toLocaleString()} filtered records
|
| 444 |
+
</button>
|
| 445 |
+
<nav className="cg-w44-route-path" aria-label="Route folder path">
|
| 446 |
+
<button type="button" aria-current={!validAt ? "page" : undefined} onClick={() => navigate(null)}>Routes</button>
|
| 447 |
+
{crumbs.map((folder) => <span key={folder.id}><b aria-hidden="true">βΊ</b>
|
| 448 |
+
<button type="button" aria-current={validAt === folder.id ? "page" : undefined}
|
| 449 |
+
onClick={() => navigate(folder.id)}>{folder.name}</button></span>)}
|
| 450 |
+
</nav>
|
| 451 |
+
<div className="cg-w44-route-folder-tools">
|
| 452 |
+
{validAt && <button type="button" className="cg-w44-route-back" onClick={() => navigate(level.parent)}>Up</button>}
|
| 453 |
+
<button type="button" className="cg-w44-route-detail" onClick={() => setCreatingFolder((value) => !value)}>New folder</button>
|
| 454 |
+
</div>
|
| 455 |
+
{creatingFolder && <div className="cg-w44-route-folder-create">
|
| 456 |
+
<input className="cg-input" value={folderName} maxLength={80} aria-label="New Route folder name"
|
| 457 |
+
onChange={(event) => setFolderName(event.target.value)} />
|
| 458 |
+
<button type="button" className="cg-btn cg-btn--primary" disabled={busy || !folderName.trim()}
|
| 459 |
+
onClick={() => { setBusy(true); void onFolderCreate(folderName.trim(), validAt).then((message) => {
|
| 460 |
+
setError(message); if (!message) { setFolderName(""); setCreatingFolder(false); }
|
| 461 |
+
}).finally(() => setBusy(false)); }}>Create</button>
|
| 462 |
+
</div>}
|
| 463 |
+
<div className="cg-w44-route-level" aria-label={level.folder ? `${level.folder.name} contents` : "Route folder contents"}>
|
| 464 |
+
{level.folders.map((folder, index) => (
|
| 465 |
+
<div key={folder.id} className="cg-w44-route-folder-row">
|
| 466 |
+
{renameId === `folder:${folder.id}` ? <>
|
| 467 |
+
<input className="cg-input" value={renameDraft} maxLength={80} aria-label={`Rename ${folder.name}`}
|
| 468 |
+
onChange={(event) => setRenameDraft(event.target.value)} />
|
| 469 |
+
<button type="button" disabled={!renameDraft.trim() || busy}
|
| 470 |
+
onClick={() => { setBusy(true); void onFolderUpdate(folder, { name: renameDraft.trim() }).then((message) => {
|
| 471 |
+
setError(message); if (!message) setRenameId(null);
|
| 472 |
+
}).finally(() => setBusy(false)); }}>Save</button>
|
| 473 |
+
</> : <button type="button" className="cg-w44-route-folder-open" onClick={() => navigate(folder.id)}>
|
| 474 |
+
<span className="cg-w44-route-folder-mark" aria-hidden="true" />{folder.name}
|
| 475 |
+
</button>}
|
| 476 |
+
<button type="button" className="cg-w44-route-more" aria-label={`Actions for ${folder.name}`}
|
| 477 |
+
aria-expanded={menuId === `folder:${folder.id}`}
|
| 478 |
+
onClick={() => setMenuId(menuId === `folder:${folder.id}` ? null : `folder:${folder.id}`)}>...</button>
|
| 479 |
+
{menuId === `folder:${folder.id}` && <div className="cg-w44-route-menu" role="menu">
|
| 480 |
+
<button type="button" role="menuitem"
|
| 481 |
+
onClick={() => { setRenameId(`folder:${folder.id}`); setRenameDraft(folder.name); setMenuId(null); }}>Rename</button>
|
| 482 |
+
<button type="button" role="menuitem" disabled={index === 0 || busy}
|
| 483 |
+
onClick={() => { const next = swap(folderIds, folder.id, -1); if (next) finish(onFolderReorder(next)); }}>Move up</button>
|
| 484 |
+
<button type="button" role="menuitem" disabled={index === folderIds.length - 1 || busy}
|
| 485 |
+
onClick={() => { const next = swap(folderIds, folder.id, 1); if (next) finish(onFolderReorder(next)); }}>Move down</button>
|
| 486 |
+
{folder.parent && <button type="button" role="menuitem"
|
| 487 |
+
onClick={() => { setMenuId(null); finish(onFolderUpdate(folder, { parent: level.parent })); }}>Move out one level</button>}
|
| 488 |
+
{folders.filter((target) => target.id !== folder.id).map((target) =>
|
| 489 |
+
<button type="button" role="menuitem" key={target.id}
|
| 490 |
+
onClick={() => { setMenuId(null); finish(onFolderUpdate(folder, { parent: target.id })); }}>
|
| 491 |
+
Move into {target.name}
|
| 492 |
+
</button>)}
|
| 493 |
+
<button type="button" role="menuitem"
|
| 494 |
+
onClick={() => { setMenuId(null); if (window.confirm(`Delete ${folder.name}? Its contents move to Routes.`)) finish(onFolderDelete(folder)); }}>Delete</button>
|
| 495 |
+
</div>}
|
| 496 |
+
</div>
|
| 497 |
+
))}
|
| 498 |
+
{level.leaves.map((item, index) => (
|
| 499 |
+
<div key={item.id} className={`cg-w44-route-row${item.outsideFilter ? " is-outside" : ""}`}>
|
| 500 |
+
<button type="button" className="cg-w44-route-toggle" aria-pressed={selectedIds.has(item.id)}
|
| 501 |
+
aria-label={`${selectedIds.has(item.id) ? "Remove" : "Include"} ${item.name}`}
|
| 502 |
+
onClick={() => onToggle(item)}><i style={{ backgroundColor: item.color }} aria-hidden="true" /></button>
|
| 503 |
+
{renameId === item.id ? <>
|
| 504 |
+
<input className="cg-input" value={renameDraft} maxLength={120} aria-label={`Rename ${item.name}`}
|
| 505 |
+
onChange={(event) => setRenameDraft(event.target.value)} />
|
| 506 |
+
<button type="button" disabled={!renameDraft.trim() || busy}
|
| 507 |
+
onClick={() => { setBusy(true); void onUpdate(item, { name: renameDraft.trim(), mapsUrl: item.mapsUrl }).then((message) => {
|
| 508 |
+
setError(message); if (!message) setRenameId(null);
|
| 509 |
+
}).finally(() => setBusy(false)); }}>Save</button>
|
| 510 |
+
</> : <button type="button" className="cg-w44-route-open" onClick={() => {
|
| 511 |
+
setError(null); setCreating(false); onActiveRouteChange(item.id);
|
| 512 |
+
}}>{item.number}. {item.name}</button>}
|
| 513 |
+
{(item.shared || item.sharedOut) && <span className="cg-w44-route-share-mark">
|
| 514 |
+
{item.shared ? `Shared by ${item.owner || "another user"}` : "Shared"}
|
| 515 |
+
</span>}
|
| 516 |
+
{item.outsideFilter && <span className="cg-w44-route-outside">Outside filter</span>}
|
| 517 |
+
<button type="button" className="cg-w44-route-more" aria-label={`Actions for ${item.name}`}
|
| 518 |
+
aria-expanded={menuId === item.id} onClick={() => setMenuId(menuId === item.id ? null : item.id)}>...</button>
|
| 519 |
+
{menuId === item.id && <div className="cg-w44-route-menu" role="menu">
|
| 520 |
+
<button type="button" role="menuitem" disabled={!item.permission.canEdit}
|
| 521 |
+
onClick={() => { setRenameId(item.id); setRenameDraft(item.name); setMenuId(null); }}>Rename</button>
|
| 522 |
+
<button type="button" role="menuitem" onClick={() => { setMenuId(null); finish(onDuplicate(item)); }}>Duplicate</button>
|
| 523 |
+
<button type="button" role="menuitem" disabled={!item.permission.canEdit}
|
| 524 |
+
onClick={() => { setMenuId(null); finish(onShare(item)); }}>Share</button>
|
| 525 |
+
{folders.map((folder) => <button type="button" role="menuitem" key={folder.id}
|
| 526 |
+
onClick={() => { setMenuId(null); finish(onRouteMove(item, folder.id)); }}>Move to {folder.name}</button>)}
|
| 527 |
+
{item.folderId && <button type="button" role="menuitem"
|
| 528 |
+
onClick={() => { setMenuId(null); finish(onRouteMove(item, null)); }}>Move to Routes</button>}
|
| 529 |
+
<button type="button" role="menuitem" disabled={index === 0 || busy}
|
| 530 |
+
onClick={() => { const next = swap(routeIds, item.id, -1); if (next) finish(onRouteReorder(next)); }}>Move up</button>
|
| 531 |
+
<button type="button" role="menuitem" disabled={index === routeIds.length - 1 || busy}
|
| 532 |
+
onClick={() => { const next = swap(routeIds, item.id, 1); if (next) finish(onRouteReorder(next)); }}>Move down</button>
|
| 533 |
+
<button type="button" role="menuitem" disabled={!item.permission.canEdit}
|
| 534 |
+
onClick={() => { setMenuId(null); if (window.confirm(`Delete ${item.name}?`)) finish(onDelete(item)); }}>Delete</button>
|
| 535 |
+
</div>}
|
| 536 |
+
</div>
|
| 537 |
+
))}
|
| 538 |
+
{!level.folders.length && !level.leaves.length && <p className="cg-w44-route-empty">
|
| 539 |
+
{folders.length || routes.length ? "This folder is empty." : "No routes yet. Create one from selected Zones or records."}
|
| 540 |
+
</p>}
|
| 541 |
+
</div>
|
| 542 |
+
{createdRoute && <div className="cg-w44-route-created" role="dialog" aria-label="Route privacy choice">
|
| 543 |
+
<p><strong>{createdRoute.name}</strong> was created. Keep it private or share it now?</p>
|
| 544 |
+
<div className="cg-form-actions">
|
| 545 |
+
<button type="button" className="cg-btn cg-btn--primary" disabled={busy}
|
| 546 |
+
onClick={() => { setBusy(true); void onShare(createdRoute).then((message) => {
|
| 547 |
+
setError(message); if (!message) onCreatedDismiss();
|
| 548 |
+
}).finally(() => setBusy(false)); }}>Share route</button>
|
| 549 |
+
<button type="button" className="cg-btn" disabled={busy} onClick={onCreatedDismiss}>Keep private</button>
|
| 550 |
+
</div>
|
| 551 |
+
</div>}
|
| 552 |
+
{error && <span className="cg-w44-route-empty" role="status">{error}</span>}
|
| 553 |
+
</section>
|
| 554 |
+
);
|
| 555 |
}
|
web/src/customer-grid/ScriptViewPanel.tsx
CHANGED
|
@@ -13,6 +13,7 @@
|
|
| 13 |
// ---------------------------------------------------------------------------
|
| 14 |
|
| 15 |
import { memo, useEffect, useRef, useState } from "react";
|
|
|
|
| 16 |
import { barScale, renderableSpec, specKindName } from "./scriptViews";
|
| 17 |
import type { DrawableSpec, ScriptRun, ScriptView as ScriptViewRecord } from "./scriptViews";
|
| 18 |
|
|
@@ -225,14 +226,14 @@ export const ScriptView = memo(function ScriptView({
|
|
| 225 |
// product a QA pass one wave ago [[a-store-outage-renames-itself-at-every-layer]].
|
| 226 |
if (view === null)
|
| 227 |
return (
|
| 228 |
-
<div className="cg-script">
|
| 229 |
<p className="cg-script-empty cg-script-empty--pad">
|
| 230 |
{loading === true ? "Opening this view." : "This script view could not be opened."}
|
| 231 |
</p>
|
| 232 |
</div>
|
| 233 |
);
|
| 234 |
return (
|
| 235 |
-
<div className="cg-script">
|
| 236 |
<div className="cg-script-body">
|
| 237 |
<section className="cg-script-pane" aria-label="Script source">
|
| 238 |
<div className="cg-script-pane-head">
|
|
|
|
| 13 |
// ---------------------------------------------------------------------------
|
| 14 |
|
| 15 |
import { memo, useEffect, useRef, useState } from "react";
|
| 16 |
+
import { foldNavOnWorkSurface } from "./navFold";
|
| 17 |
import { barScale, renderableSpec, specKindName } from "./scriptViews";
|
| 18 |
import type { DrawableSpec, ScriptRun, ScriptView as ScriptViewRecord } from "./scriptViews";
|
| 19 |
|
|
|
|
| 226 |
// product a QA pass one wave ago [[a-store-outage-renames-itself-at-every-layer]].
|
| 227 |
if (view === null)
|
| 228 |
return (
|
| 229 |
+
<div className="cg-script" onPointerDown={foldNavOnWorkSurface}>
|
| 230 |
<p className="cg-script-empty cg-script-empty--pad">
|
| 231 |
{loading === true ? "Opening this view." : "This script view could not be opened."}
|
| 232 |
</p>
|
| 233 |
</div>
|
| 234 |
);
|
| 235 |
return (
|
| 236 |
+
<div className="cg-script" onPointerDown={foldNavOnWorkSurface}>
|
| 237 |
<div className="cg-script-body">
|
| 238 |
<section className="cg-script-pane" aria-label="Script source">
|
| 239 |
<div className="cg-script-pane-head">
|
web/src/customer-grid/TimeSeriesPanel.tsx
CHANGED
|
@@ -32,6 +32,7 @@ import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
|
| 32 |
import { fetchTimeseries } from "./apiBridge";
|
| 33 |
import type { SurfaceScope } from "./apiBridge";
|
| 34 |
import { isStreamlitComponent } from "./hostBridge";
|
|
|
|
| 35 |
import {
|
| 36 |
DEFAULT_TS_BUCKET,
|
| 37 |
DEFAULT_TS_LAST_N,
|
|
@@ -367,7 +368,7 @@ export default function TimeSeriesPanel({
|
|
| 367 |
// component β the grid still runs inside app.py and a throw here would take the page.
|
| 368 |
if (embedded) {
|
| 369 |
return (
|
| 370 |
-
<div className="cg-mode-empty">
|
| 371 |
The time-series view runs in the web app. Open Loopable in a browser tab to see it.
|
| 372 |
</div>
|
| 373 |
);
|
|
@@ -375,7 +376,7 @@ export default function TimeSeriesPanel({
|
|
| 375 |
|
| 376 |
if (!eligible.length) {
|
| 377 |
return (
|
| 378 |
-
<div className="cg-mode-empty">
|
| 379 |
This table has no number fields to plot. A time series needs either a metric with a
|
| 380 |
period, or a numeric column to snapshot β add one from a column menu, then pick it here.
|
| 381 |
</div>
|
|
@@ -392,7 +393,7 @@ export default function TimeSeriesPanel({
|
|
| 392 |
snapshotSelected.length > 0 && sheet.columns.length === 0 && state !== "loading";
|
| 393 |
|
| 394 |
return (
|
| 395 |
-
<div className="cg-ts">
|
| 396 |
<div className="cg-ts-bar">
|
| 397 |
<label className="cg-ts-ctl">
|
| 398 |
<span className="cg-ts-ctl-k">Period</span>
|
|
|
|
| 32 |
import { fetchTimeseries } from "./apiBridge";
|
| 33 |
import type { SurfaceScope } from "./apiBridge";
|
| 34 |
import { isStreamlitComponent } from "./hostBridge";
|
| 35 |
+
import { foldNavOnWorkSurface } from "./navFold";
|
| 36 |
import {
|
| 37 |
DEFAULT_TS_BUCKET,
|
| 38 |
DEFAULT_TS_LAST_N,
|
|
|
|
| 368 |
// component β the grid still runs inside app.py and a throw here would take the page.
|
| 369 |
if (embedded) {
|
| 370 |
return (
|
| 371 |
+
<div className="cg-mode-empty" onPointerDown={foldNavOnWorkSurface}>
|
| 372 |
The time-series view runs in the web app. Open Loopable in a browser tab to see it.
|
| 373 |
</div>
|
| 374 |
);
|
|
|
|
| 376 |
|
| 377 |
if (!eligible.length) {
|
| 378 |
return (
|
| 379 |
+
<div className="cg-mode-empty" onPointerDown={foldNavOnWorkSurface}>
|
| 380 |
This table has no number fields to plot. A time series needs either a metric with a
|
| 381 |
period, or a numeric column to snapshot β add one from a column menu, then pick it here.
|
| 382 |
</div>
|
|
|
|
| 393 |
snapshotSelected.length > 0 && sheet.columns.length === 0 && state !== "loading";
|
| 394 |
|
| 395 |
return (
|
| 396 |
+
<div className="cg-ts" onPointerDown={foldNavOnWorkSurface}>
|
| 397 |
<div className="cg-ts-bar">
|
| 398 |
<label className="cg-ts-ctl">
|
| 399 |
<span className="cg-ts-ctl-k">Period</span>
|
web/src/customer-grid/Toolbar.tsx
CHANGED
|
@@ -27,6 +27,7 @@ import type {
|
|
| 27 |
ScopeCounts,
|
| 28 |
SortRule,
|
| 29 |
SortSpec,
|
|
|
|
| 30 |
ViewConfig,
|
| 31 |
} from "./types";
|
| 32 |
import { viewDisplayMode } from "./types";
|
|
@@ -35,7 +36,8 @@ import { viewDisplayMode } from "./types";
|
|
| 35 |
import { PIVOT_WINDOWS, PIVOT_WINDOW_LABELS } from "./types";
|
| 36 |
import { COPY_PARTS, COPY_PART_KEYS, copyViewConfig } from "./copyConfig";
|
| 37 |
import type { CopyPart } from "./copyConfig";
|
| 38 |
-
import { directionLabel, filterTreeConj, filterTreeNodes, isFilterGroup, isGroupableField
|
|
|
|
| 39 |
from "./types";
|
| 40 |
import type { WindowSpec } from "./windows";
|
| 41 |
import { AnchoredOverlay } from "./OverlaySurface";
|
|
@@ -52,8 +54,10 @@ import { FilterBuilderPanel, FieldsHidePanel, Popover } from "../filter-kit";
|
|
| 52 |
import { MEASURE_OP_LIST, countConditions, newRuleId, opsForType } from "../filter-kit/ops";
|
| 53 |
import "./filters.css";
|
| 54 |
|
| 55 |
-
|
| 56 |
fields: Field[];
|
|
|
|
|
|
|
| 57 |
visible: Set<string>;
|
| 58 |
/** Wave 16 C-TOPIC β the plural noun for what a row IS ("customers" / "products"). Only
|
| 59 |
* copy that NAMES the row uses it; structural words ("record", "view") stay shared. */
|
|
@@ -74,6 +78,12 @@ export interface ToolbarProps {
|
|
| 74 |
onDeleteField?: (key: string) => void;
|
| 75 |
/** The Hide fields edit icon reuses ColumnMenu's existing normal field editor. */
|
| 76 |
onEditField?: (key: string, anchor: DOMRect) => void;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 77 |
|
| 78 |
/**
|
| 79 |
* ββ W38-T07 (owner instruction 12) β THE ONE COLOUR CONTROL, and it names a FIELD rather than
|
|
@@ -256,6 +266,22 @@ export interface ToolbarProps {
|
|
| 256 |
onFullscreen?: () => void;
|
| 257 |
}
|
| 258 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 259 |
// --- tiny inline icons (14px, stroke = currentColor) -----------------------
|
| 260 |
const ic = { width: 14, height: 14, viewBox: "0 0 16 16", fill: "none" } as const;
|
| 261 |
const stroke = {
|
|
@@ -319,6 +345,13 @@ function IconEdit() {
|
|
| 319 |
}
|
| 320 |
// W41-T42 β two nodes and the edge between them, at the same 14px/1.5 stroke weight every other
|
| 321 |
// button in this strip wears. The relation is the LINE, which is the whole idea of the control.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 322 |
function IconRelational() {
|
| 323 |
return (
|
| 324 |
<svg {...ic} aria-hidden>
|
|
@@ -557,12 +590,13 @@ function SortBuilder({
|
|
| 557 |
sorts: SortSpec;
|
| 558 |
onSorts: (s: SortSpec) => void;
|
| 559 |
}) {
|
|
|
|
| 560 |
const update = (i: number, patch: Partial<SortRule>) =>
|
| 561 |
onSorts(sorts.map((s, j) => (j === i ? { ...s, ...patch } : s)));
|
| 562 |
const remove = (i: number) => onSorts(sorts.filter((_, j) => j !== i));
|
| 563 |
const add = () => {
|
| 564 |
const used = new Set(sorts.map((s) => s.colId));
|
| 565 |
-
const f =
|
| 566 |
if (!f) return;
|
| 567 |
onSorts([...sorts, { colId: f.key, dir: "asc" }]);
|
| 568 |
};
|
|
@@ -590,7 +624,7 @@ function SortBuilder({
|
|
| 590 |
ariaLabel="Sort field"
|
| 591 |
value={rule.colId}
|
| 592 |
onChange={(key) => update(i, { colId: key })}
|
| 593 |
-
fields={
|
| 594 |
key: fl.key, label: fl.label, type: fl.type,
|
| 595 |
}))}
|
| 596 |
/>
|
|
@@ -667,6 +701,7 @@ const ROW_OPTIONS: { mode: RowHeightMode; label: string }[] = [
|
|
| 667 |
|
| 668 |
export default function Toolbar({
|
| 669 |
fields,
|
|
|
|
| 670 |
visible,
|
| 671 |
nouns = "customers",
|
| 672 |
lockedKey,
|
|
@@ -677,6 +712,12 @@ export default function Toolbar({
|
|
| 677 |
deletableKeys,
|
| 678 |
onDeleteField,
|
| 679 |
onEditField,
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 680 |
colorField,
|
| 681 |
colorChoices,
|
| 682 |
onColorField,
|
|
@@ -724,6 +765,7 @@ export default function Toolbar({
|
|
| 724 |
onFullscreen,
|
| 725 |
}: ToolbarProps) {
|
| 726 |
const shownCount = fields.filter((f) => visible.has(f.key)).length;
|
|
|
|
| 727 |
|
| 728 |
const fieldByKey = useMemo(() => {
|
| 729 |
const m = new Map<string, Field>();
|
|
@@ -814,7 +856,7 @@ export default function Toolbar({
|
|
| 814 |
return;
|
| 815 |
}
|
| 816 |
const f = filterSeed.key ? fieldByKey.get(filterSeed.key) : undefined;
|
| 817 |
-
if (!f || f.filterable === false) return;
|
| 818 |
onFilters([...filters, { colId: f.key, op: opsForType(f.type)[0], value: "" }]);
|
| 819 |
}, [filterSeed, fieldByKey, measureByKey, filters, onFilters]);
|
| 820 |
|
|
@@ -847,7 +889,7 @@ export default function Toolbar({
|
|
| 847 |
: "Color";
|
| 848 |
// W41-T42 β the same idiom `colorLabel` and `groupLabel` already use: a control that HAS a
|
| 849 |
// current answer names it on the trigger, so the reader does not have to open it to find out.
|
| 850 |
-
const relationalLabel = relational ? `
|
| 851 |
|
| 852 |
/**
|
| 853 |
* R11's greying, as one attribute. `inert` is not in React 18's JSX typings (it landed with
|
|
@@ -890,6 +932,17 @@ export default function Toolbar({
|
|
| 890 |
deletableKeys={deletableKeys}
|
| 891 |
onDeleteField={onDeleteField}
|
| 892 |
onEditField={onEditField}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 893 |
/>
|
| 894 |
)}
|
| 895 |
</Popover>
|
|
@@ -1176,11 +1229,14 @@ export default function Toolbar({
|
|
| 1176 |
{onFullscreen && (
|
| 1177 |
<button
|
| 1178 |
type="button"
|
| 1179 |
-
className="cg-tb-btn cg-fullscreen-toggle"
|
| 1180 |
aria-pressed={fullscreen}
|
|
|
|
|
|
|
| 1181 |
onClick={onFullscreen}
|
| 1182 |
>
|
| 1183 |
-
|
|
|
|
| 1184 |
</button>
|
| 1185 |
)}
|
| 1186 |
|
|
|
|
| 27 |
ScopeCounts,
|
| 28 |
SortRule,
|
| 29 |
SortSpec,
|
| 30 |
+
Viewer,
|
| 31 |
ViewConfig,
|
| 32 |
} from "./types";
|
| 33 |
import { viewDisplayMode } from "./types";
|
|
|
|
| 36 |
import { PIVOT_WINDOWS, PIVOT_WINDOW_LABELS } from "./types";
|
| 37 |
import { COPY_PARTS, COPY_PART_KEYS, copyViewConfig } from "./copyConfig";
|
| 38 |
import type { CopyPart } from "./copyConfig";
|
| 39 |
+
import { directionLabel, filterTreeConj, filterTreeNodes, isFilterGroup, isGroupableField,
|
| 40 |
+
isOfferableField, offerableFields }
|
| 41 |
from "./types";
|
| 42 |
import type { WindowSpec } from "./windows";
|
| 43 |
import { AnchoredOverlay } from "./OverlaySurface";
|
|
|
|
| 54 |
import { MEASURE_OP_LIST, countConditions, newRuleId, opsForType } from "../filter-kit/ops";
|
| 55 |
import "./filters.css";
|
| 56 |
|
| 57 |
+
interface ToolbarBaseProps {
|
| 58 |
fields: Field[];
|
| 59 |
+
/** Identity used only to classify shared fields into ownership sections. */
|
| 60 |
+
viewer?: Viewer;
|
| 61 |
visible: Set<string>;
|
| 62 |
/** Wave 16 C-TOPIC β the plural noun for what a row IS ("customers" / "products"). Only
|
| 63 |
* copy that NAMES the row uses it; structural words ("record", "view") stay shared. */
|
|
|
|
| 78 |
onDeleteField?: (key: string) => void;
|
| 79 |
/** The Hide fields edit icon reuses ColumnMenu's existing normal field editor. */
|
| 80 |
onEditField?: (key: string, anchor: DOMRect) => void;
|
| 81 |
+
onSetFieldsHidden?: ((keys: string[], hidden: boolean) => void) | null;
|
| 82 |
+
onShareFields?: ((keys: string[]) => void) | null;
|
| 83 |
+
onReassignFields?: ((keys: string[]) => void) | null;
|
| 84 |
+
onDeleteFields?: ((keys: string[]) => void) | null;
|
| 85 |
+
onRemoveField?: ((key: string) => void) | null;
|
| 86 |
+
manager?: boolean;
|
| 87 |
|
| 88 |
/**
|
| 89 |
* ββ W38-T07 (owner instruction 12) β THE ONE COLOUR CONTROL, and it names a FIELD rather than
|
|
|
|
| 266 |
onFullscreen?: () => void;
|
| 267 |
}
|
| 268 |
|
| 269 |
+
export interface ToolbarManagerProps extends ToolbarBaseProps {
|
| 270 |
+
manager: true;
|
| 271 |
+
viewer: Viewer | undefined;
|
| 272 |
+
onSetFieldsHidden: ((keys: string[], hidden: boolean) => void) | null;
|
| 273 |
+
onShareFields: ((keys: string[]) => void) | null;
|
| 274 |
+
onReassignFields: ((keys: string[]) => void) | null;
|
| 275 |
+
onDeleteFields: ((keys: string[]) => void) | null;
|
| 276 |
+
onRemoveField: ((key: string) => void) | null;
|
| 277 |
+
}
|
| 278 |
+
|
| 279 |
+
export interface ToolbarPlainProps extends ToolbarBaseProps {
|
| 280 |
+
manager?: false;
|
| 281 |
+
}
|
| 282 |
+
|
| 283 |
+
export type ToolbarProps = ToolbarManagerProps | ToolbarPlainProps;
|
| 284 |
+
|
| 285 |
// --- tiny inline icons (14px, stroke = currentColor) -----------------------
|
| 286 |
const ic = { width: 14, height: 14, viewBox: "0 0 16 16", fill: "none" } as const;
|
| 287 |
const stroke = {
|
|
|
|
| 345 |
}
|
| 346 |
// W41-T42 β two nodes and the edge between them, at the same 14px/1.5 stroke weight every other
|
| 347 |
// button in this strip wears. The relation is the LINE, which is the whole idea of the control.
|
| 348 |
+
function IconFullScreen() {
|
| 349 |
+
return (
|
| 350 |
+
<svg {...ic} aria-hidden>
|
| 351 |
+
<path d="M2.5 6V2.5H6M10 2.5h3.5V6M13.5 10v3.5H10M6 13.5H2.5V10" {...stroke} />
|
| 352 |
+
</svg>
|
| 353 |
+
);
|
| 354 |
+
}
|
| 355 |
function IconRelational() {
|
| 356 |
return (
|
| 357 |
<svg {...ic} aria-hidden>
|
|
|
|
| 590 |
sorts: SortSpec;
|
| 591 |
onSorts: (s: SortSpec) => void;
|
| 592 |
}) {
|
| 593 |
+
const offered = useMemo(() => offerableFields(fields), [fields]);
|
| 594 |
const update = (i: number, patch: Partial<SortRule>) =>
|
| 595 |
onSorts(sorts.map((s, j) => (j === i ? { ...s, ...patch } : s)));
|
| 596 |
const remove = (i: number) => onSorts(sorts.filter((_, j) => j !== i));
|
| 597 |
const add = () => {
|
| 598 |
const used = new Set(sorts.map((s) => s.colId));
|
| 599 |
+
const f = offered.find((fl) => !used.has(fl.key)) ?? offered[0];
|
| 600 |
if (!f) return;
|
| 601 |
onSorts([...sorts, { colId: f.key, dir: "asc" }]);
|
| 602 |
};
|
|
|
|
| 624 |
ariaLabel="Sort field"
|
| 625 |
value={rule.colId}
|
| 626 |
onChange={(key) => update(i, { colId: key })}
|
| 627 |
+
fields={offered.map((fl) => ({
|
| 628 |
key: fl.key, label: fl.label, type: fl.type,
|
| 629 |
}))}
|
| 630 |
/>
|
|
|
|
| 701 |
|
| 702 |
export default function Toolbar({
|
| 703 |
fields,
|
| 704 |
+
viewer,
|
| 705 |
visible,
|
| 706 |
nouns = "customers",
|
| 707 |
lockedKey,
|
|
|
|
| 712 |
deletableKeys,
|
| 713 |
onDeleteField,
|
| 714 |
onEditField,
|
| 715 |
+
manager = false,
|
| 716 |
+
onSetFieldsHidden,
|
| 717 |
+
onShareFields,
|
| 718 |
+
onReassignFields,
|
| 719 |
+
onDeleteFields,
|
| 720 |
+
onRemoveField,
|
| 721 |
colorField,
|
| 722 |
colorChoices,
|
| 723 |
onColorField,
|
|
|
|
| 765 |
onFullscreen,
|
| 766 |
}: ToolbarProps) {
|
| 767 |
const shownCount = fields.filter((f) => visible.has(f.key)).length;
|
| 768 |
+
const fullscreenLabel = fullscreen ? "Exit full screen" : "Full screen";
|
| 769 |
|
| 770 |
const fieldByKey = useMemo(() => {
|
| 771 |
const m = new Map<string, Field>();
|
|
|
|
| 856 |
return;
|
| 857 |
}
|
| 858 |
const f = filterSeed.key ? fieldByKey.get(filterSeed.key) : undefined;
|
| 859 |
+
if (!f || !isOfferableField(f) || f.filterable === false) return;
|
| 860 |
onFilters([...filters, { colId: f.key, op: opsForType(f.type)[0], value: "" }]);
|
| 861 |
}, [filterSeed, fieldByKey, measureByKey, filters, onFilters]);
|
| 862 |
|
|
|
|
| 889 |
: "Color";
|
| 890 |
// W41-T42 β the same idiom `colorLabel` and `groupLabel` already use: a control that HAS a
|
| 891 |
// current answer names it on the trigger, so the reader does not have to open it to find out.
|
| 892 |
+
const relationalLabel = relational ? `Related: ${relational.label}` : "Related";
|
| 893 |
|
| 894 |
/**
|
| 895 |
* R11's greying, as one attribute. `inert` is not in React 18's JSX typings (it landed with
|
|
|
|
| 932 |
deletableKeys={deletableKeys}
|
| 933 |
onDeleteField={onDeleteField}
|
| 934 |
onEditField={onEditField}
|
| 935 |
+
viewer={viewer}
|
| 936 |
+
{...(manager
|
| 937 |
+
? {
|
| 938 |
+
manager: true as const,
|
| 939 |
+
onSetFieldsHidden: onSetFieldsHidden ?? null,
|
| 940 |
+
onShareFields: onShareFields ?? null,
|
| 941 |
+
onReassignFields: onReassignFields ?? null,
|
| 942 |
+
onDeleteFields: onDeleteFields ?? null,
|
| 943 |
+
onRemoveField: onRemoveField ?? null,
|
| 944 |
+
}
|
| 945 |
+
: { manager: false as const })}
|
| 946 |
/>
|
| 947 |
)}
|
| 948 |
</Popover>
|
|
|
|
| 1229 |
{onFullscreen && (
|
| 1230 |
<button
|
| 1231 |
type="button"
|
| 1232 |
+
className={"cg-tb-btn cg-fullscreen-toggle" + (fullscreen ? " is-active" : "")}
|
| 1233 |
aria-pressed={fullscreen}
|
| 1234 |
+
aria-label={fullscreenLabel}
|
| 1235 |
+
title={fullscreenLabel}
|
| 1236 |
onClick={onFullscreen}
|
| 1237 |
>
|
| 1238 |
+
<IconFullScreen />
|
| 1239 |
+
<span className="cg-tb-label">{fullscreenLabel}</span>
|
| 1240 |
</button>
|
| 1241 |
)}
|
| 1242 |
|
web/src/customer-grid/ViewSidebar.tsx
CHANGED
|
@@ -1,4 +1,4 @@
|
|
| 1 |
-
import { useEffect, useMemo, useState } from "react";
|
| 2 |
import type { ReactNode } from "react";
|
| 3 |
import type { KeyboardEvent as ReactKeyboardEvent } from "react";
|
| 4 |
import { AnchoredOverlay } from "./OverlaySurface";
|
|
@@ -44,6 +44,14 @@ import { FolderMark, LockMark, MenuLabel, ModeIcon, ToneModeIcon } from "./icons
|
|
| 44 |
*/
|
| 45 |
import { WORKSPACE_STALE_EVENT, signal } from "../apiContract";
|
| 46 |
import { ROOT_FOLDER_ID } from "./folders";
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 47 |
// β W32-T23 (owner item 17) β THE BELL, from the shared layer rather than redrawn here.
|
| 48 |
// The alert row wore `cohortAdd` (a LIST with a plus), which names "add to a cohort" on the
|
| 49 |
// one row that creates an ALERT β a borrowed mark is a small lie a menu repeats every time
|
|
@@ -56,7 +64,6 @@ import { BellIcon, StarIcon } from "../ui/icons";
|
|
| 56 |
// `isSyntheticFolderId`, and `noUnusedLocals` turns a leftover import into a build error rather
|
| 57 |
// than into dead weight. The constant itself is still exported and still used by `folders.ts`.
|
| 58 |
import {
|
| 59 |
-
folderHiddenByCollapse,
|
| 60 |
folderNesting,
|
| 61 |
groupByFolder,
|
| 62 |
isSyntheticFolderId,
|
|
@@ -222,6 +229,16 @@ export function viewShareMark(
|
|
| 222 |
}
|
| 223 |
|
| 224 |
interface ViewSidebarProps {
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 225 |
views: SavedView[];
|
| 226 |
activeViewId: string;
|
| 227 |
saveState: "saved" | "saving";
|
|
@@ -450,6 +467,437 @@ interface ViewSidebarProps {
|
|
| 450 |
onToggleChat?: () => void;
|
| 451 |
}
|
| 452 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 453 |
/**
|
| 454 |
* β WAVE 41 Β· T35 (owner instruction 11) β THE FOLDER ICON PICKER: ONE COPY, TWO DOORS.
|
| 455 |
*
|
|
@@ -553,7 +1001,35 @@ function FolderIconPicker({
|
|
| 553 |
);
|
| 554 |
}
|
| 555 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 556 |
export default function ViewSidebar({
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 557 |
agentPanel = null,
|
| 558 |
agentOpen = false,
|
| 559 |
onToggleAgent,
|
|
@@ -578,7 +1054,7 @@ export default function ViewSidebar({
|
|
| 578 |
onExport,
|
| 579 |
onExportXlsxViews,
|
| 580 |
exportableViewIds,
|
| 581 |
-
folders,
|
| 582 |
folderIdOf,
|
| 583 |
onFolderCreate,
|
| 584 |
onFolderRename,
|
|
@@ -598,6 +1074,15 @@ export default function ViewSidebar({
|
|
| 598 |
actionAnchor,
|
| 599 |
onActionAnchorConsumed,
|
| 600 |
}: ViewSidebarProps) {
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 601 |
/**
|
| 602 |
* I14 β creating a view now always knows WHICH KIND of view is being created, because the
|
| 603 |
* flyout is the only door in. `null` = not creating; a mode = the name step for that mode.
|
|
@@ -640,6 +1125,8 @@ export default function ViewSidebar({
|
|
| 640 |
const exportView = exportFor
|
| 641 |
? views.find((view) => view.id === exportFor.viewId)
|
| 642 |
: undefined;
|
|
|
|
|
|
|
| 643 |
const addView = addFor ? views.find((view) => view.id === addFor.viewId) : undefined;
|
| 644 |
const menuView = menu ? views.find((view) => view.id === menu.viewId) : undefined;
|
| 645 |
useEffect(() => {
|
|
@@ -683,7 +1170,8 @@ export default function ViewSidebar({
|
|
| 683 |
* server preference, and adding one would defeat instruction 13's own first clause: a
|
| 684 |
* preference that survives a reload is a folder that is open when the user next logs in.
|
| 685 |
*/
|
| 686 |
-
|
|
|
|
| 687 |
const [folderMenu, setFolderMenu] = useState<{ id: string; anchor: HTMLElement } | null>(null);
|
| 688 |
/**
|
| 689 |
* β W41-T35 (instruction 11) β WHICH FOLDER'S MARK IS BEING CHANGED, and off which button.
|
|
@@ -874,6 +1362,12 @@ export default function ViewSidebar({
|
|
| 874 |
() => folderNesting(foldersOn ? (folders as GridFolder[]) : []),
|
| 875 |
[foldersOn, folders]
|
| 876 |
);
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 877 |
/**
|
| 878 |
* ββ WAVE 41 Β· T37 (owner instruction 14) β THE GROUPING RUNS ONCE PER INPUT CHANGE, NOT
|
| 879 |
* ONCE PER RENDER.
|
|
@@ -1004,16 +1498,82 @@ export default function ViewSidebar({
|
|
| 1004 |
* it never touches `opened`, so clearing the search returns each folder to exactly the state
|
| 1005 |
* the user left it in.
|
| 1006 |
*/
|
| 1007 |
-
const
|
| 1008 |
-
|
| 1009 |
-
|
| 1010 |
-
|
| 1011 |
-
|
| 1012 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1013 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1014 |
}
|
| 1015 |
-
return
|
| 1016 |
-
}, [groups,
|
| 1017 |
const folderMenuF = folderMenu ? folders?.find((f) => f.id === folderMenu.id) : undefined;
|
| 1018 |
/**
|
| 1019 |
* ββ W41-T35 β THE FOLDER WHOSE MARK IS BEING CHANGED, AND THE SECOND REFUSAL OF A SYNTHETIC
|
|
@@ -1050,20 +1610,6 @@ export default function ViewSidebar({
|
|
| 1050 |
* β BUILT ONLY WHILE A SEARCH IS LIVE. With no needle the set is never walked and the rule it
|
| 1051 |
* serves never fires, so the idle rail pays nothing for it.
|
| 1052 |
*/
|
| 1053 |
-
const searchKeepsFolder = useMemo(() => {
|
| 1054 |
-
const keep = new Set<string>();
|
| 1055 |
-
if (viewNeedle) {
|
| 1056 |
-
for (const g of groups) {
|
| 1057 |
-
if (!g.folder || g.items.length === 0) continue;
|
| 1058 |
-
let up = nesting.parent[g.folder.id] ?? null;
|
| 1059 |
-
while (up && !keep.has(up)) {
|
| 1060 |
-
keep.add(up);
|
| 1061 |
-
up = nesting.parent[up] ?? null;
|
| 1062 |
-
}
|
| 1063 |
-
}
|
| 1064 |
-
}
|
| 1065 |
-
return keep;
|
| 1066 |
-
}, [groups, nesting, viewNeedle]);
|
| 1067 |
const addPreview = addTarget && folderAddPreview ? folderAddPreview(addTarget) : null;
|
| 1068 |
/**
|
| 1069 |
* ONE pair of drop handlers per group, serving TWO drags β a view being filed into this
|
|
@@ -1216,7 +1762,7 @@ export default function ViewSidebar({
|
|
| 1216 |
* β IT CAN ONLY ADD. Nothing here removes an id, so this cannot close a folder the user
|
| 1217 |
* opened, and the same-set short-circuit keeps a repeat create from re-rendering the rail.
|
| 1218 |
*/
|
| 1219 |
-
if (into)
|
| 1220 |
// cleanFolderIcon returns undefined for the all-defaults pair, so a folder the user
|
| 1221 |
// never restyled stays byte-identical to a pre-wave-9 one (the no-churn rule).
|
| 1222 |
onFolderCreate?.(value, cleanFolderIcon(folderIcon), into);
|
|
@@ -1303,7 +1849,7 @@ export default function ViewSidebar({
|
|
| 1303 |
{agentPanel}
|
| 1304 |
<aside
|
| 1305 |
className={"cg-views" + (railShut ? " is-collapsed" : "")}
|
| 1306 |
-
aria-label="
|
| 1307 |
>
|
| 1308 |
{/* Owner item 11 β the rail's own minimize control: the same three-bars glyph as the
|
| 1309 |
shell nav's, because the two rails are one idea ("a navigation bar folds"). */}
|
|
@@ -1398,6 +1944,17 @@ export default function ViewSidebar({
|
|
| 1398 |
badge's ABSENCE from this row and its PRESENCE on the view rows, so re-adding one
|
| 1399 |
reds it. */}
|
| 1400 |
</div>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1401 |
{/*
|
| 1402 |
I13 β the "Views / All changes saved" header block is GONE and everything moved up.
|
| 1403 |
|
|
@@ -1670,16 +2227,63 @@ export default function ViewSidebar({
|
|
| 1670 |
</AnchoredOverlay>
|
| 1671 |
)}
|
| 1672 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1673 |
<div className="cg-view-list cg-views-scroll">
|
| 1674 |
-
{
|
| 1675 |
const gid = group.folder?.id ?? null;
|
| 1676 |
-
// Item 9 β while a search is live, a folder with no matches is noise, not a target.
|
| 1677 |
-
// β W41-T33 β β¦UNLESS A FOLDER INSIDE IT MATCHED. Once folders nest, "no matching views
|
| 1678 |
-
// of its own" and "nothing under here at all" stop being the same fact: dropping a
|
| 1679 |
-
// parent on the first would leave its matching child indented under whatever row
|
| 1680 |
-
// happened to precede it, attached to the wrong folder on screen.
|
| 1681 |
-
if (viewNeedle && group.folder && group.items.length === 0
|
| 1682 |
-
&& !searchKeepsFolder.has(group.folder.id)) return null;
|
| 1683 |
/**
|
| 1684 |
* ββ WAVE 41 Β· T33 (instruction 12, R1) β HOW DEEP THIS FOLDER SITS, AND WHETHER IT
|
| 1685 |
* SHOWS AT ALL.
|
|
@@ -1689,12 +2293,7 @@ export default function ViewSidebar({
|
|
| 1689 |
* fall to level 1 and to "not hidden" β which is exactly where they rendered before this
|
| 1690 |
* ticket. The same is true of both `folder: null` groups.
|
| 1691 |
*/
|
| 1692 |
-
const
|
| 1693 |
-
// β A FOLDER INSIDE A COLLAPSED FOLDER DOES NOT RENDER. `shut` below hides a folder's
|
| 1694 |
-
// VIEWS; without this its child FOLDERS would keep their rows and stay indented under a
|
| 1695 |
-
// parent that is no longer showing anything, which reads as the collapse having half
|
| 1696 |
-
// worked. Ancestors only, so the collapsed folder itself keeps the head you re-open it by.
|
| 1697 |
-
if (gid && folderHiddenByCollapse(nesting, gid, collapsed)) return null;
|
| 1698 |
/**
|
| 1699 |
* ββ WAVE 40 Β· T28 (owner instruction 30) β THE PIN GROUP: the unfiled default views,
|
| 1700 |
* rendered above every folder.
|
|
@@ -1736,7 +2335,7 @@ export default function ViewSidebar({
|
|
| 1736 |
const isManaged =
|
| 1737 |
(group.folder as (GridFolder & { managedBy?: "loopable" }) | undefined)?.managedBy ===
|
| 1738 |
"loopable";
|
| 1739 |
-
const
|
| 1740 |
return (
|
| 1741 |
<div
|
| 1742 |
/* β W40-T28 β a key of its own. Both this group and the ungrouped section have a null
|
|
@@ -1755,13 +2354,12 @@ export default function ViewSidebar({
|
|
| 1755 |
* stylesheet would need one rule per level to a cap the model owns, and the two
|
| 1756 |
* numbers would then have to be kept equal by hand.
|
| 1757 |
*/
|
| 1758 |
-
style={depth > 1 ? { marginLeft: (depth - 1) * 12 } : undefined}
|
| 1759 |
className={
|
| 1760 |
/* β W40-T28 β `gid === null`, not `isRoot`: the pin group wears the SAME class as
|
| 1761 |
the ungrouped section (no head, the rail's measured root indent) because it is the
|
| 1762 |
same shape of thing rendered in a different place. DESIGN.md Β§4 β this is an
|
| 1763 |
existing element joining the existing rhythm, not a new control shape. */
|
| 1764 |
-
(
|
| 1765 |
(!isPinnedGroup && dropTarget === (gid ?? "__root__") ? " is-drop" : "") +
|
| 1766 |
// Item 19 β the insertion rule reads "the folder you are dragging lands HERE":
|
| 1767 |
// above this folder, or above the ungrouped section, which is after them all.
|
|
@@ -1797,7 +2395,8 @@ export default function ViewSidebar({
|
|
| 1797 |
// at `null` beside a `gid` that is `null` for this very section β that is the
|
| 1798 |
// `foldDrag === gid` trap two lines up, which faded the whole ungrouped section
|
| 1799 |
// permanently once already. `isRoot` is a separate boolean, so the two cannot collide.
|
| 1800 |
-
(isRoot && viewDrag !== null ? " is-viewdrop" : "")
|
|
|
|
| 1801 |
}
|
| 1802 |
{/* No drop handlers on the synthetic group β see `isSynthetic`. Spreading `{}`
|
| 1803 |
rather than branching the element keeps ONE render path for every group.
|
|
@@ -1808,7 +2407,7 @@ export default function ViewSidebar({
|
|
| 1808 |
somewhere else on screen. The ungrouped section below is the one root target. */
|
| 1809 |
...(isSynthetic || isManaged || isPinnedGroup ? {} : dropHandlers(gid))}
|
| 1810 |
>
|
| 1811 |
-
{group.folder && (
|
| 1812 |
<div
|
| 1813 |
className="cg-fold-head"
|
| 1814 |
// ββ Item 19 β the folder itself is the drag handle βββββββββββββββββββββ
|
|
@@ -1840,7 +2439,6 @@ export default function ViewSidebar({
|
|
| 1840 |
<button
|
| 1841 |
type="button"
|
| 1842 |
className="cg-fold-toggle"
|
| 1843 |
-
aria-expanded={!shut}
|
| 1844 |
/**
|
| 1845 |
* β W41-T34 β THE CLICK IS READ OFF `shut`, THE STATE THE CHEVRON IS DRAWING,
|
| 1846 |
* not off membership of `opened`.
|
|
@@ -1853,18 +2451,9 @@ export default function ViewSidebar({
|
|
| 1853 |
* open once the search cleared. The user pressed "close" and got "open", one
|
| 1854 |
* gesture later. Reading the drawn state makes the click mean what it looks like.
|
| 1855 |
*/
|
| 1856 |
-
|
| 1857 |
-
|
| 1858 |
-
const next = new Set(prev);
|
| 1859 |
-
if (shut) next.add(group.folder!.id);
|
| 1860 |
-
else next.delete(group.folder!.id);
|
| 1861 |
-
return next;
|
| 1862 |
-
})
|
| 1863 |
-
}
|
| 1864 |
>
|
| 1865 |
-
<span className={"cg-fold-chev" + (shut ? " is-shut" : "")} aria-hidden>
|
| 1866 |
-
βΎ
|
| 1867 |
-
</span>
|
| 1868 |
{/* I14/I15 β the folder wears its chosen mark; a folder that never chose one
|
| 1869 |
(every pre-wave-9 folder) renders the default grey folder shape, which is
|
| 1870 |
precisely "existing folders get the folder icon". */}
|
|
@@ -1966,9 +2555,7 @@ export default function ViewSidebar({
|
|
| 1966 |
)}
|
| 1967 |
</div>
|
| 1968 |
)}
|
| 1969 |
-
{
|
| 1970 |
-
file something into a folder you have tidied away. */}
|
| 1971 |
-
{!shut &&
|
| 1972 |
group.items.map((view) => {
|
| 1973 |
const active = view.id === activeViewId;
|
| 1974 |
const renaming = renamingId === view.id;
|
|
@@ -2273,7 +2860,8 @@ export default function ViewSidebar({
|
|
| 2273 |
</div>
|
| 2274 |
);
|
| 2275 |
})}
|
| 2276 |
-
{group.folder &&
|
|
|
|
| 2277 |
<div className="cg-fold-empty">Empty. Drag a view here.</div>
|
| 2278 |
)}
|
| 2279 |
</div>
|
|
@@ -2289,6 +2877,7 @@ export default function ViewSidebar({
|
|
| 2289 |
free and this section has nothing left to render.
|
| 2290 |
The lock MARK moved onto the ordinary view row, where `kind === "locked"` drives it. */}
|
| 2291 |
</div>
|
|
|
|
| 2292 |
|
| 2293 |
{/* I11c β the folder "β¦" menu. Rename Β· Add to cohort Β· Duplicate Β· Delete.
|
| 2294 |
WAVE 20 item 22 β every row now carries the SAME icon vocabulary the view row's
|
|
@@ -2495,6 +3084,56 @@ export default function ViewSidebar({
|
|
| 2495 |
</AnchoredOverlay>
|
| 2496 |
)}
|
| 2497 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2498 |
{/* Item 12 (C-LOCK) β the lock picker. Lists the cohorts this reader can see, marks the
|
| 2499 |
current one, and offers Unlock when there is one: a lock removable only from
|
| 2500 |
somewhere other than where it was applied is a trap, and the owner asked for a
|
|
@@ -2756,6 +3395,18 @@ export default function ViewSidebar({
|
|
| 2756 |
>
|
| 2757 |
<MenuLabel icon="duplicate" text="Duplicate" />
|
| 2758 |
</button>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2759 |
{/* WAVE 20 items 23/26 (R10) β "who else can reach this view", the same
|
| 2760 |
editor a folder and a database open. Deliberately NOT gated on
|
| 2761 |
`canEditMenuView`: the server decides who may administer (owner or
|
|
|
|
| 1 |
+
import { useEffect, useMemo, useRef, useState } from "react";
|
| 2 |
import type { ReactNode } from "react";
|
| 3 |
import type { KeyboardEvent as ReactKeyboardEvent } from "react";
|
| 4 |
import { AnchoredOverlay } from "./OverlaySurface";
|
|
|
|
| 44 |
*/
|
| 45 |
import { WORKSPACE_STALE_EVENT, signal } from "../apiContract";
|
| 46 |
import { ROOT_FOLDER_ID } from "./folders";
|
| 47 |
+
import {
|
| 48 |
+
folderPath,
|
| 49 |
+
groupDataDatabases,
|
| 50 |
+
levelAt,
|
| 51 |
+
pathStorageKey,
|
| 52 |
+
resolveStoredPath,
|
| 53 |
+
} from "./dataPath";
|
| 54 |
+
import type { DataDatabase, DataDatabaseFolder } from "./dataPath";
|
| 55 |
// β W32-T23 (owner item 17) β THE BELL, from the shared layer rather than redrawn here.
|
| 56 |
// The alert row wore `cohortAdd` (a LIST with a plus), which names "add to a cohort" on the
|
| 57 |
// one row that creates an ALERT β a borrowed mark is a small lie a menu repeats every time
|
|
|
|
| 64 |
// `isSyntheticFolderId`, and `noUnusedLocals` turns a leftover import into a build error rather
|
| 65 |
// than into dead weight. The constant itself is still exported and still used by `folders.ts`.
|
| 66 |
import {
|
|
|
|
| 67 |
folderNesting,
|
| 68 |
groupByFolder,
|
| 69 |
isSyntheticFolderId,
|
|
|
|
| 229 |
}
|
| 230 |
|
| 231 |
interface ViewSidebarProps {
|
| 232 |
+
/** Granted databases live in this secondary navigator, never in the global shell rail. */
|
| 233 |
+
databases?: readonly DataDatabase[];
|
| 234 |
+
activeDatabaseKey?: string;
|
| 235 |
+
databaseFolders?: readonly DataDatabaseFolder[];
|
| 236 |
+
onSelectDatabase?: (key: string) => void;
|
| 237 |
+
onDatabaseMove?: (key: string, folderId: string | null) => void;
|
| 238 |
+
onDatabaseFolderRename?: (folderId: string, name: string) => void;
|
| 239 |
+
onDatabaseFolderDelete?: (folderId: string) => void;
|
| 240 |
+
renderDatabaseActions?: (database: DataDatabase) => ReactNode;
|
| 241 |
+
databaseCreateControl?: ReactNode;
|
| 242 |
views: SavedView[];
|
| 243 |
activeViewId: string;
|
| 244 |
saveState: "saved" | "saving";
|
|
|
|
| 467 |
onToggleChat?: () => void;
|
| 468 |
}
|
| 469 |
|
| 470 |
+
interface DataDatabaseNavigatorProps {
|
| 471 |
+
databases: readonly DataDatabase[];
|
| 472 |
+
activeDatabaseKey: string;
|
| 473 |
+
folders: readonly DataDatabaseFolder[];
|
| 474 |
+
onSelect?: (key: string) => void;
|
| 475 |
+
onMove?: (key: string, folderId: string | null) => void;
|
| 476 |
+
onFolderRename?: (folderId: string, name: string) => void;
|
| 477 |
+
onFolderDelete?: (folderId: string) => void;
|
| 478 |
+
renderActions?: (database: DataDatabase) => ReactNode;
|
| 479 |
+
createControl?: ReactNode;
|
| 480 |
+
children: ReactNode;
|
| 481 |
+
}
|
| 482 |
+
|
| 483 |
+
type DataNavigatorLevel =
|
| 484 |
+
| { kind: "root" }
|
| 485 |
+
| { kind: "origin"; label: string }
|
| 486 |
+
| { kind: "folder"; id: string }
|
| 487 |
+
| { kind: "database"; key: string };
|
| 488 |
+
|
| 489 |
+
function dataNavigatorLevelKey(level: DataNavigatorLevel): string {
|
| 490 |
+
if (level.kind === "root") return "root";
|
| 491 |
+
if (level.kind === "origin") return `origin:${level.label}`;
|
| 492 |
+
if (level.kind === "folder") return `folder:${level.id}`;
|
| 493 |
+
return `database:${level.key}`;
|
| 494 |
+
}
|
| 495 |
+
|
| 496 |
+
/** Windows-style Data path rendered with the same segmented-path anatomy as the View path. */
|
| 497 |
+
function DataDatabaseNavigator({
|
| 498 |
+
databases,
|
| 499 |
+
activeDatabaseKey,
|
| 500 |
+
folders,
|
| 501 |
+
onSelect,
|
| 502 |
+
onMove,
|
| 503 |
+
onFolderRename,
|
| 504 |
+
onFolderDelete,
|
| 505 |
+
renderActions,
|
| 506 |
+
createControl,
|
| 507 |
+
children,
|
| 508 |
+
}: DataDatabaseNavigatorProps) {
|
| 509 |
+
const [draggedDatabase, setDraggedDatabase] = useState<string | null>(null);
|
| 510 |
+
const [folderMenu, setFolderMenu] = useState<{ folderId: string; anchor: HTMLElement } | null>(
|
| 511 |
+
null
|
| 512 |
+
);
|
| 513 |
+
const [renamingFolder, setRenamingFolder] = useState<string | null>(null);
|
| 514 |
+
const [folderName, setFolderName] = useState("");
|
| 515 |
+
|
| 516 |
+
const dropDatabase = (event: React.DragEvent<HTMLElement>, folderId: string | null) => {
|
| 517 |
+
if (!onMove) return;
|
| 518 |
+
const key = event.dataTransfer.getData("application/x-aios-database") || draggedDatabase;
|
| 519 |
+
if (!key) return;
|
| 520 |
+
event.preventDefault();
|
| 521 |
+
event.stopPropagation();
|
| 522 |
+
setDraggedDatabase(null);
|
| 523 |
+
onMove(key, folderId);
|
| 524 |
+
};
|
| 525 |
+
const dropProps = (folderId: string | null) =>
|
| 526 |
+
onMove
|
| 527 |
+
? {
|
| 528 |
+
onDragOver: (event: React.DragEvent<HTMLElement>) => {
|
| 529 |
+
if (!event.dataTransfer.types.includes("application/x-aios-database")) return;
|
| 530 |
+
event.preventDefault();
|
| 531 |
+
event.stopPropagation();
|
| 532 |
+
event.dataTransfer.dropEffect = "move";
|
| 533 |
+
},
|
| 534 |
+
onDrop: (event: React.DragEvent<HTMLElement>) => dropDatabase(event, folderId),
|
| 535 |
+
}
|
| 536 |
+
: {};
|
| 537 |
+
|
| 538 |
+
const sourceGroups = useMemo(
|
| 539 |
+
() => groupDataDatabases(databases.filter((database) => !database.folderId)),
|
| 540 |
+
[databases]
|
| 541 |
+
);
|
| 542 |
+
const parentOfDatabase = (database: DataDatabase): DataNavigatorLevel =>
|
| 543 |
+
database.folderId
|
| 544 |
+
? { kind: "folder", id: database.folderId }
|
| 545 |
+
: { kind: "origin", label: groupDataDatabases([database])[0]?.label ?? "Loopable" };
|
| 546 |
+
const levelsForDatabase = (database: DataDatabase): DataNavigatorLevel[] => [
|
| 547 |
+
{ kind: "root" },
|
| 548 |
+
parentOfDatabase(database),
|
| 549 |
+
{ kind: "database", key: database.key },
|
| 550 |
+
];
|
| 551 |
+
const [dataPathState, setDataPathState] = useState<{
|
| 552 |
+
levels: DataNavigatorLevel[];
|
| 553 |
+
at: number;
|
| 554 |
+
}>(() => {
|
| 555 |
+
const database = databases.find((candidate) => candidate.key === activeDatabaseKey);
|
| 556 |
+
const levels = database ? levelsForDatabase(database) : [{ kind: "root" } as const];
|
| 557 |
+
return { levels, at: levels.length - 1 };
|
| 558 |
+
});
|
| 559 |
+
const activeDataKey = useRef(activeDatabaseKey);
|
| 560 |
+
const dataLevel = dataPathState.levels[dataPathState.at] ?? { kind: "root" as const };
|
| 561 |
+
const canDataBack = dataPathState.at > 0;
|
| 562 |
+
const canDataForward = dataPathState.at < dataPathState.levels.length - 1;
|
| 563 |
+
const pushDataLevel = (level: DataNavigatorLevel) => {
|
| 564 |
+
setDataPathState((current) => ({
|
| 565 |
+
levels: [...current.levels.slice(0, current.at + 1), level],
|
| 566 |
+
at: current.at + 1,
|
| 567 |
+
}));
|
| 568 |
+
};
|
| 569 |
+
const stepDataLevel = (delta: number) => {
|
| 570 |
+
setDataPathState((current) => {
|
| 571 |
+
const at = current.at + delta;
|
| 572 |
+
return at < 0 || at >= current.levels.length ? current : { ...current, at };
|
| 573 |
+
});
|
| 574 |
+
};
|
| 575 |
+
useEffect(() => {
|
| 576 |
+
if (activeDataKey.current === activeDatabaseKey) return;
|
| 577 |
+
activeDataKey.current = activeDatabaseKey;
|
| 578 |
+
setDataPathState((current) => {
|
| 579 |
+
const here = current.levels[current.at];
|
| 580 |
+
if (here?.kind === "database" && here.key === activeDatabaseKey) return current;
|
| 581 |
+
const database = databases.find((candidate) => candidate.key === activeDatabaseKey);
|
| 582 |
+
const levels = database ? levelsForDatabase(database) : [{ kind: "root" } as const];
|
| 583 |
+
return { levels, at: levels.length - 1 };
|
| 584 |
+
});
|
| 585 |
+
}, [activeDatabaseKey, databases]);
|
| 586 |
+
const pathDatabase =
|
| 587 |
+
dataLevel.kind === "database"
|
| 588 |
+
? databases.find((database) => database.key === dataLevel.key)
|
| 589 |
+
: undefined;
|
| 590 |
+
const pathFolder =
|
| 591 |
+
dataLevel.kind === "folder" ? folders.find((folder) => folder.id === dataLevel.id) : undefined;
|
| 592 |
+
// Wave 44 QA / owner ruling: an address is a sequence of exact destinations. A joined label
|
| 593 |
+
// wired only to Back looks like a path but cannot do what a Windows path does.
|
| 594 |
+
const dataPathSegments: { level: DataNavigatorLevel; label: string }[] = [
|
| 595 |
+
{ level: { kind: "root" }, label: "Data" },
|
| 596 |
+
];
|
| 597 |
+
if (dataLevel.kind === "origin") {
|
| 598 |
+
dataPathSegments.push({ level: dataLevel, label: dataLevel.label });
|
| 599 |
+
} else if (dataLevel.kind === "folder") {
|
| 600 |
+
dataPathSegments.push({ level: dataLevel, label: pathFolder?.name ?? "Folder" });
|
| 601 |
+
} else if (dataLevel.kind === "database" && pathDatabase) {
|
| 602 |
+
const parent = parentOfDatabase(pathDatabase);
|
| 603 |
+
dataPathSegments.push({
|
| 604 |
+
level: parent,
|
| 605 |
+
label:
|
| 606 |
+
parent.kind === "folder"
|
| 607 |
+
? folders.find((folder) => folder.id === parent.id)?.name ?? "Folder"
|
| 608 |
+
: parent.kind === "origin"
|
| 609 |
+
? parent.label
|
| 610 |
+
: "Data",
|
| 611 |
+
});
|
| 612 |
+
dataPathSegments.push({ level: dataLevel, label: pathDatabase.label });
|
| 613 |
+
}
|
| 614 |
+
const visitDataLevel = (level: DataNavigatorLevel) => {
|
| 615 |
+
if (dataNavigatorLevelKey(level) === dataNavigatorLevelKey(dataLevel)) return;
|
| 616 |
+
pushDataLevel(level);
|
| 617 |
+
};
|
| 618 |
+
const openDatabase = (database: DataDatabase) => {
|
| 619 |
+
if (database.externalHref) return;
|
| 620 |
+
visitDataLevel({ kind: "database", key: database.key });
|
| 621 |
+
onSelect?.(database.key);
|
| 622 |
+
};
|
| 623 |
+
const pathDatabaseRow = (database: DataDatabase) => {
|
| 624 |
+
const active = database.key === activeDatabaseKey;
|
| 625 |
+
const draggable = !!onMove && !database.protected && database.managedBy !== "loopable";
|
| 626 |
+
const content = (
|
| 627 |
+
<>
|
| 628 |
+
<FolderMark icon={database.icon} size={16} />
|
| 629 |
+
<span className="cg-fold-name">{database.label}</span>
|
| 630 |
+
{database.locked ? (
|
| 631 |
+
<span
|
| 632 |
+
className="cg-data-database-lock"
|
| 633 |
+
role="img"
|
| 634 |
+
aria-label={`${database.label}, locked database`}
|
| 635 |
+
title="Locked database. Records are managed by its source; fields remain editable."
|
| 636 |
+
>
|
| 637 |
+
<LockMark size={12} />
|
| 638 |
+
</span>
|
| 639 |
+
) : null}
|
| 640 |
+
</>
|
| 641 |
+
);
|
| 642 |
+
return (
|
| 643 |
+
<div
|
| 644 |
+
key={database.key}
|
| 645 |
+
className={
|
| 646 |
+
"cg-fold cg-data-database" +
|
| 647 |
+
(active ? " is-active" : "") +
|
| 648 |
+
(draggedDatabase === database.key ? " is-dragging" : "")
|
| 649 |
+
}
|
| 650 |
+
draggable={draggable}
|
| 651 |
+
onDragStart={(event) => {
|
| 652 |
+
event.dataTransfer.setData("application/x-aios-database", database.key);
|
| 653 |
+
event.dataTransfer.effectAllowed = "move";
|
| 654 |
+
setDraggedDatabase(database.key);
|
| 655 |
+
}}
|
| 656 |
+
onDragEnd={() => setDraggedDatabase(null)}
|
| 657 |
+
>
|
| 658 |
+
<div className="cg-fold-head">
|
| 659 |
+
{database.externalHref ? (
|
| 660 |
+
<a
|
| 661 |
+
className="cg-fold-toggle"
|
| 662 |
+
href={database.externalHref}
|
| 663 |
+
target="_blank"
|
| 664 |
+
rel="noreferrer"
|
| 665 |
+
aria-label={`Open ${database.label}`}
|
| 666 |
+
>
|
| 667 |
+
{content}
|
| 668 |
+
</a>
|
| 669 |
+
) : (
|
| 670 |
+
<button
|
| 671 |
+
type="button"
|
| 672 |
+
className="cg-fold-toggle"
|
| 673 |
+
aria-current={active ? "page" : undefined}
|
| 674 |
+
aria-label={`Open database ${database.label}`}
|
| 675 |
+
onClick={() => openDatabase(database)}
|
| 676 |
+
>
|
| 677 |
+
{content}
|
| 678 |
+
</button>
|
| 679 |
+
)}
|
| 680 |
+
{renderActions?.(database)}
|
| 681 |
+
</div>
|
| 682 |
+
</div>
|
| 683 |
+
);
|
| 684 |
+
};
|
| 685 |
+
|
| 686 |
+
// CustomerGrid also renders this sidebar in embedded/query surfaces. Keep those surfaces'
|
| 687 |
+
// existing View-only navigator when the shell has not supplied a database contract.
|
| 688 |
+
if (databases.length === 0 || !activeDatabaseKey || !onSelect) return <>{children}</>;
|
| 689 |
+
|
| 690 |
+
const levelDatabases =
|
| 691 |
+
dataLevel.kind === "origin"
|
| 692 |
+
? sourceGroups.find((group) => group.label === dataLevel.label)?.databases ?? []
|
| 693 |
+
: dataLevel.kind === "folder"
|
| 694 |
+
? databases.filter((database) => database.folderId === dataLevel.id)
|
| 695 |
+
: [];
|
| 696 |
+
|
| 697 |
+
return (
|
| 698 |
+
<div className="cg-data-tree" data-data-path-tree>
|
| 699 |
+
<nav
|
| 700 |
+
className="cg-fold-head cg-data-path cg-segmented-path"
|
| 701 |
+
data-data-path-history
|
| 702 |
+
aria-label="Data location"
|
| 703 |
+
>
|
| 704 |
+
<button
|
| 705 |
+
type="button"
|
| 706 |
+
className="cg-path-history-button"
|
| 707 |
+
aria-label="Back"
|
| 708 |
+
title="Back"
|
| 709 |
+
disabled={!canDataBack}
|
| 710 |
+
onClick={() => stepDataLevel(-1)}
|
| 711 |
+
>
|
| 712 |
+
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" aria-hidden="true">
|
| 713 |
+
<path
|
| 714 |
+
d="M9.8 3.6 5.4 8l4.4 4.4"
|
| 715 |
+
stroke="currentColor"
|
| 716 |
+
strokeWidth="1.35"
|
| 717 |
+
strokeLinecap="round"
|
| 718 |
+
strokeLinejoin="round"
|
| 719 |
+
/>
|
| 720 |
+
</svg>
|
| 721 |
+
</button>
|
| 722 |
+
<span className="cg-path-segments">
|
| 723 |
+
{dataPathSegments.map((segment, index) => {
|
| 724 |
+
const current = dataNavigatorLevelKey(segment.level) === dataNavigatorLevelKey(dataLevel);
|
| 725 |
+
return (
|
| 726 |
+
<span className="cg-path-segment-wrap" key={dataNavigatorLevelKey(segment.level)}>
|
| 727 |
+
{index > 0 ? <span className="cg-path-separator" aria-hidden="true">βΊ</span> : null}
|
| 728 |
+
<button
|
| 729 |
+
type="button"
|
| 730 |
+
className="cg-path-segment"
|
| 731 |
+
data-data-path-segment={dataNavigatorLevelKey(segment.level)}
|
| 732 |
+
aria-current={current ? "page" : undefined}
|
| 733 |
+
disabled={current}
|
| 734 |
+
title={segment.label}
|
| 735 |
+
onClick={() => visitDataLevel(segment.level)}
|
| 736 |
+
>
|
| 737 |
+
{segment.label}
|
| 738 |
+
</button>
|
| 739 |
+
</span>
|
| 740 |
+
);
|
| 741 |
+
})}
|
| 742 |
+
</span>
|
| 743 |
+
{canDataForward ? (
|
| 744 |
+
<button
|
| 745 |
+
type="button"
|
| 746 |
+
className="cg-path-history-button"
|
| 747 |
+
aria-label="Forward"
|
| 748 |
+
title="Forward"
|
| 749 |
+
onClick={() => stepDataLevel(1)}
|
| 750 |
+
>
|
| 751 |
+
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" aria-hidden="true">
|
| 752 |
+
<path
|
| 753 |
+
d="M6.2 3.6 10.6 8l-4.4 4.4"
|
| 754 |
+
stroke="currentColor"
|
| 755 |
+
strokeWidth="1.35"
|
| 756 |
+
strokeLinecap="round"
|
| 757 |
+
strokeLinejoin="round"
|
| 758 |
+
/>
|
| 759 |
+
</svg>
|
| 760 |
+
</button>
|
| 761 |
+
) : null}
|
| 762 |
+
</nav>
|
| 763 |
+
|
| 764 |
+
{dataLevel.kind === "root" ? (
|
| 765 |
+
<div className="cg-data-path-level" data-data-level="root">
|
| 766 |
+
{sourceGroups.map((group) => (
|
| 767 |
+
<div key={group.label} className="cg-fold cg-data-origin" {...dropProps(null)}>
|
| 768 |
+
<div className="cg-fold-head">
|
| 769 |
+
<button
|
| 770 |
+
type="button"
|
| 771 |
+
className="cg-fold-toggle"
|
| 772 |
+
aria-label={`Open folder ${group.label}`}
|
| 773 |
+
onClick={() => pushDataLevel({ kind: "origin", label: group.label })}
|
| 774 |
+
>
|
| 775 |
+
<FolderMark size={16} />
|
| 776 |
+
<span className="cg-fold-name">{group.label}</span>
|
| 777 |
+
<span className="cg-fold-count">{group.databases.length}</span>
|
| 778 |
+
</button>
|
| 779 |
+
</div>
|
| 780 |
+
</div>
|
| 781 |
+
))}
|
| 782 |
+
{folders.map((folder) => {
|
| 783 |
+
const members = databases.filter((database) => database.folderId === folder.id);
|
| 784 |
+
return (
|
| 785 |
+
<div
|
| 786 |
+
key={folder.id}
|
| 787 |
+
className="cg-fold cg-data-user-folder"
|
| 788 |
+
{...dropProps(folder.id)}
|
| 789 |
+
>
|
| 790 |
+
<div className="cg-fold-head">
|
| 791 |
+
<button
|
| 792 |
+
type="button"
|
| 793 |
+
className="cg-fold-toggle"
|
| 794 |
+
aria-label={`Open folder ${folder.name}`}
|
| 795 |
+
onClick={() => pushDataLevel({ kind: "folder", id: folder.id })}
|
| 796 |
+
>
|
| 797 |
+
<FolderMark size={16} />
|
| 798 |
+
<span className="cg-fold-name">{folder.name}</span>
|
| 799 |
+
<span className="cg-fold-count">{members.length}</span>
|
| 800 |
+
</button>
|
| 801 |
+
{onFolderRename || onFolderDelete ? (
|
| 802 |
+
<button
|
| 803 |
+
type="button"
|
| 804 |
+
className="cg-view-more"
|
| 805 |
+
aria-label={`Actions for ${folder.name}`}
|
| 806 |
+
aria-haspopup="menu"
|
| 807 |
+
onClick={(event) => {
|
| 808 |
+
setFolderMenu({ folderId: folder.id, anchor: event.currentTarget });
|
| 809 |
+
setRenamingFolder(null);
|
| 810 |
+
setFolderName(folder.name);
|
| 811 |
+
}}
|
| 812 |
+
>
|
| 813 |
+
Β·Β·Β·
|
| 814 |
+
</button>
|
| 815 |
+
) : null}
|
| 816 |
+
</div>
|
| 817 |
+
</div>
|
| 818 |
+
);
|
| 819 |
+
})}
|
| 820 |
+
</div>
|
| 821 |
+
) : dataLevel.kind === "database" ? (
|
| 822 |
+
<div className="cg-data-database-views" data-data-level="database">
|
| 823 |
+
{children}
|
| 824 |
+
</div>
|
| 825 |
+
) : (
|
| 826 |
+
<div className="cg-data-path-level" data-data-level={dataLevel.kind} {...dropProps(null)}>
|
| 827 |
+
{levelDatabases.map(pathDatabaseRow)}
|
| 828 |
+
{levelDatabases.length === 0 ? (
|
| 829 |
+
<div className="cg-fold-empty">No databases in this folder.</div>
|
| 830 |
+
) : null}
|
| 831 |
+
</div>
|
| 832 |
+
)}
|
| 833 |
+
|
| 834 |
+
{dataLevel.kind === "root" && createControl ? (
|
| 835 |
+
<div className="cg-data-create">{createControl}</div>
|
| 836 |
+
) : null}
|
| 837 |
+
{folderMenu ? (
|
| 838 |
+
<AnchoredOverlay
|
| 839 |
+
anchor={folderMenu.anchor}
|
| 840 |
+
className="cg-view-menu"
|
| 841 |
+
role="menu"
|
| 842 |
+
ariaLabel="Database folder actions"
|
| 843 |
+
onDismiss={() => setFolderMenu(null)}
|
| 844 |
+
placement="right-start"
|
| 845 |
+
>
|
| 846 |
+
{renamingFolder === folderMenu.folderId ? (
|
| 847 |
+
<form
|
| 848 |
+
className="cg-data-folder-rename"
|
| 849 |
+
onSubmit={(event) => {
|
| 850 |
+
event.preventDefault();
|
| 851 |
+
const clean = folderName.trim().replace(/\s+/g, " ");
|
| 852 |
+
if (clean) onFolderRename?.(folderMenu.folderId, clean);
|
| 853 |
+
setFolderMenu(null);
|
| 854 |
+
}}
|
| 855 |
+
>
|
| 856 |
+
<input
|
| 857 |
+
className="cg-input"
|
| 858 |
+
autoFocus
|
| 859 |
+
value={folderName}
|
| 860 |
+
maxLength={40}
|
| 861 |
+
aria-label="Database folder name"
|
| 862 |
+
onChange={(event) => setFolderName(event.target.value)}
|
| 863 |
+
/>
|
| 864 |
+
<button type="submit" className="cg-btn cg-btn--primary" disabled={!folderName.trim()}>
|
| 865 |
+
Save
|
| 866 |
+
</button>
|
| 867 |
+
</form>
|
| 868 |
+
) : (
|
| 869 |
+
<>
|
| 870 |
+
{onFolderRename ? (
|
| 871 |
+
<button
|
| 872 |
+
type="button"
|
| 873 |
+
role="menuitem"
|
| 874 |
+
onClick={() => setRenamingFolder(folderMenu.folderId)}
|
| 875 |
+
>
|
| 876 |
+
Rename
|
| 877 |
+
</button>
|
| 878 |
+
) : null}
|
| 879 |
+
{onFolderDelete ? (
|
| 880 |
+
<button
|
| 881 |
+
type="button"
|
| 882 |
+
role="menuitem"
|
| 883 |
+
className="is-danger"
|
| 884 |
+
onClick={() => {
|
| 885 |
+
onFolderDelete(folderMenu.folderId);
|
| 886 |
+
setFolderMenu(null);
|
| 887 |
+
}}
|
| 888 |
+
>
|
| 889 |
+
Delete folder
|
| 890 |
+
</button>
|
| 891 |
+
) : null}
|
| 892 |
+
</>
|
| 893 |
+
)}
|
| 894 |
+
</AnchoredOverlay>
|
| 895 |
+
) : null}
|
| 896 |
+
</div>
|
| 897 |
+
);
|
| 898 |
+
|
| 899 |
+
}
|
| 900 |
+
|
| 901 |
/**
|
| 902 |
* β WAVE 41 Β· T35 (owner instruction 11) β THE FOLDER ICON PICKER: ONE COPY, TWO DOORS.
|
| 903 |
*
|
|
|
|
| 1001 |
);
|
| 1002 |
}
|
| 1003 |
|
| 1004 |
+
function readRailPath(databaseKey: string): string | null {
|
| 1005 |
+
try {
|
| 1006 |
+
const stored = localStorage.getItem(pathStorageKey(databaseKey));
|
| 1007 |
+
return typeof stored === "string" && stored !== "" ? stored : null;
|
| 1008 |
+
} catch {
|
| 1009 |
+
return null;
|
| 1010 |
+
}
|
| 1011 |
+
}
|
| 1012 |
+
|
| 1013 |
+
function writeRailPath(databaseKey: string, folderId: string | null): void {
|
| 1014 |
+
try {
|
| 1015 |
+
const key = pathStorageKey(databaseKey);
|
| 1016 |
+
if (folderId) localStorage.setItem(key, folderId);
|
| 1017 |
+
else localStorage.removeItem(key);
|
| 1018 |
+
} catch {
|
| 1019 |
+
// Storage is optional; losing this convenience must never take down the navigation.
|
| 1020 |
+
}
|
| 1021 |
+
}
|
| 1022 |
+
|
| 1023 |
export default function ViewSidebar({
|
| 1024 |
+
databases = [],
|
| 1025 |
+
activeDatabaseKey = "",
|
| 1026 |
+
databaseFolders = [],
|
| 1027 |
+
onSelectDatabase,
|
| 1028 |
+
onDatabaseMove,
|
| 1029 |
+
onDatabaseFolderRename,
|
| 1030 |
+
onDatabaseFolderDelete,
|
| 1031 |
+
renderDatabaseActions,
|
| 1032 |
+
databaseCreateControl,
|
| 1033 |
agentPanel = null,
|
| 1034 |
agentOpen = false,
|
| 1035 |
onToggleAgent,
|
|
|
|
| 1054 |
onExport,
|
| 1055 |
onExportXlsxViews,
|
| 1056 |
exportableViewIds,
|
| 1057 |
+
folders: suppliedFolders,
|
| 1058 |
folderIdOf,
|
| 1059 |
onFolderCreate,
|
| 1060 |
onFolderRename,
|
|
|
|
| 1074 |
actionAnchor,
|
| 1075 |
onActionAnchorConsumed,
|
| 1076 |
}: ViewSidebarProps) {
|
| 1077 |
+
// The old managed "Loopable" View folder put an origin label inside every database. Origin now
|
| 1078 |
+
// belongs one level up in the Data tree, so its views fall back into the database's root group.
|
| 1079 |
+
const folders = useMemo(
|
| 1080 |
+
() =>
|
| 1081 |
+
suppliedFolders?.filter(
|
| 1082 |
+
(folder) => (folder as GridFolder & { managedBy?: "loopable" }).managedBy !== "loopable"
|
| 1083 |
+
),
|
| 1084 |
+
[suppliedFolders]
|
| 1085 |
+
);
|
| 1086 |
/**
|
| 1087 |
* I14 β creating a view now always knows WHICH KIND of view is being created, because the
|
| 1088 |
* flyout is the only door in. `null` = not creating; a mode = the name step for that mode.
|
|
|
|
| 1125 |
const exportView = exportFor
|
| 1126 |
? views.find((view) => view.id === exportFor.viewId)
|
| 1127 |
: undefined;
|
| 1128 |
+
const [moveFor, setMoveFor] = useState<{ viewId: string; anchor: HTMLElement } | null>(null);
|
| 1129 |
+
const moveView = moveFor ? views.find((view) => view.id === moveFor.viewId) : undefined;
|
| 1130 |
const addView = addFor ? views.find((view) => view.id === addFor.viewId) : undefined;
|
| 1131 |
const menuView = menu ? views.find((view) => view.id === menu.viewId) : undefined;
|
| 1132 |
useEffect(() => {
|
|
|
|
| 1170 |
* server preference, and adding one would defeat instruction 13's own first clause: a
|
| 1171 |
* preference that survives a reload is a folder that is open when the user next logs in.
|
| 1172 |
*/
|
| 1173 |
+
// Recovered from 7f6a1c0 (W42-T43): one location replaces the old expand/collapse tree.
|
| 1174 |
+
const [at, setAt] = useState<string | null>(() => readRailPath(activeDatabaseKey));
|
| 1175 |
const [folderMenu, setFolderMenu] = useState<{ id: string; anchor: HTMLElement } | null>(null);
|
| 1176 |
/**
|
| 1177 |
* β W41-T35 (instruction 11) β WHICH FOLDER'S MARK IS BEING CHANGED, and off which button.
|
|
|
|
| 1362 |
() => folderNesting(foldersOn ? (folders as GridFolder[]) : []),
|
| 1363 |
[foldersOn, folders]
|
| 1364 |
);
|
| 1365 |
+
const canFileMenuView =
|
| 1366 |
+
foldersOn && !!menuView && mayFileView(menuView, canEditMenuView);
|
| 1367 |
+
const moveFolders = useMemo(
|
| 1368 |
+
() => nesting.ordered.filter((folder) => !isSyntheticFolderId(folder.id)),
|
| 1369 |
+
[nesting]
|
| 1370 |
+
);
|
| 1371 |
/**
|
| 1372 |
* ββ WAVE 41 Β· T37 (owner instruction 14) β THE GROUPING RUNS ONCE PER INPUT CHANGE, NOT
|
| 1373 |
* ONCE PER RENDER.
|
|
|
|
| 1498 |
* it never touches `opened`, so clearing the search returns each folder to exactly the state
|
| 1499 |
* the user left it in.
|
| 1500 |
*/
|
| 1501 |
+
const standableIds = useMemo(
|
| 1502 |
+
() => groups.flatMap((group) => (group.folder ? [group.folder.id] : [])),
|
| 1503 |
+
[groups]
|
| 1504 |
+
);
|
| 1505 |
+
const atId = useMemo(() => {
|
| 1506 |
+
if (at === null) return null;
|
| 1507 |
+
if (viewNeedle) return at;
|
| 1508 |
+
return resolveStoredPath(at, standableIds);
|
| 1509 |
+
}, [at, standableIds, viewNeedle]);
|
| 1510 |
+
useEffect(() => {
|
| 1511 |
+
if (activeDatabaseKey) writeRailPath(activeDatabaseKey, at);
|
| 1512 |
+
}, [activeDatabaseKey, at]);
|
| 1513 |
+
const level = useMemo(
|
| 1514 |
+
() =>
|
| 1515 |
+
levelAt(
|
| 1516 |
+
atId,
|
| 1517 |
+
foldersOn ? (folders as GridFolder[]) : [],
|
| 1518 |
+
shownViews,
|
| 1519 |
+
(view) => (folderIdOf ? folderIdOf(view.id) : null)
|
| 1520 |
+
),
|
| 1521 |
+
[atId, foldersOn, folders, shownViews, folderIdOf]
|
| 1522 |
+
);
|
| 1523 |
+
const crumbs = useMemo(
|
| 1524 |
+
() => folderPath(atId, foldersOn ? (folders as GridFolder[]) : []),
|
| 1525 |
+
[atId, foldersOn, folders]
|
| 1526 |
+
);
|
| 1527 |
+
const atLabel = useMemo(
|
| 1528 |
+
() =>
|
| 1529 |
+
atId === null
|
| 1530 |
+
? null
|
| 1531 |
+
: groups.find((group) => group.folder?.id === atId)?.folder?.name ?? null,
|
| 1532 |
+
[atId, groups]
|
| 1533 |
+
);
|
| 1534 |
+
// The folder id travels with every visible crumb. This is what makes a depth-three click jump
|
| 1535 |
+
// straight to depth one instead of quietly behaving like the adjacent Back button again.
|
| 1536 |
+
const viewPathSegments: { id: string | null; label: string }[] = [
|
| 1537 |
+
{ id: null, label: "All views" },
|
| 1538 |
+
...(crumbs.length > 0
|
| 1539 |
+
? crumbs.map((folder) => ({ id: folder.id, label: folder.name }))
|
| 1540 |
+
: atId !== null
|
| 1541 |
+
? [{ id: atId, label: atLabel ?? "Folder" }]
|
| 1542 |
+
: []),
|
| 1543 |
+
];
|
| 1544 |
+
const levelGroups = useMemo(() => {
|
| 1545 |
+
const pin: typeof groups = [];
|
| 1546 |
+
const heads: typeof groups = [];
|
| 1547 |
+
const leaves: typeof groups = [];
|
| 1548 |
+
const childIds = new Set(
|
| 1549 |
+
atId !== null && isSyntheticFolderId(atId) ? [] : level.folders.map((folder) => folder.id)
|
| 1550 |
+
);
|
| 1551 |
+
for (const group of groups) {
|
| 1552 |
+
const groupId = group.folder?.id ?? null;
|
| 1553 |
+
if (viewNeedle) {
|
| 1554 |
+
if (group.items.length > 0) leaves.push(group);
|
| 1555 |
+
continue;
|
| 1556 |
+
}
|
| 1557 |
+
if (group.pinned === true) {
|
| 1558 |
+
if (atId === null) pin.push(group);
|
| 1559 |
+
continue;
|
| 1560 |
+
}
|
| 1561 |
+
if (groupId === null) {
|
| 1562 |
+
if (atId === null) leaves.push(group);
|
| 1563 |
+
continue;
|
| 1564 |
+
}
|
| 1565 |
+
if (groupId === atId) {
|
| 1566 |
+
leaves.push(group);
|
| 1567 |
+
continue;
|
| 1568 |
}
|
| 1569 |
+
if (isSyntheticFolderId(groupId)) {
|
| 1570 |
+
if (atId === null) heads.push(group);
|
| 1571 |
+
continue;
|
| 1572 |
+
}
|
| 1573 |
+
if (childIds.has(groupId)) heads.push(group);
|
| 1574 |
}
|
| 1575 |
+
return { heads, rows: [...pin, ...heads, ...leaves] };
|
| 1576 |
+
}, [groups, level, atId, viewNeedle]);
|
| 1577 |
const folderMenuF = folderMenu ? folders?.find((f) => f.id === folderMenu.id) : undefined;
|
| 1578 |
/**
|
| 1579 |
* ββ W41-T35 β THE FOLDER WHOSE MARK IS BEING CHANGED, AND THE SECOND REFUSAL OF A SYNTHETIC
|
|
|
|
| 1610 |
* β BUILT ONLY WHILE A SEARCH IS LIVE. With no needle the set is never walked and the rule it
|
| 1611 |
* serves never fires, so the idle rail pays nothing for it.
|
| 1612 |
*/
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1613 |
const addPreview = addTarget && folderAddPreview ? folderAddPreview(addTarget) : null;
|
| 1614 |
/**
|
| 1615 |
* ONE pair of drop handlers per group, serving TWO drags β a view being filed into this
|
|
|
|
| 1762 |
* β IT CAN ONLY ADD. Nothing here removes an id, so this cannot close a folder the user
|
| 1763 |
* opened, and the same-set short-circuit keeps a repeat create from re-rendering the rail.
|
| 1764 |
*/
|
| 1765 |
+
if (into) setAt(into);
|
| 1766 |
// cleanFolderIcon returns undefined for the all-defaults pair, so a folder the user
|
| 1767 |
// never restyled stays byte-identical to a pre-wave-9 one (the no-churn rule).
|
| 1768 |
onFolderCreate?.(value, cleanFolderIcon(folderIcon), into);
|
|
|
|
| 1849 |
{agentPanel}
|
| 1850 |
<aside
|
| 1851 |
className={"cg-views" + (railShut ? " is-collapsed" : "")}
|
| 1852 |
+
aria-label={databases.length ? "Data and View navigation" : "Views"}
|
| 1853 |
>
|
| 1854 |
{/* Owner item 11 β the rail's own minimize control: the same three-bars glyph as the
|
| 1855 |
shell nav's, because the two rails are one idea ("a navigation bar folds"). */}
|
|
|
|
| 1944 |
badge's ABSENCE from this row and its PRESENCE on the view rows, so re-adding one
|
| 1945 |
reds it. */}
|
| 1946 |
</div>
|
| 1947 |
+
<DataDatabaseNavigator
|
| 1948 |
+
databases={databases}
|
| 1949 |
+
activeDatabaseKey={activeDatabaseKey}
|
| 1950 |
+
folders={databaseFolders}
|
| 1951 |
+
onSelect={onSelectDatabase}
|
| 1952 |
+
onMove={onDatabaseMove}
|
| 1953 |
+
onFolderRename={onDatabaseFolderRename}
|
| 1954 |
+
onFolderDelete={onDatabaseFolderDelete}
|
| 1955 |
+
renderActions={renderDatabaseActions}
|
| 1956 |
+
createControl={databaseCreateControl}
|
| 1957 |
+
>
|
| 1958 |
{/*
|
| 1959 |
I13 β the "Views / All changes saved" header block is GONE and everything moved up.
|
| 1960 |
|
|
|
|
| 2227 |
</AnchoredOverlay>
|
| 2228 |
)}
|
| 2229 |
|
| 2230 |
+
{viewNeedle ? (
|
| 2231 |
+
<div className="cg-fold-empty" data-view-folder-path>
|
| 2232 |
+
Showing matches in every folder
|
| 2233 |
+
</div>
|
| 2234 |
+
) : (
|
| 2235 |
+
<nav
|
| 2236 |
+
className="cg-fold-head cg-view-path cg-segmented-path"
|
| 2237 |
+
data-view-folder-path
|
| 2238 |
+
aria-label="View folder location"
|
| 2239 |
+
>
|
| 2240 |
+
<button
|
| 2241 |
+
type="button"
|
| 2242 |
+
className="cg-path-history-button"
|
| 2243 |
+
aria-label="Back to parent folder"
|
| 2244 |
+
title="Back to parent folder"
|
| 2245 |
+
disabled={atId === null}
|
| 2246 |
+
onClick={() => setAt(level.parent)}
|
| 2247 |
+
>
|
| 2248 |
+
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" aria-hidden="true">
|
| 2249 |
+
<path
|
| 2250 |
+
d="M9.8 3.6 5.4 8l4.4 4.4"
|
| 2251 |
+
stroke="currentColor"
|
| 2252 |
+
strokeWidth="1.35"
|
| 2253 |
+
strokeLinecap="round"
|
| 2254 |
+
strokeLinejoin="round"
|
| 2255 |
+
/>
|
| 2256 |
+
</svg>
|
| 2257 |
+
</button>
|
| 2258 |
+
<span className="cg-path-segments">
|
| 2259 |
+
{viewPathSegments.map((segment, index) => {
|
| 2260 |
+
const current = segment.id === atId;
|
| 2261 |
+
return (
|
| 2262 |
+
<span className="cg-path-segment-wrap" key={segment.id ?? "root"}>
|
| 2263 |
+
{index > 0 ? (
|
| 2264 |
+
<span className="cg-path-separator" aria-hidden="true">βΊ</span>
|
| 2265 |
+
) : null}
|
| 2266 |
+
<button
|
| 2267 |
+
type="button"
|
| 2268 |
+
className="cg-path-segment"
|
| 2269 |
+
data-view-path-segment={segment.id ?? "root"}
|
| 2270 |
+
aria-current={current ? "page" : undefined}
|
| 2271 |
+
disabled={current}
|
| 2272 |
+
title={segment.label}
|
| 2273 |
+
onClick={() => setAt(segment.id)}
|
| 2274 |
+
>
|
| 2275 |
+
{segment.label}
|
| 2276 |
+
</button>
|
| 2277 |
+
</span>
|
| 2278 |
+
);
|
| 2279 |
+
})}
|
| 2280 |
+
</span>
|
| 2281 |
+
</nav>
|
| 2282 |
+
)}
|
| 2283 |
+
|
| 2284 |
<div className="cg-view-list cg-views-scroll">
|
| 2285 |
+
{levelGroups.rows.map((group) => {
|
| 2286 |
const gid = group.folder?.id ?? null;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2287 |
/**
|
| 2288 |
* ββ WAVE 41 Β· T33 (instruction 12, R1) β HOW DEEP THIS FOLDER SITS, AND WHETHER IT
|
| 2289 |
* SHOWS AT ALL.
|
|
|
|
| 2293 |
* fall to level 1 and to "not hidden" β which is exactly where they rendered before this
|
| 2294 |
* ticket. The same is true of both `folder: null` groups.
|
| 2295 |
*/
|
| 2296 |
+
const asLeaves = !group.folder || gid === atId || !!viewNeedle;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2297 |
/**
|
| 2298 |
* ββ WAVE 40 Β· T28 (owner instruction 30) β THE PIN GROUP: the unfiled default views,
|
| 2299 |
* rendered above every folder.
|
|
|
|
| 2335 |
const isManaged =
|
| 2336 |
(group.folder as (GridFolder & { managedBy?: "loopable" }) | undefined)?.managedBy ===
|
| 2337 |
"loopable";
|
| 2338 |
+
const isLevelFolder = asLeaves && gid !== null && !isSynthetic && !viewNeedle;
|
| 2339 |
return (
|
| 2340 |
<div
|
| 2341 |
/* β W40-T28 β a key of its own. Both this group and the ungrouped section have a null
|
|
|
|
| 2354 |
* stylesheet would need one rule per level to a cap the model owns, and the two
|
| 2355 |
* numbers would then have to be kept equal by hand.
|
| 2356 |
*/
|
|
|
|
| 2357 |
className={
|
| 2358 |
/* β W40-T28 β `gid === null`, not `isRoot`: the pin group wears the SAME class as
|
| 2359 |
the ungrouped section (no head, the rail's measured root indent) because it is the
|
| 2360 |
same shape of thing rendered in a different place. DESIGN.md Β§4 β this is an
|
| 2361 |
existing element joining the existing rhythm, not a new control shape. */
|
| 2362 |
+
(asLeaves ? "cg-fold-root" : "cg-fold") +
|
| 2363 |
(!isPinnedGroup && dropTarget === (gid ?? "__root__") ? " is-drop" : "") +
|
| 2364 |
// Item 19 β the insertion rule reads "the folder you are dragging lands HERE":
|
| 2365 |
// above this folder, or above the ungrouped section, which is after them all.
|
|
|
|
| 2395 |
// at `null` beside a `gid` that is `null` for this very section β that is the
|
| 2396 |
// `foldDrag === gid` trap two lines up, which faded the whole ungrouped section
|
| 2397 |
// permanently once already. `isRoot` is a separate boolean, so the two cannot collide.
|
| 2398 |
+
(isRoot && viewDrag !== null ? " is-viewdrop" : "") +
|
| 2399 |
+
(isLevelFolder && viewDrag !== null ? " is-viewdrop" : "")
|
| 2400 |
}
|
| 2401 |
{/* No drop handlers on the synthetic group β see `isSynthetic`. Spreading `{}`
|
| 2402 |
rather than branching the element keeps ONE render path for every group.
|
|
|
|
| 2407 |
somewhere else on screen. The ungrouped section below is the one root target. */
|
| 2408 |
...(isSynthetic || isManaged || isPinnedGroup ? {} : dropHandlers(gid))}
|
| 2409 |
>
|
| 2410 |
+
{group.folder && !asLeaves && (
|
| 2411 |
<div
|
| 2412 |
className="cg-fold-head"
|
| 2413 |
// ββ Item 19 β the folder itself is the drag handle βββββββββββββββββββββ
|
|
|
|
| 2439 |
<button
|
| 2440 |
type="button"
|
| 2441 |
className="cg-fold-toggle"
|
|
|
|
| 2442 |
/**
|
| 2443 |
* β W41-T34 β THE CLICK IS READ OFF `shut`, THE STATE THE CHEVRON IS DRAWING,
|
| 2444 |
* not off membership of `opened`.
|
|
|
|
| 2451 |
* open once the search cleared. The user pressed "close" and got "open", one
|
| 2452 |
* gesture later. Reading the drawn state makes the click mean what it looks like.
|
| 2453 |
*/
|
| 2454 |
+
aria-label={`Open folder ${group.folder.name}`}
|
| 2455 |
+
onClick={() => setAt(group.folder!.id)}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2456 |
>
|
|
|
|
|
|
|
|
|
|
| 2457 |
{/* I14/I15 β the folder wears its chosen mark; a folder that never chose one
|
| 2458 |
(every pre-wave-9 folder) renders the default grey folder shape, which is
|
| 2459 |
precisely "existing folders get the folder icon". */}
|
|
|
|
| 2555 |
)}
|
| 2556 |
</div>
|
| 2557 |
)}
|
| 2558 |
+
{asLeaves &&
|
|
|
|
|
|
|
| 2559 |
group.items.map((view) => {
|
| 2560 |
const active = view.id === activeViewId;
|
| 2561 |
const renaming = renamingId === view.id;
|
|
|
|
| 2860 |
</div>
|
| 2861 |
);
|
| 2862 |
})}
|
| 2863 |
+
{group.folder && asLeaves && group.items.length === 0
|
| 2864 |
+
&& levelGroups.heads.length === 0 && (
|
| 2865 |
<div className="cg-fold-empty">Empty. Drag a view here.</div>
|
| 2866 |
)}
|
| 2867 |
</div>
|
|
|
|
| 2877 |
free and this section has nothing left to render.
|
| 2878 |
The lock MARK moved onto the ordinary view row, where `kind === "locked"` drives it. */}
|
| 2879 |
</div>
|
| 2880 |
+
</DataDatabaseNavigator>
|
| 2881 |
|
| 2882 |
{/* I11c β the folder "β¦" menu. Rename Β· Add to cohort Β· Duplicate Β· Delete.
|
| 2883 |
WAVE 20 item 22 β every row now carries the SAME icon vocabulary the view row's
|
|
|
|
| 3084 |
</AnchoredOverlay>
|
| 3085 |
)}
|
| 3086 |
|
| 3087 |
+
{moveFor && moveView && (() => {
|
| 3088 |
+
const currentId = folderIdOf ? folderIdOf(moveFor.viewId) : null;
|
| 3089 |
+
const fileInto = (folderId: string | null) => {
|
| 3090 |
+
onItemMove?.(moveFor.viewId, folderId ?? ROOT_FOLDER_ID);
|
| 3091 |
+
setMoveFor(null);
|
| 3092 |
+
};
|
| 3093 |
+
return (
|
| 3094 |
+
<AnchoredOverlay
|
| 3095 |
+
anchor={moveFor.anchor}
|
| 3096 |
+
className="cg-pop"
|
| 3097 |
+
placement="bottom-end"
|
| 3098 |
+
role="dialog"
|
| 3099 |
+
ariaLabel={`Move ${viewDisplayName(moveView)} to a folder`}
|
| 3100 |
+
onDismiss={() => setMoveFor(null)}
|
| 3101 |
+
dataKind="view-move-to"
|
| 3102 |
+
>
|
| 3103 |
+
<div className="cg-pop-title">Move to</div>
|
| 3104 |
+
<div className="cg-pop-list" data-full-folder-path-picker>
|
| 3105 |
+
<button
|
| 3106 |
+
type="button"
|
| 3107 |
+
className={
|
| 3108 |
+
"cg-pick-row" +
|
| 3109 |
+
(currentId === null || currentId === ROOT_FOLDER_ID ? " is-on" : "")
|
| 3110 |
+
}
|
| 3111 |
+
onClick={() => fileInto(null)}
|
| 3112 |
+
>
|
| 3113 |
+
<FolderMark size={16} />
|
| 3114 |
+
Top level
|
| 3115 |
+
</button>
|
| 3116 |
+
{moveFolders.map((folder) => (
|
| 3117 |
+
<button
|
| 3118 |
+
type="button"
|
| 3119 |
+
key={folder.id}
|
| 3120 |
+
className={"cg-pick-row" + (folder.id === currentId ? " is-on" : "")}
|
| 3121 |
+
style={{ paddingLeft: 6 + (nesting.depth[folder.id] ?? 0) * 12 }}
|
| 3122 |
+
title={folderPath(folder.id, moveFolders).map((part) => part.name).join(" / ")}
|
| 3123 |
+
onClick={() => fileInto(folder.id)}
|
| 3124 |
+
>
|
| 3125 |
+
<FolderMark icon={folder.icon} size={16} />
|
| 3126 |
+
{folder.name}
|
| 3127 |
+
</button>
|
| 3128 |
+
))}
|
| 3129 |
+
{moveFolders.length === 0 ? (
|
| 3130 |
+
<div className="cg-pop-note">There are no folders in this database yet.</div>
|
| 3131 |
+
) : null}
|
| 3132 |
+
</div>
|
| 3133 |
+
</AnchoredOverlay>
|
| 3134 |
+
);
|
| 3135 |
+
})()}
|
| 3136 |
+
|
| 3137 |
{/* Item 12 (C-LOCK) β the lock picker. Lists the cohorts this reader can see, marks the
|
| 3138 |
current one, and offers Unlock when there is one: a lock removable only from
|
| 3139 |
somewhere other than where it was applied is a trap, and the owner asked for a
|
|
|
|
| 3395 |
>
|
| 3396 |
<MenuLabel icon="duplicate" text="Duplicate" />
|
| 3397 |
</button>
|
| 3398 |
+
{canFileMenuView && (
|
| 3399 |
+
<button
|
| 3400 |
+
type="button"
|
| 3401 |
+
role="menuitem"
|
| 3402 |
+
onClick={() => {
|
| 3403 |
+
setMoveFor({ viewId: menuView.id, anchor: menu.anchor });
|
| 3404 |
+
setMenu(null);
|
| 3405 |
+
}}
|
| 3406 |
+
>
|
| 3407 |
+
<MenuLabel icon={<FolderMark size={16} />} text="Move to" />
|
| 3408 |
+
</button>
|
| 3409 |
+
)}
|
| 3410 |
{/* WAVE 20 items 23/26 (R10) β "who else can reach this view", the same
|
| 3411 |
editor a folder and a database open. Deliberately NOT gated on
|
| 3412 |
`canEditMenuView`: the server decides who may administer (owner or
|
web/src/customer-grid/apiBridge.ts
CHANGED
|
@@ -949,6 +949,47 @@ export interface RollupSourceTopic {
|
|
| 949 |
measures: { key: string; label: string; format: string; description: string }[];
|
| 950 |
}
|
| 951 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 952 |
export async function patchTableField(
|
| 953 |
tableKey: string,
|
| 954 |
fieldKey: string,
|
|
@@ -1098,6 +1139,105 @@ export async function deleteTableField(
|
|
| 1098 |
}
|
| 1099 |
}
|
| 1100 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1101 |
/**
|
| 1102 |
* ββ 2026-08-09 β THE DEFINITION SHAPE, NOT A THREE-KEY SUMMARY.
|
| 1103 |
*
|
|
|
|
| 949 |
measures: { key: string; label: string; format: string; description: string }[];
|
| 950 |
}
|
| 951 |
|
| 952 |
+
/**
|
| 953 |
+
* W42-T08/T37: the semantic one-hop authoring offer is deliberately fetched from its own
|
| 954 |
+
* endpoint. It is not a projection of RollupSourceOffer: hop dimensions carry their real
|
| 955 |
+
* date/number/text types, which choose the filter operators rendered by FilterBuilderPanel.
|
| 956 |
+
*/
|
| 957 |
+
export interface HopTopic {
|
| 958 |
+
key: string;
|
| 959 |
+
label: string;
|
| 960 |
+
dims: Field[];
|
| 961 |
+
measures: { key: string; label: string }[];
|
| 962 |
+
}
|
| 963 |
+
|
| 964 |
+
export interface HopTopicOffer {
|
| 965 |
+
topics: HopTopic[];
|
| 966 |
+
windows: { key: string; label: string }[];
|
| 967 |
+
omissions: { topic: string; label: string; reasons: string[] }[];
|
| 968 |
+
}
|
| 969 |
+
|
| 970 |
+
/** Preserve the server's typed dimensions; malformed envelopes fail closed to an empty offer. */
|
| 971 |
+
export function hopTopicOfferFromBody(body: unknown): HopTopicOffer {
|
| 972 |
+
const raw = body && typeof body === "object" && !Array.isArray(body)
|
| 973 |
+
? body as Partial<HopTopicOffer>
|
| 974 |
+
: null;
|
| 975 |
+
return {
|
| 976 |
+
topics: Array.isArray(raw?.topics) ? raw.topics : [],
|
| 977 |
+
windows: Array.isArray(raw?.windows) ? raw.windows : [],
|
| 978 |
+
omissions: Array.isArray(raw?.omissions) ? raw.omissions : [],
|
| 979 |
+
};
|
| 980 |
+
}
|
| 981 |
+
|
| 982 |
+
export async function fetchHopTopics(): Promise<HopTopicOffer> {
|
| 983 |
+
const empty: HopTopicOffer = { topics: [], windows: [], omissions: [] };
|
| 984 |
+
try {
|
| 985 |
+
const res = await fetch(`${API_V1}/grid/hop-topics`, { credentials: CREDENTIALS });
|
| 986 |
+
if (handledSession(res) || !res.ok) return empty;
|
| 987 |
+
return hopTopicOfferFromBody(await readJson(res));
|
| 988 |
+
} catch {
|
| 989 |
+
return empty;
|
| 990 |
+
}
|
| 991 |
+
}
|
| 992 |
+
|
| 993 |
export async function patchTableField(
|
| 994 |
tableKey: string,
|
| 995 |
fieldKey: string,
|
|
|
|
| 1139 |
}
|
| 1140 |
}
|
| 1141 |
|
| 1142 |
+
/** Per-column verdict returned by the plural schema delete door. */
|
| 1143 |
+
export interface FieldDeleteResult {
|
| 1144 |
+
key: string;
|
| 1145 |
+
status: "deleted" | "refused";
|
| 1146 |
+
code?: string;
|
| 1147 |
+
reason?: string;
|
| 1148 |
+
contract?: unknown;
|
| 1149 |
+
removed?: unknown;
|
| 1150 |
+
}
|
| 1151 |
+
|
| 1152 |
+
export interface FieldDeleteOutcome {
|
| 1153 |
+
deleted: string[];
|
| 1154 |
+
refused: string[];
|
| 1155 |
+
results: FieldDeleteResult[];
|
| 1156 |
+
/** The server accepted the request but did not name any affected key. */
|
| 1157 |
+
unreadable: boolean;
|
| 1158 |
+
}
|
| 1159 |
+
|
| 1160 |
+
const DELETE_ANSWER_NAMED_NO_COLUMN =
|
| 1161 |
+
"The server accepted that delete without saying which columns went, so the table is being read " +
|
| 1162 |
+
"again rather than guessed at.";
|
| 1163 |
+
|
| 1164 |
+
function refusedWholesale(
|
| 1165 |
+
fieldKeys: readonly string[],
|
| 1166 |
+
reason: string | undefined,
|
| 1167 |
+
code: string,
|
| 1168 |
+
unreadable = false,
|
| 1169 |
+
): FieldDeleteOutcome {
|
| 1170 |
+
return {
|
| 1171 |
+
deleted: [],
|
| 1172 |
+
refused: [...fieldKeys],
|
| 1173 |
+
results: fieldKeys.map((key) => ({ key, status: "refused" as const, code, reason })),
|
| 1174 |
+
unreadable,
|
| 1175 |
+
};
|
| 1176 |
+
}
|
| 1177 |
+
|
| 1178 |
+
/**
|
| 1179 |
+
* Delete every selected definition through one request, including a one-item selection. The
|
| 1180 |
+
* caller reconciles only the keys the server explicitly reports as deleted.
|
| 1181 |
+
*/
|
| 1182 |
+
export async function deleteTableFields(
|
| 1183 |
+
tableKey: string,
|
| 1184 |
+
fieldKeys: readonly string[],
|
| 1185 |
+
): Promise<FieldDeleteOutcome> {
|
| 1186 |
+
if (fieldKeys.length === 0) {
|
| 1187 |
+
return { deleted: [], refused: [], results: [], unreadable: false };
|
| 1188 |
+
}
|
| 1189 |
+
let res: Response;
|
| 1190 |
+
try {
|
| 1191 |
+
res = await fetch(`${API_V1}/tables/${encodeURIComponent(tableKey)}/fields/delete`, {
|
| 1192 |
+
method: "POST",
|
| 1193 |
+
credentials: CREDENTIALS,
|
| 1194 |
+
headers: JSON_HEADERS,
|
| 1195 |
+
body: JSON.stringify({ keys: [...fieldKeys] }),
|
| 1196 |
+
});
|
| 1197 |
+
} catch {
|
| 1198 |
+
return refusedWholesale(fieldKeys, "That delete did not reach the server.", "unreachable");
|
| 1199 |
+
}
|
| 1200 |
+
if (handledSession(res)) return refusedWholesale(fieldKeys, undefined, "session_ended");
|
| 1201 |
+
const body = (await readJson(res)) as {
|
| 1202 |
+
results?: unknown;
|
| 1203 |
+
deleted?: unknown;
|
| 1204 |
+
refused?: unknown;
|
| 1205 |
+
error?: { message?: string; code?: string };
|
| 1206 |
+
} | null;
|
| 1207 |
+
if (!res.ok) {
|
| 1208 |
+
const code = typeof body?.error?.code === "string" ? body.error.code : "refused";
|
| 1209 |
+
return refusedWholesale(fieldKeys, refusalMessage(body, res.status), code);
|
| 1210 |
+
}
|
| 1211 |
+
const results: FieldDeleteResult[] = [];
|
| 1212 |
+
if (Array.isArray(body?.results)) {
|
| 1213 |
+
for (const entry of body.results) {
|
| 1214 |
+
const raw = entry as Record<string, unknown> | null;
|
| 1215 |
+
if (!raw || typeof raw.key !== "string") continue;
|
| 1216 |
+
results.push({
|
| 1217 |
+
key: raw.key,
|
| 1218 |
+
status: raw.status === "deleted" ? "deleted" : "refused",
|
| 1219 |
+
code: typeof raw.code === "string" ? raw.code : undefined,
|
| 1220 |
+
reason: typeof raw.reason === "string" ? raw.reason : undefined,
|
| 1221 |
+
contract: raw.contract,
|
| 1222 |
+
removed: raw.removed,
|
| 1223 |
+
});
|
| 1224 |
+
}
|
| 1225 |
+
} else {
|
| 1226 |
+
const named = (value: unknown): string[] =>
|
| 1227 |
+
Array.isArray(value) ? value.filter((key): key is string => typeof key === "string") : [];
|
| 1228 |
+
for (const key of named(body?.deleted)) results.push({ key, status: "deleted" });
|
| 1229 |
+
for (const key of named(body?.refused)) results.push({ key, status: "refused" });
|
| 1230 |
+
}
|
| 1231 |
+
if (results.length === 0) {
|
| 1232 |
+
dropTableRowsCache(tableKey);
|
| 1233 |
+
return refusedWholesale(fieldKeys, DELETE_ANSWER_NAMED_NO_COLUMN, "unreadable_answer", true);
|
| 1234 |
+
}
|
| 1235 |
+
const deleted = results.filter((item) => item.status === "deleted").map((item) => item.key);
|
| 1236 |
+
const refused = results.filter((item) => item.status === "refused").map((item) => item.key);
|
| 1237 |
+
if (deleted.length > 0) dropTableRowsCache(tableKey);
|
| 1238 |
+
return { deleted, refused, results, unreadable: false };
|
| 1239 |
+
}
|
| 1240 |
+
|
| 1241 |
/**
|
| 1242 |
* ββ 2026-08-09 β THE DEFINITION SHAPE, NOT A THREE-KEY SUMMARY.
|
| 1243 |
*
|
web/src/customer-grid/dataPath.ts
CHANGED
|
@@ -1,4 +1,7 @@
|
|
| 1 |
-
|
|
|
|
|
|
|
|
|
|
| 2 |
// this describes only the Data workspace's secondary location.
|
| 3 |
export interface DataPath {
|
| 4 |
database: string;
|
|
@@ -6,6 +9,156 @@ export interface DataPath {
|
|
| 6 |
field?: string;
|
| 7 |
}
|
| 8 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 9 |
export function dataPathHash(path: DataPath): string {
|
| 10 |
const query = new URLSearchParams({ database: path.database });
|
| 11 |
if (path.view) query.set("view", path.view);
|
|
|
|
| 1 |
+
import type { FolderIcon } from "./types";
|
| 2 |
+
import { folderNesting, ROOT_FOLDER_ID } from "./folders";
|
| 3 |
+
|
| 4 |
+
// Canonical, shareable Data addressing. The shell keeps the global main navigation;
|
| 5 |
// this describes only the Data workspace's secondary location.
|
| 6 |
export interface DataPath {
|
| 7 |
database: string;
|
|
|
|
| 9 |
field?: string;
|
| 10 |
}
|
| 11 |
|
| 12 |
+
/** A granted database as rendered by the Data workspace's secondary navigator. */
|
| 13 |
+
export interface DataDatabase {
|
| 14 |
+
key: string;
|
| 15 |
+
label: string;
|
| 16 |
+
source?: string;
|
| 17 |
+
managedBy?: "loopable";
|
| 18 |
+
protected?: boolean;
|
| 19 |
+
locked?: boolean;
|
| 20 |
+
icon?: FolderIcon;
|
| 21 |
+
folderId?: string;
|
| 22 |
+
externalHref?: string;
|
| 23 |
+
}
|
| 24 |
+
|
| 25 |
+
export interface DataDatabaseFolder {
|
| 26 |
+
id: string;
|
| 27 |
+
name: string;
|
| 28 |
+
}
|
| 29 |
+
|
| 30 |
+
export interface DataDatabaseGroup {
|
| 31 |
+
label: string;
|
| 32 |
+
databases: DataDatabase[];
|
| 33 |
+
}
|
| 34 |
+
|
| 35 |
+
/** The structural folder contract shared by database folders and View folders (W42-T41). */
|
| 36 |
+
export interface PathFolder {
|
| 37 |
+
id: string;
|
| 38 |
+
name: string;
|
| 39 |
+
parent?: string | null;
|
| 40 |
+
}
|
| 41 |
+
|
| 42 |
+
export interface FolderLevel<F, T> {
|
| 43 |
+
folder: F | null;
|
| 44 |
+
folders: F[];
|
| 45 |
+
leaves: T[];
|
| 46 |
+
parent: string | null;
|
| 47 |
+
depth: number;
|
| 48 |
+
}
|
| 49 |
+
|
| 50 |
+
function levelIdOf(raw: string | null | undefined, known: ReadonlySet<string>): string | null {
|
| 51 |
+
if (raw == null || raw === ROOT_FOLDER_ID) return null;
|
| 52 |
+
return known.has(raw) ? raw : null;
|
| 53 |
+
}
|
| 54 |
+
|
| 55 |
+
/**
|
| 56 |
+
* W42-T41's one level resolver. It keeps folders and leaves separate so every renderer lists
|
| 57 |
+
* folders first, and it takes the parent answer from the existing cycle-safe nesting model.
|
| 58 |
+
*/
|
| 59 |
+
export function levelAt<F extends PathFolder, T>(
|
| 60 |
+
at: string | null | undefined,
|
| 61 |
+
folders: readonly F[],
|
| 62 |
+
items: readonly T[],
|
| 63 |
+
folderIdOf: (item: T) => string | null | undefined
|
| 64 |
+
): FolderLevel<F, T> {
|
| 65 |
+
const list = [...folders];
|
| 66 |
+
const byId = new Map<string, F>(list.map((folder) => [folder.id, folder]));
|
| 67 |
+
const known = new Set(byId.keys());
|
| 68 |
+
const nesting = folderNesting(list);
|
| 69 |
+
const hereId = levelIdOf(at, known);
|
| 70 |
+
const here = hereId == null ? null : (byId.get(hereId) ?? null);
|
| 71 |
+
const parent = here ? (nesting.parent[here.id] ?? null) : null;
|
| 72 |
+
const subfolders: F[] = [];
|
| 73 |
+
for (const folder of nesting.ordered) {
|
| 74 |
+
const own = byId.get(folder.id);
|
| 75 |
+
if (!own) continue;
|
| 76 |
+
if ((nesting.parent[folder.id] ?? null) === (here?.id ?? null)) subfolders.push(own);
|
| 77 |
+
}
|
| 78 |
+
const leaves = items.filter(
|
| 79 |
+
(item) => levelIdOf(folderIdOf(item), known) === (here?.id ?? null)
|
| 80 |
+
);
|
| 81 |
+
return {
|
| 82 |
+
folder: here,
|
| 83 |
+
folders: subfolders,
|
| 84 |
+
leaves,
|
| 85 |
+
parent,
|
| 86 |
+
depth: here ? (nesting.depth[here.id] ?? 1) : 0,
|
| 87 |
+
};
|
| 88 |
+
}
|
| 89 |
+
|
| 90 |
+
/** Outermost-first breadcrumb over the same cycle-safe parent map as {@link levelAt}. */
|
| 91 |
+
export function folderPath<F extends PathFolder>(
|
| 92 |
+
at: string | null | undefined,
|
| 93 |
+
folders: readonly F[]
|
| 94 |
+
): F[] {
|
| 95 |
+
const list = [...folders];
|
| 96 |
+
const byId = new Map<string, F>(list.map((folder) => [folder.id, folder]));
|
| 97 |
+
const nesting = folderNesting(list);
|
| 98 |
+
let cursor = levelIdOf(at, new Set(byId.keys()));
|
| 99 |
+
const path: F[] = [];
|
| 100 |
+
const walked = new Set<string>();
|
| 101 |
+
while (cursor) {
|
| 102 |
+
if (walked.has(cursor)) break;
|
| 103 |
+
walked.add(cursor);
|
| 104 |
+
const folder = byId.get(cursor);
|
| 105 |
+
if (!folder) break;
|
| 106 |
+
path.unshift(folder);
|
| 107 |
+
cursor = nesting.parent[cursor] ?? null;
|
| 108 |
+
}
|
| 109 |
+
return path;
|
| 110 |
+
}
|
| 111 |
+
|
| 112 |
+
const VIEW_PATH_KEY_PREFIX = "aios-views-at";
|
| 113 |
+
|
| 114 |
+
/** W42-T45: stable per-database browser slot for the open View folder. */
|
| 115 |
+
export function pathStorageKey(databaseKey: string): string {
|
| 116 |
+
return `${VIEW_PATH_KEY_PREFIX}-${typeof databaseKey === "string" ? databaseKey : ""}`;
|
| 117 |
+
}
|
| 118 |
+
|
| 119 |
+
/** Refuse a stale stored folder id instead of restoring an empty, unreachable level. */
|
| 120 |
+
export function resolveStoredPath(
|
| 121 |
+
stored: string | null | undefined,
|
| 122 |
+
validIds: Iterable<string> | null | undefined
|
| 123 |
+
): string | null {
|
| 124 |
+
if (typeof stored !== "string" || stored === "") return null;
|
| 125 |
+
if (!validIds || typeof validIds[Symbol.iterator] !== "function") return null;
|
| 126 |
+
for (const id of validIds) if (id === stored) return stored;
|
| 127 |
+
return null;
|
| 128 |
+
}
|
| 129 |
+
|
| 130 |
+
/**
|
| 131 |
+
* The database tree is grouped by the provenance the server supplied, never by a tenant label.
|
| 132 |
+
* Blank and automation-created tables are Loopable-generated; managed system tables carry the
|
| 133 |
+
* stronger `managedBy` signal. Connected sources keep their own server-provided name.
|
| 134 |
+
*/
|
| 135 |
+
export function dataDatabaseOrigin(database: DataDatabase): string {
|
| 136 |
+
const source = database.source?.trim() ?? "";
|
| 137 |
+
const normalized = source.toLowerCase();
|
| 138 |
+
if (
|
| 139 |
+
database.managedBy === "loopable" ||
|
| 140 |
+
normalized === "loopable" ||
|
| 141 |
+
normalized === "blank" ||
|
| 142 |
+
normalized === "automation" ||
|
| 143 |
+
!normalized
|
| 144 |
+
) {
|
| 145 |
+
return "Loopable";
|
| 146 |
+
}
|
| 147 |
+
return source;
|
| 148 |
+
}
|
| 149 |
+
|
| 150 |
+
/** Preserve the granted order inside each origin and the first-seen order of origin folders. */
|
| 151 |
+
export function groupDataDatabases(databases: readonly DataDatabase[]): DataDatabaseGroup[] {
|
| 152 |
+
const groups = new Map<string, DataDatabase[]>();
|
| 153 |
+
for (const database of databases) {
|
| 154 |
+
const label = dataDatabaseOrigin(database);
|
| 155 |
+
const current = groups.get(label);
|
| 156 |
+
if (current) current.push(database);
|
| 157 |
+
else groups.set(label, [database]);
|
| 158 |
+
}
|
| 159 |
+
return [...groups].map(([label, grouped]) => ({ label, databases: grouped }));
|
| 160 |
+
}
|
| 161 |
+
|
| 162 |
export function dataPathHash(path: DataPath): string {
|
| 163 |
const query = new URLSearchParams({ database: path.database });
|
| 164 |
if (path.view) query.set("view", path.view);
|
web/src/customer-grid/formulaEngine.ts
CHANGED
|
@@ -6,7 +6,11 @@
|
|
| 6 |
//
|
| 7 |
// GRAMMAR (v2 β the shared contract; v1 remains a strict subset):
|
| 8 |
// numbers 1 0.5 .5 1200.75 (no separators, no exponents)
|
| 9 |
-
// strings "text" with "" escaping a quote β Excel's own rule
|
|
|
|
|
|
|
|
|
|
|
|
|
| 10 |
// booleans TRUE FALSE (bare constants)
|
| 11 |
// field refs {revenue_ytd} (slug charset [A-Za-z0-9_])
|
| 12 |
// arithmetic + - * / ^ ( ) (usual precedence; ^ is
|
|
@@ -21,7 +25,29 @@
|
|
| 21 |
// logic IF AND OR NOT IFERROR ISBLANK
|
| 22 |
// text CONCATENATE/CONCAT LEFT RIGHT MID LEN TRIM
|
| 23 |
// UPPER LOWER PROPER VALUE TEXT
|
|
|
|
|
|
|
| 24 |
// date TODAY YEAR MONTH DAY DAYS (ISO YYYY-MM-DD)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 25 |
//
|
| 26 |
// THE ONE RULE, unchanged: **any error β BLANK, never a wrong number.** An
|
| 27 |
// unknown ref, a divide-by-zero, a boolean fed to arithmetic, an unreadable
|
|
@@ -67,10 +93,12 @@ export type FormulaAst =
|
|
| 67 |
export type FormulaFn =
|
| 68 |
| "ABS" | "ROUND" | "ROUNDUP" | "ROUNDDOWN" | "INT" | "MOD" | "SQRT" | "POWER"
|
| 69 |
| "EXP" | "LN" | "SUM" | "AVERAGE" | "COUNT" | "COUNTA" | "MIN" | "MAX"
|
| 70 |
-
| "IF" | "AND" | "OR" | "NOT" | "IFERROR" | "ISBLANK"
|
| 71 |
| "CONCATENATE" | "LEFT" | "RIGHT" | "MID" | "LEN" | "TRIM"
|
| 72 |
| "UPPER" | "LOWER" | "PROPER" | "VALUE" | "TEXT"
|
| 73 |
-
| "
|
|
|
|
|
|
|
| 74 |
|
| 75 |
const MANY = 30; // variadic cap β bounded, far above any honest use
|
| 76 |
|
|
@@ -97,6 +125,9 @@ const FN_ARITY: Record<FormulaFn, [number, number]> = {
|
|
| 97 |
NOT: [1, 1],
|
| 98 |
IFERROR: [2, 2],
|
| 99 |
ISBLANK: [1, 1],
|
|
|
|
|
|
|
|
|
|
| 100 |
CONCATENATE: [1, MANY],
|
| 101 |
LEFT: [1, 2],
|
| 102 |
RIGHT: [1, 2],
|
|
@@ -108,11 +139,23 @@ const FN_ARITY: Record<FormulaFn, [number, number]> = {
|
|
| 108 |
PROPER: [1, 1],
|
| 109 |
VALUE: [1, 1],
|
| 110 |
TEXT: [2, 2],
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 111 |
TODAY: [0, 0],
|
| 112 |
YEAR: [1, 1],
|
| 113 |
MONTH: [1, 1],
|
| 114 |
DAY: [1, 1],
|
| 115 |
DAYS: [2, 2],
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 116 |
};
|
| 117 |
|
| 118 |
/** Excel spells it CONCAT in modern versions; both names, one function. */
|
|
@@ -153,15 +196,20 @@ function tokenize(src: string): Token[] | string {
|
|
| 153 |
i = end + 1;
|
| 154 |
continue;
|
| 155 |
}
|
| 156 |
-
// "string" β Excel's own escape:
|
| 157 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 158 |
let j = i + 1;
|
| 159 |
let s = "";
|
| 160 |
for (;;) {
|
| 161 |
if (j >= src.length) return "a text value is missing its closing quote";
|
| 162 |
-
if (src[j] ===
|
| 163 |
-
if (src[j + 1] ===
|
| 164 |
-
s +=
|
| 165 |
j += 2;
|
| 166 |
continue;
|
| 167 |
}
|
|
@@ -354,7 +402,9 @@ export function parseFormula(src: string): ParseResult {
|
|
| 354 |
}
|
| 355 |
const fn = (FN_ALIASES[upper] ?? upper) as FormulaFn;
|
| 356 |
if (!(fn in FN_ARITY))
|
| 357 |
-
|
|
|
|
|
|
|
| 358 |
pos += 1;
|
| 359 |
if (!isOp("(")) return fail(`${fn} must be called with parentheses: ${fn}(β¦)`);
|
| 360 |
pos += 1;
|
|
@@ -501,6 +551,187 @@ function dateSerial(p: { y: number; m: number; d: number }): number {
|
|
| 501 |
return Date.UTC(p.y, p.m - 1, p.d) / 86_400_000;
|
| 502 |
}
|
| 503 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 504 |
/**
|
| 505 |
* TEXT(value, format) β the common Excel number formats, fail-closed:
|
| 506 |
* "0" "0.00" fixed decimals
|
|
@@ -709,6 +940,18 @@ function evalNode(n: FormulaAst, get: (key: string) => unknown, env: FormulaEnv)
|
|
| 709 |
const v = ev(n.args[0]);
|
| 710 |
return v == null || v === "";
|
| 711 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 712 |
case "CONCATENATE":
|
| 713 |
return n.args.map((a) => asText(ev(a))).join("");
|
| 714 |
case "LEFT":
|
|
@@ -750,6 +993,75 @@ function evalNode(n: FormulaAst, get: (key: string) => unknown, env: FormulaEnv)
|
|
| 750 |
if (v == null || typeof fmt !== "string") return null;
|
| 751 |
return textFormat(v, fmt);
|
| 752 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 753 |
case "TODAY":
|
| 754 |
return typeof env.today === "string" && dateParts(env.today) ? env.today : null;
|
| 755 |
case "YEAR":
|
|
@@ -766,6 +1078,46 @@ function evalNode(n: FormulaAst, get: (key: string) => unknown, env: FormulaEnv)
|
|
| 766 |
if (!end || !start) return null;
|
| 767 |
return Math.round(dateSerial(end) - dateSerial(start));
|
| 768 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 769 |
}
|
| 770 |
return null;
|
| 771 |
}
|
|
@@ -774,6 +1126,25 @@ function evalNode(n: FormulaAst, get: (key: string) => unknown, env: FormulaEnv)
|
|
| 774 |
}
|
| 775 |
}
|
| 776 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 777 |
function cmpNums(op: "<" | "<=" | ">" | ">=" | "=" | "!=", l: number, r: number): boolean {
|
| 778 |
switch (op) {
|
| 779 |
case "<": return l < r;
|
|
@@ -855,6 +1226,58 @@ export function orderFormulas(sources: ReadonlyMap<string, string>): {
|
|
| 855 |
* can walk the graph; `selfKey` names the field being edited (absent on
|
| 856 |
* create, where no cycle is possible yet).
|
| 857 |
*/
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 858 |
export function validateFormula(
|
| 859 |
src: string,
|
| 860 |
knownKeys: ReadonlySet<string>,
|
|
@@ -863,6 +1286,8 @@ export function validateFormula(
|
|
| 863 |
): { ok: boolean; error?: string; refs: string[] } {
|
| 864 |
const parsed = parseFormula(src);
|
| 865 |
if (!parsed.ok) return { ok: false, error: parsed.error, refs: [] };
|
|
|
|
|
|
|
| 866 |
for (const k of parsed.refs) {
|
| 867 |
if (!knownKeys.has(k) && !formulaSources.has(k))
|
| 868 |
return { ok: false, error: `{${k}} is not a field of this table`, refs: parsed.refs };
|
|
|
|
| 6 |
//
|
| 7 |
// GRAMMAR (v2 β the shared contract; v1 remains a strict subset):
|
| 8 |
// numbers 1 0.5 .5 1200.75 (no separators, no exponents)
|
| 9 |
+
// strings "text" with "" escaping a quote β Excel's own rule.
|
| 10 |
+
// 'text' with '' escaping a quote β the SAME literal, in
|
| 11 |
+
// the spelling Airtable's own docs use for a unit or format
|
| 12 |
+
// argument: DATETIME_DIFF({a}, {b}, 'days'). A formula the
|
| 13 |
+
// user copies out of that documentation must parse.
|
| 14 |
// booleans TRUE FALSE (bare constants)
|
| 15 |
// field refs {revenue_ytd} (slug charset [A-Za-z0-9_])
|
| 16 |
// arithmetic + - * / ^ ( ) (usual precedence; ^ is
|
|
|
|
| 25 |
// logic IF AND OR NOT IFERROR ISBLANK
|
| 26 |
// text CONCATENATE/CONCAT LEFT RIGHT MID LEN TRIM
|
| 27 |
// UPPER LOWER PROPER VALUE TEXT
|
| 28 |
+
// SUBSTITUTE FIND REGEX_EXTRACT REGEX_REPLACE
|
| 29 |
+
// logic SWITCH
|
| 30 |
// date TODAY YEAR MONTH DAY DAYS (ISO YYYY-MM-DD)
|
| 31 |
+
// DATEADD DATETIME_DIFF DATETIME_FORMAT
|
| 32 |
+
//
|
| 33 |
+
// WAVE 42 G7 β REGEX, SUBSTITUTION AND DATE ARITHMETIC. Three notes that are
|
| 34 |
+
// load-bearing rather than decorative:
|
| 35 |
+
//
|
| 36 |
+
// 1. A REGEX PATTERN IS USER INPUT REACHING A REGEX ENGINE. This runs in the
|
| 37 |
+
// tenant's one process, so an unbounded pattern is a denial of service and
|
| 38 |
+
// not merely a slow cell. `safeRegex` below is the ONLY door to `RegExp`:
|
| 39 |
+
// it caps the pattern, caps the SUBJECT (backtracking is exponential in
|
| 40 |
+
// the input, so this cap does more work than any shape test), and refuses
|
| 41 |
+
// the (a+)+ / (a*)* nested-unbounded-quantifier shape outright.
|
| 42 |
+
// 2. A PATTERN MAY NOT CONTAIN `{`. The host's structural validator reads
|
| 43 |
+
// `{...}` as a FIELD REFERENCE wherever it appears, including inside a
|
| 44 |
+
// string, so `"[0-9]{3}"` is refused on save. Refusing it here too means
|
| 45 |
+
// the user gets an error while typing instead of a save that fails later.
|
| 46 |
+
// The cost is that the `\d{4}` idiom is unavailable; `\d\d\d\d` works.
|
| 47 |
+
// 3. DATES ARE CALENDAR DATES. DATEADD/DATETIME_DIFF/DATETIME_FORMAT take and
|
| 48 |
+
// return the ISO day this engine already speaks. Time units (hours,
|
| 49 |
+
// minutes, seconds) are BLANK rather than approximated, and bare 'm' is
|
| 50 |
+
// refused because it means minutes to some readers and months to others.
|
| 51 |
//
|
| 52 |
// THE ONE RULE, unchanged: **any error β BLANK, never a wrong number.** An
|
| 53 |
// unknown ref, a divide-by-zero, a boolean fed to arithmetic, an unreadable
|
|
|
|
| 93 |
export type FormulaFn =
|
| 94 |
| "ABS" | "ROUND" | "ROUNDUP" | "ROUNDDOWN" | "INT" | "MOD" | "SQRT" | "POWER"
|
| 95 |
| "EXP" | "LN" | "SUM" | "AVERAGE" | "COUNT" | "COUNTA" | "MIN" | "MAX"
|
| 96 |
+
| "IF" | "AND" | "OR" | "NOT" | "IFERROR" | "ISBLANK" | "SWITCH"
|
| 97 |
| "CONCATENATE" | "LEFT" | "RIGHT" | "MID" | "LEN" | "TRIM"
|
| 98 |
| "UPPER" | "LOWER" | "PROPER" | "VALUE" | "TEXT"
|
| 99 |
+
| "SUBSTITUTE" | "FIND" | "REGEX_EXTRACT" | "REGEX_REPLACE"
|
| 100 |
+
| "TODAY" | "YEAR" | "MONTH" | "DAY" | "DAYS"
|
| 101 |
+
| "DATEADD" | "DATETIME_DIFF" | "DATETIME_FORMAT";
|
| 102 |
|
| 103 |
const MANY = 30; // variadic cap β bounded, far above any honest use
|
| 104 |
|
|
|
|
| 125 |
NOT: [1, 1],
|
| 126 |
IFERROR: [2, 2],
|
| 127 |
ISBLANK: [1, 1],
|
| 128 |
+
// SWITCH(subject, pattern, result, [pattern, result]β¦, [fallback]) β at least
|
| 129 |
+
// one pair, so three arguments is the floor.
|
| 130 |
+
SWITCH: [3, MANY],
|
| 131 |
CONCATENATE: [1, MANY],
|
| 132 |
LEFT: [1, 2],
|
| 133 |
RIGHT: [1, 2],
|
|
|
|
| 139 |
PROPER: [1, 1],
|
| 140 |
VALUE: [1, 1],
|
| 141 |
TEXT: [2, 2],
|
| 142 |
+
// SUBSTITUTE(text, old, new, [occurrence]) β the 4th argument picks ONE
|
| 143 |
+
// occurrence, 1-based; without it every occurrence is replaced.
|
| 144 |
+
SUBSTITUTE: [3, 4],
|
| 145 |
+
// FIND(stringToFind, whereToSearch, [startFromPosition]) β NEEDLE FIRST.
|
| 146 |
+
FIND: [2, 3],
|
| 147 |
+
REGEX_EXTRACT: [2, 2],
|
| 148 |
+
REGEX_REPLACE: [3, 3],
|
| 149 |
TODAY: [0, 0],
|
| 150 |
YEAR: [1, 1],
|
| 151 |
MONTH: [1, 1],
|
| 152 |
DAY: [1, 1],
|
| 153 |
DAYS: [2, 2],
|
| 154 |
+
// DATEADD(date, count, units) and DATETIME_DIFF(date1, date2, [units]) β
|
| 155 |
+
// Airtable's own order, confirmed against its documentation screenshots.
|
| 156 |
+
DATEADD: [3, 3],
|
| 157 |
+
DATETIME_DIFF: [2, 3],
|
| 158 |
+
DATETIME_FORMAT: [2, 2],
|
| 159 |
};
|
| 160 |
|
| 161 |
/** Excel spells it CONCAT in modern versions; both names, one function. */
|
|
|
|
| 196 |
i = end + 1;
|
| 197 |
continue;
|
| 198 |
}
|
| 199 |
+
// "string" / 'string' β Excel's own escape: a doubled quote is one quote.
|
| 200 |
+
// ONE literal in two spellings: Airtable's documentation writes a unit or a
|
| 201 |
+
// date format in single quotes ('days', 'MM/DD/YYYY') and a user pastes it
|
| 202 |
+
// exactly as printed, so both must parse. A quote of the OTHER kind inside
|
| 203 |
+
// is an ordinary character, which is what makes "it's" and 'say "hi"' work.
|
| 204 |
+
if (c === '"' || c === "'") {
|
| 205 |
+
const q = c;
|
| 206 |
let j = i + 1;
|
| 207 |
let s = "";
|
| 208 |
for (;;) {
|
| 209 |
if (j >= src.length) return "a text value is missing its closing quote";
|
| 210 |
+
if (src[j] === q) {
|
| 211 |
+
if (src[j + 1] === q) {
|
| 212 |
+
s += q;
|
| 213 |
j += 2;
|
| 214 |
continue;
|
| 215 |
}
|
|
|
|
| 402 |
}
|
| 403 |
const fn = (FN_ALIASES[upper] ?? upper) as FormulaFn;
|
| 404 |
if (!(fn in FN_ARITY))
|
| 405 |
+
// β STANDING RULE 2. This message carried an em dash until wave 42; it is
|
| 406 |
+
// user-facing copy, so the sentence is rewritten rather than the character dropped.
|
| 407 |
+
return fail(`${upper} is not a function this engine knows. The formula help lists what is available.`);
|
| 408 |
pos += 1;
|
| 409 |
if (!isOp("(")) return fail(`${fn} must be called with parentheses: ${fn}(β¦)`);
|
| 410 |
pos += 1;
|
|
|
|
| 551 |
return Date.UTC(p.y, p.m - 1, p.d) / 86_400_000;
|
| 552 |
}
|
| 553 |
|
| 554 |
+
// ---------------------------------------------------------------------------
|
| 555 |
+
// WAVE 42 G7 β the bounded regex door.
|
| 556 |
+
// ---------------------------------------------------------------------------
|
| 557 |
+
|
| 558 |
+
/** Longest pattern a formula may hand to the regex engine. */
|
| 559 |
+
export const MAX_REGEX_PATTERN = 200;
|
| 560 |
+
/** Longest subject a pattern may run OVER. Catastrophic backtracking is
|
| 561 |
+
* exponential in the INPUT length, so this cap is the load-bearing one: a
|
| 562 |
+
* pathological pattern over 4 000 characters is slow, over a 100 KB long-text
|
| 563 |
+
* field it is a hung tab. */
|
| 564 |
+
export const MAX_REGEX_SUBJECT = 4_000;
|
| 565 |
+
/** Longest text result a substitution may produce, so a replacement cannot be
|
| 566 |
+
* used to inflate one cell into megabytes. */
|
| 567 |
+
export const MAX_TEXT_RESULT = 20_000;
|
| 568 |
+
|
| 569 |
+
/**
|
| 570 |
+
* The catastrophic shape: a parenthesised group whose body already carries an
|
| 571 |
+
* unbounded quantifier, quantified AGAIN. `(a+)+`, `(a*)*`, `(?:\d+)*` and
|
| 572 |
+
* friends. Matching those against a non-matching subject is exponential.
|
| 573 |
+
*
|
| 574 |
+
* β It is applied ONLY to a pattern, never to whole formula source. `({a} + {b}) * 2`
|
| 575 |
+
* has exactly this character shape and is ordinary arithmetic.
|
| 576 |
+
*/
|
| 577 |
+
const NESTED_QUANT = /\((?:[^()\\]|\\.)*[*+](?:[^()\\]|\\.)*\)\??\s*[*+]/;
|
| 578 |
+
|
| 579 |
+
/** Compiled patterns, so a formula re-evaluated per row per render compiles
|
| 580 |
+
* once rather than once per cell. Bounded, and cleared wholesale when full. */
|
| 581 |
+
const RX_CACHE = new Map<string, RegExp | null>();
|
| 582 |
+
const RX_CACHE_MAX = 200;
|
| 583 |
+
|
| 584 |
+
/**
|
| 585 |
+
* The ONE door to `RegExp` in this engine. Returns null (which is BLANK, the
|
| 586 |
+
* engine's one rule) for anything unbounded, malformed, or carrying `{`.
|
| 587 |
+
*/
|
| 588 |
+
function safeRegex(pattern: string, flags: string): RegExp | null {
|
| 589 |
+
if (typeof pattern !== "string") return null;
|
| 590 |
+
if (pattern === "" || pattern.length > MAX_REGEX_PATTERN) return null;
|
| 591 |
+
// `{` cannot appear: the host reads `{...}` as a field reference wherever it
|
| 592 |
+
// sits, so a pattern containing one is refused on SAVE. Refusing it here
|
| 593 |
+
// keeps both sides saying the same thing.
|
| 594 |
+
if (pattern.includes("{") || pattern.includes("}")) return null;
|
| 595 |
+
if (NESTED_QUANT.test(pattern)) return null;
|
| 596 |
+
// The separator is written as an ESCAPE, not as a literal NUL byte. A raw NUL byte in the
|
| 597 |
+
// source makes every `grep` classify this file as BINARY and skip it silently, which
|
| 598 |
+
// blinds any gate or reader that searches it -- the file is unsearchable, not merely
|
| 599 |
+
// odd. The runtime value is identical; only the source encoding changes.
|
| 600 |
+
const key = flags + "\u0000" + pattern;
|
| 601 |
+
const hit = RX_CACHE.get(key);
|
| 602 |
+
if (hit !== undefined) return hit;
|
| 603 |
+
let rx: RegExp | null = null;
|
| 604 |
+
try {
|
| 605 |
+
rx = new RegExp(pattern, flags);
|
| 606 |
+
} catch {
|
| 607 |
+
rx = null;
|
| 608 |
+
}
|
| 609 |
+
if (RX_CACHE.size >= RX_CACHE_MAX) RX_CACHE.clear();
|
| 610 |
+
RX_CACHE.set(key, rx);
|
| 611 |
+
return rx;
|
| 612 |
+
}
|
| 613 |
+
|
| 614 |
+
// ---------------------------------------------------------------------------
|
| 615 |
+
// WAVE 42 G7 β calendar arithmetic over the ISO day this engine already speaks.
|
| 616 |
+
// ---------------------------------------------------------------------------
|
| 617 |
+
|
| 618 |
+
type DateUnit = "d" | "w" | "M" | "Q" | "y";
|
| 619 |
+
|
| 620 |
+
/**
|
| 621 |
+
* Airtable's unit words, plus the unambiguous single letters. Bare 'm' is
|
| 622 |
+
* ABSENT on purpose: it reads as minutes to one person and months to another,
|
| 623 |
+
* and a date silently off by 30 days is exactly the wrong-number-with-a-
|
| 624 |
+
* confident-face this engine refuses to produce.
|
| 625 |
+
*/
|
| 626 |
+
const DATE_UNITS: Record<string, DateUnit> = {
|
| 627 |
+
day: "d", days: "d", d: "d",
|
| 628 |
+
week: "w", weeks: "w", w: "w",
|
| 629 |
+
month: "M", months: "M",
|
| 630 |
+
quarter: "Q", quarters: "Q", q: "Q",
|
| 631 |
+
year: "y", years: "y", y: "y",
|
| 632 |
+
};
|
| 633 |
+
|
| 634 |
+
function dateUnit(v: Value): DateUnit | null {
|
| 635 |
+
if (typeof v !== "string") return null;
|
| 636 |
+
const k = v.trim().toLowerCase();
|
| 637 |
+
return DATE_UNITS[k] ?? null;
|
| 638 |
+
}
|
| 639 |
+
|
| 640 |
+
function pad(n: number, width: number): string {
|
| 641 |
+
const s = String(Math.abs(n));
|
| 642 |
+
return (n < 0 ? "-" : "") + (s.length >= width ? s : "0".repeat(width - s.length) + s);
|
| 643 |
+
}
|
| 644 |
+
|
| 645 |
+
function isoFromParts(p: { y: number; m: number; d: number }): string {
|
| 646 |
+
return pad(p.y, 4) + "-" + pad(p.m, 2) + "-" + pad(p.d, 2);
|
| 647 |
+
}
|
| 648 |
+
|
| 649 |
+
function daysInMonth(y: number, m: number): number {
|
| 650 |
+
return new Date(Date.UTC(y, m, 0)).getUTCDate();
|
| 651 |
+
}
|
| 652 |
+
|
| 653 |
+
/** Calendar month arithmetic with Excel's clamp: 31 Jan plus one month is the
|
| 654 |
+
* 28th (or 29th) of February, never the 3rd of March. */
|
| 655 |
+
function addMonths(p: { y: number; m: number; d: number }, k: number) {
|
| 656 |
+
const total = p.y * 12 + (p.m - 1) + k;
|
| 657 |
+
const y = Math.floor(total / 12);
|
| 658 |
+
const m = total - y * 12 + 1;
|
| 659 |
+
return { y, m, d: Math.min(p.d, daysInMonth(y, m)) };
|
| 660 |
+
}
|
| 661 |
+
|
| 662 |
+
function partsFromSerial(serial: number) {
|
| 663 |
+
const d = new Date(serial * 86_400_000);
|
| 664 |
+
return { y: d.getUTCFullYear(), m: d.getUTCMonth() + 1, d: d.getUTCDate() };
|
| 665 |
+
}
|
| 666 |
+
|
| 667 |
+
/** Whole months from `b` to `a`, the calendar way: 31 Jan to 28 Feb is 0. */
|
| 668 |
+
function wholeMonths(
|
| 669 |
+
a: { y: number; m: number; d: number },
|
| 670 |
+
b: { y: number; m: number; d: number }
|
| 671 |
+
): number {
|
| 672 |
+
let n = (a.y - b.y) * 12 + (a.m - b.m);
|
| 673 |
+
if (n > 0 && a.d < b.d) n -= 1;
|
| 674 |
+
if (n < 0 && a.d > b.d) n += 1;
|
| 675 |
+
return n;
|
| 676 |
+
}
|
| 677 |
+
|
| 678 |
+
const MONTH_NAMES = [
|
| 679 |
+
"January", "February", "March", "April", "May", "June",
|
| 680 |
+
"July", "August", "September", "October", "November", "December",
|
| 681 |
+
];
|
| 682 |
+
const DAY_NAMES = [
|
| 683 |
+
"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday",
|
| 684 |
+
];
|
| 685 |
+
|
| 686 |
+
/** Longest format string DATETIME_FORMAT will look at. */
|
| 687 |
+
const MAX_DATE_FORMAT = 64;
|
| 688 |
+
|
| 689 |
+
/**
|
| 690 |
+
* DATETIME_FORMAT's token set: YYYY YY MMMM MMM MM M DD D dddd ddd Q, with
|
| 691 |
+
* `[literal]` escaping a run of text. Punctuation passes through. An
|
| 692 |
+
* UNRECOGNISED letter is BLANK, never a guess at what it meant, which is
|
| 693 |
+
* `textFormat`'s convention one function up and the same reason for it.
|
| 694 |
+
*/
|
| 695 |
+
function formatDate(p: { y: number; m: number; d: number }, fmt: string): string | null {
|
| 696 |
+
if (fmt.length === 0 || fmt.length > MAX_DATE_FORMAT) return null;
|
| 697 |
+
const dow = ((Math.round(dateSerial(p)) % 7) + 7 + 4) % 7; // serial 0 was a Thursday
|
| 698 |
+
let out = "";
|
| 699 |
+
let i = 0;
|
| 700 |
+
while (i < fmt.length) {
|
| 701 |
+
const ch = fmt[i];
|
| 702 |
+
if (ch === "[") {
|
| 703 |
+
const end = fmt.indexOf("]", i + 1);
|
| 704 |
+
if (end < 0) return null;
|
| 705 |
+
out += fmt.slice(i + 1, end);
|
| 706 |
+
i = end + 1;
|
| 707 |
+
continue;
|
| 708 |
+
}
|
| 709 |
+
const m = /^(YYYY|YY|MMMM|MMM|MM|M|DDDD|DD|D|dddd|ddd|Q)/.exec(fmt.slice(i));
|
| 710 |
+
if (m) {
|
| 711 |
+
switch (m[0]) {
|
| 712 |
+
case "YYYY": out += pad(p.y, 4); break;
|
| 713 |
+
case "YY": out += pad(p.y % 100, 2); break;
|
| 714 |
+
case "MMMM": out += MONTH_NAMES[p.m - 1]; break;
|
| 715 |
+
case "MMM": out += MONTH_NAMES[p.m - 1].slice(0, 3); break;
|
| 716 |
+
case "MM": out += pad(p.m, 2); break;
|
| 717 |
+
case "M": out += String(p.m); break;
|
| 718 |
+
case "DDDD":
|
| 719 |
+
case "dddd": out += DAY_NAMES[dow]; break;
|
| 720 |
+
case "ddd": out += DAY_NAMES[dow].slice(0, 3); break;
|
| 721 |
+
case "DD": out += pad(p.d, 2); break;
|
| 722 |
+
case "D": out += String(p.d); break;
|
| 723 |
+
case "Q": out += String(Math.floor((p.m - 1) / 3) + 1); break;
|
| 724 |
+
}
|
| 725 |
+
i += m[0].length;
|
| 726 |
+
continue;
|
| 727 |
+
}
|
| 728 |
+
if (/[A-Za-z]/.test(ch)) return null; // an unknown token is blank, not a literal
|
| 729 |
+
out += ch;
|
| 730 |
+
i += 1;
|
| 731 |
+
}
|
| 732 |
+
return out;
|
| 733 |
+
}
|
| 734 |
+
|
| 735 |
/**
|
| 736 |
* TEXT(value, format) β the common Excel number formats, fail-closed:
|
| 737 |
* "0" "0.00" fixed decimals
|
|
|
|
| 940 |
const v = ev(n.args[0]);
|
| 941 |
return v == null || v === "";
|
| 942 |
}
|
| 943 |
+
case "SWITCH": {
|
| 944 |
+
// SWITCH(subject, pattern, result, [pattern, result]β¦, [fallback]).
|
| 945 |
+
// LAZY like IF: only the arm that wins is evaluated, so a guard arm
|
| 946 |
+
// can protect the arithmetic in the arm beside it.
|
| 947 |
+
const subject = ev(n.args[0]);
|
| 948 |
+
let i = 1;
|
| 949 |
+
for (; i + 1 < n.args.length; i += 2) {
|
| 950 |
+
if (switchMatch(subject, ev(n.args[i]))) return ev(n.args[i + 1]);
|
| 951 |
+
}
|
| 952 |
+
// A leftover odd argument is the fallback; without one, blank.
|
| 953 |
+
return i < n.args.length ? ev(n.args[i]) : null;
|
| 954 |
+
}
|
| 955 |
case "CONCATENATE":
|
| 956 |
return n.args.map((a) => asText(ev(a))).join("");
|
| 957 |
case "LEFT":
|
|
|
|
| 993 |
if (v == null || typeof fmt !== "string") return null;
|
| 994 |
return textFormat(v, fmt);
|
| 995 |
}
|
| 996 |
+
case "SUBSTITUTE": {
|
| 997 |
+
// SUBSTITUTE(text, oldText, newText, [occurrence]) β plain text, no
|
| 998 |
+
// pattern, so nothing here reaches the regex engine.
|
| 999 |
+
const s = asText(ev(n.args[0]));
|
| 1000 |
+
const oldText = asText(ev(n.args[1]));
|
| 1001 |
+
const newText = asText(ev(n.args[2]));
|
| 1002 |
+
if (oldText === "") return s; // replacing nothing is the identity
|
| 1003 |
+
let out: string = s;
|
| 1004 |
+
if (n.args.length > 3) {
|
| 1005 |
+
const k = asNumber(ev(n.args[3]));
|
| 1006 |
+
if (k == null || !Number.isInteger(k) || k < 1) return null;
|
| 1007 |
+
let from = 0;
|
| 1008 |
+
let seen = 0;
|
| 1009 |
+
for (;;) {
|
| 1010 |
+
const at = s.indexOf(oldText, from);
|
| 1011 |
+
if (at < 0) return s; // fewer than k occurrences: unchanged
|
| 1012 |
+
seen += 1;
|
| 1013 |
+
if (seen === k) {
|
| 1014 |
+
out = s.slice(0, at) + newText + s.slice(at + oldText.length);
|
| 1015 |
+
break;
|
| 1016 |
+
}
|
| 1017 |
+
from = at + oldText.length;
|
| 1018 |
+
}
|
| 1019 |
+
} else {
|
| 1020 |
+
out = s.split(oldText).join(newText);
|
| 1021 |
+
}
|
| 1022 |
+
return out.length > MAX_TEXT_RESULT ? null : out;
|
| 1023 |
+
}
|
| 1024 |
+
case "FIND": {
|
| 1025 |
+
// FIND(stringToFind, whereToSearch, [startFromPosition]) β NEEDLE
|
| 1026 |
+
// FIRST, 1-based, and 0 (not blank) when it is not there, because
|
| 1027 |
+
// "absent" is an answer and callers test it with = 0.
|
| 1028 |
+
// Case-SENSITIVE, as FIND is in both Excel and Airtable.
|
| 1029 |
+
const needle = asText(ev(n.args[0]));
|
| 1030 |
+
const hay = asText(ev(n.args[1]));
|
| 1031 |
+
let start = 1;
|
| 1032 |
+
if (n.args.length > 2) {
|
| 1033 |
+
const k = asNumber(ev(n.args[2]));
|
| 1034 |
+
if (k == null || !Number.isInteger(k) || k < 1) return null;
|
| 1035 |
+
start = k;
|
| 1036 |
+
}
|
| 1037 |
+
const at = hay.indexOf(needle, start - 1);
|
| 1038 |
+
return at < 0 ? 0 : at + 1;
|
| 1039 |
+
}
|
| 1040 |
+
case "REGEX_EXTRACT": {
|
| 1041 |
+
// REGEX_EXTRACT(text, pattern) -> the FIRST WHOLE MATCH, blank when
|
| 1042 |
+
// the pattern does not match. (Airtable returns the whole match, not
|
| 1043 |
+
// a capture group; a group is still useful for grouping alternation.)
|
| 1044 |
+
const s = asText(ev(n.args[0]));
|
| 1045 |
+
const pat = ev(n.args[1]);
|
| 1046 |
+
if (typeof pat !== "string" || s.length > MAX_REGEX_SUBJECT) return null;
|
| 1047 |
+
const rx = safeRegex(pat, "");
|
| 1048 |
+
if (!rx) return null;
|
| 1049 |
+
const m = rx.exec(s);
|
| 1050 |
+
return m ? m[0] : null;
|
| 1051 |
+
}
|
| 1052 |
+
case "REGEX_REPLACE": {
|
| 1053 |
+
// REGEX_REPLACE(text, pattern, replacement) -> EVERY match replaced.
|
| 1054 |
+
const s = asText(ev(n.args[0]));
|
| 1055 |
+
const pat = ev(n.args[1]);
|
| 1056 |
+
const rep = asText(ev(n.args[2]));
|
| 1057 |
+
if (typeof pat !== "string" || s.length > MAX_REGEX_SUBJECT) return null;
|
| 1058 |
+
if (rep.length > MAX_REGEX_PATTERN) return null;
|
| 1059 |
+
const rx = safeRegex(pat, "g");
|
| 1060 |
+
if (!rx) return null;
|
| 1061 |
+
rx.lastIndex = 0; // a cached /g/ regex carries state between calls
|
| 1062 |
+
const out = s.replace(rx, rep);
|
| 1063 |
+
return out.length > MAX_TEXT_RESULT ? null : out;
|
| 1064 |
+
}
|
| 1065 |
case "TODAY":
|
| 1066 |
return typeof env.today === "string" && dateParts(env.today) ? env.today : null;
|
| 1067 |
case "YEAR":
|
|
|
|
| 1078 |
if (!end || !start) return null;
|
| 1079 |
return Math.round(dateSerial(end) - dateSerial(start));
|
| 1080 |
}
|
| 1081 |
+
case "DATEADD": {
|
| 1082 |
+
// DATEADD(date, count, units) -> the ISO day, shifted. Airtable's own
|
| 1083 |
+
// argument order, read off its documentation.
|
| 1084 |
+
const p = dateParts(ev(n.args[0]));
|
| 1085 |
+
const count = asNumber(ev(n.args[1]));
|
| 1086 |
+
const unit = dateUnit(ev(n.args[2]));
|
| 1087 |
+
if (!p || count == null || !unit) return null;
|
| 1088 |
+
const k = Math.trunc(count);
|
| 1089 |
+
if (!Number.isFinite(k) || Math.abs(k) > 1_000_000) return null;
|
| 1090 |
+
if (unit === "M") return isoFromParts(addMonths(p, k));
|
| 1091 |
+
if (unit === "Q") return isoFromParts(addMonths(p, k * 3));
|
| 1092 |
+
if (unit === "y") return isoFromParts(addMonths(p, k * 12));
|
| 1093 |
+
const shifted = dateSerial(p) + (unit === "w" ? k * 7 : k);
|
| 1094 |
+
if (!Number.isFinite(shifted) || Math.abs(shifted) > 3_000_000) return null;
|
| 1095 |
+
return isoFromParts(partsFromSerial(shifted));
|
| 1096 |
+
}
|
| 1097 |
+
case "DATETIME_DIFF": {
|
| 1098 |
+
// DATETIME_DIFF(date1, date2, [units]) = date1 MINUS date2, so a due
|
| 1099 |
+
// date ahead of a start date is POSITIVE. Units default to days.
|
| 1100 |
+
// Truncated toward zero: a part-week is not a week.
|
| 1101 |
+
const a = dateParts(ev(n.args[0]));
|
| 1102 |
+
const b = dateParts(ev(n.args[1]));
|
| 1103 |
+
if (!a || !b) return null;
|
| 1104 |
+
const unit = n.args.length > 2 ? dateUnit(ev(n.args[2])) : "d";
|
| 1105 |
+
if (!unit) return null;
|
| 1106 |
+
const days = Math.round(dateSerial(a) - dateSerial(b));
|
| 1107 |
+
if (unit === "d") return days;
|
| 1108 |
+
if (unit === "w") return Math.trunc(days / 7);
|
| 1109 |
+
const months = wholeMonths(a, b);
|
| 1110 |
+
if (unit === "M") return months;
|
| 1111 |
+
if (unit === "Q") return Math.trunc(months / 3);
|
| 1112 |
+
return Math.trunc(months / 12);
|
| 1113 |
+
}
|
| 1114 |
+
case "DATETIME_FORMAT": {
|
| 1115 |
+
// DATETIME_FORMAT(date, format) -> text in the caller's spelling.
|
| 1116 |
+
const p = dateParts(ev(n.args[0]));
|
| 1117 |
+
const fmt = ev(n.args[1]);
|
| 1118 |
+
if (!p || typeof fmt !== "string") return null;
|
| 1119 |
+
return formatDate(p, fmt);
|
| 1120 |
+
}
|
| 1121 |
}
|
| 1122 |
return null;
|
| 1123 |
}
|
|
|
|
| 1126 |
}
|
| 1127 |
}
|
| 1128 |
|
| 1129 |
+
/**
|
| 1130 |
+
* SWITCH's arm test. It follows the engine's OWN equality rather than inventing
|
| 1131 |
+
* a second one: numbers (and numeric text) compare numerically, text compares
|
| 1132 |
+
* case-insensitively after trimming, and blank matches blank. A mixed pair does
|
| 1133 |
+
* NOT match, so it simply falls through to the next arm or the fallback.
|
| 1134 |
+
*/
|
| 1135 |
+
function switchMatch(subject: Value, pattern: Value): boolean {
|
| 1136 |
+
if (subject == null || subject === "") return pattern == null || pattern === "";
|
| 1137 |
+
if (pattern == null || pattern === "") return false;
|
| 1138 |
+
if (typeof subject === "boolean" || typeof pattern === "boolean")
|
| 1139 |
+
return subject === pattern;
|
| 1140 |
+
const a = asNumber(subject);
|
| 1141 |
+
const b = asNumber(pattern);
|
| 1142 |
+
if (a != null && b != null) return a === b;
|
| 1143 |
+
if (typeof subject === "string" && typeof pattern === "string")
|
| 1144 |
+
return subject.trim().toLowerCase() === pattern.trim().toLowerCase();
|
| 1145 |
+
return false;
|
| 1146 |
+
}
|
| 1147 |
+
|
| 1148 |
function cmpNums(op: "<" | "<=" | ">" | ">=" | "=" | "!=", l: number, r: number): boolean {
|
| 1149 |
switch (op) {
|
| 1150 |
case "<": return l < r;
|
|
|
|
| 1226 |
* can walk the graph; `selfKey` names the field being edited (absent on
|
| 1227 |
* create, where no cycle is possible yet).
|
| 1228 |
*/
|
| 1229 |
+
/**
|
| 1230 |
+
* ββ THE COMPOSITE HOLE, closed at AUTHORING time (wave 42 G7).
|
| 1231 |
+
*
|
| 1232 |
+
* A pattern this engine refuses at EVALUATION time is still a formula that parses, and the
|
| 1233 |
+
* host's wall is structural, so `REGEX_EXTRACT({notes}, "[0-9]{3}")` SAVES and then reads
|
| 1234 |
+
* blank forever with nothing going red. That is this ticket's own scar wearing the other
|
| 1235 |
+
* face: last time a legal formula could not be stored, this time an unusable one can.
|
| 1236 |
+
*
|
| 1237 |
+
* So a pattern written as a LITERAL is put through `safeRegex` here, where the author is
|
| 1238 |
+
* still looking at it. A pattern assembled at run time cannot be judged from the tree and
|
| 1239 |
+
* degrades to blank, which is the engine's one rule and the honest answer.
|
| 1240 |
+
*/
|
| 1241 |
+
function badPattern(ast: FormulaAst): string | null {
|
| 1242 |
+
let problem: string | null = null;
|
| 1243 |
+
const walk = (n: FormulaAst): void => {
|
| 1244 |
+
if (problem) return;
|
| 1245 |
+
switch (n.t) {
|
| 1246 |
+
case "neg":
|
| 1247 |
+
walk(n.e);
|
| 1248 |
+
return;
|
| 1249 |
+
case "bin":
|
| 1250 |
+
case "cmp":
|
| 1251 |
+
walk(n.l);
|
| 1252 |
+
walk(n.r);
|
| 1253 |
+
return;
|
| 1254 |
+
case "call": {
|
| 1255 |
+
if (n.fn === "REGEX_EXTRACT" || n.fn === "REGEX_REPLACE") {
|
| 1256 |
+
const p = n.args[1];
|
| 1257 |
+
if (p && p.t === "str") {
|
| 1258 |
+
if (p.v.includes("{") || p.v.includes("}"))
|
| 1259 |
+
problem =
|
| 1260 |
+
"a search pattern cannot contain { or }, because a formula reads those as a " +
|
| 1261 |
+
"field name. Write \\d\\d\\d rather than \\d{3}.";
|
| 1262 |
+
else if (p.v === "" || p.v.length > MAX_REGEX_PATTERN)
|
| 1263 |
+
problem = `a search pattern must be 1 to ${MAX_REGEX_PATTERN} characters long`;
|
| 1264 |
+
else if (safeRegex(p.v, "") === null)
|
| 1265 |
+
problem =
|
| 1266 |
+
"that search pattern is either not valid or could run for an unbounded time. " +
|
| 1267 |
+
"A repeat inside a repeated group, such as (a+)+, is refused.";
|
| 1268 |
+
}
|
| 1269 |
+
}
|
| 1270 |
+
n.args.forEach(walk);
|
| 1271 |
+
return;
|
| 1272 |
+
}
|
| 1273 |
+
default:
|
| 1274 |
+
return;
|
| 1275 |
+
}
|
| 1276 |
+
};
|
| 1277 |
+
walk(ast);
|
| 1278 |
+
return problem;
|
| 1279 |
+
}
|
| 1280 |
+
|
| 1281 |
export function validateFormula(
|
| 1282 |
src: string,
|
| 1283 |
knownKeys: ReadonlySet<string>,
|
|
|
|
| 1286 |
): { ok: boolean; error?: string; refs: string[] } {
|
| 1287 |
const parsed = parseFormula(src);
|
| 1288 |
if (!parsed.ok) return { ok: false, error: parsed.error, refs: [] };
|
| 1289 |
+
const patternError = badPattern(parsed.ast);
|
| 1290 |
+
if (patternError) return { ok: false, error: patternError, refs: parsed.refs };
|
| 1291 |
for (const k of parsed.refs) {
|
| 1292 |
if (!knownKeys.has(k) && !formulaSources.has(k))
|
| 1293 |
return { ok: false, error: `{${k}} is not a field of this table`, refs: parsed.refs };
|
web/src/customer-grid/map.css
CHANGED
|
@@ -250,51 +250,76 @@
|
|
| 250 |
.cg-w44-route-select:focus-visible, .cg-w44-route-detail:focus-visible, .cg-w44-route-back:focus-visible, .cg-w44-route-stops button:focus-visible { outline: 2px solid var(--lp-blue-deep); outline-offset: 2px; }
|
| 251 |
.cg-w44-route-empty { margin: 0; color: var(--lp-muted); }
|
| 252 |
.cg-w44-route-stops { display: grid; gap: 4px; margin: 0; padding-left: 20px; }
|
| 253 |
-
.cg-w44-route-stops li { display:
|
| 254 |
-
.cg-w44-route-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 255 |
.cg-w44-route-label, .cg-w44-route-sources { display: grid; gap: 4px; min-width: 0; color: var(--cg-text); font: 500 var(--lp-fs-3xs)/1.4 Inter, system-ui, sans-serif; }
|
| 256 |
.cg-w44-route-sources { margin: 0; padding: 6px; border: 1px solid var(--lp-line); border-radius: var(--lp-r-sm); }
|
| 257 |
.cg-w44-route-sources label { display: flex; gap: 5px; align-items: center; }
|
| 258 |
.cg-w44-route-stops button, .cg-w44-route-back, .cg-w44-route-maps { color: var(--lp-blue-deep); }
|
| 259 |
.cg-w44-route-warning { color: var(--lp-yellow-deep); font: 500 var(--lp-fs-3xs)/1.4 Inter, system-ui, sans-serif; }
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 260 |
|
| 261 |
.cg-map-zones {
|
| 262 |
-
display:
|
| 263 |
-
align-items:
|
| 264 |
-
|
| 265 |
-
gap: 6px;
|
| 266 |
width: 100%;
|
| 267 |
-
padding-top:
|
| 268 |
-
border-top: 1px solid var(--lp-line);
|
| 269 |
}
|
| 270 |
|
| 271 |
.cg-map-zone-control {
|
| 272 |
-
display:
|
| 273 |
-
flex: 0 1 160px;
|
| 274 |
-
flex-direction: column;
|
| 275 |
gap: 3px;
|
| 276 |
color: var(--lp-muted);
|
| 277 |
font: 500 var(--lp-fs-3xs)/1.35 Inter, system-ui, sans-serif;
|
| 278 |
}
|
| 279 |
|
| 280 |
-
.cg-map-zone-chooser {
|
| 281 |
-
position: relative;
|
| 282 |
-
}
|
| 283 |
-
|
| 284 |
.cg-map-zone-choices {
|
| 285 |
-
position: absolute;
|
| 286 |
-
z-index: 4;
|
| 287 |
-
top: calc(100% + 4px);
|
| 288 |
-
left: 0;
|
| 289 |
display: grid;
|
| 290 |
-
width:
|
| 291 |
max-height: 248px;
|
| 292 |
overflow-y: auto;
|
| 293 |
padding: 5px;
|
| 294 |
border: 1px solid var(--lp-line);
|
| 295 |
-
border-radius:
|
| 296 |
-
background: var(--lp-
|
| 297 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 298 |
}
|
| 299 |
|
| 300 |
.cg-map-zone-choice {
|
|
@@ -310,9 +335,23 @@
|
|
| 310 |
font: 500 var(--lp-fs-2xs)/1.35 Inter, system-ui, sans-serif;
|
| 311 |
}
|
| 312 |
|
| 313 |
-
.cg-map-zone-choice:hover { background: var(--lp-
|
| 314 |
|
| 315 |
.cg-map-zone-choice input { margin: 0; }
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 316 |
|
| 317 |
.cg-map-zone-swatch {
|
| 318 |
width: 9px;
|
|
@@ -327,6 +366,8 @@
|
|
| 327 |
font: 400 var(--lp-fs-2xs)/1.35 Inter, system-ui, sans-serif;
|
| 328 |
}
|
| 329 |
|
|
|
|
|
|
|
| 330 |
/* --- the address lookup (T37) ---------------------------------------------
|
| 331 |
*
|
| 332 |
* β THE PROGRESS LINE IS A REQUIREMENT, NOT A COURTESY. The free geocoder allows about one
|
|
|
|
| 250 |
.cg-w44-route-select:focus-visible, .cg-w44-route-detail:focus-visible, .cg-w44-route-back:focus-visible, .cg-w44-route-stops button:focus-visible { outline: 2px solid var(--lp-blue-deep); outline-offset: 2px; }
|
| 251 |
.cg-w44-route-empty { margin: 0; color: var(--lp-muted); }
|
| 252 |
.cg-w44-route-stops { display: grid; gap: 4px; margin: 0; padding-left: 20px; }
|
| 253 |
+
.cg-w44-route-stops li { display: grid; grid-template-columns: minmax(0, 1fr) auto; align-items: center; gap: 4px 8px; }
|
| 254 |
+
.cg-w44-route-stop-open { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
| 255 |
+
.cg-w44-route-stop-actions { display: inline-flex; align-items: flex-end; gap: 4px; }
|
| 256 |
+
.cg-w44-route-outside { grid-column: 1 / -1; color: var(--lp-muted); font: 500 var(--lp-fs-3xs)/1.4 Inter, system-ui, sans-serif; }
|
| 257 |
+
.cg-w44-route-position { display: grid; gap: 2px; color: var(--lp-muted); font-size: var(--lp-fs-3xs); }
|
| 258 |
+
.cg-w44-route-order { box-sizing: border-box; width: 46px; height: 28px; padding: 3px 5px; border: 1px solid var(--lp-line); border-radius: var(--lp-r-sm); background: var(--cg-white); color: inherit; font: inherit; text-align: center; }
|
| 259 |
+
.cg-w44-route-order:focus-visible { outline: 2px solid var(--lp-blue-deep); outline-offset: 1px; }
|
| 260 |
+
.cg-w44-route-order:disabled { opacity: 0.55; cursor: not-allowed; }
|
| 261 |
+
.cg-w44-route-step, .cg-w44-route-position-apply { min-height: 28px; border-radius: var(--lp-r-sm); }
|
| 262 |
+
.cg-w44-route-step { display: grid; width: 28px; padding: 5px; place-items: center; }
|
| 263 |
+
.cg-w44-route-step svg { width: 14px; height: 14px; fill: none; stroke: currentColor; stroke-linecap: round; stroke-linejoin: round; stroke-width: 1.6; }
|
| 264 |
+
.cg-w44-route-position-apply { padding: 4px 6px; }
|
| 265 |
+
.cg-w44-route-step:hover:not(:disabled), .cg-w44-route-position-apply:hover:not(:disabled) { background: var(--lp-blue-tint); }
|
| 266 |
+
.cg-w44-route-step:disabled, .cg-w44-route-position-apply:disabled { opacity: 0.55; cursor: not-allowed; }
|
| 267 |
+
.cg-w44-route-order-error { grid-column: 1 / -1; color: var(--lp-red-deep); font: 500 var(--lp-fs-3xs)/1.4 Inter, system-ui, sans-serif; }
|
| 268 |
.cg-w44-route-label, .cg-w44-route-sources { display: grid; gap: 4px; min-width: 0; color: var(--cg-text); font: 500 var(--lp-fs-3xs)/1.4 Inter, system-ui, sans-serif; }
|
| 269 |
.cg-w44-route-sources { margin: 0; padding: 6px; border: 1px solid var(--lp-line); border-radius: var(--lp-r-sm); }
|
| 270 |
.cg-w44-route-sources label { display: flex; gap: 5px; align-items: center; }
|
| 271 |
.cg-w44-route-stops button, .cg-w44-route-back, .cg-w44-route-maps { color: var(--lp-blue-deep); }
|
| 272 |
.cg-w44-route-warning { color: var(--lp-yellow-deep); font: 500 var(--lp-fs-3xs)/1.4 Inter, system-ui, sans-serif; }
|
| 273 |
+
.cg-w44-route-edit, .cg-w44-route-prompt { display: grid; gap: 7px; padding-top: 8px; border-top: 1px solid var(--lp-line); }
|
| 274 |
+
.cg-w44-route-prompt p { margin: 0; color: var(--cg-text); font: 500 var(--lp-fs-2xs)/1.4 Inter, system-ui, sans-serif; }
|
| 275 |
+
|
| 276 |
+
.cg-map-zone-trigger {
|
| 277 |
+
display: inline-flex;
|
| 278 |
+
align-items: center;
|
| 279 |
+
gap: 5px;
|
| 280 |
+
}
|
| 281 |
+
|
| 282 |
+
.cg-map-zone-trigger svg {
|
| 283 |
+
width: 12px;
|
| 284 |
+
height: 8px;
|
| 285 |
+
fill: none;
|
| 286 |
+
stroke: currentColor;
|
| 287 |
+
stroke-width: 1.5;
|
| 288 |
+
stroke-linecap: round;
|
| 289 |
+
stroke-linejoin: round;
|
| 290 |
+
}
|
| 291 |
|
| 292 |
.cg-map-zones {
|
| 293 |
+
display: grid;
|
| 294 |
+
align-items: stretch;
|
| 295 |
+
gap: 8px;
|
|
|
|
| 296 |
width: 100%;
|
| 297 |
+
padding-top: 8px;
|
|
|
|
| 298 |
}
|
| 299 |
|
| 300 |
.cg-map-zone-control {
|
| 301 |
+
display: grid;
|
|
|
|
|
|
|
| 302 |
gap: 3px;
|
| 303 |
color: var(--lp-muted);
|
| 304 |
font: 500 var(--lp-fs-3xs)/1.35 Inter, system-ui, sans-serif;
|
| 305 |
}
|
| 306 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 307 |
.cg-map-zone-choices {
|
|
|
|
|
|
|
|
|
|
|
|
|
| 308 |
display: grid;
|
| 309 |
+
width: 100%;
|
| 310 |
max-height: 248px;
|
| 311 |
overflow-y: auto;
|
| 312 |
padding: 5px;
|
| 313 |
border: 1px solid var(--lp-line);
|
| 314 |
+
border-radius: var(--lp-r-sm);
|
| 315 |
+
background: var(--lp-surface);
|
| 316 |
+
}
|
| 317 |
+
|
| 318 |
+
.cg-map-zone-option {
|
| 319 |
+
display: grid;
|
| 320 |
+
grid-template-columns: minmax(0, 1fr) auto;
|
| 321 |
+
align-items: center;
|
| 322 |
+
gap: 6px;
|
| 323 |
}
|
| 324 |
|
| 325 |
.cg-map-zone-choice {
|
|
|
|
| 335 |
font: 500 var(--lp-fs-2xs)/1.35 Inter, system-ui, sans-serif;
|
| 336 |
}
|
| 337 |
|
| 338 |
+
.cg-map-zone-choice:hover { background: var(--lp-surface-2); }
|
| 339 |
|
| 340 |
.cg-map-zone-choice input { margin: 0; }
|
| 341 |
+
.cg-map-zone-choice input:disabled { cursor: not-allowed; opacity: 0.45; }
|
| 342 |
+
|
| 343 |
+
.cg-map-zone-edit {
|
| 344 |
+
border: 0;
|
| 345 |
+
background: transparent;
|
| 346 |
+
font: inherit;
|
| 347 |
+
color: var(--lp-blue-deep);
|
| 348 |
+
cursor: pointer;
|
| 349 |
+
padding: 4px 6px;
|
| 350 |
+
border-radius: var(--lp-r-sm);
|
| 351 |
+
}
|
| 352 |
+
|
| 353 |
+
.cg-map-zone-edit:hover { background: var(--lp-blue-tint); }
|
| 354 |
+
.cg-map-zone-edit:focus-visible { outline: 2px solid var(--lp-blue-deep); outline-offset: 2px; }
|
| 355 |
|
| 356 |
.cg-map-zone-swatch {
|
| 357 |
width: 9px;
|
|
|
|
| 366 |
font: 400 var(--lp-fs-2xs)/1.35 Inter, system-ui, sans-serif;
|
| 367 |
}
|
| 368 |
|
| 369 |
+
.cg-map-zone-editor .cg-btn { justify-self: start; }
|
| 370 |
+
|
| 371 |
/* --- the address lookup (T37) ---------------------------------------------
|
| 372 |
*
|
| 373 |
* β THE PROGRESS LINE IS A REQUIREMENT, NOT A COURTESY. The free geocoder allows about one
|
web/src/customer-grid/navFold.ts
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import type { PointerEvent as ReactPointerEvent } from "react";
|
| 2 |
+
|
| 3 |
+
import { NAV_MINIMIZE_EVENT, signal } from "../apiContract";
|
| 4 |
+
|
| 5 |
+
type WorkSurfacePointer = Pick<
|
| 6 |
+
ReactPointerEvent<HTMLElement>,
|
| 7 |
+
"button" | "detail" | "isPrimary"
|
| 8 |
+
>;
|
| 9 |
+
|
| 10 |
+
/** Fold the global rail when the primary pointer enters a view's body. */
|
| 11 |
+
export function foldNavOnWorkSurface(event: WorkSurfacePointer): void {
|
| 12 |
+
if (event.button !== 0 || event.isPrimary === false || event.detail > 1) return;
|
| 13 |
+
signal(NAV_MINIMIZE_EVENT);
|
| 14 |
+
}
|
| 15 |
+
|
| 16 |
+
/** Grid uses a cell callback rather than a rendered host element. */
|
| 17 |
+
export function foldGridCell(): void {
|
| 18 |
+
signal(NAV_MINIMIZE_EVENT);
|
| 19 |
+
}
|
web/src/customer-grid/routeLinks.ts
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { googleRouteUrls, isPlottable } from "./mapProjection";
|
| 2 |
+
|
| 3 |
+
export interface LocatedRouteStop {
|
| 4 |
+
pid: number;
|
| 5 |
+
lat: number;
|
| 6 |
+
lon: number;
|
| 7 |
+
}
|
| 8 |
+
|
| 9 |
+
export interface NormalizedRouteMapLink {
|
| 10 |
+
url: string;
|
| 11 |
+
index: number;
|
| 12 |
+
start: number;
|
| 13 |
+
end: number;
|
| 14 |
+
stopIds: number[];
|
| 15 |
+
}
|
| 16 |
+
|
| 17 |
+
export interface NormalizedRouteMapLinks {
|
| 18 |
+
links: NormalizedRouteMapLink[];
|
| 19 |
+
missingStopIds: number[];
|
| 20 |
+
refusal: string | null;
|
| 21 |
+
}
|
| 22 |
+
|
| 23 |
+
/** Build bounded Maps links from the server-ordered, already-authorized Route stop ids.
|
| 24 |
+
* A missing coordinate refuses the whole hand-off rather than quietly omitting that customer. */
|
| 25 |
+
export function normalizedRouteMapLinks(
|
| 26 |
+
orderedStopIds: readonly number[],
|
| 27 |
+
locatedStops: readonly LocatedRouteStop[],
|
| 28 |
+
coarsePointer = false,
|
| 29 |
+
): NormalizedRouteMapLinks {
|
| 30 |
+
const byPid = new Map(locatedStops
|
| 31 |
+
.filter((stop) => Number.isSafeInteger(stop.pid) && isPlottable(stop.lat, stop.lon))
|
| 32 |
+
.map((stop) => [stop.pid, stop]));
|
| 33 |
+
const missingStopIds = orderedStopIds.filter((pid) => !byPid.has(pid));
|
| 34 |
+
if (missingStopIds.length) return { links: [], missingStopIds, refusal: null };
|
| 35 |
+
if (orderedStopIds.length < 2) return {
|
| 36 |
+
links: [], missingStopIds: [], refusal: "Add at least two located stops to open this Route in Maps.",
|
| 37 |
+
};
|
| 38 |
+
|
| 39 |
+
const ordered = orderedStopIds.map((pid) => byPid.get(pid)!);
|
| 40 |
+
const links = googleRouteUrls(ordered, { coarsePointer, maxStops: 10 }).map((link) => ({
|
| 41 |
+
...link,
|
| 42 |
+
stopIds: ordered.slice(link.start, link.end).map((stop) => stop.pid),
|
| 43 |
+
}));
|
| 44 |
+
const covered = links.flatMap((link, index) => index ? link.stopIds.slice(1) : link.stopIds);
|
| 45 |
+
const complete = links.length > 0
|
| 46 |
+
&& links.every((link) => link.stopIds.length >= 2 && link.stopIds.length <= 10)
|
| 47 |
+
&& JSON.stringify(covered) === JSON.stringify(orderedStopIds);
|
| 48 |
+
return complete
|
| 49 |
+
? { links, missingStopIds: [], refusal: null }
|
| 50 |
+
: { links: [], missingStopIds: [],
|
| 51 |
+
refusal: "The Maps links could not include every Route stop in order." };
|
| 52 |
+
}
|
web/src/customer-grid/routeStopMove.ts
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import type { MapRouteDto } from "./routeZoneTypes";
|
| 2 |
+
|
| 3 |
+
export type RouteStopMoveFailure =
|
| 4 |
+
| "blank"
|
| 5 |
+
| "not-integer"
|
| 6 |
+
| "out-of-range"
|
| 7 |
+
| "invalid-route"
|
| 8 |
+
| "duplicate-route"
|
| 9 |
+
| "missing-stop";
|
| 10 |
+
|
| 11 |
+
export type RouteStopMovePlan =
|
| 12 |
+
| {
|
| 13 |
+
ok: true;
|
| 14 |
+
changed: boolean;
|
| 15 |
+
target: number;
|
| 16 |
+
orderedStopIds: number[];
|
| 17 |
+
positions: number[];
|
| 18 |
+
}
|
| 19 |
+
| { ok: false; code: RouteStopMoveFailure; message: string };
|
| 20 |
+
|
| 21 |
+
/**
|
| 22 |
+
* Turn raw input into one normalized move. The raw value never reaches the request callback.
|
| 23 |
+
* A valid plan also carries the complete dense permutation the server is expected to persist.
|
| 24 |
+
*/
|
| 25 |
+
export function routeStopMovePlan(
|
| 26 |
+
stopIds: readonly number[], customerPid: number, raw: string
|
| 27 |
+
): RouteStopMovePlan {
|
| 28 |
+
const ids = [...stopIds];
|
| 29 |
+
if (ids.some((pid) => !Number.isSafeInteger(pid) || pid <= 0)) {
|
| 30 |
+
return { ok: false, code: "invalid-route",
|
| 31 |
+
message: "This Route has an invalid stop, so its order cannot be changed." };
|
| 32 |
+
}
|
| 33 |
+
if (new Set(ids).size !== ids.length) {
|
| 34 |
+
return { ok: false, code: "duplicate-route",
|
| 35 |
+
message: "This Route has duplicate stops, so its order cannot be changed." };
|
| 36 |
+
}
|
| 37 |
+
const current = ids.indexOf(customerPid);
|
| 38 |
+
if (current < 0) {
|
| 39 |
+
return { ok: false, code: "missing-stop",
|
| 40 |
+
message: "This stop is no longer in the Route." };
|
| 41 |
+
}
|
| 42 |
+
const text = raw.trim();
|
| 43 |
+
if (!text) {
|
| 44 |
+
return { ok: false, code: "blank",
|
| 45 |
+
message: "Enter a whole-number position before moving this stop." };
|
| 46 |
+
}
|
| 47 |
+
if (!/^[0-9]+$/.test(text)) {
|
| 48 |
+
return { ok: false, code: "not-integer", message: "A position must be a whole number." };
|
| 49 |
+
}
|
| 50 |
+
const target = Number(text);
|
| 51 |
+
if (!Number.isSafeInteger(target) || target < 1 || target > ids.length) {
|
| 52 |
+
return { ok: false, code: "out-of-range",
|
| 53 |
+
message: `Choose a position from 1 to ${ids.length}.` };
|
| 54 |
+
}
|
| 55 |
+
const orderedStopIds = [...ids];
|
| 56 |
+
orderedStopIds.splice(target - 1, 0, orderedStopIds.splice(current, 1)[0]);
|
| 57 |
+
const positions = orderedStopIds.map((_pid, index) => index + 1);
|
| 58 |
+
if (orderedStopIds.length !== ids.length || new Set(orderedStopIds).size !== ids.length ||
|
| 59 |
+
positions.some((position, index) => position !== index + 1)) {
|
| 60 |
+
return { ok: false, code: "duplicate-route",
|
| 61 |
+
message: "This Route could not preserve one position per stop." };
|
| 62 |
+
}
|
| 63 |
+
return {
|
| 64 |
+
ok: true,
|
| 65 |
+
changed: target !== current + 1,
|
| 66 |
+
target,
|
| 67 |
+
orderedStopIds,
|
| 68 |
+
positions,
|
| 69 |
+
};
|
| 70 |
+
}
|
| 71 |
+
|
| 72 |
+
/**
|
| 73 |
+
* The one submission door used by typed positions and Earlier/Later arrows. Invalid input and a
|
| 74 |
+
* no-op return before `move`, which is the caller's normalized network endpoint.
|
| 75 |
+
*/
|
| 76 |
+
export async function submitRouteStopMove(
|
| 77 |
+
route: MapRouteDto,
|
| 78 |
+
customerPid: number,
|
| 79 |
+
raw: string,
|
| 80 |
+
move: (route: MapRouteDto, customerPid: number, order: number) => Promise<string | null>,
|
| 81 |
+
): Promise<{ error: string | null; moved: boolean }> {
|
| 82 |
+
const plan = routeStopMovePlan(route.visibleStopIds, customerPid, raw);
|
| 83 |
+
if (!plan.ok) return { error: plan.message, moved: false };
|
| 84 |
+
if (!plan.changed) return { error: null, moved: false };
|
| 85 |
+
const error = await move(route, customerPid, plan.target);
|
| 86 |
+
return { error, moved: error === null };
|
| 87 |
+
}
|
web/src/customer-grid/routeZoneApi.ts
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import type { RouteDeliveryDto, RouteDeliveryRequest } from "./routeZoneTypes";
|
| 2 |
+
|
| 3 |
+
export const CUSTOMER_ZONE_TABLE = "customer_data";
|
| 4 |
+
|
| 5 |
+
export function usesNormalizedCustomerZones(tableKey: string): boolean {
|
| 6 |
+
return tableKey === CUSTOMER_ZONE_TABLE;
|
| 7 |
+
}
|
| 8 |
+
|
| 9 |
+
export function zoneCollectionPath(tableKey: string): string {
|
| 10 |
+
return usesNormalizedCustomerZones(tableKey)
|
| 11 |
+
? "/api/v1/customers/zones"
|
| 12 |
+
: `/api/v1/geo/zones?tableKey=${encodeURIComponent(tableKey)}`;
|
| 13 |
+
}
|
| 14 |
+
|
| 15 |
+
export function zoneItemPath(tableKey: string, zoneId: string): string {
|
| 16 |
+
return usesNormalizedCustomerZones(tableKey)
|
| 17 |
+
? `/api/v1/customers/zones/${encodeURIComponent(zoneId)}`
|
| 18 |
+
: `/api/v1/geo/zones/${encodeURIComponent(zoneId)}`;
|
| 19 |
+
}
|
| 20 |
+
|
| 21 |
+
/** Customer membership is server-derived from its polygon/ZIP definition and current rows.
|
| 22 |
+
* Generic table Maps retain their established explicit-membership DTO. */
|
| 23 |
+
export function zoneMutationPayload(
|
| 24 |
+
tableKey: string,
|
| 25 |
+
sourceViewId: string | null,
|
| 26 |
+
draft: Record<string, unknown>,
|
| 27 |
+
): Record<string, unknown> {
|
| 28 |
+
if (!usesNormalizedCustomerZones(tableKey)) return { tableKey, ...draft };
|
| 29 |
+
const { memberships: _browserMemberships, ...serverOwned } = draft;
|
| 30 |
+
void _browserMemberships;
|
| 31 |
+
return { ...serverOwned, sourceViewId };
|
| 32 |
+
}
|
| 33 |
+
|
| 34 |
+
type FetchResult = {
|
| 35 |
+
ok: boolean;
|
| 36 |
+
json: () => Promise<unknown>;
|
| 37 |
+
};
|
| 38 |
+
|
| 39 |
+
export type RouteDeliveryFetch = (
|
| 40 |
+
input: string,
|
| 41 |
+
init: { method: string; credentials: "same-origin"; headers: Record<string, string>; body: string },
|
| 42 |
+
) => Promise<FetchResult>;
|
| 43 |
+
|
| 44 |
+
export async function requestRouteDelivery(
|
| 45 |
+
routeId: string,
|
| 46 |
+
request: RouteDeliveryRequest,
|
| 47 |
+
fetcher: RouteDeliveryFetch = fetch as RouteDeliveryFetch,
|
| 48 |
+
): Promise<{ delivery?: RouteDeliveryDto; error?: string }> {
|
| 49 |
+
try {
|
| 50 |
+
const response = await fetcher(
|
| 51 |
+
`/api/v1/customers/routes/${encodeURIComponent(routeId)}/deliveries`,
|
| 52 |
+
{
|
| 53 |
+
method: "POST",
|
| 54 |
+
credentials: "same-origin",
|
| 55 |
+
headers: { "Content-Type": "application/json" },
|
| 56 |
+
body: JSON.stringify(request),
|
| 57 |
+
},
|
| 58 |
+
);
|
| 59 |
+
const body = await response.json().catch(() => null) as {
|
| 60 |
+
delivery?: RouteDeliveryDto;
|
| 61 |
+
error?: { message?: string };
|
| 62 |
+
detail?: { message?: string };
|
| 63 |
+
} | null;
|
| 64 |
+
if (!response.ok) return {
|
| 65 |
+
error: body?.error?.message || body?.detail?.message || "The Route delivery could not be scheduled.",
|
| 66 |
+
};
|
| 67 |
+
if (!body?.delivery) return { error: "The Route delivery returned no saved schedule." };
|
| 68 |
+
return { delivery: body.delivery };
|
| 69 |
+
} catch {
|
| 70 |
+
return { error: "The Route delivery could not be scheduled." };
|
| 71 |
+
}
|
| 72 |
+
}
|
web/src/customer-grid/routeZoneTypes.ts
CHANGED
|
@@ -5,9 +5,39 @@ export interface ZoneGeometry {
|
|
| 5 |
}
|
| 6 |
|
| 7 |
export interface MapZoneDto {
|
| 8 |
-
id: string; name: string; color: string; geometryGeoJson: ZoneGeometry;
|
| 9 |
zipCodes: string[]; visible: boolean; memberships: number[];
|
| 10 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 11 |
}
|
| 12 |
|
| 13 |
export interface MapRouteDto {
|
|
@@ -15,9 +45,30 @@ export interface MapRouteDto {
|
|
| 15 |
outsideFilter: boolean;
|
| 16 |
permission: { canEdit: boolean; sourceViewId: string };
|
| 17 |
source: { viewId: string; revision: string };
|
|
|
|
|
|
|
| 18 |
mapsUrl?: string;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 19 |
}
|
| 20 |
|
|
|
|
|
|
|
| 21 |
export interface RouteSelectionRequest { routeIds: string[]; viewState: Record<string, unknown>; }
|
| 22 |
|
| 23 |
export interface RouteSelectionResponse {
|
|
@@ -56,6 +107,29 @@ export function normalizedZoneZipCodes(value: string): string[] {
|
|
| 56 |
return [...new Set(value.split(/[\s,]+/).filter((zip) => /^\d{5}(?:-\d{4})?$/.test(zip)))];
|
| 57 |
}
|
| 58 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 59 |
/** Only a bounded HTTPS Google Maps link may leave the in-app Route detail. */
|
| 60 |
export function boundedGoogleMapsUrl(value: string | undefined): string | null {
|
| 61 |
if (!value || value.length > 2_048) return null;
|
|
|
|
| 5 |
}
|
| 6 |
|
| 7 |
export interface MapZoneDto {
|
| 8 |
+
id: string; name: string; color: string; geometryGeoJson: ZoneGeometry | null;
|
| 9 |
zipCodes: string[]; visible: boolean; memberships: number[];
|
| 10 |
+
geographicField?: string;
|
| 11 |
+
membershipRevision?: number;
|
| 12 |
+
sourceViewId?: string | null;
|
| 13 |
+
createdBy?: string;
|
| 14 |
+
createdAt?: string;
|
| 15 |
+
permission?: { canEdit?: boolean; canDelete?: boolean };
|
| 16 |
+
}
|
| 17 |
+
|
| 18 |
+
export interface RouteDeliveryDto {
|
| 19 |
+
id: string;
|
| 20 |
+
name: string;
|
| 21 |
+
recipient: string;
|
| 22 |
+
schedule: { cron?: string; enabled?: boolean; timezone?: string };
|
| 23 |
+
snapshot: {
|
| 24 |
+
routeId: string;
|
| 25 |
+
sourceViewId: string;
|
| 26 |
+
sourceViewRevision: string;
|
| 27 |
+
sourceViewName: string;
|
| 28 |
+
timezone: string;
|
| 29 |
+
routeField: string;
|
| 30 |
+
orderedStopIds: number[];
|
| 31 |
+
mapsPerLink: number;
|
| 32 |
+
};
|
| 33 |
+
createdBy?: string;
|
| 34 |
+
created?: string;
|
| 35 |
+
}
|
| 36 |
+
|
| 37 |
+
export interface RouteDeliveryRequest {
|
| 38 |
+
recipient: string;
|
| 39 |
+
timezone: string;
|
| 40 |
+
mapsPerLink: number;
|
| 41 |
}
|
| 42 |
|
| 43 |
export interface MapRouteDto {
|
|
|
|
| 45 |
outsideFilter: boolean;
|
| 46 |
permission: { canEdit: boolean; sourceViewId: string };
|
| 47 |
source: { viewId: string; revision: string };
|
| 48 |
+
/** Read-through of a saved route-order field. It remains visible without mutating on GET. */
|
| 49 |
+
compatibility?: "legacy-route-order";
|
| 50 |
mapsUrl?: string;
|
| 51 |
+
owner: string;
|
| 52 |
+
shared: boolean;
|
| 53 |
+
sharedOut: boolean;
|
| 54 |
+
hasShares: boolean;
|
| 55 |
+
sharedRole: "view" | "edit" | null;
|
| 56 |
+
/** Generic field bridge address consumed by the established Share dialog. */
|
| 57 |
+
shareId: string;
|
| 58 |
+
/** This reader's personal Route filing; it never changes the shared Route object. */
|
| 59 |
+
folderId: string | null;
|
| 60 |
+
navOrder: number;
|
| 61 |
+
}
|
| 62 |
+
|
| 63 |
+
export interface MapRouteFolderDto {
|
| 64 |
+
id: string;
|
| 65 |
+
name: string;
|
| 66 |
+
parent: string | null;
|
| 67 |
+
order: number;
|
| 68 |
}
|
| 69 |
|
| 70 |
+
export type MapRouteUpdate = { name: string; mapsUrl?: string };
|
| 71 |
+
|
| 72 |
export interface RouteSelectionRequest { routeIds: string[]; viewState: Record<string, unknown>; }
|
| 73 |
|
| 74 |
export interface RouteSelectionResponse {
|
|
|
|
| 107 |
return [...new Set(value.split(/[\s,]+/).filter((zip) => /^\d{5}(?:-\d{4})?$/.test(zip)))];
|
| 108 |
}
|
| 109 |
|
| 110 |
+
type ZoneMembershipRow = Record<string, unknown> & { pid?: unknown };
|
| 111 |
+
|
| 112 |
+
/** Build the scoped membership snapshot as explicit selection OR matching ZIP rows. */
|
| 113 |
+
export function zoneMembershipPids(
|
| 114 |
+
selected: Iterable<number>,
|
| 115 |
+
rows: readonly ZoneMembershipRow[],
|
| 116 |
+
zipCodes: readonly string[],
|
| 117 |
+
geographicField = "",
|
| 118 |
+
): number[] {
|
| 119 |
+
const wanted = new Set(zipCodes.map((zip) => String(zip).trim().toUpperCase()).filter(Boolean));
|
| 120 |
+
const zipKeys = ["zip", "zip_code", "postal_code", "postalCode"];
|
| 121 |
+
if (/zip|postal/i.test(geographicField) && !zipKeys.includes(geographicField))
|
| 122 |
+
zipKeys.push(geographicField);
|
| 123 |
+
const matches = [];
|
| 124 |
+
if (wanted.size) {
|
| 125 |
+
for (const row of rows) {
|
| 126 |
+
const matchesZip = zipKeys.some((key) => wanted.has(String(row[key] ?? "").trim().toUpperCase()));
|
| 127 |
+
if (matchesZip) matches.push(Number(row.pid));
|
| 128 |
+
}
|
| 129 |
+
}
|
| 130 |
+
return routeSourceStopIds([...selected, ...matches]);
|
| 131 |
+
}
|
| 132 |
+
|
| 133 |
/** Only a bounded HTTPS Google Maps link may leave the in-app Route detail. */
|
| 134 |
export function boundedGoogleMapsUrl(value: string | undefined): string | null {
|
| 135 |
if (!value || value.length > 2_048) return null;
|
web/src/customer-grid/types.ts
CHANGED
|
@@ -254,9 +254,11 @@ export const CREATABLE_TYPES: readonly FieldType[] = [
|
|
| 254 |
* asymmetry is honest rather than an oversight, and it is the reason the exported set below is
|
| 255 |
* `string[]` while its first half is not.
|
| 256 |
*/
|
| 257 |
-
const ADVANCED_FIELD_KINDS: readonly FieldType[] = [
|
|
|
|
|
|
|
| 258 |
|
| 259 |
-
/** The advanced set the picker groups on: the
|
| 260 |
* which joins by VALUE because it cannot join by type. */
|
| 261 |
export const ADVANCED_CREATE_KINDS: readonly string[] = [...ADVANCED_FIELD_KINDS, "geocode"];
|
| 262 |
|
|
@@ -268,6 +270,48 @@ export const ADVANCED_CREATE_KINDS: readonly string[] = [...ADVANCED_FIELD_KINDS
|
|
| 268 |
*/
|
| 269 |
export const ADVANCED_TYPES_HEADING = "Advanced";
|
| 270 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 271 |
/** A run of field-type picker rows under an optional heading. `heading: null` is the ordinary
|
| 272 |
* group, deliberately unlabelled: naming the majority case is chrome nobody reads, and the
|
| 273 |
* divider under it already says where the ordinary list ends. */
|
|
@@ -357,15 +401,34 @@ export function isPickType(t: FieldType): boolean {
|
|
| 357 |
return t === "select" || t === "user" || t === "multiselect";
|
| 358 |
}
|
| 359 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 360 |
/**
|
| 361 |
-
* One choice per line, blanks dropped, duplicates collapsed, order preserved,
|
| 362 |
* Case-INSENSITIVE dedupe: "Blocked" and "blocked" are one choice to a human, so the first
|
| 363 |
* spelling wins rather than the column growing two pills that look like a typo.
|
| 364 |
*
|
| 365 |
* Lives here, not in ColumnMenu.tsx β a component file that also exports plain functions
|
| 366 |
* breaks React fast refresh (the same reason counts.ts is its own module).
|
| 367 |
*/
|
| 368 |
-
export function parseOptions(text: string):
|
| 369 |
const seen = new Set<string>();
|
| 370 |
const out: string[] = [];
|
| 371 |
for (const raw of text.split("\n")) {
|
|
@@ -376,7 +439,24 @@ export function parseOptions(text: string): string[] {
|
|
| 376 |
seen.add(k);
|
| 377 |
out.push(v);
|
| 378 |
}
|
| 379 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 380 |
}
|
| 381 |
|
| 382 |
/**
|
|
@@ -411,8 +491,19 @@ export function uniqueDisplayName(
|
|
| 411 |
* min(cycles missed, 3) x AOV β our arithmetic, not an object the business has β and a
|
| 412 |
* condition on it reads as a fact about the customer. It still displays and still sorts.
|
| 413 |
*/
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 414 |
export function filterableFields(fields: Field[]): Field[] {
|
| 415 |
-
return fields.filter((f) => f.filterable !== false);
|
| 416 |
}
|
| 417 |
|
| 418 |
/** Wave-5 item 10 β per-field display format. One optional bag; each type reads its half. */
|
|
@@ -1722,6 +1813,17 @@ export function fieldEditMode(field: Pick<Field, "permissions">): FieldEditMode
|
|
| 1722 |
return cleanFieldPermissions(field.permissions, "collaborative").edit;
|
| 1723 |
}
|
| 1724 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1725 |
/**
|
| 1726 |
* May this viewer EDIT this field's cell values? The client-side COURTESY check β it decides
|
| 1727 |
* what renders editable and which menu entries appear; the host's fail-closed enforcement is
|
|
@@ -1736,7 +1838,8 @@ export function fieldEditMode(field: Pick<Field, "permissions">): FieldEditMode
|
|
| 1736 |
* of a leaver's field would need a database edit to fix anything).
|
| 1737 |
*/
|
| 1738 |
export function mayEditField(field: Field, viewer: Viewer | undefined): boolean {
|
| 1739 |
-
if (field.source !== "overlay"
|
|
|
|
| 1740 |
// β 2026-08-07 β the DERIVED half of `link`. Read per-field rather than by type, because the
|
| 1741 |
// other half of the same type is a relation a person builds by hand. The host wall is
|
| 1742 |
// `core.user_tables.is_computed_cell`, read by `grid_events`; this is the courtesy in front
|
|
@@ -2089,6 +2192,7 @@ export function directionLabel(t: FieldType, dir: "asc" | "desc"): string {
|
|
| 2089 |
* "(empty)" group every other type uses.
|
| 2090 |
*/
|
| 2091 |
export function isGroupableField(field: Field, lockedKey: string): boolean {
|
|
|
|
| 2092 |
return (
|
| 2093 |
field.type === "status" ||
|
| 2094 |
field.type === "select" ||
|
|
@@ -2113,6 +2217,12 @@ export interface Field {
|
|
| 2113 |
labelCorrectionId?: string;
|
| 2114 |
type: FieldType;
|
| 2115 |
source: FieldSource;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2116 |
/** Owner-controlled lifecycle lock; it blocks deletion without blocking edits. */
|
| 2117 |
deletionLocked?: boolean;
|
| 2118 |
/** C3's declared field provenance; the client renders it rather than inferring it. */
|
|
@@ -2165,6 +2275,12 @@ export interface Field {
|
|
| 2165 |
* missing menu row to a 400 nobody expected.
|
| 2166 |
*/
|
| 2167 |
kind?: string;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2168 |
/** Host-computed effective Share field role for this viewer. */
|
| 2169 |
sharedRole?: FieldShareRole;
|
| 2170 |
/**
|
|
@@ -2575,6 +2691,29 @@ export const ROLLUP_FNS = [
|
|
| 2575 |
] as const;
|
| 2576 |
export type RollupFn = (typeof ROLLUP_FNS)[number];
|
| 2577 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2578 |
/** The rollup functions whose RESULT is a number β the render/align/sort family. */
|
| 2579 |
export const ROLLUP_NUMERIC_FNS: ReadonlySet<string> =
|
| 2580 |
new Set(["sum", "average", "stdev", "min", "max", "count", "counta", "countall"]);
|
|
@@ -3415,6 +3554,89 @@ export function filterTreeConj(tree: FilterTree | null | undefined): Conjunction
|
|
| 3415 |
return tree?.conj === "or" ? "or" : "and";
|
| 3416 |
}
|
| 3417 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3418 |
export type RowHeightMode = "short" | "medium" | "tall";
|
| 3419 |
export type ThemeMode = "light" | "dark";
|
| 3420 |
|
|
@@ -3777,6 +3999,28 @@ export function pivotResponse(body: unknown): PivotResponse | null {
|
|
| 3777 |
};
|
| 3778 |
}
|
| 3779 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3780 |
/**
|
| 3781 |
* wave17 R1 / contract C-LOCKV β **`"locked"` joins the vocabulary, and it is the whole of the
|
| 3782 |
* client's model of a locked view.**
|
|
|
|
| 254 |
* asymmetry is honest rather than an oversight, and it is the reason the exported set below is
|
| 255 |
* `string[]` while its first half is not.
|
| 256 |
*/
|
| 257 |
+
const ADVANCED_FIELD_KINDS: readonly FieldType[] = [
|
| 258 |
+
"automation", "json", "code", "ai_enrich", "link", "rollup", "formula",
|
| 259 |
+
];
|
| 260 |
|
| 261 |
+
/** The advanced set the picker groups on: the seven real types above plus the geocode pseudo-kind,
|
| 262 |
* which joins by VALUE because it cannot join by type. */
|
| 263 |
export const ADVANCED_CREATE_KINDS: readonly string[] = [...ADVANCED_FIELD_KINDS, "geocode"];
|
| 264 |
|
|
|
|
| 270 |
*/
|
| 271 |
export const ADVANCED_TYPES_HEADING = "Advanced";
|
| 272 |
|
| 273 |
+
/** One compact plain-language line for every create-menu row, including rollup presets. */
|
| 274 |
+
export const TYPE_DESCRIPTIONS: Record<
|
| 275 |
+
FieldType | "measure" | "geocode" | "count" | "lookup",
|
| 276 |
+
string
|
| 277 |
+
> = {
|
| 278 |
+
text: "Words typed in by hand: a name, a note, a reference.",
|
| 279 |
+
status: "A workflow state chosen from a fixed list.",
|
| 280 |
+
select: "One choice from a list you define.",
|
| 281 |
+
multiselect: "Any number of choices from a list you define.",
|
| 282 |
+
user: "The person a record belongs to.",
|
| 283 |
+
int: "A whole number, with no decimals.",
|
| 284 |
+
currency: "An amount of money, shown with its symbol.",
|
| 285 |
+
pct: "A percentage, stored as the number people say out loud.",
|
| 286 |
+
date: "A calendar date, with an optional time of day.",
|
| 287 |
+
checkbox: "A yes or no box.",
|
| 288 |
+
phone: "A phone number, dialable from the cell.",
|
| 289 |
+
email: "An email address, ready to write to.",
|
| 290 |
+
url: "A web address that opens in a new tab.",
|
| 291 |
+
rating: "A score out of five, drawn as stars.",
|
| 292 |
+
created_time: "When the record was first created. Filled in for you.",
|
| 293 |
+
formula: "A value calculated from this row's other columns.",
|
| 294 |
+
automation: "A value a scheduled job writes; nobody types into it.",
|
| 295 |
+
metric: "A business number over a time window, computed at read time.",
|
| 296 |
+
image: "A picture: uploaded here, or named from the catalog.",
|
| 297 |
+
json: "A structured document such as an API response or a webhook body.",
|
| 298 |
+
code: "A snippet of code, shown in the language you choose.",
|
| 299 |
+
ai_enrich: "A value the assistant fills in from a prompt you write.",
|
| 300 |
+
link: "Points at rows of another database, so this row can reach them.",
|
| 301 |
+
rollup: "Folds many records into one value: linked rows, or a live topic matched on a column.",
|
| 302 |
+
measure: "A business number this workspace already publishes, over a period you pick.",
|
| 303 |
+
geocode: "Latitude and longitude, read from an address column of this database.",
|
| 304 |
+
count: "How many records this row links to. A rollup, with the folding already chosen.",
|
| 305 |
+
lookup: "Shows a column of linked records. A rollup, with the folding already chosen.",
|
| 306 |
+
};
|
| 307 |
+
|
| 308 |
+
/** Runtime user databases do not own creation timestamps, so their create picker withholds it. */
|
| 309 |
+
export const UT_UNSUPPORTED_CREATE_KINDS: readonly string[] = ["created_time"];
|
| 310 |
+
|
| 311 |
+
export function offerableCreateKind(value: string, isUserTable: boolean): boolean {
|
| 312 |
+
return !isUserTable || !UT_UNSUPPORTED_CREATE_KINDS.includes(value);
|
| 313 |
+
}
|
| 314 |
+
|
| 315 |
/** A run of field-type picker rows under an optional heading. `heading: null` is the ordinary
|
| 316 |
* group, deliberately unlabelled: naming the majority case is chrome nobody reads, and the
|
| 317 |
* divider under it already says where the ordinary list ends. */
|
|
|
|
| 401 |
return t === "select" || t === "user" || t === "multiselect";
|
| 402 |
}
|
| 403 |
|
| 404 |
+
export interface ParsedOptions {
|
| 405 |
+
options: string[];
|
| 406 |
+
entered: number;
|
| 407 |
+
refused: number;
|
| 408 |
+
limit: number | null;
|
| 409 |
+
message: string | null;
|
| 410 |
+
}
|
| 411 |
+
|
| 412 |
+
/** Read the one explicit server-published option limit; absent or conflicting means fail closed. */
|
| 413 |
+
export function serverOptionLimit(fields: readonly Field[]): number | null {
|
| 414 |
+
const declared = new Set<number>();
|
| 415 |
+
for (const field of fields) {
|
| 416 |
+
const value = field.limits?.maxOptions;
|
| 417 |
+
if (typeof value === "number" && Number.isInteger(value) && value > 0)
|
| 418 |
+
declared.add(value);
|
| 419 |
+
}
|
| 420 |
+
return declared.size === 1 ? [...declared][0] : null;
|
| 421 |
+
}
|
| 422 |
+
|
| 423 |
/**
|
| 424 |
+
* One choice per line, blanks dropped, duplicates collapsed, order preserved, never truncated.
|
| 425 |
* Case-INSENSITIVE dedupe: "Blocked" and "blocked" are one choice to a human, so the first
|
| 426 |
* spelling wins rather than the column growing two pills that look like a typo.
|
| 427 |
*
|
| 428 |
* Lives here, not in ColumnMenu.tsx β a component file that also exports plain functions
|
| 429 |
* breaks React fast refresh (the same reason counts.ts is its own module).
|
| 430 |
*/
|
| 431 |
+
export function parseOptions(text: string, maxOptions: unknown): ParsedOptions {
|
| 432 |
const seen = new Set<string>();
|
| 433 |
const out: string[] = [];
|
| 434 |
for (const raw of text.split("\n")) {
|
|
|
|
| 439 |
seen.add(k);
|
| 440 |
out.push(v);
|
| 441 |
}
|
| 442 |
+
const limit = typeof maxOptions === "number" && Number.isInteger(maxOptions) && maxOptions > 0
|
| 443 |
+
? maxOptions : null;
|
| 444 |
+
if (limit === null) {
|
| 445 |
+
return {
|
| 446 |
+
options: out, entered: out.length, refused: out.length, limit,
|
| 447 |
+
message: "Choices cannot be saved because the server did not publish an option limit. Reload the database, then try again.",
|
| 448 |
+
};
|
| 449 |
+
}
|
| 450 |
+
const refused = Math.max(0, out.length - limit);
|
| 451 |
+
return {
|
| 452 |
+
options: out,
|
| 453 |
+
entered: out.length,
|
| 454 |
+
refused,
|
| 455 |
+
limit,
|
| 456 |
+
message: refused
|
| 457 |
+
? `This list has ${out.length} choices; the server limit is ${limit}, so ${refused} would be rejected. Remove ${refused} choices, then save.`
|
| 458 |
+
: null,
|
| 459 |
+
};
|
| 460 |
}
|
| 461 |
|
| 462 |
/**
|
|
|
|
| 491 |
* min(cycles missed, 3) x AOV β our arithmetic, not an object the business has β and a
|
| 492 |
* condition on it reads as a fact about the customer. It still displays and still sorts.
|
| 493 |
*/
|
| 494 |
+
export const ROUTE_PROJECTION_KEY = "routes";
|
| 495 |
+
|
| 496 |
+
/** Absent means offerable so old payloads keep their behaviour. */
|
| 497 |
+
export function isOfferableField(field: Field): boolean {
|
| 498 |
+
return field.offerable !== false;
|
| 499 |
+
}
|
| 500 |
+
|
| 501 |
+
export function offerableFields(fields: readonly Field[]): Field[] {
|
| 502 |
+
return fields.filter(isOfferableField);
|
| 503 |
+
}
|
| 504 |
+
|
| 505 |
export function filterableFields(fields: Field[]): Field[] {
|
| 506 |
+
return fields.filter((f) => isOfferableField(f) && f.filterable !== false);
|
| 507 |
}
|
| 508 |
|
| 509 |
/** Wave-5 item 10 β per-field display format. One optional bag; each type reads its half. */
|
|
|
|
| 1813 |
return cleanFieldPermissions(field.permissions, "collaborative").edit;
|
| 1814 |
}
|
| 1815 |
|
| 1816 |
+
/**
|
| 1817 |
+
* A connector-owned value may have one explicitly declared overlay override. This is deliberately
|
| 1818 |
+
* narrower than `source === "odoo"`: the canonical host contract has to name both the one field
|
| 1819 |
+
* and the overlay destination before the client offers any value-edit door.
|
| 1820 |
+
*/
|
| 1821 |
+
export function mayOverrideSourceValue(
|
| 1822 |
+
field: Pick<Field, "key" | "source" | "valueOverride">
|
| 1823 |
+
): boolean {
|
| 1824 |
+
return field.key === "maps_url" && field.source === "odoo" && field.valueOverride === "overlay";
|
| 1825 |
+
}
|
| 1826 |
+
|
| 1827 |
/**
|
| 1828 |
* May this viewer EDIT this field's cell values? The client-side COURTESY check β it decides
|
| 1829 |
* what renders editable and which menu entries appear; the host's fail-closed enforcement is
|
|
|
|
| 1838 |
* of a leaver's field would need a database edit to fix anything).
|
| 1839 |
*/
|
| 1840 |
export function mayEditField(field: Field, viewer: Viewer | undefined): boolean {
|
| 1841 |
+
if ((field.source !== "overlay" && !mayOverrideSourceValue(field)) ||
|
| 1842 |
+
READONLY_CELL_TYPES.has(field.type)) return false;
|
| 1843 |
// β 2026-08-07 β the DERIVED half of `link`. Read per-field rather than by type, because the
|
| 1844 |
// other half of the same type is a relation a person builds by hand. The host wall is
|
| 1845 |
// `core.user_tables.is_computed_cell`, read by `grid_events`; this is the courtesy in front
|
|
|
|
| 2192 |
* "(empty)" group every other type uses.
|
| 2193 |
*/
|
| 2194 |
export function isGroupableField(field: Field, lockedKey: string): boolean {
|
| 2195 |
+
if (!isOfferableField(field)) return false;
|
| 2196 |
return (
|
| 2197 |
field.type === "status" ||
|
| 2198 |
field.type === "select" ||
|
|
|
|
| 2217 |
labelCorrectionId?: string;
|
| 2218 |
type: FieldType;
|
| 2219 |
source: FieldSource;
|
| 2220 |
+
/**
|
| 2221 |
+
* Exact source-backed value exception. The connector value remains the fallback; a normal
|
| 2222 |
+
* overlay cell may override it, and clearing that overlay restores the source. Only maps_url
|
| 2223 |
+
* is admitted at the host and client walls.
|
| 2224 |
+
*/
|
| 2225 |
+
valueOverride?: "overlay";
|
| 2226 |
/** Owner-controlled lifecycle lock; it blocks deletion without blocking edits. */
|
| 2227 |
deletionLocked?: boolean;
|
| 2228 |
/** C3's declared field provenance; the client renders it rather than inferring it. */
|
|
|
|
| 2275 |
* missing menu row to a 400 nobody expected.
|
| 2276 |
*/
|
| 2277 |
kind?: string;
|
| 2278 |
+
/** False withholds this stored field from generic pickers without hiding or deleting it. */
|
| 2279 |
+
offerable?: boolean;
|
| 2280 |
+
/** Server-owned limits. Missing maxOptions makes choice editing fail closed. */
|
| 2281 |
+
limits?: { maxOptions?: number };
|
| 2282 |
+
/** A shared same-key definition won; the viewer's personal definition remains stored. */
|
| 2283 |
+
superseded?: { stratum?: string; owner?: string | null; label?: string | null };
|
| 2284 |
/** Host-computed effective Share field role for this viewer. */
|
| 2285 |
sharedRole?: FieldShareRole;
|
| 2286 |
/**
|
|
|
|
| 2691 |
] as const;
|
| 2692 |
export type RollupFn = (typeof ROLLUP_FNS)[number];
|
| 2693 |
|
| 2694 |
+
/** Count and Lookup are discoverability presets over Rollup, never new field kinds. */
|
| 2695 |
+
export const ROLLUP_PRESETS = ["count", "lookup"] as const;
|
| 2696 |
+
export type RollupPreset = (typeof ROLLUP_PRESETS)[number];
|
| 2697 |
+
|
| 2698 |
+
export const ROLLUP_PRESET_FNS: Record<RollupPreset, RollupFn> = {
|
| 2699 |
+
count: "countall",
|
| 2700 |
+
lookup: "arrayjoin",
|
| 2701 |
+
};
|
| 2702 |
+
|
| 2703 |
+
/** Exact preset recognition prevents a reduced editor from hiding non-preset configuration. */
|
| 2704 |
+
export function rollupPresetOf(
|
| 2705 |
+
bag: NonNullable<Field["rollup"]> | null | undefined
|
| 2706 |
+
): RollupPreset | null {
|
| 2707 |
+
if (!bag || bag.source) return null;
|
| 2708 |
+
const plain =
|
| 2709 |
+
!bag.limit && !bag.sortBy && !bag.sortDir && !bag.distinctBy
|
| 2710 |
+
&& !(bag.where && bag.where.length) && !(bag.conditions && bag.conditions.length);
|
| 2711 |
+
if (!plain || !bag.link) return null;
|
| 2712 |
+
if (bag.fn === ROLLUP_PRESET_FNS.count && !bag.field) return "count";
|
| 2713 |
+
if (bag.fn === ROLLUP_PRESET_FNS.lookup && !!bag.field) return "lookup";
|
| 2714 |
+
return null;
|
| 2715 |
+
}
|
| 2716 |
+
|
| 2717 |
/** The rollup functions whose RESULT is a number β the render/align/sort family. */
|
| 2718 |
export const ROLLUP_NUMERIC_FNS: ReadonlySet<string> =
|
| 2719 |
new Set(["sum", "average", "stdev", "min", "max", "count", "counta", "countall"]);
|
|
|
|
| 3554 |
return tree?.conj === "or" ? "or" : "and";
|
| 3555 |
}
|
| 3556 |
|
| 3557 |
+
/* --- WAVE-42 R22 β route projection ordering -------------------------------- */
|
| 3558 |
+
|
| 3559 |
+
/** The declared kind of a per-route stop-position field. */
|
| 3560 |
+
export const ROUTE_ORDER_KIND = "route_order";
|
| 3561 |
+
|
| 3562 |
+
/** Why a route projection sort was refused, or the route column that makes it meaningful. */
|
| 3563 |
+
export type RouteSortVerdict =
|
| 3564 |
+
| { ok: true; routeKey: string }
|
| 3565 |
+
| { ok: false; reason: "no-route" | "many-routes" | "not-narrowing" };
|
| 3566 |
+
|
| 3567 |
+
export const ROUTE_SORT_REFUSAL_TEXT =
|
| 3568 |
+
"Route order only means something inside one route. Filter this view to a single route, then sort by it.";
|
| 3569 |
+
|
| 3570 |
+
/** These operators assert that a record belongs to the route named by the field. */
|
| 3571 |
+
const ROUTE_MEMBERSHIP_OPS: ReadonlySet<string> = new Set([
|
| 3572 |
+
"isNotEmpty", "eq", "gt", "gte", "lt", "lte", "between",
|
| 3573 |
+
]);
|
| 3574 |
+
|
| 3575 |
+
export function isRouteOrderField(field: Field): boolean {
|
| 3576 |
+
return field.kind === ROUTE_ORDER_KIND;
|
| 3577 |
+
}
|
| 3578 |
+
|
| 3579 |
+
function nodeTouchesRoute(node: FilterNode, routeKeys: ReadonlySet<string>): boolean {
|
| 3580 |
+
if (isFilterGroup(node)) {
|
| 3581 |
+
return node.children.some((child) => nodeTouchesRoute(child, routeKeys));
|
| 3582 |
+
}
|
| 3583 |
+
return node != null && typeof node === "object" && routeKeys.has(node.colId);
|
| 3584 |
+
}
|
| 3585 |
+
|
| 3586 |
+
/**
|
| 3587 |
+
* A stop number is an ordinal inside one route. Only a root filter that provably narrows the
|
| 3588 |
+
* view to exactly one route makes the aggregate `routes` projection sortable. Nested route
|
| 3589 |
+
* groups and root ORs fail closed because treating either as narrowing would be a guess.
|
| 3590 |
+
*/
|
| 3591 |
+
export function singleRouteScope(
|
| 3592 |
+
tree: FilterTree | null | undefined,
|
| 3593 |
+
fields: Field[],
|
| 3594 |
+
): RouteSortVerdict {
|
| 3595 |
+
const routeKeys = new Set(fields.filter(isRouteOrderField).map((field) => field.key));
|
| 3596 |
+
const nodes = filterTreeNodes(tree);
|
| 3597 |
+
if (filterTreeConj(tree) === "or" && nodes.length > 1) {
|
| 3598 |
+
return { ok: false, reason: "not-narrowing" };
|
| 3599 |
+
}
|
| 3600 |
+
const named = new Set<string>();
|
| 3601 |
+
for (const node of nodes) {
|
| 3602 |
+
if (isFilterGroup(node)) {
|
| 3603 |
+
if (nodeTouchesRoute(node, routeKeys)) return { ok: false, reason: "not-narrowing" };
|
| 3604 |
+
continue;
|
| 3605 |
+
}
|
| 3606 |
+
if (node == null || typeof node !== "object") continue;
|
| 3607 |
+
if (!routeKeys.has(node.colId) || !ROUTE_MEMBERSHIP_OPS.has(node.op)) continue;
|
| 3608 |
+
named.add(node.colId);
|
| 3609 |
+
}
|
| 3610 |
+
if (named.size === 0) return { ok: false, reason: "no-route" };
|
| 3611 |
+
if (named.size > 1) return { ok: false, reason: "many-routes" };
|
| 3612 |
+
return { ok: true, routeKey: [...named][0] };
|
| 3613 |
+
}
|
| 3614 |
+
|
| 3615 |
+
/** Explain why sorting the aggregate routes projection is unavailable; ordinary fields pass. */
|
| 3616 |
+
export function routeSortRefusal(
|
| 3617 |
+
colId: string,
|
| 3618 |
+
tree: FilterTree | null | undefined,
|
| 3619 |
+
fields: Field[],
|
| 3620 |
+
): string | null {
|
| 3621 |
+
if (colId !== ROUTE_PROJECTION_KEY) return null;
|
| 3622 |
+
return singleRouteScope(tree, fields).ok ? null : ROUTE_SORT_REFUSAL_TEXT;
|
| 3623 |
+
}
|
| 3624 |
+
|
| 3625 |
+
/** Extract one route's numeric stop from `Route A - 3, Route B - 7`; missing stays missing. */
|
| 3626 |
+
export function routeStopPosition(cell: unknown, routeLabel: string): number | null {
|
| 3627 |
+
if (typeof cell !== "string") return null;
|
| 3628 |
+
const wanted = routeLabel.trim();
|
| 3629 |
+
if (!wanted) return null;
|
| 3630 |
+
for (const entry of cell.split(",")) {
|
| 3631 |
+
const text = entry.trim();
|
| 3632 |
+
const cut = text.lastIndexOf(" - ");
|
| 3633 |
+
if (cut < 0 || text.slice(0, cut).trim() !== wanted) continue;
|
| 3634 |
+
const value = Number.parseInt(text.slice(cut + 3).trim(), 10);
|
| 3635 |
+
if (Number.isFinite(value)) return value;
|
| 3636 |
+
}
|
| 3637 |
+
return null;
|
| 3638 |
+
}
|
| 3639 |
+
|
| 3640 |
export type RowHeightMode = "short" | "medium" | "tall";
|
| 3641 |
export type ThemeMode = "light" | "dark";
|
| 3642 |
|
|
|
|
| 3999 |
};
|
| 4000 |
}
|
| 4001 |
|
| 4002 |
+
/** Safely read the server-authored reason from every supported non-2xx envelope. */
|
| 4003 |
+
export function pivotRefusalFromBody(body: unknown): PivotRefusal | null {
|
| 4004 |
+
if (!body || typeof body !== "object" || Array.isArray(body)) return null;
|
| 4005 |
+
const value = body as Record<string, unknown>;
|
| 4006 |
+
const text = (candidate: unknown): string =>
|
| 4007 |
+
typeof candidate === "string" ? candidate.trim() : "";
|
| 4008 |
+
const nested = value.refusal;
|
| 4009 |
+
if (nested && typeof nested === "object" && !Array.isArray(nested)) {
|
| 4010 |
+
const refusal = nested as Record<string, unknown>;
|
| 4011 |
+
if (text(refusal.reason)) {
|
| 4012 |
+
return { reason: text(refusal.reason), subject: text(refusal.subject) };
|
| 4013 |
+
}
|
| 4014 |
+
}
|
| 4015 |
+
const wrapped = value.error;
|
| 4016 |
+
if (wrapped && typeof wrapped === "object" && !Array.isArray(wrapped)) {
|
| 4017 |
+
const error = wrapped as Record<string, unknown>;
|
| 4018 |
+
if (text(error.message)) return { reason: text(error.message), subject: "" };
|
| 4019 |
+
}
|
| 4020 |
+
const flat = text(value.reason) || text(value.detail) || text(value.message);
|
| 4021 |
+
return flat ? { reason: flat, subject: text(value.subject) } : null;
|
| 4022 |
+
}
|
| 4023 |
+
|
| 4024 |
/**
|
| 4025 |
* wave17 R1 / contract C-LOCKV β **`"locked"` joins the vocabulary, and it is the whole of the
|
| 4026 |
* client's model of a locked view.**
|