fsanyoto commited on
Commit
06aad61
·
verified ·
1 Parent(s): fae17d1

Deploy AIOS web (React glide grid + FastAPI slice)

Browse files
RELEASES.json CHANGED
@@ -1,5 +1,5 @@
1
  {
2
- "current": "0c1b893",
3
  "releases": [
4
  {
5
  "version": "v68",
 
1
  {
2
+ "current": "d4e3e31",
3
  "releases": [
4
  {
5
  "version": "v68",
VERSION CHANGED
@@ -1 +1 @@
1
- 0c1b893
 
1
+ d4e3e31
api/routes_grid.py CHANGED
@@ -129,6 +129,26 @@ def _audit_timestamps(scope, pids, hidden_keys, runtime):
129
  return out
130
 
131
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
132
  @router.get("/workspace")
133
  def workspace(scope: str = "customer",
134
  session: Session = Depends(require_session)):
@@ -208,6 +228,9 @@ def workspace(scope: str = "customer",
208
  workspace["userAvatars"] = {}
209
  workspace["scopeKey"] = scope
210
  workspace["auditTimestamps"] = _audit_timestamps(scope, g["pids"], set(), session.runtime)
 
 
 
211
  # ⭐ W31-T20 — R6's SECOND SENTENCE REACHES THE BROWSER. On a read-through grid too large
212
  # for one window the pid set is empty, so cohort membership and a shared view's
213
  # `memberPids` are UNRESOLVED here (both fail closed, and `workspace_wire` already stamps
@@ -260,6 +283,9 @@ def workspace(scope: str = "customer",
260
  workspace["userAvatars"] = {}
261
  workspace["scopeKey"] = scope
262
  workspace["auditTimestamps"] = _audit_timestamps(scope, g["pids"], set(), session.runtime)
 
 
 
263
  return {"workspace": workspace}
264
 
265
  # The storage key mirrors the host's own convention byte-for-byte (app.py's `_table_grid`
@@ -346,6 +372,9 @@ def workspace(scope: str = "customer",
346
  workspace["scopeKey"] = scope
347
  ctx = _ctx(session, g["fields"], g["pids"], scope_key=scope)
348
  workspace["auditTimestamps"] = _audit_timestamps(scope, g["pids"], ctx.hidden_keys, session.runtime)
 
 
 
349
  if scope == "cohort":
350
  workspace["cohortMode"] = True
351
  # The create pane offers "this cohort table only" (default) vs "all customer tables".
 
129
  return out
130
 
131
 
132
+ def _database_key_for_scope(scope):
133
+ """The durable database key behind a grid scope.
134
+
135
+ ``customer`` and ``product`` are renderer spellings; database setup is keyed by the same
136
+ registry names the schema drawer uses. Keeping this translation at the workspace boundary
137
+ lets every Map consume one database-owned setting without teaching a View about it.
138
+ """
139
+ if scope == "product":
140
+ return "product_data"
141
+ if str(scope).startswith("ut_"):
142
+ return str(scope)
143
+ return "customer_data"
144
+
145
+
146
+ def _map_setup(scope, fields, runtime):
147
+ """The usable Map override for this session's already-walled field contract."""
148
+ from core import database_setup
149
+ return database_setup.map_for(_database_key_for_scope(scope), fields, st=runtime)
150
+
151
+
152
  @router.get("/workspace")
153
  def workspace(scope: str = "customer",
154
  session: Session = Depends(require_session)):
 
228
  workspace["userAvatars"] = {}
229
  workspace["scopeKey"] = scope
230
  workspace["auditTimestamps"] = _audit_timestamps(scope, g["pids"], set(), session.runtime)
231
+ map_setup = _map_setup(scope, workspace["fields"], session.runtime)
232
+ if map_setup:
233
+ workspace["mapSetup"] = map_setup
234
  # ⭐ W31-T20 — R6's SECOND SENTENCE REACHES THE BROWSER. On a read-through grid too large
235
  # for one window the pid set is empty, so cohort membership and a shared view's
236
  # `memberPids` are UNRESOLVED here (both fail closed, and `workspace_wire` already stamps
 
283
  workspace["userAvatars"] = {}
284
  workspace["scopeKey"] = scope
285
  workspace["auditTimestamps"] = _audit_timestamps(scope, g["pids"], set(), session.runtime)
286
+ map_setup = _map_setup(scope, workspace["fields"], session.runtime)
287
+ if map_setup:
288
+ workspace["mapSetup"] = map_setup
289
  return {"workspace": workspace}
290
 
291
  # The storage key mirrors the host's own convention byte-for-byte (app.py's `_table_grid`
 
372
  workspace["scopeKey"] = scope
373
  ctx = _ctx(session, g["fields"], g["pids"], scope_key=scope)
374
  workspace["auditTimestamps"] = _audit_timestamps(scope, g["pids"], ctx.hidden_keys, session.runtime)
375
+ map_setup = _map_setup(scope, workspace["fields"], session.runtime)
376
+ if map_setup:
377
+ workspace["mapSetup"] = map_setup
378
  if scope == "cohort":
379
  workspace["cohortMode"] = True
380
  # The create pane offers "this cohort table only" (default) vs "all customer tables".
api/routes_nav.py CHANGED
@@ -917,6 +917,47 @@ def _schema_means(key: str) -> dict:
917
  return {}
918
 
919
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
920
  @router.get("/nav/schema/{key}")
921
  def nav_schema(key: str, session: Session = Depends(require_session)):
922
  """The database's schema drawer payload: its field contract + the semantic measures this
@@ -977,16 +1018,19 @@ def nav_schema(key: str, session: Session = Depends(require_session)):
977
  # key, because no user table maps to a topic; see `_schema_means` for why that is written
978
  # as a lookup rather than a special case.
979
  ut_means = _schema_means(key)
980
- return {"key": key,
981
- "label": (_read_nav_meta(session.runtime).get(key, {}).get("name")
982
- or defn.get("label") or key),
983
- "source": defn.get("source") or "Blank",
984
- "fields": [{"key": f["key"], "label": f["label"], "type": f["type"],
985
- "source": f.get("source") or "overlay",
986
- "description": str(f.get("description") or ""),
987
- "means": ut_means.get(f["key"], "")}
988
- for f in base if f.get("key") not in hidden],
989
- "measures": []}
 
 
 
990
  session.require(key)
991
  pages = perms.nav_pages(session.user) or []
992
  page = next((p for p in pages if p.get("key") == key), None)
@@ -1086,4 +1130,38 @@ def nav_schema(key: str, session: Session = Depends(require_session)):
1086
  # is the sentence's ORIGINAL and still correct case, a key for which no field
1087
  # contract was ever assembled.
1088
  out["note"] = "This database has not published a field contract yet."
 
1089
  return out
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
917
  return {}
918
 
919
 
920
+ def _may_configure_database_setup(key, session):
921
+ """Whether this session may change tenant-wide setup for one database.
922
+
923
+ Built-in databases have no personal owner, so their setup is administrative. A user table
924
+ follows its existing database-editor authority: its creator, an administrator, or an editor
925
+ grant. Reading a schema remains wider than configuring it.
926
+ """
927
+ if str(key).startswith("ut_"):
928
+ try:
929
+ import core.user_tables as user_tables
930
+ return user_tables.may_edit_database(
931
+ key, session.uname, session.admin, st=session.runtime)
932
+ except Exception:
933
+ return False
934
+ return bool(session.admin)
935
+
936
+
937
+ def _map_setup_payload(key, fields, session):
938
+ """The schema drawer's Map section, using fields this session may legitimately configure."""
939
+ from core import database_setup
940
+
941
+ can_configure = _may_configure_database_setup(key, session)
942
+ option_fields = fields
943
+ # An admin may configure a built-in database's tenant-wide custom fields even though the
944
+ # compact schema drawer's historical field table is the canonical Odoo contract. The
945
+ # permission editor already owns that richer vocabulary, including tenant-generated fields.
946
+ # A non-admin editor stays on the field-walled schema list supplied to this request.
947
+ if can_configure and session.admin:
948
+ try:
949
+ from routes_admin import _module_fields
950
+ option_fields = _module_fields(key, session=session)
951
+ import core.schema_overlay as schema_overlay
952
+ option_fields, _hidden = schema_overlay.for_grid(
953
+ key, option_fields, st=session.runtime, contract=option_fields)
954
+ except Exception:
955
+ option_fields = fields
956
+ options = database_setup.coordinate_fields(option_fields)
957
+ active = database_setup.map_for(key, options, st=session.runtime)
958
+ return {"canConfigure": can_configure, "fields": options, **active}
959
+
960
+
961
  @router.get("/nav/schema/{key}")
962
  def nav_schema(key: str, session: Session = Depends(require_session)):
963
  """The database's schema drawer payload: its field contract + the semantic measures this
 
1018
  # key, because no user table maps to a topic; see `_schema_means` for why that is written
1019
  # as a lookup rather than a special case.
1020
  ut_means = _schema_means(key)
1021
+ ut_fields = [{"key": f["key"], "label": f["label"], "type": f["type"],
1022
+ "source": f.get("source") or "overlay",
1023
+ "description": str(f.get("description") or ""),
1024
+ "means": ut_means.get(f["key"], "")}
1025
+ for f in base if f.get("key") not in hidden]
1026
+ out = {"key": key,
1027
+ "label": (_read_nav_meta(session.runtime).get(key, {}).get("name")
1028
+ or defn.get("label") or key),
1029
+ "source": defn.get("source") or "Blank",
1030
+ "fields": ut_fields,
1031
+ "measures": []}
1032
+ out["map"] = _map_setup_payload(key, ut_fields, session)
1033
+ return out
1034
  session.require(key)
1035
  pages = perms.nav_pages(session.user) or []
1036
  page = next((p for p in pages if p.get("key") == key), None)
 
1130
  # is the sentence's ORIGINAL and still correct case, a key for which no field
1131
  # contract was ever assembled.
1132
  out["note"] = "This database has not published a field contract yet."
1133
+ out["map"] = _map_setup_payload(key, fields, session)
1134
  return out
1135
+
1136
+
1137
+ @router.put("/nav/schema/{key}/map")
1138
+ def update_schema_map_setup(key: str, body: dict = Body(default=None),
1139
+ session: Session = Depends(require_session)):
1140
+ """Set one database's custom Map latitude/longitude pair from its schema drawer.
1141
+
1142
+ The ordinary schema route is intentionally called first: it is the existing database and
1143
+ field wall, so this write cannot turn a key guessed in the URL into a setup record or expose
1144
+ a field the requester cannot configure. It never writes through Odoo; only the tenant's own
1145
+ setup document changes.
1146
+ """
1147
+ body = body if isinstance(body, dict) else {}
1148
+ if "latField" not in body or "lonField" not in body:
1149
+ raise err(400, "bad_request", "choose both coordinate fields or clear the custom source")
1150
+ schema = nav_schema(key, session)
1151
+ map_payload = schema.get("map") if isinstance(schema, dict) else None
1152
+ if not isinstance(map_payload, dict) or not map_payload.get("canConfigure"):
1153
+ raise err(403, "forbidden", "you cannot change this database's setup")
1154
+ if not session.runtime.available():
1155
+ raise err(503, "store_unavailable", "the tenant store is unavailable. Nothing was saved.")
1156
+ try:
1157
+ from core import database_setup
1158
+ active = database_setup.set_map(
1159
+ key, body.get("latField"), body.get("lonField"),
1160
+ map_payload.get("fields") or [], st=session.runtime)
1161
+ except database_setup.DatabaseSetupRefused as exc:
1162
+ raise err(400, "bad_map_setup", str(exc))
1163
+ except Exception:
1164
+ raise err(503, "store_unavailable", "the Map setup was not saved.")
1165
+ return {"map": {"canConfigure": True,
1166
+ "fields": map_payload.get("fields") or [],
1167
+ **active}}
platform/aios_grid.py CHANGED
@@ -2699,9 +2699,8 @@ def _clean_display(raw, valid_keys):
2699
  """Structural passthrough for a view's `config.display` (wave-6 item 10), fail-closed.
2700
 
2701
  `{mode, dateField?, stackField?, titleField?, colorField?, sizeField?, coordField?, charts?}` — mode
2702
- must be known. Bare `grid` is the absent default, but Grid + `coordField` is the one durable
2703
- pre-Map setup state: a person may choose their location column before opening Map. Every field
2704
- ref must name a field this table has (a ref to a deleted field is DROPPED and the client falls
2705
  back to its per-mode default); unknown keys are
2706
  dropped. What each mode MEANS — calendar wants a date-family field, kanban a select-family
2707
  stack, map a single-select to colour by and a numeric to size by — is the client's
@@ -2730,10 +2729,10 @@ def _clean_display(raw, valid_keys):
2730
  mode = raw.get('mode')
2731
  if mode not in DISPLAY_MODES:
2732
  return None
2733
- # Grid is normally represented by an absent display object. The custom Map location picker is
2734
- # deliberately reachable *before* Map, though, so retain this one valid field reference while
2735
- # refusing every unrelated Grid-only display setting. Without this narrow exception Setup
2736
- # appears to work, then silently loses its selection on the next server round trip.
2737
  if mode == 'grid':
2738
  coord_field = raw.get('coordField')
2739
  return {'mode': 'grid', 'coordField': coord_field} if coord_field in valid_keys else None
@@ -2742,10 +2741,8 @@ def _clean_display(raw, valid_keys):
2742
  # saved 'dashboard' view reads back as 'chart' from here on; nothing writes 'dashboard'.
2743
  mode = _LEGACY_MODES.get(mode, mode)
2744
  out = {'mode': mode}
2745
- # ⭐ W37-T28 (owner item 15) — `coordField`: ONE column holding `"lat,lon"`, so a map is no
2746
- # longer a customers-only feature. It joins this loop rather than getting a clause of its own
2747
- # because it IS a field ref with the same drop-if-deleted rule; `customer-grid/types.ts`
2748
- # gains it in the SAME change, which is contract C2's whole point.
2749
  for ref in ('dateField', 'stackField', 'titleField', 'colorField', 'sizeField', 'coordField'):
2750
  if raw.get(ref) in valid_keys:
2751
  out[ref] = raw[ref]
 
2699
  """Structural passthrough for a view's `config.display` (wave-6 item 10), fail-closed.
2700
 
2701
  `{mode, dateField?, stackField?, titleField?, colorField?, sizeField?, coordField?, charts?}` — mode
2702
+ must be known. `coordField` is retained only to read older saved Views; new Map source setup
2703
+ is database-owned. Every field ref must name a field this table has (a ref to a deleted field is DROPPED and the client falls
 
2704
  back to its per-mode default); unknown keys are
2705
  dropped. What each mode MEANS — calendar wants a date-family field, kanban a select-family
2706
  stack, map a single-select to colour by and a numeric to size by — is the client's
 
2729
  mode = raw.get('mode')
2730
  if mode not in DISPLAY_MODES:
2731
  return None
2732
+ # Grid is normally represented by an absent display object. Retain a valid legacy Map source
2733
+ # when an older configured Map view returns here, while refusing every unrelated Grid-only
2734
+ # display setting. Without this compatibility exception existing views lose their pins on the
2735
+ # next server round trip.
2736
  if mode == 'grid':
2737
  coord_field = raw.get('coordField')
2738
  return {'mode': 'grid', 'coordField': coord_field} if coord_field in valid_keys else None
 
2741
  # saved 'dashboard' view reads back as 'chart' from here on; nothing writes 'dashboard'.
2742
  mode = _LEGACY_MODES.get(mode, mode)
2743
  out = {'mode': mode}
2744
+ # `coordField` is the older per-View fallback. Keep it in the regular field-ref loop so a
2745
+ # deleted source fails safely; the current source is served separately as database setup.
 
 
2746
  for ref in ('dateField', 'stackField', 'titleField', 'colorField', 'sizeField', 'coordField'):
2747
  if raw.get(ref) in valid_keys:
2748
  out[ref] = raw[ref]
platform/core/database_setup.py ADDED
@@ -0,0 +1,156 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Durable, tenant-scoped setup for one database.
2
+
3
+ The document is deliberately separate from a saved View. A View arranges one person's
4
+ reading of records; a database setup names a property every Map of that database must share.
5
+ The first section is ``map.latField`` + ``map.lonField``: the two actual database columns used
6
+ to plot records. Future database-owned setup sections extend the record below rather than adding
7
+ another per-View preference.
8
+
9
+ Document shape::
10
+
11
+ {"<database key>": {"map": {"latField": "latitude", "lonField": "longitude"}}}
12
+
13
+ An absent map section means "try the database's built-in ``lat``/``lon`` transport values".
14
+ That is an honest default for every database: a Map can always open; only records without a
15
+ usable location fail to produce pins.
16
+ """
17
+
18
+ STORE_KEY = "database_setup"
19
+ COORDINATE_FIELD_TYPES = frozenset({
20
+ "text", "int", "currency", "pct", "rating", "number", "float", "decimal",
21
+ })
22
+ _LEGACY_COMPOSITE_FIELD_TYPES = frozenset({"text", "url", "email"})
23
+ MAX_FIELD_KEY = 160
24
+
25
+
26
+ class DatabaseSetupRefused(ValueError):
27
+ """A setup input that cannot become a durable database setting."""
28
+
29
+
30
+ def coordinate_fields(fields):
31
+ """The fields that can carry one latitude or longitude value.
32
+
33
+ The caller supplies its served field contract, so a hidden or removed field can never be
34
+ exposed by this small configuration record. A coordinate can be a numeric cell or text that
35
+ parses as one; status and choice values remain deliberately excluded.
36
+ """
37
+ out = []
38
+ seen = set()
39
+ for field in fields or ():
40
+ if not isinstance(field, dict):
41
+ continue
42
+ key = field.get("key")
43
+ if not isinstance(key, str) or not key or key in seen:
44
+ continue
45
+ if field.get("type") not in COORDINATE_FIELD_TYPES:
46
+ continue
47
+ seen.add(key)
48
+ out.append({"key": key,
49
+ "label": str(field.get("label") or key),
50
+ "type": str(field.get("type") or "text")})
51
+ return out
52
+
53
+
54
+ def _read(st):
55
+ """Read this tenant's setup document; callers always provide their tenant runtime."""
56
+ if st is None:
57
+ raise DatabaseSetupRefused("a tenant store handle is required")
58
+ doc = st.get(STORE_KEY)
59
+ return doc if isinstance(doc, dict) else {}
60
+
61
+
62
+ def map_for(database_key, fields, *, st):
63
+ """The currently usable Map setup for a served field contract.
64
+
65
+ A stale setup is ignored rather than guessed. If either configured field was removed or
66
+ hidden, Map falls back to its built-in pair until an editor chooses another source.
67
+ """
68
+ allowed = {field["key"]: field for field in coordinate_fields(fields)}
69
+ if not allowed:
70
+ return {}
71
+ try:
72
+ entry = _read(st).get(str(database_key))
73
+ except Exception:
74
+ # A setup read is additive display metadata. The grid remains usable and Map retains
75
+ # its historical lat/lon fallback while the store is unavailable.
76
+ return {}
77
+ bag = entry.get("map") if isinstance(entry, dict) else None
78
+ if not isinstance(bag, dict):
79
+ return {}
80
+ lat_field, lon_field = bag.get("latField"), bag.get("lonField")
81
+ if (isinstance(lat_field, str) and isinstance(lon_field, str)
82
+ and lat_field != lon_field and lat_field in allowed and lon_field in allowed):
83
+ return {"latField": lat_field, "lonField": lon_field}
84
+ # A short-lived prerelease used one composite text field. Keep reading it so no tenant loses
85
+ # pins, but new setup always saves the explicit pair above.
86
+ legacy = bag.get("coordField")
87
+ if (isinstance(legacy, str) and legacy in allowed
88
+ and allowed[legacy].get("type") in _LEGACY_COMPOSITE_FIELD_TYPES):
89
+ return {"coordField": legacy}
90
+ return {}
91
+
92
+
93
+ def set_map(database_key, lat_field, lon_field, fields, *, st):
94
+ """Atomically set or clear one database's custom Map latitude/longitude pair.
95
+
96
+ Both values as ``None`` clear the custom override and restore the built-in lat/lon fallback.
97
+ The updater
98
+ preserves every other database and any future setup section, so this first setting establishes
99
+ a stable per-database setup home rather than another one-off bucket.
100
+ """
101
+ key = str(database_key or "").strip()
102
+ if not key:
103
+ raise DatabaseSetupRefused("a database key is required")
104
+
105
+ def clean_field(value, label):
106
+ if value is None:
107
+ return None
108
+ if not isinstance(value, str):
109
+ raise DatabaseSetupRefused(f"the {label} field must be text or null")
110
+ value = value.strip()
111
+ if not value:
112
+ return None
113
+ if len(value) > MAX_FIELD_KEY:
114
+ raise DatabaseSetupRefused(f"the {label} field name is too long")
115
+ return value
116
+
117
+ lat_field = clean_field(lat_field, "latitude")
118
+ lon_field = clean_field(lon_field, "longitude")
119
+ if (lat_field is None) != (lon_field is None):
120
+ raise DatabaseSetupRefused("choose both latitude and longitude fields, or use built-in coordinates")
121
+ if lat_field is not None and lat_field == lon_field:
122
+ raise DatabaseSetupRefused("latitude and longitude must use different fields")
123
+ allowed = {field["key"] for field in coordinate_fields(fields)}
124
+ if lat_field is not None and (lat_field not in allowed or lon_field not in allowed):
125
+ raise DatabaseSetupRefused("choose latitude and longitude fields from this database")
126
+ if st is None:
127
+ raise DatabaseSetupRefused("a tenant store handle is required")
128
+
129
+ def update(raw):
130
+ document = dict(raw) if isinstance(raw, dict) else {}
131
+ entry = dict(document.get(key) or {}) if isinstance(document.get(key), dict) else {}
132
+ map_bag = dict(entry.get("map") or {}) if isinstance(entry.get("map"), dict) else {}
133
+ # Also remove the prerelease composite shape: one save migrates the database to its
134
+ # explicit coordinate pair while preserving any unrelated future Map settings.
135
+ map_bag.pop("coordField", None)
136
+ if lat_field is None:
137
+ map_bag.pop("latField", None)
138
+ map_bag.pop("lonField", None)
139
+ else:
140
+ map_bag["latField"] = lat_field
141
+ map_bag["lonField"] = lon_field
142
+ if map_bag:
143
+ entry["map"] = map_bag
144
+ else:
145
+ entry.pop("map", None)
146
+ if entry:
147
+ document[key] = entry
148
+ else:
149
+ document.pop(key, None)
150
+ return document
151
+
152
+ try:
153
+ st.update(STORE_KEY, update, flush="sync")
154
+ except Exception as exc:
155
+ raise DatabaseSetupRefused("the database setup could not be saved") from exc
156
+ return map_for(key, fields, st=st)
web/src/customer-grid/CustomerGrid.tsx CHANGED
@@ -122,8 +122,7 @@ import type { GridFolder } from "./types";
122
  import type { FieldStamps } from "./optimism";
123
  import { evalFormula, orderFormulas, parseFormula } from "./formulaEngine";
124
  import type { FormulaAst } from "./formulaEngine";
125
- import { CalendarSettings, CalendarView, KanbanView, ListView, MapSettings, MapSetup, ModeSwitch } from "./viewModes";
126
- import { hasBuiltInMapCoordinates, isMapCoordinateField, mapCoordinatesReady } from "./mapSetup";
127
  import { SwipeView } from "./SwipeView";
128
  import type { SwipeSpec } from "./SwipeView";
129
  // The chart engine lives in `viz/` since EXIT wave 2 (W2-5/Y3) — the grid is now
@@ -738,18 +737,6 @@ function withColorField(config: ViewConfig, key: string): ViewConfig {
738
  return { ...config, colorBy: key || null, display: cleanDisplay(display) };
739
  }
740
 
741
- /**
742
- * The one writer for Map's custom location field. Setup is available on Grid as well as Map, so
743
- * an absent display spec must become a grid-carried spec rather than making a painted control inert.
744
- */
745
- function withMapCoordinateField(config: ViewConfig, key: string): ViewConfig {
746
- const spec = cleanDisplay(config.display) ?? { mode: "grid" as const };
747
- const display: DisplaySpec = { ...spec };
748
- if (key) display.coordField = key;
749
- else delete display.coordField;
750
- return { ...config, display: cleanDisplay(display) };
751
- }
752
-
753
  /** Atomically scrub every view reference to the fields the server actually removed. */
754
  export function configWithoutFields(
755
  config: ViewConfig,
@@ -7310,20 +7297,8 @@ function CustomerGridSurface({
7310
  [config, updateConfig]
7311
  );
7312
 
7313
- // Wave-6 item 10 — display-mode plumbing. W13 (contract C4 as AMENDED 2026-07-28):
7314
- // `config.display` is the ONE home for the field picks, so leaving a mode must NOT
7315
- // wipe them — returning to grid keeps the refs in the draft (mode 'grid' + refs;
7316
- // cleanDisplay's carry), which is what lets the next Kanban/Calendar restore the
7317
- // chosen field instead of feeding the select its default. A view that never picked
7318
- // stays byte-identical (ref-less grid normalizes to absent, the legacy rule).
7319
- const hasDefaultMapCoordinates = useMemo(
7320
- () => hasBuiltInMapCoordinates(fields, rawRows),
7321
- [fields, rawRows]
7322
- );
7323
- const mapReady = useMemo(
7324
- () => mapCoordinatesReady(fields, rawRows, displaySpec?.coordField),
7325
- [fields, rawRows, displaySpec?.coordField]
7326
- );
7327
  const setDisplayMode = useCallback(
7328
  (m: DisplayMode) => {
7329
  // I12 (C3) — a locked view's MODE is frozen. The switcher is already hidden for one,
@@ -7334,10 +7309,6 @@ function CustomerGridSurface({
7334
  // callback is declared above it.)
7335
  const av = views.find((v) => v.id === activeViewId);
7336
  if (av && isModeFrozen(av)) return;
7337
- if (m === "map" && !mapReady) {
7338
- signal(TOAST_EVENT, "Map needs coordinates. Open Setup and choose a coordinate field first.");
7339
- return;
7340
- }
7341
  const spec = displaySpec;
7342
  if (m === "grid") {
7343
  updateConfig({
@@ -7348,7 +7319,7 @@ function CustomerGridSurface({
7348
  }
7349
  updateConfig({ ...config, display: { ...(spec ?? {}), mode: m } });
7350
  },
7351
- [config, displaySpec, updateConfig, views, activeViewId, mapReady]
7352
  );
7353
  // C4 (amended): the pick is written INTO display and the selects are FED from the
7354
  // view def (`display.<field>`), never from component state that dies on unmount.
@@ -7522,34 +7493,22 @@ function CustomerGridSurface({
7522
  [fields]
7523
  );
7524
  /**
7525
- * ⭐⭐ W37-T28 (item 15) — THE MAP'S COORDINATE COLUMN, chosen per view.
7526
- *
7527
- * ⛔ ONE field holding `"lat,lon"`, never a PAIR of props (D-4). Absent keeps the hardcoded
7528
- * `lat`/`lon` column pair, which is what every map view saved before this wave carries and is
7529
- * the whole reason this is not a migration.
7530
- * ⚠ The choices are deliberately WIDE (D-5: "any field whose cell can hold `lat,lon` text"), and
7531
- * that costs nothing — a cell that does not parse yields no pin and lands in the existing
7532
- * "N matching records have no location" chip rather than in an error.
7533
  */
7534
- const coordFieldChoices = useMemo(
7535
- () => fields.filter(isMapCoordinateField),
7536
- [fields]
7537
- );
7538
- const mapCoordField = displaySpec?.coordField
7539
- ? coordFieldChoices.find((f) => f.key === displaySpec.coordField)
 
 
 
 
 
 
7540
  : undefined;
7541
- /**
7542
- * ⛔ ITS OWN CALLBACK, NOT A FIFTH KEY ON `onPickField` (D-5, and D tried the union first).
7543
- * `setDisplayField` is typed to the narrow four-key union, so widening the prop makes this
7544
- * handler unassignable under `strictFunctionTypes` — in MY file, which D may not edit. One extra
7545
- * prop is cheaper than a red `tsc` for four lanes.
7546
- */
7547
- const onPickCoordField = useCallback(
7548
- (key: string) => {
7549
- updateConfig(withMapCoordinateField(config, key));
7550
- },
7551
- [config, updateConfig]
7552
- );
7553
  /**
7554
  * ⛔⛔ AN ADAPTER, AND IT EXISTS BECAUSE THE STORED SHAPE IS DECLARED TWICE (reported as
7555
  * `NOTE C-23`). `types.ts::CatalogViewSpec` mirrors `aios_grid._clean_catalog_spec`, which emits
@@ -8000,10 +7959,6 @@ function CustomerGridSurface({
8000
  no longer offers a second control for choosing it. `colorFieldChoices` survives too and
8001
  now feeds the toolbar's one Color control. */
8002
  onPickField={setDisplayField}
8003
- /* ⭐ W37-T28 (item 15) — the coordinate picker's three props. D's own guard renders the
8004
- control only when `coordChoices.length > 0 && onPickCoordField`, so there is no
8005
- arrangement that paints a control which does nothing
8006
- (`web_map::coord-picker-has-a-handler` asserts it by name). */
8007
  // Items 3 + 4 (C-DISP). `kanbanClamp` is absent-means-clamped, so the boolean handed
8008
  // down is `!== false` rather than a truthiness test — the one place that distinction
8009
  // decides whether the user's opt-out survives a reload.
@@ -8018,18 +7973,6 @@ function CustomerGridSurface({
8018
  onCalendarMetrics={setCalendarMetrics}
8019
  />
8020
  );
8021
- // ⭐ Wave-23 C7 — the open document, resolved exactly like the picker's value below it:
8022
- // the OPTIMISTIC edit wins over the raw record, so a save the server has not echoed yet is
8023
- // what re-opening the cell shows (the echo-suppression law — reading the raw row here would
8024
- // make a just-saved document appear to revert).
8025
- const mapSetupControl = serverWindowed || embedded || isQueryPreview ? undefined : (
8026
- <MapSetup
8027
- coordField={mapCoordField}
8028
- coordChoices={coordFieldChoices}
8029
- hasDefaultCoordinates={hasDefaultMapCoordinates}
8030
- onPickCoordField={onPickCoordField}
8031
- />
8032
- );
8033
  const jsonField = jsonAt ? fieldByKey.get(jsonAt.fieldKey) : undefined;
8034
  const jsonRow = jsonAt ? rawRows.find((r) => r.pid === jsonAt.pid) : undefined;
8035
  const jsonValue = String(
@@ -8773,7 +8716,6 @@ function CustomerGridSurface({
8773
  serverWindowed={serverWindowed}
8774
  cohortAction={cohortAction}
8775
  filterSeed={filterSeed}
8776
- setupControl={mapSetupControl}
8777
  modeControl={modeControl}
8778
  /* ⭐⭐ W41-T42 · R11 — BOTH CONTROL ROWS STAY VISIBLE and THIS one is the greyed,
8779
  unclickable primary. Not hidden and not collapsed to a chip: the conditions the
@@ -8802,10 +8744,6 @@ function CustomerGridSurface({
8802
  {workspaceDrawer && <aside className="cg-workspace-drawer" aria-label={workspaceDrawer === "notes" ? "Notes" : "History"}><header><strong>{workspaceDrawer === "notes" ? "Notes" : "History"}</strong><button type="button" className="cg-icon-button" aria-label="Close drawer" onClick={() => setWorkspaceDrawer(null)}>×</button></header>{drawerBusy && <span className="lp-spin" role="status" aria-label="Loading" />}{drawerError && <p role="alert">{drawerError}</p>}{workspaceDrawer === "notes" ? <><div className="cg-note-tabs" role="group" aria-label="Notes scope"><button type="button" className="cg-note-tab" aria-pressed={notesMode === "database"} onClick={() => setNotesMode("database")}>Database note</button><button type="button" className="cg-note-tab" aria-pressed={notesMode === "view"} onClick={() => setNotesMode("view")}>View note</button></div><div className="cg-note-feed" aria-live="polite">{savedNote ? <article className="cg-record-comment"><div className="cg-record-comment-avatar" aria-hidden>{noteInitials(savedNote.author)}</div><div className="cg-record-comment-content"><div className="cg-record-comment-meta"><strong>{savedNote.author || "Unknown"}</strong><time dateTime={savedNote.updated}>{noteWhen(savedNote.updated)}</time><button type="button" className="cg-note-edit" aria-label={notesMode === "view" ? "Edit this View note" : "Edit this Database note"} title="Edit note" onClick={() => { setSharedNote(savedNote.body); setNoteEditing(true); window.setTimeout(() => document.getElementById("cg-note-input")?.focus(), 0); }}>Edit</button></div><p>{savedNote.body}</p></div></article> : !drawerBusy && <div className="cg-record-comment-state">No note yet. Write the first one below.</div>}</div><form className="cg-note-compose cg-record-comment-compose" onSubmit={(event) => { event.preventDefault(); void saveSharedNote(); }}><label htmlFor="cg-note-input">{noteEditing ? (notesMode === "view" ? "Editing this View note" : "Editing this Database note") : savedNote ? (notesMode === "view" ? "Update this View note" : "Update this Database note") : (notesMode === "view" ? "Add a View note" : "Add a Database note")}</label><textarea id="cg-note-input" className="cg-note-input" value={sharedNote} maxLength={100000} placeholder={noteEditing ? "Edit the note and save your changes" : savedNote ? "Write a new version of this note" : "Share context with the team here"} onChange={(event) => setSharedNote(event.target.value)} onKeyDown={(event) => { if ((event.ctrlKey || event.metaKey) && event.key === "Enter") { event.preventDefault(); event.currentTarget.form?.requestSubmit(); } }} /><div className="cg-record-comment-compose-foot"><span>Ctrl/Cmd + Enter to save</span>{noteEditing && <button type="button" className="cg-note-cancel" onClick={() => { setNoteEditing(false); setSharedNote(""); }}>Cancel</button>}<button type="submit" disabled={drawerBusy || noteSaving || !sharedNote.trim()}>{noteSaving ? "Saving…" : noteEditing ? "Save changes" : savedNote ? "Update note" : "Save note"}</button></div></form></> : <><label>Retention<select className="cg-select" value={historyRetention} onChange={(event) => setHistoryRetention(Number(event.target.value) as 30 | 90)}><option value={30}>30 days</option><option value={90}>90 days · platform admin</option></select></label>{historyPid == null ? <p>Select one record to inspect its history.</p> : historyRows.length === 0 && !drawerBusy ? <p>No retained changes.</p> : <ol className="cg-history-list">{historyRows.map((event, index) => <li key={String(event.id ?? index)}><strong>{String(event.field ?? event.fieldKey ?? "Record")}</strong><span>{String(event.updatedAt ?? event.at ?? "")}</span><button type="button" className="cg-link-btn" onClick={async () => { if (!window.confirm("Restore this recorded value? This writes a new auditable change and does not erase history.")) return; const id = String(event.id ?? ""); const restoreUrl = scope.startsWith("ut_") ? `${API_V1}/tables/${encodeURIComponent(scope)}/history/${encodeURIComponent(id)}/restore` : `${API_V1}/grid/history/${encodeURIComponent(id)}/restore?scope=${encodeURIComponent(scope)}`; const response = await fetch(restoreUrl, { method: "POST", credentials: CREDENTIALS, headers: { "Content-Type": "application/json" }, body: JSON.stringify({ rowId: historyPid, field: event.field ?? event.fieldKey, retentionDays: historyRetention }) }); if (!response.ok) setDrawerError("Restore was refused. Your current value was not changed."); else setWorkspaceDrawer(null); }}>Restore…</button></li>)}</ol>}</>}</aside>}
8803
  {displayMode === "map" && !pivotOn && (
8804
  <MapSettings
8805
- coordField={mapCoordField}
8806
- coordChoices={coordFieldChoices}
8807
- hasDefaultCoordinates={hasDefaultMapCoordinates}
8808
- onPickCoordField={onPickCoordField}
8809
  sizeField={mapSizeField}
8810
  sizeChoices={sizeFieldChoices}
8811
  onPickSizeField={(key) => setDisplayField("sizeField", key)}
@@ -9479,8 +9417,9 @@ function CustomerGridSurface({
9479
  field={fieldByKey.get(lockedKey)!}
9480
  colorField={mapColorField}
9481
  sizeField={mapSizeField}
9482
- /* ⭐⭐ W37-T28 (item 15) — ONE column holding `"lat,lon"`, chosen per view. Absent
9483
- keeps the hardcoded `lat`/`lon` PAIR, which every pre-wave map view relies on. */
 
9484
  coordField={mapCoordField}
9485
  /* ⛔ THE MAP ASKS AND NEVER WRITES (D-12). The lookup control refuses to render
9486
  without this callback, so there is no arrangement of props in which a person can
 
122
  import type { FieldStamps } from "./optimism";
123
  import { evalFormula, orderFormulas, parseFormula } from "./formulaEngine";
124
  import type { FormulaAst } from "./formulaEngine";
125
+ import { CalendarSettings, CalendarView, KanbanView, ListView, MapSettings, ModeSwitch } from "./viewModes";
 
126
  import { SwipeView } from "./SwipeView";
127
  import type { SwipeSpec } from "./SwipeView";
128
  // The chart engine lives in `viz/` since EXIT wave 2 (W2-5/Y3) — the grid is now
 
737
  return { ...config, colorBy: key || null, display: cleanDisplay(display) };
738
  }
739
 
 
 
 
 
 
 
 
 
 
 
 
 
740
  /** Atomically scrub every view reference to the fields the server actually removed. */
741
  export function configWithoutFields(
742
  config: ViewConfig,
 
7297
  [config, updateConfig]
7298
  );
7299
 
7300
+ // Per-View display choices survive mode changes. Database-owned Map setup is intentionally
7301
+ // outside this config: every Map of the database shares it via the workspace envelope.
 
 
 
 
 
 
 
 
 
 
 
 
7302
  const setDisplayMode = useCallback(
7303
  (m: DisplayMode) => {
7304
  // I12 (C3) — a locked view's MODE is frozen. The switcher is already hidden for one,
 
7309
  // callback is declared above it.)
7310
  const av = views.find((v) => v.id === activeViewId);
7311
  if (av && isModeFrozen(av)) return;
 
 
 
 
7312
  const spec = displaySpec;
7313
  if (m === "grid") {
7314
  updateConfig({
 
7319
  }
7320
  updateConfig({ ...config, display: { ...(spec ?? {}), mode: m } });
7321
  },
7322
+ [config, displaySpec, updateConfig, views, activeViewId]
7323
  );
7324
  // C4 (amended): the pick is written INTO display and the selects are FED from the
7325
  // view def (`display.<field>`), never from component state that dies on unmount.
 
7493
  [fields]
7494
  );
7495
  /**
7496
+ * Map location is a database setup, not a View preference. The configured pair wins; an older
7497
+ * composite saved-View key remains a read-only fallback for existing tenants.
 
 
 
 
 
 
7498
  */
7499
+ const databaseMapLatitudeField = payload?.workspace?.mapSetup?.latField;
7500
+ const databaseMapLongitudeField = payload?.workspace?.mapSetup?.lonField;
7501
+ const mapCoordinateFields = useMemo(() => {
7502
+ if (!databaseMapLatitudeField || !databaseMapLongitudeField) return undefined;
7503
+ const latitude = fields.find((field) => field.key === databaseMapLatitudeField);
7504
+ const longitude = fields.find((field) => field.key === databaseMapLongitudeField);
7505
+ return latitude && longitude && latitude.key !== longitude.key ? { latitude, longitude } : undefined;
7506
+ }, [databaseMapLatitudeField, databaseMapLongitudeField, fields]);
7507
+ const databaseMapCoordField = payload?.workspace?.mapSetup?.coordField;
7508
+ const legacyMapCoordField = displaySpec?.coordField;
7509
+ const mapCoordField = !mapCoordinateFields && (databaseMapCoordField || legacyMapCoordField)
7510
+ ? fields.find((field) => field.key === (databaseMapCoordField || legacyMapCoordField))
7511
  : undefined;
 
 
 
 
 
 
 
 
 
 
 
 
7512
  /**
7513
  * ⛔⛔ AN ADAPTER, AND IT EXISTS BECAUSE THE STORED SHAPE IS DECLARED TWICE (reported as
7514
  * `NOTE C-23`). `types.ts::CatalogViewSpec` mirrors `aios_grid._clean_catalog_spec`, which emits
 
7959
  no longer offers a second control for choosing it. `colorFieldChoices` survives too and
7960
  now feeds the toolbar's one Color control. */
7961
  onPickField={setDisplayField}
 
 
 
 
7962
  // Items 3 + 4 (C-DISP). `kanbanClamp` is absent-means-clamped, so the boolean handed
7963
  // down is `!== false` rather than a truthiness test — the one place that distinction
7964
  // decides whether the user's opt-out survives a reload.
 
7973
  onCalendarMetrics={setCalendarMetrics}
7974
  />
7975
  );
 
 
 
 
 
 
 
 
 
 
 
 
7976
  const jsonField = jsonAt ? fieldByKey.get(jsonAt.fieldKey) : undefined;
7977
  const jsonRow = jsonAt ? rawRows.find((r) => r.pid === jsonAt.pid) : undefined;
7978
  const jsonValue = String(
 
8716
  serverWindowed={serverWindowed}
8717
  cohortAction={cohortAction}
8718
  filterSeed={filterSeed}
 
8719
  modeControl={modeControl}
8720
  /* ⭐⭐ W41-T42 · R11 — BOTH CONTROL ROWS STAY VISIBLE and THIS one is the greyed,
8721
  unclickable primary. Not hidden and not collapsed to a chip: the conditions the
 
8744
  {workspaceDrawer && <aside className="cg-workspace-drawer" aria-label={workspaceDrawer === "notes" ? "Notes" : "History"}><header><strong>{workspaceDrawer === "notes" ? "Notes" : "History"}</strong><button type="button" className="cg-icon-button" aria-label="Close drawer" onClick={() => setWorkspaceDrawer(null)}>×</button></header>{drawerBusy && <span className="lp-spin" role="status" aria-label="Loading" />}{drawerError && <p role="alert">{drawerError}</p>}{workspaceDrawer === "notes" ? <><div className="cg-note-tabs" role="group" aria-label="Notes scope"><button type="button" className="cg-note-tab" aria-pressed={notesMode === "database"} onClick={() => setNotesMode("database")}>Database note</button><button type="button" className="cg-note-tab" aria-pressed={notesMode === "view"} onClick={() => setNotesMode("view")}>View note</button></div><div className="cg-note-feed" aria-live="polite">{savedNote ? <article className="cg-record-comment"><div className="cg-record-comment-avatar" aria-hidden>{noteInitials(savedNote.author)}</div><div className="cg-record-comment-content"><div className="cg-record-comment-meta"><strong>{savedNote.author || "Unknown"}</strong><time dateTime={savedNote.updated}>{noteWhen(savedNote.updated)}</time><button type="button" className="cg-note-edit" aria-label={notesMode === "view" ? "Edit this View note" : "Edit this Database note"} title="Edit note" onClick={() => { setSharedNote(savedNote.body); setNoteEditing(true); window.setTimeout(() => document.getElementById("cg-note-input")?.focus(), 0); }}>Edit</button></div><p>{savedNote.body}</p></div></article> : !drawerBusy && <div className="cg-record-comment-state">No note yet. Write the first one below.</div>}</div><form className="cg-note-compose cg-record-comment-compose" onSubmit={(event) => { event.preventDefault(); void saveSharedNote(); }}><label htmlFor="cg-note-input">{noteEditing ? (notesMode === "view" ? "Editing this View note" : "Editing this Database note") : savedNote ? (notesMode === "view" ? "Update this View note" : "Update this Database note") : (notesMode === "view" ? "Add a View note" : "Add a Database note")}</label><textarea id="cg-note-input" className="cg-note-input" value={sharedNote} maxLength={100000} placeholder={noteEditing ? "Edit the note and save your changes" : savedNote ? "Write a new version of this note" : "Share context with the team here"} onChange={(event) => setSharedNote(event.target.value)} onKeyDown={(event) => { if ((event.ctrlKey || event.metaKey) && event.key === "Enter") { event.preventDefault(); event.currentTarget.form?.requestSubmit(); } }} /><div className="cg-record-comment-compose-foot"><span>Ctrl/Cmd + Enter to save</span>{noteEditing && <button type="button" className="cg-note-cancel" onClick={() => { setNoteEditing(false); setSharedNote(""); }}>Cancel</button>}<button type="submit" disabled={drawerBusy || noteSaving || !sharedNote.trim()}>{noteSaving ? "Saving…" : noteEditing ? "Save changes" : savedNote ? "Update note" : "Save note"}</button></div></form></> : <><label>Retention<select className="cg-select" value={historyRetention} onChange={(event) => setHistoryRetention(Number(event.target.value) as 30 | 90)}><option value={30}>30 days</option><option value={90}>90 days · platform admin</option></select></label>{historyPid == null ? <p>Select one record to inspect its history.</p> : historyRows.length === 0 && !drawerBusy ? <p>No retained changes.</p> : <ol className="cg-history-list">{historyRows.map((event, index) => <li key={String(event.id ?? index)}><strong>{String(event.field ?? event.fieldKey ?? "Record")}</strong><span>{String(event.updatedAt ?? event.at ?? "")}</span><button type="button" className="cg-link-btn" onClick={async () => { if (!window.confirm("Restore this recorded value? This writes a new auditable change and does not erase history.")) return; const id = String(event.id ?? ""); const restoreUrl = scope.startsWith("ut_") ? `${API_V1}/tables/${encodeURIComponent(scope)}/history/${encodeURIComponent(id)}/restore` : `${API_V1}/grid/history/${encodeURIComponent(id)}/restore?scope=${encodeURIComponent(scope)}`; const response = await fetch(restoreUrl, { method: "POST", credentials: CREDENTIALS, headers: { "Content-Type": "application/json" }, body: JSON.stringify({ rowId: historyPid, field: event.field ?? event.fieldKey, retentionDays: historyRetention }) }); if (!response.ok) setDrawerError("Restore was refused. Your current value was not changed."); else setWorkspaceDrawer(null); }}>Restore…</button></li>)}</ol>}</>}</aside>}
8745
  {displayMode === "map" && !pivotOn && (
8746
  <MapSettings
 
 
 
 
8747
  sizeField={mapSizeField}
8748
  sizeChoices={sizeFieldChoices}
8749
  onPickSizeField={(key) => setDisplayField("sizeField", key)}
 
9417
  field={fieldByKey.get(lockedKey)!}
9418
  colorField={mapColorField}
9419
  sizeField={mapSizeField}
9420
+ /* Database setup wins. A saved View's old coordField is only a silent fallback for
9421
+ tenants that created Map views before setup moved into View schema. */
9422
+ coordinateFields={mapCoordinateFields}
9423
  coordField={mapCoordField}
9424
  /* ⛔ THE MAP ASKS AND NEVER WRITES (D-12). The lookup control refuses to render
9425
  without this callback, so there is no arrangement of props in which a person can
web/src/customer-grid/MapView.tsx CHANGED
@@ -522,6 +522,25 @@ function coord(v: Row[keyof Row]): number | null {
522
  return Number.isFinite(n) ? n : null;
523
  }
524
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
525
  function numOrNull(v: Row[keyof Row]): number | null {
526
  if (v == null || v === "") return null;
527
  const n = typeof v === "number" ? v : Number(v);
@@ -548,6 +567,7 @@ function DrawZoneIcon() {
548
  export function MapView({
549
  rows,
550
  field,
 
551
  coordField,
552
  colorField,
553
  sizeField,
@@ -568,14 +588,17 @@ export function MapView({
568
  rows: Row[];
569
  /** The locked identity column — pin tooltips and aria labels. */
570
  field: Field;
571
- /**
572
- * W37-T34 — the view's `display.coordField`, resolved to a real field by the caller exactly
573
- * like `colorField`/`sizeField`. Its cell holds `"lat,lon"` (contract C7).
574
  *
575
  * ⛔ OPTIONAL, AND THE ABSENT CASE IS NOT "NO MAP" — it is the `lat`/`lon` column pair the
576
- * customers mirror has always carried. That fallback is the ONLY reason this change is not a
577
- * migration: every existing map view stored no `coordField`, and every one of them keeps
578
- * painting exactly what it painted before.
 
 
 
 
 
579
  */
580
  coordField?: Field;
581
  /** I3 — the view's `display.colorField`, already resolved to a real field. */
@@ -985,16 +1008,7 @@ export function MapView({
985
  const points = useMemo(() => {
986
  const out: MapPoint[] = [];
987
  for (const r of mapRows) {
988
- // W37-T34 — the chosen field first, the historic `lat`/`lon` pair when no field is chosen.
989
- const at = coordField
990
- ? parseLatLon(r[coordField.key])
991
- : (() => {
992
- const lat = coord(r.lat);
993
- const lon = coord(r.lon);
994
- if (lat == null || lon == null) return null;
995
- if (Math.abs(lat) > 90 || Math.abs(lon) > 180) return null;
996
- return { lat, lon };
997
- })();
998
  if (!at) continue;
999
  const { lat, lon } = at;
1000
  out.push({
@@ -1010,7 +1024,7 @@ export function MapView({
1010
  });
1011
  }
1012
  return out;
1013
- }, [mapRows, field.key, coordField, colorField, sizeField]);
1014
  const noCoords = mapRows.length - points.length;
1015
 
1016
  /**
@@ -1057,17 +1071,11 @@ export function MapView({
1057
  const out: Record<number, { lat: number; lon: number }> = {};
1058
  for (const row of (allRows?.length ? allRows : mapRows)) {
1059
  if (out[row.pid]) continue;
1060
- const at = coordField
1061
- ? parseLatLon(row[coordField.key])
1062
- : (() => {
1063
- const lat = coord(row.lat);
1064
- const lon = coord(row.lon);
1065
- return lat == null || lon == null || !isPlottable(lat, lon) ? null : { lat, lon };
1066
- })();
1067
  if (at) out[row.pid] = { lat: at.lat, lon: at.lon };
1068
  }
1069
  return out;
1070
- }, [allRows, mapRows, coordField]);
1071
 
1072
  const loadZones = useCallback(async () => {
1073
  zoneRequestRef.current.controller?.abort();
@@ -1994,17 +2002,11 @@ export function MapView({
1994
  const located = [] as { pid: number; lat: number; lon: number }[];
1995
  for (const row of (allRows?.length ? allRows : mapRows)) {
1996
  if (!wanted.has(row.pid)) continue;
1997
- const at = coordField
1998
- ? parseLatLon(row[coordField.key])
1999
- : (() => {
2000
- const lat = coord(row.lat);
2001
- const lon = coord(row.lon);
2002
- return lat == null || lon == null || !isPlottable(lat, lon) ? null : { lat, lon };
2003
- })();
2004
  if (at) located.push({ pid: row.pid, lat: at.lat, lon: at.lon });
2005
  }
2006
  return normalizedRouteMapLinks(activeNamedRoute.visibleStopIds, located, coarsePointer);
2007
- }, [activeNamedRoute, allRows, coarsePointer, coordField, mapRows]);
2008
  const activeRouteMapsRefusal = activeRouteMaps.missingStopIds.length
2009
  ? `${activeRouteMaps.missingStopIds.length.toLocaleString()} Route stop${activeRouteMaps.missingStopIds.length === 1 ? " has" : "s have"} no map location. Add coordinates before opening Maps links.`
2010
  : activeRouteMaps.refusal;
@@ -3325,7 +3327,7 @@ export function MapView({
3325
  if (!view || !fit) {
3326
  return (
3327
  <div className="cg-mode-empty">
3328
- No records with a location to map yet.
3329
  {noCoords > 0 &&
3330
  ` ${noCoords.toLocaleString()} matching record${noCoords === 1 ? "" : "s"} have no location.`}
3331
  {/* The way OUT of the empty state, offered from inside it. Selecting records and looking
 
522
  return Number.isFinite(n) ? n : null;
523
  }
524
 
525
+ type CoordinateFields = { latitude: Field; longitude: Field };
526
+
527
+ /** Resolve one row through database setup, then legacy composite setup, then built-in transport. */
528
+ function rowCoordinates(
529
+ row: Row,
530
+ coordinateFields?: CoordinateFields,
531
+ coordField?: Field,
532
+ ): { lat: number; lon: number } | null {
533
+ if (coordinateFields) {
534
+ const lat = coord(row[coordinateFields.latitude.key]);
535
+ const lon = coord(row[coordinateFields.longitude.key]);
536
+ return lat == null || lon == null || !isPlottable(lat, lon) ? null : { lat, lon };
537
+ }
538
+ if (coordField) return parseLatLon(row[coordField.key]);
539
+ const lat = coord(row.lat);
540
+ const lon = coord(row.lon);
541
+ return lat == null || lon == null || !isPlottable(lat, lon) ? null : { lat, lon };
542
+ }
543
+
544
  function numOrNull(v: Row[keyof Row]): number | null {
545
  if (v == null || v === "") return null;
546
  const n = typeof v === "number" ? v : Number(v);
 
567
  export function MapView({
568
  rows,
569
  field,
570
+ coordinateFields,
571
  coordField,
572
  colorField,
573
  sizeField,
 
588
  rows: Row[];
589
  /** The locked identity column — pin tooltips and aria labels. */
590
  field: Field;
591
+ /** The database's configured latitude and longitude fields, resolved by the caller.
 
 
592
  *
593
  * ⛔ OPTIONAL, AND THE ABSENT CASE IS NOT "NO MAP" — it is the `lat`/`lon` column pair the
594
+ * customers mirror has always carried. */
595
+ coordinateFields?: CoordinateFields;
596
+ /**
597
+ * Legacy composite location field from an older saved View or prerelease database setup.
598
+ * It remains a backwards-compatible fallback after the database-owned coordinate pair.
599
+ *
600
+ * That fallback is the ONLY reason this change is not a migration: every map without a custom
601
+ * source keeps painting exactly what it painted before.
602
  */
603
  coordField?: Field;
604
  /** I3 — the view's `display.colorField`, already resolved to a real field. */
 
1008
  const points = useMemo(() => {
1009
  const out: MapPoint[] = [];
1010
  for (const r of mapRows) {
1011
+ const at = rowCoordinates(r, coordinateFields, coordField);
 
 
 
 
 
 
 
 
 
1012
  if (!at) continue;
1013
  const { lat, lon } = at;
1014
  out.push({
 
1024
  });
1025
  }
1026
  return out;
1027
+ }, [mapRows, field.key, coordinateFields, coordField, colorField, sizeField]);
1028
  const noCoords = mapRows.length - points.length;
1029
 
1030
  /**
 
1071
  const out: Record<number, { lat: number; lon: number }> = {};
1072
  for (const row of (allRows?.length ? allRows : mapRows)) {
1073
  if (out[row.pid]) continue;
1074
+ const at = rowCoordinates(row, coordinateFields, coordField);
 
 
 
 
 
 
1075
  if (at) out[row.pid] = { lat: at.lat, lon: at.lon };
1076
  }
1077
  return out;
1078
+ }, [allRows, mapRows, coordinateFields, coordField]);
1079
 
1080
  const loadZones = useCallback(async () => {
1081
  zoneRequestRef.current.controller?.abort();
 
2002
  const located = [] as { pid: number; lat: number; lon: number }[];
2003
  for (const row of (allRows?.length ? allRows : mapRows)) {
2004
  if (!wanted.has(row.pid)) continue;
2005
+ const at = rowCoordinates(row, coordinateFields, coordField);
 
 
 
 
 
 
2006
  if (at) located.push({ pid: row.pid, lat: at.lat, lon: at.lon });
2007
  }
2008
  return normalizedRouteMapLinks(activeNamedRoute.visibleStopIds, located, coarsePointer);
2009
+ }, [activeNamedRoute, allRows, coarsePointer, coordinateFields, coordField, mapRows]);
2010
  const activeRouteMapsRefusal = activeRouteMaps.missingStopIds.length
2011
  ? `${activeRouteMaps.missingStopIds.length.toLocaleString()} Route stop${activeRouteMaps.missingStopIds.length === 1 ? " has" : "s have"} no map location. Add coordinates before opening Maps links.`
2012
  : activeRouteMaps.refusal;
 
3327
  if (!view || !fit) {
3328
  return (
3329
  <div className="cg-mode-empty">
3330
+ No records with a location to map yet. Set latitude and longitude fields in View schema to plot records.
3331
  {noCoords > 0 &&
3332
  ` ${noCoords.toLocaleString()} matching record${noCoords === 1 ? "" : "s"} have no location.`}
3333
  {/* The way OUT of the empty state, offered from inside it. Selecting records and looking
web/src/customer-grid/Toolbar.tsx CHANGED
@@ -226,11 +226,6 @@ interface ToolbarBaseProps {
226
  measure?: { key: string; window: WindowSpec };
227
  n: number;
228
  } | null;
229
- /**
230
- * The leftmost setup door, built by CustomerGrid because it owns any view-level
231
- * configuration. It must remain reachable before a person can enter a mode that needs it.
232
- */
233
- setupControl?: ReactNode;
234
  /** Wave-6 item 10 — the view-mode switcher (Grid · List · Calendar · Kanban), built by
235
  * CustomerGrid (it owns the display config). A slot, like `cohortAction`, so the toolbar
236
  * stays presentational. */
@@ -803,7 +798,6 @@ export default function Toolbar({
803
  serverWindowed = false,
804
  cohortAction,
805
  filterSeed = null,
806
- setupControl,
807
  modeControl,
808
  frozen = false,
809
  relationalTargets = [],
@@ -964,9 +958,6 @@ export default function Toolbar({
964
  : undefined
965
  }
966
  >
967
- {/* Setup comes first so a mode can never direct a person to a configuration control that
968
- only appears after that mode has already opened. */}
969
- {setupControl}
970
  {/* Wave-6 item 10 — the view-mode switcher decides what everything to its right operates
971
  on. */}
972
  {modeControl}
 
226
  measure?: { key: string; window: WindowSpec };
227
  n: number;
228
  } | null;
 
 
 
 
 
229
  /** Wave-6 item 10 — the view-mode switcher (Grid · List · Calendar · Kanban), built by
230
  * CustomerGrid (it owns the display config). A slot, like `cohortAction`, so the toolbar
231
  * stays presentational. */
 
798
  serverWindowed = false,
799
  cohortAction,
800
  filterSeed = null,
 
801
  modeControl,
802
  frozen = false,
803
  relationalTargets = [],
 
958
  : undefined
959
  }
960
  >
 
 
 
961
  {/* Wave-6 item 10 — the view-mode switcher decides what everything to its right operates
962
  on. */}
963
  {modeControl}
web/src/customer-grid/types.ts CHANGED
@@ -681,17 +681,9 @@ export interface DisplaySpec {
681
  /** Wave-8 contract C2 (I5) — map bubble size, a numeric/measure field key. */
682
  sizeField?: string;
683
  /**
684
- * ⭐⭐ W37-T28 (owner item 15) — THE MAP'S COORDINATE COLUMN: one field key whose cell holds
685
- * `"lat,lon"` (C7's pair, six decimals, written by the geocode field).
686
- *
687
- * ⛔ ONE KEY, NOT A PAIR (D-4). The map read hardcoded `r.lat`/`r.lon` — two columns only the
688
- * customers pool has — which is why a map was a customers-only feature. Under C7 the geocode
689
- * field writes BOTH numbers into ONE cell, so the view names one column.
690
- * ⚠ ABSENT KEEPS THE `lat`/`lon` PAIR, and that is what makes this not a migration: every map
691
- * view saved before this wave stored no `coordField`, and `MapView` still reads the pair when
692
- * none is chosen (D gates that fallback by name, `coord-latlon-fallback-kept`).
693
- * ⚠ It joins the ordinary field-ref loop in BOTH validators, so a ref to a deleted column is
694
- * dropped and the map falls back rather than plotting nothing against a key that matches no cell.
695
  */
696
  coordField?: string;
697
  /** Wave-8 contract C2 (I19) — the Dashboard mode's chart list, max 12.
@@ -1444,9 +1436,7 @@ export function cleanDisplay(raw: unknown): DisplaySpec | undefined {
1444
  // I10 (C2) — fold 'dashboard' to 'chart' AFTER the membership test above, mirroring
1445
  // `aios_grid._clean_display`. Every view saved before the rename reads back as a chart.
1446
  const out: DisplaySpec = { mode: normalizeDisplayMode(d.mode as DisplayMode) };
1447
- // ⭐ W37-T28 — `coordField` joins the ref loop rather than getting a clause of its own: it IS a
1448
- // field ref, with the same drop-if-deleted rule, and a bespoke clause would be a second set of
1449
- // rules for one question. The HOST's loop gains it in the same change (C2's mirror).
1450
  for (const k of ["dateField", "stackField", "titleField", "colorField", "sizeField",
1451
  "coordField"] as const) {
1452
  const v = d[k];
@@ -4531,6 +4521,12 @@ export interface GridWorkspace {
4531
  storageKey: string;
4532
  views: SavedView[];
4533
  activeViewId?: string;
 
 
 
 
 
 
4534
  /**
4535
  * ⭐⭐ WAVE 31 · T20 — LIMITS THE ENVELOPE ITSELF COULD NOT MEET, which is a different question
4536
  * from the rows payload's `limits` and needs its own answer.
 
681
  /** Wave-8 contract C2 (I5) — map bubble size, a numeric/measure field key. */
682
  sizeField?: string;
683
  /**
684
+ * Legacy only: older saved Views stored one composite `latitude, longitude` field here.
685
+ * New configuration is database-owned in `workspace.mapSetup`; this value stays parseable as a
686
+ * fallback so existing tenants retain their pins until they choose the database setup.
 
 
 
 
 
 
 
 
687
  */
688
  coordField?: string;
689
  /** Wave-8 contract C2 (I19) — the Dashboard mode's chart list, max 12.
 
1436
  // I10 (C2) — fold 'dashboard' to 'chart' AFTER the membership test above, mirroring
1437
  // `aios_grid._clean_display`. Every view saved before the rename reads back as a chart.
1438
  const out: DisplaySpec = { mode: normalizeDisplayMode(d.mode as DisplayMode) };
1439
+ // Legacy Map source keys remain in the field-ref loop so a deleted column clears the fallback.
 
 
1440
  for (const k of ["dateField", "stackField", "titleField", "colorField", "sizeField",
1441
  "coordField"] as const) {
1442
  const v = d[k];
 
4521
  storageKey: string;
4522
  views: SavedView[];
4523
  activeViewId?: string;
4524
+ /**
4525
+ * Tenant-wide setup for the database this grid draws. It is deliberately outside a View:
4526
+ * all Maps of one database use the same optional custom latitude/longitude pair, while absence
4527
+ * preserves the built-in `lat`/`lon` transport fallback. `coordField` is prerelease legacy only.
4528
+ */
4529
+ mapSetup?: { latField?: string; lonField?: string; coordField?: string };
4530
  /**
4531
  * ⭐⭐ WAVE 31 · T20 — LIMITS THE ENVELOPE ITSELF COULD NOT MEET, which is a different question
4532
  * from the rows payload's `limits` and needs its own answer.
web/src/customer-grid/viewModes.tsx CHANGED
@@ -116,17 +116,6 @@ function IconRouteZone() {
116
  );
117
  }
118
 
119
- /** R10: Location. A single map pin, the same pin the waypoint icon is built from, so the row
120
- * reads as one family rather than three unrelated marks. */
121
- function IconLocation() {
122
- return (
123
- <svg {...mapIc} aria-hidden>
124
- <path d="M8 1.8a3.2 3.2 0 0 1 3.2 3.2c0 2.4-3.2 5.9-3.2 5.9S4.8 7.4 4.8 5A3.2 3.2 0 0 1 8 1.8Z" {...mapStroke} />
125
- <circle cx="8" cy="5" r="1.15" {...mapStroke} />
126
- </svg>
127
- );
128
- }
129
-
130
  /** R10: Size. Two discs of different radius - the control sizes a pin BY a field, so the mark is
131
  * the comparison itself. */
132
  function IconSizeBy() {
@@ -519,79 +508,8 @@ export function CalendarSettings({
519
  );
520
  }
521
 
522
- /**
523
- * The one vocabulary both Map's persistent Setup door and its in-map quick picker use.
524
- * A database earns the default only when it actually supplies the historic lat/lon pair;
525
- * every other database must name one field containing `latitude, longitude`.
526
- */
527
- function mapLocationChoices(hasDefaultCoordinates: boolean, coordChoices: Field[]) {
528
- return [
529
- ...(hasDefaultCoordinates
530
- ? [{ key: "", label: "Built-in lat/lon columns", type: undefined }]
531
- : []),
532
- ...coordChoices.map((field) => ({
533
- key: field.key, label: `Location: ${field.label}`, type: field.type,
534
- })),
535
- ];
536
- }
537
-
538
- /**
539
- * Map setup is intentionally available before Map opens. A mode must never be the only route to
540
- * configuring the prerequisite that lets a person enter that mode.
541
- */
542
- export function MapSetup({
543
- coordField,
544
- coordChoices,
545
- hasDefaultCoordinates,
546
- onPickCoordField,
547
- }: {
548
- coordField?: Field;
549
- coordChoices: Field[];
550
- hasDefaultCoordinates: boolean;
551
- onPickCoordField: (key: string) => void;
552
- }) {
553
- const locations = mapLocationChoices(hasDefaultCoordinates, coordChoices);
554
- const value = coordField?.key ?? (hasDefaultCoordinates ? "" : undefined);
555
- return (
556
- <Popover label="Setup" icon={<IconLocation />} active={!!coordField}>
557
- {(close) => (
558
- <div className="cg-pop-body cg-builder">
559
- <div className="cg-pop-title">Map setup</div>
560
- <p className="cg-builder-caption">
561
- Use built-in lat/lon columns when available, or choose one field containing latitude, longitude.
562
- </p>
563
- {locations.length > 0 ? (
564
- <div className="cg-cond-line">
565
- <span className="cg-cond-prefix">Location</span>
566
- <FieldSelectButton
567
- className="cg-cond-field"
568
- ariaLabel="Map location field"
569
- placeholder="Choose a location field…"
570
- value={value}
571
- onChange={(key) => {
572
- onPickCoordField(key);
573
- close();
574
- }}
575
- fields={locations}
576
- />
577
- </div>
578
- ) : (
579
- <div className="cg-builder-empty">
580
- Add a text field that stores latitude, longitude before opening Map.
581
- </div>
582
- )}
583
- </div>
584
- )}
585
- </Popover>
586
- );
587
- }
588
-
589
  /** Map-only settings live beneath the main Filter / Sort / Group navigation. */
590
  export function MapSettings({
591
- coordField,
592
- coordChoices,
593
- hasDefaultCoordinates,
594
- onPickCoordField,
595
  sizeField,
596
  sizeChoices,
597
  onPickSizeField,
@@ -599,10 +517,6 @@ export function MapSettings({
599
  selectedCount,
600
  onToggleRoute,
601
  }: {
602
- coordField?: Field;
603
- coordChoices: Field[];
604
- hasDefaultCoordinates: boolean;
605
- onPickCoordField: (key: string) => void;
606
  sizeField?: Field;
607
  sizeChoices: Field[];
608
  onPickSizeField: (key: string) => void;
@@ -610,13 +524,11 @@ export function MapSettings({
610
  selectedCount: number;
611
  onToggleRoute: () => void;
612
  }) {
613
- const locations = mapLocationChoices(hasDefaultCoordinates, coordChoices);
614
  /**
615
  * W42-T24 retained contract: this row never self-hides. Route is a navigation into saved
616
- * routes as well as a planner for the current selection, so it must remain reachable before
617
- * this map has coordinate/size choices or selected records. The Route toggle below means the
618
- * row is never empty.
619
- */
620
  return (
621
  <div className="cg-map-settings" aria-label="Map settings">
622
  <button
@@ -630,19 +542,6 @@ export function MapSettings({
630
  <IconRouteZone />
631
  <span>Routes{selectedCount >= 2 ? ` / ${selectedCount} selected` : ""}</span>
632
  </button>
633
- {locations.length > 0 && (
634
- <span className="cg-mode-field-mark" aria-hidden><IconLocation /></span>
635
- )}
636
- {locations.length > 0 && (
637
- <FieldSelectButton
638
- className="cg-mode-field"
639
- ariaLabel="Plot pins from"
640
- placeholder="Choose a location field…"
641
- value={coordField?.key ?? (hasDefaultCoordinates ? "" : undefined)}
642
- onChange={onPickCoordField}
643
- fields={locations}
644
- />
645
- )}
646
  {sizeChoices.length > 0 && (
647
  <span className="cg-mode-field-mark" aria-hidden><IconSizeBy /></span>
648
  )}
 
116
  );
117
  }
118
 
 
 
 
 
 
 
 
 
 
 
 
119
  /** R10: Size. Two discs of different radius - the control sizes a pin BY a field, so the mark is
120
  * the comparison itself. */
121
  function IconSizeBy() {
 
508
  );
509
  }
510
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
511
  /** Map-only settings live beneath the main Filter / Sort / Group navigation. */
512
  export function MapSettings({
 
 
 
 
513
  sizeField,
514
  sizeChoices,
515
  onPickSizeField,
 
517
  selectedCount,
518
  onToggleRoute,
519
  }: {
 
 
 
 
520
  sizeField?: Field;
521
  sizeChoices: Field[];
522
  onPickSizeField: (key: string) => void;
 
524
  selectedCount: number;
525
  onToggleRoute: () => void;
526
  }) {
 
527
  /**
528
  * W42-T24 retained contract: this row never self-hides. Route is a navigation into saved
529
+ * routes as well as a planner for the current selection, so it remains reachable before this
530
+ * map has size choices or selected records. The Route toggle below means the row is never empty.
531
+ */
 
532
  return (
533
  <div className="cg-map-settings" aria-label="Map settings">
534
  <button
 
542
  <IconRouteZone />
543
  <span>Routes{selectedCount >= 2 ? ` / ${selectedCount} selected` : ""}</span>
544
  </button>
 
 
 
 
 
 
 
 
 
 
 
 
 
545
  {sizeChoices.length > 0 && (
546
  <span className="cg-mode-field-mark" aria-hidden><IconSizeBy /></span>
547
  )}
web/src/shell/NavExtras.tsx CHANGED
@@ -12,8 +12,9 @@
12
 
13
  import { useEffect, useRef, useState } from "react";
14
  import type { ReactNode } from "react";
15
- import { fetchSchema } from "./nav";
16
  import type { NavFolder, SchemaPayload, TableFootprint } from "./nav";
 
17
  // ⚠ WAVE 19 R8 / C1 — IMPORTED, NEVER REDEFINED, and the contract says so in as
18
  // many words ("Shapes/tones = the grid's existing vocabulary verbatim (12
19
  // shapes, 5 tones); B imports, never redefines"). A second copy of this
@@ -825,12 +826,24 @@ export function SchemaDrawer({
825
  const [state, setState] = useState<
826
  { phase: "loading" } | { phase: "ready"; schema: SchemaPayload } | { phase: "error" }
827
  >({ phase: "loading" });
 
 
 
828
  useEffect(() => {
829
  let cancelled = false;
830
  setState({ phase: "loading" });
 
 
 
831
  fetchSchema(schemaKey).then((schema) => {
832
  if (cancelled) return;
833
  setState(schema ? { phase: "ready", schema } : { phase: "error" });
 
 
 
 
 
 
834
  });
835
  return () => {
836
  cancelled = true;
@@ -843,6 +856,33 @@ export function SchemaDrawer({
843
  document.addEventListener("keydown", onKey, true);
844
  return () => document.removeEventListener("keydown", onKey, true);
845
  }, [onClose]);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
846
  return (
847
  <div className="shell-schema-backdrop" onMouseDown={onClose}>
848
  <aside
@@ -884,6 +924,79 @@ export function SchemaDrawer({
884
  {state.schema.note && (
885
  <div className="shell-schema-note">{state.schema.note}</div>
886
  )}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
887
  {state.schema.fields.length > 0 && (
888
  <>
889
  <div className="shell-schema-kicker">
 
12
 
13
  import { useEffect, useRef, useState } from "react";
14
  import type { ReactNode } from "react";
15
+ import { fetchSchema, saveSchemaMap } from "./nav";
16
  import type { NavFolder, SchemaPayload, TableFootprint } from "./nav";
17
+ import { WORKSPACE_STALE_EVENT, signal } from "../apiContract";
18
  // ⚠ WAVE 19 R8 / C1 — IMPORTED, NEVER REDEFINED, and the contract says so in as
19
  // many words ("Shapes/tones = the grid's existing vocabulary verbatim (12
20
  // shapes, 5 tones); B imports, never redefines"). A second copy of this
 
826
  const [state, setState] = useState<
827
  { phase: "loading" } | { phase: "ready"; schema: SchemaPayload } | { phase: "error" }
828
  >({ phase: "loading" });
829
+ const [mapSaving, setMapSaving] = useState(false);
830
+ const [mapError, setMapError] = useState("");
831
+ const [mapDraft, setMapDraft] = useState({ latField: "", lonField: "" });
832
  useEffect(() => {
833
  let cancelled = false;
834
  setState({ phase: "loading" });
835
+ setMapSaving(false);
836
+ setMapError("");
837
+ setMapDraft({ latField: "", lonField: "" });
838
  fetchSchema(schemaKey).then((schema) => {
839
  if (cancelled) return;
840
  setState(schema ? { phase: "ready", schema } : { phase: "error" });
841
+ if (schema) {
842
+ setMapDraft({
843
+ latField: schema.map.latField ?? "",
844
+ lonField: schema.map.lonField ?? "",
845
+ });
846
+ }
847
  });
848
  return () => {
849
  cancelled = true;
 
856
  document.addEventListener("keydown", onKey, true);
857
  return () => document.removeEventListener("keydown", onKey, true);
858
  }, [onClose]);
859
+ const mapPairIncomplete = Boolean(mapDraft.latField) !== Boolean(mapDraft.lonField);
860
+ const saveMap = async () => {
861
+ if (state.phase !== "ready" || !state.schema.map.canConfigure || mapSaving) return;
862
+ if (mapPairIncomplete) {
863
+ setMapError("Choose both a latitude and a longitude field, or leave both on Built-in.");
864
+ return;
865
+ }
866
+ setMapSaving(true);
867
+ setMapError("");
868
+ const map = await saveSchemaMap(
869
+ schemaKey,
870
+ mapDraft.latField || undefined,
871
+ mapDraft.lonField || undefined,
872
+ );
873
+ setMapSaving(false);
874
+ if (!map) {
875
+ setMapError("The Map setup was not saved. Try again.");
876
+ return;
877
+ }
878
+ setState((current) => current.phase === "ready"
879
+ ? { ...current, schema: { ...current.schema, map } }
880
+ : current);
881
+ setMapDraft({ latField: map.latField ?? "", lonField: map.lonField ?? "" });
882
+ // Map consumes this database-owned setting from its workspace envelope. Reuse the existing
883
+ // refresh signal so an open Map changes immediately without coupling the shell to grid state.
884
+ signal(WORKSPACE_STALE_EVENT);
885
+ };
886
  return (
887
  <div className="shell-schema-backdrop" onMouseDown={onClose}>
888
  <aside
 
924
  {state.schema.note && (
925
  <div className="shell-schema-note">{state.schema.note}</div>
926
  )}
927
+ <div className="shell-schema-kicker">Map</div>
928
+ <div className="shell-schema-card shell-schema-map-setup">
929
+ <div className="shell-schema-setup-label">Pin location</div>
930
+ {state.schema.map.canConfigure ? (
931
+ <>
932
+ <label className="shell-schema-setup-control">
933
+ <span>Latitude</span>
934
+ <select
935
+ aria-label="Map latitude field"
936
+ value={mapDraft.latField}
937
+ disabled={mapSaving}
938
+ onChange={(event) => {
939
+ setMapError("");
940
+ setMapDraft((draft) => ({ ...draft, latField: event.target.value }));
941
+ }}
942
+ >
943
+ <option value="">Built-in lat</option>
944
+ {state.schema.map.fields.map((field) => (
945
+ <option key={field.key} value={field.key}>
946
+ {field.label}
947
+ </option>
948
+ ))}
949
+ </select>
950
+ </label>
951
+ <label className="shell-schema-setup-control">
952
+ <span>Longitude</span>
953
+ <select
954
+ aria-label="Map longitude field"
955
+ value={mapDraft.lonField}
956
+ disabled={mapSaving}
957
+ onChange={(event) => {
958
+ setMapError("");
959
+ setMapDraft((draft) => ({ ...draft, lonField: event.target.value }));
960
+ }}
961
+ >
962
+ <option value="">Built-in lon</option>
963
+ {state.schema.map.fields.map((field) => (
964
+ <option key={field.key} value={field.key}>
965
+ {field.label}
966
+ </option>
967
+ ))}
968
+ </select>
969
+ </label>
970
+ {mapPairIncomplete && (
971
+ <div className="shell-schema-setup-status" role="status">
972
+ Choose the other coordinate field to save this pair.
973
+ </div>
974
+ )}
975
+ <div className="shell-schema-setup-actions">
976
+ <button
977
+ type="button"
978
+ disabled={mapSaving || mapPairIncomplete}
979
+ onClick={() => void saveMap()}
980
+ >
981
+ {mapSaving ? "Saving…" : "Save Map setup"}
982
+ </button>
983
+ </div>
984
+ </>
985
+ ) : (
986
+ <div className="shell-schema-setup-value">
987
+ {state.schema.map.latField && state.schema.map.lonField
988
+ ? `${state.schema.map.fields.find((field) => field.key === state.schema.map.latField)?.label ?? state.schema.map.latField} / ${state.schema.map.fields.find((field) => field.key === state.schema.map.lonField)?.label ?? state.schema.map.lonField}`
989
+ : state.schema.map.fields.find((field) => field.key === state.schema.map.coordField)?.label
990
+ ?? "Built-in lat / lon when supplied"}
991
+ </div>
992
+ )}
993
+ <p className="shell-schema-setup-help">
994
+ {state.schema.map.canConfigure
995
+ ? "Choose the latitude and longitude fields used to plot records. Leave both on Built-in to use the default lat / lon pair. Map stays available for every database."
996
+ : "A database editor can choose custom latitude and longitude fields here. Map stays available for every database."}
997
+ </p>
998
+ {mapError && <div className="shell-schema-setup-error" role="alert">{mapError}</div>}
999
+ </div>
1000
  {state.schema.fields.length > 0 && (
1001
  <>
1002
  <div className="shell-schema-kicker">
web/src/shell/nav.ts CHANGED
@@ -795,15 +795,63 @@ export interface SchemaField {
795
  options?: string[];
796
  }
797
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
798
  export interface SchemaPayload {
799
  key: string;
800
  label: string;
801
  source: string;
802
  fields: SchemaField[];
803
  measures: { key: string; label: string; type: string }[];
 
804
  note?: string;
805
  }
806
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
807
  export function parseSchema(body: unknown): SchemaPayload | null {
808
  if (!body || typeof body !== "object") return null;
809
  const b = body as Record<string, unknown>;
@@ -839,6 +887,7 @@ export function parseSchema(body: unknown): SchemaPayload | null {
839
  source: String(b.source ?? ""),
840
  fields,
841
  measures,
 
842
  ...(typeof b.note === "string" && b.note ? { note: b.note } : {}),
843
  };
844
  }
@@ -855,6 +904,28 @@ export async function fetchSchema(key: string): Promise<SchemaPayload | null> {
855
  }
856
  }
857
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
858
  /**
859
  * What the shell does with an entry:
860
  * native — this tree renders it (a hash route)
 
795
  options?: string[];
796
  }
797
 
798
+ /** One field a database editor may use for one half of a Map coordinate pair. */
799
+ export interface SchemaMapField {
800
+ key: string;
801
+ label: string;
802
+ type: string;
803
+ }
804
+
805
+ /** Database-owned Map setup, served alongside the schema rather than a saved View. */
806
+ export interface SchemaMapSetup {
807
+ canConfigure: boolean;
808
+ fields: SchemaMapField[];
809
+ latField?: string;
810
+ lonField?: string;
811
+ /** Prerelease compatibility only; new setup saves the explicit pair above. */
812
+ coordField?: string;
813
+ }
814
+
815
  export interface SchemaPayload {
816
  key: string;
817
  label: string;
818
  source: string;
819
  fields: SchemaField[];
820
  measures: { key: string; label: string; type: string }[];
821
+ map: SchemaMapSetup;
822
  note?: string;
823
  }
824
 
825
+ function parseSchemaMap(raw: unknown): SchemaMapSetup {
826
+ const source = raw && typeof raw === "object" ? raw as Record<string, unknown> : {};
827
+ const fields: SchemaMapField[] = [];
828
+ if (Array.isArray(source.fields)) {
829
+ for (const field of source.fields) {
830
+ if (!field || typeof field !== "object") continue;
831
+ const f = field as Record<string, unknown>;
832
+ if (typeof f.key !== "string" || !f.key) continue;
833
+ fields.push({
834
+ key: f.key,
835
+ label: typeof f.label === "string" && f.label ? f.label : f.key,
836
+ type: String(f.type ?? ""),
837
+ });
838
+ }
839
+ }
840
+ return {
841
+ canConfigure: source.canConfigure === true,
842
+ fields,
843
+ ...(typeof source.coordField === "string" && source.coordField
844
+ ? { coordField: source.coordField }
845
+ : {}),
846
+ ...(typeof source.latField === "string" && source.latField
847
+ ? { latField: source.latField }
848
+ : {}),
849
+ ...(typeof source.lonField === "string" && source.lonField
850
+ ? { lonField: source.lonField }
851
+ : {}),
852
+ };
853
+ }
854
+
855
  export function parseSchema(body: unknown): SchemaPayload | null {
856
  if (!body || typeof body !== "object") return null;
857
  const b = body as Record<string, unknown>;
 
887
  source: String(b.source ?? ""),
888
  fields,
889
  measures,
890
+ map: parseSchemaMap(b.map),
891
  ...(typeof b.note === "string" && b.note ? { note: b.note } : {}),
892
  };
893
  }
 
904
  }
905
  }
906
 
907
+ /** Persist one database's Map coordinate pair; two absent keys restore built-in `lat`/`lon`. */
908
+ export async function saveSchemaMap(
909
+ key: string,
910
+ latField: string | undefined,
911
+ lonField: string | undefined,
912
+ ): Promise<SchemaMapSetup | null> {
913
+ try {
914
+ const res = await fetch(`${API_V1}/nav/schema/${encodeURIComponent(key)}/map`, {
915
+ method: "PUT",
916
+ credentials: CREDENTIALS,
917
+ headers: { "Content-Type": "application/json" },
918
+ body: JSON.stringify({ latField: latField || null, lonField: lonField || null }),
919
+ });
920
+ if (!res.ok) return null;
921
+ const body = await res.json() as { map?: unknown } | null;
922
+ if (!body || !("map" in body)) return null;
923
+ return parseSchemaMap(body.map);
924
+ } catch {
925
+ return null;
926
+ }
927
+ }
928
+
929
  /**
930
  * What the shell does with an entry:
931
  * native — this tree renders it (a hash route)
web/src/styles/wave46/schema-viewer.css CHANGED
@@ -122,6 +122,109 @@
122
  background: var(--lp-wash);
123
  }
124
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
125
  /* `.set-card--rows`' lesson: inside a bordered card the final hairline has
126
  nothing under it to separate and reads as a stray underline. */
127
  .shell-schema .shell-schema-card tbody tr:last-child td {
 
122
  background: var(--lp-wash);
123
  }
124
 
125
+ /* The first database-owned setup section. It uses the same contained-card hierarchy as the
126
+ field list, but a normal form control is clearer than a faux map-toolbar picker: this choice
127
+ belongs to the database schema, not to one currently open View. */
128
+ .shell-schema .shell-schema-map-setup {
129
+ display: grid;
130
+ gap: 8px;
131
+ }
132
+
133
+ .shell-schema .shell-schema-setup-label {
134
+ font-size: var(--lp-fs-xs);
135
+ font-weight: 620;
136
+ color: var(--lp-ink);
137
+ }
138
+
139
+ .shell-schema .shell-schema-setup-control {
140
+ display: grid;
141
+ gap: 4px;
142
+ }
143
+
144
+ .shell-schema .shell-schema-setup-control > span {
145
+ font-size: var(--lp-fs-2xs);
146
+ font-weight: 620;
147
+ color: var(--lp-muted);
148
+ }
149
+
150
+ .shell-schema .shell-schema-setup-control select {
151
+ width: 100%;
152
+ border: 1px solid var(--lp-line);
153
+ border-radius: var(--lp-r-sm);
154
+ background: var(--lp-surface);
155
+ color: var(--lp-ink);
156
+ font: inherit;
157
+ padding: 7px 9px;
158
+ }
159
+
160
+ .shell-schema .shell-schema-setup-control select:focus-visible {
161
+ outline: 2px solid var(--lp-blue-deep);
162
+ outline-offset: 1px;
163
+ }
164
+
165
+ .shell-schema .shell-schema-setup-control select:disabled {
166
+ color: var(--lp-muted);
167
+ opacity: 0.65;
168
+ cursor: not-allowed;
169
+ }
170
+
171
+ .shell-schema .shell-schema-setup-actions {
172
+ display: flex;
173
+ justify-content: flex-end;
174
+ margin-top: 2px;
175
+ }
176
+
177
+ .shell-schema .shell-schema-setup-actions button {
178
+ border: 1px solid var(--lp-line);
179
+ border-radius: var(--lp-r-sm);
180
+ background: var(--lp-surface);
181
+ color: var(--lp-ink);
182
+ font: inherit;
183
+ font-size: var(--lp-fs-xs);
184
+ font-weight: 620;
185
+ padding: 6px 9px;
186
+ cursor: pointer;
187
+ }
188
+
189
+ @media (hover: hover) and (pointer: fine) {
190
+ .shell-schema .shell-schema-setup-actions button:hover:enabled {
191
+ border-color: var(--lp-blue-deep);
192
+ }
193
+ }
194
+
195
+ .shell-schema .shell-schema-setup-actions button:focus-visible {
196
+ outline: 2px solid var(--lp-blue-deep);
197
+ outline-offset: 1px;
198
+ }
199
+
200
+ .shell-schema .shell-schema-setup-actions button:disabled {
201
+ color: var(--lp-muted);
202
+ opacity: 0.65;
203
+ cursor: not-allowed;
204
+ }
205
+
206
+ .shell-schema .shell-schema-setup-value,
207
+ .shell-schema .shell-schema-setup-help,
208
+ .shell-schema .shell-schema-setup-status,
209
+ .shell-schema .shell-schema-setup-error {
210
+ margin: 0;
211
+ font-size: var(--lp-fs-2xs);
212
+ line-height: 1.4;
213
+ }
214
+
215
+ .shell-schema .shell-schema-setup-value {
216
+ color: var(--lp-ink);
217
+ }
218
+
219
+ .shell-schema .shell-schema-setup-help,
220
+ .shell-schema .shell-schema-setup-status {
221
+ color: var(--lp-muted);
222
+ }
223
+
224
+ .shell-schema .shell-schema-setup-error {
225
+ color: var(--lp-red-deep);
226
+ }
227
+
228
  /* `.set-card--rows`' lesson: inside a bordered card the final hairline has
229
  nothing under it to separate and reads as a stray underline. */
230
  .shell-schema .shell-schema-card tbody tr:last-child td {