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

Deploy AIOS web (React glide grid + FastAPI slice)

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. RELEASES.json +7 -1
  2. VERSION +1 -1
  3. api/deps.py +25 -8
  4. api/formula_runtime.py +264 -3
  5. api/main.py +5 -0
  6. api/odoo_relational.py +121 -7
  7. api/routes_connectors.py +551 -7
  8. api/routes_dependents.py +168 -0
  9. api/routes_keychain.py +100 -2
  10. api/routes_monid.py +300 -0
  11. api/routes_query.py +86 -7
  12. api/routes_shares.py +16 -2
  13. api/routes_sheet.py +502 -0
  14. platform/aios_grid_fields.json +14 -7
  15. platform/core/connector_directory.py +464 -0
  16. platform/core/dependents.py +515 -0
  17. platform/core/grid_events.py +1 -1
  18. platform/core/keychain.py +7 -0
  19. platform/core/monid.py +651 -0
  20. platform/core/perm_scope.py +16 -0
  21. platform/core/sheets.py +418 -0
  22. platform/core/user_tables.py +104 -7
  23. platform/harness/meta_store.py +74 -7
  24. platform/model/metrics/gl.yml +6 -0
  25. platform/model/metrics/receivables.yml +3 -0
  26. platform/model/topics/odoo_accounts.yml +24 -0
  27. platform/model/topics/odoo_bills.yml +27 -0
  28. platform/model/topics/odoo_invoices.yml +19 -0
  29. platform/model/topics/odoo_orders.yml +26 -0
  30. platform/model/topics/odoo_vendors.yml +22 -0
  31. platform/model/topics/receivables.yml +6 -0
  32. platform/model/topics/sales_lines.yml +9 -0
  33. platform/modules/product_data.py +213 -4
  34. platform/modules/sheet.py +421 -0
  35. platform/modules/warehouse.py +81 -0
  36. web/public/sample_customers.json +4 -4
  37. web/src/connectors/ConnectorModal.tsx +698 -0
  38. web/src/connectors/ConnectorsPage.tsx +584 -195
  39. web/src/connectors/DatabasesTab.tsx +438 -0
  40. web/src/connectors/DirectoryChips.tsx +117 -0
  41. web/src/connectors/KeychainTab.tsx +416 -0
  42. web/src/connectors/MonidRunDialog.tsx +414 -0
  43. web/src/connectors/RelationshipDiagram.tsx +770 -0
  44. web/src/connectors/ViewDeleteDisclosure.tsx +299 -0
  45. web/src/customer-grid/CustomerGrid.tsx +0 -0
  46. web/src/customer-grid/TimeSeriesPanel.tsx +66 -17
  47. web/src/customer-grid/viewModes.tsx +60 -18
  48. web/src/settings/SettingsModal.tsx +154 -61
  49. web/src/sheet/BindingEditor.tsx +208 -0
  50. web/src/sheet/CellActionBar.tsx +99 -0
RELEASES.json CHANGED
@@ -1,6 +1,12 @@
1
  {
2
- "current": "c4dc318",
3
  "releases": [
 
 
 
 
 
 
4
  {
5
  "version": "v68",
6
  "sha": "62b065a",
 
1
  {
2
+ "current": "daad0a1",
3
  "releases": [
4
+ {
5
+ "version": "v69",
6
+ "sha": "8598f56",
7
+ "date": "2026-09-02",
8
+ "subject": "release v69: wave48-continuation validated + hotfixes v67/v68/d4e3e31 + go-live QA repairs (Supplier option limit, optio"
9
+ },
10
  {
11
  "version": "v68",
12
  "sha": "62b065a",
VERSION CHANGED
@@ -1 +1 @@
1
- c4dc318
 
1
+ daad0a1
api/deps.py CHANGED
@@ -65,8 +65,25 @@ class Session:
65
  # invisible: a row the rail offers that the route 403s, or the reverse. The
66
  # editor's explicit grant lands here too, so a database an administrator ticked
67
  # is reachable by URL as well as visible in the rail.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
68
  import core.perm_scope as _perm_scope
69
- if not _perm_scope.nav_may_open(self.user, module_key):
70
  raise err(403, "forbidden", f"your account does not have access to {module_key}")
71
  tcfg = getattr(self.runtime.tenant, "config", None) or {}
72
  tmods = tcfg.get("modules", "all")
@@ -645,7 +662,7 @@ def assistant_source_status(session: Session, databases=None):
645
  if not _assistant_tenant_allows(session, key):
646
  row["visible"] = bool(perm_scope.may_access(session.user, key))
647
  row["reason"] = ("this workspace's catalogue does not list it as an assistant "
648
- "source — an administrator can add it")
649
  continue
650
  if perm_scope.assistant_entry(session.user, key) is None:
651
  row["visible"] = bool(perm_scope.may_access(session.user, key))
@@ -660,7 +677,7 @@ def assistant_source_status(session: Session, databases=None):
660
  # `is_migrated` and `may_access`, and `product_data` carries the SAME grant as
661
  # `customer_data` under one record — so the divergence is not visible in the perms
662
  # document and guessing at it once already produced a wrong answer.
663
- row["reason"] = ("the assistant cannot resolve a data grant for it yet — this is a "
664
  "known gap (D-276), not something you have set wrongly")
665
  continue
666
  row["permitted"] = True
@@ -677,7 +694,7 @@ def assistant_source_status(session: Session, databases=None):
677
  if isinstance(entry, tuple) and len(entry) >= 2 and isinstance(entry[1], (list, tuple)):
678
  row["answerable"] = True
679
  else:
680
- row["reason"] = "no snapshot loaded yet — open this database once, then ask"
681
  continue
682
  if not key.startswith("ut_"):
683
  continue
@@ -866,16 +883,16 @@ def require_session(request: Request, response: Response) -> Session:
866
  raise err(401, "no_session", "sign in to continue")
867
  claims = aios_session.read(raw)
868
  if not claims:
869
- raise err(401, "invalid_session", "your session has expired — sign in again")
870
  user = _user_for(claims)
871
  if not user:
872
- raise err(401, "invalid_session", "your session has expired — sign in again")
873
  try:
874
  rt = runtime.get_runtime(claims["t"])
875
  except KeyError:
876
  # An unknown tenant slug is a 401, not a 404: the cookie is not a valid identity for this
877
  # deployment, and confirming which slugs exist would answer a question we were not asked.
878
- raise err(401, "invalid_session", "your session has expired — sign in again")
879
  fresh, _ = aios_session.mint(claims["t"], user["username"], int(user.get("epoch") or 0),
880
  absolute_expiry=claims["x"])
881
  aios_session.set_cookie(response, request, fresh)
@@ -920,7 +937,7 @@ def require_changes_session(request: Request, response: Response) -> Session | N
920
  raw = request.cookies.get(aios_session.COOKIE_NAME)
921
  claims = aios_session.read(raw) if raw else None
922
  if not claims or not str(claims.get("t") or "").strip() or not str(claims.get("u") or "").strip():
923
- raise err(401, "invalid_session", "your session has expired — sign in again")
924
  return None
925
 
926
 
 
65
  # invisible: a row the rail offers that the route 403s, or the reverse. The
66
  # editor's explicit grant lands here too, so a database an administrator ticked
67
  # is reachable by URL as well as visible in the rail.
68
+ #
69
+ # ⭐⭐ W49-T23 / D-612 — `st=self.runtime` IS LOAD-BEARING AND IT WAS MISSING HERE.
70
+ # `nav_may_open`'s third leg hands a `ut_*` key to `user_tables.may_open(..., st=st)`, and
71
+ # `user_tables._st(None)` falls back to the PROCESS-DEFAULT store — not this caller's
72
+ # tenant. So without this argument the wall answered a question about somebody else's
73
+ # tenant and happened to be right only while the process default equalled the session
74
+ # tenant. `routes_charts._require_database` had already been written with the argument
75
+ # (its docstring carries the measurement: a 403 on
76
+ # `?database=ut_w39_visual_qa_20260820t214846z` for a user who could read and edit that
77
+ # very table through the grid, and a 200 for the identical request once the process
78
+ # default happened to match); this is that shape folded back into the one chokepoint, so
79
+ # the two can no longer give different answers.
80
+ # ⚠ IT WIDENS NOTHING. Threading the session's own runtime makes this ask exactly the
81
+ # store the nav rail, `_require_database` and `user_tables.may_open` already ask; every
82
+ # answer it can change is one that was previously computed against the wrong tenant.
83
+ # The live `ut_*` caller is `routes_grid._pivot_side`, and `grid_pivot` runs
84
+ # `perm_scope.pivot_scope(..., st=session.runtime)` over the same key regardless.
85
  import core.perm_scope as _perm_scope
86
+ if not _perm_scope.nav_may_open(self.user, module_key, st=self.runtime):
87
  raise err(403, "forbidden", f"your account does not have access to {module_key}")
88
  tcfg = getattr(self.runtime.tenant, "config", None) or {}
89
  tmods = tcfg.get("modules", "all")
 
662
  if not _assistant_tenant_allows(session, key):
663
  row["visible"] = bool(perm_scope.may_access(session.user, key))
664
  row["reason"] = ("this workspace's catalogue does not list it as an assistant "
665
+ "source. An administrator can add it")
666
  continue
667
  if perm_scope.assistant_entry(session.user, key) is None:
668
  row["visible"] = bool(perm_scope.may_access(session.user, key))
 
677
  # `is_migrated` and `may_access`, and `product_data` carries the SAME grant as
678
  # `customer_data` under one record — so the divergence is not visible in the perms
679
  # document and guessing at it once already produced a wrong answer.
680
+ row["reason"] = ("the assistant cannot resolve a data grant for it yet. This is a "
681
  "known gap (D-276), not something you have set wrongly")
682
  continue
683
  row["permitted"] = True
 
694
  if isinstance(entry, tuple) and len(entry) >= 2 and isinstance(entry[1], (list, tuple)):
695
  row["answerable"] = True
696
  else:
697
+ row["reason"] = "no snapshot loaded yet. Open this database once, then ask"
698
  continue
699
  if not key.startswith("ut_"):
700
  continue
 
883
  raise err(401, "no_session", "sign in to continue")
884
  claims = aios_session.read(raw)
885
  if not claims:
886
+ raise err(401, "invalid_session", "your session has expired. Sign in again")
887
  user = _user_for(claims)
888
  if not user:
889
+ raise err(401, "invalid_session", "your session has expired. Sign in again")
890
  try:
891
  rt = runtime.get_runtime(claims["t"])
892
  except KeyError:
893
  # An unknown tenant slug is a 401, not a 404: the cookie is not a valid identity for this
894
  # deployment, and confirming which slugs exist would answer a question we were not asked.
895
+ raise err(401, "invalid_session", "your session has expired. Sign in again")
896
  fresh, _ = aios_session.mint(claims["t"], user["username"], int(user.get("epoch") or 0),
897
  absolute_expiry=claims["x"])
898
  aios_session.set_cookie(response, request, fresh)
 
937
  raw = request.cookies.get(aios_session.COOKIE_NAME)
938
  claims = aios_session.read(raw) if raw else None
939
  if not claims or not str(claims.get("t") or "").strip() or not str(claims.get("u") or "").strip():
940
+ raise err(401, "invalid_session", "your session has expired. Sign in again")
941
  return None
942
 
943
 
api/formula_runtime.py CHANGED
@@ -26,7 +26,10 @@ MAX_DEFINITIONS = 100
26
  MAX_BATCH_ROWS = 1000
27
  MANY = 30
28
  AUTHORITY = "server"
29
- CONSUMERS = ("preview", "grid", "filter", "export", "automation", "query", "timeseries")
 
 
 
30
  FN_ARITY = {
31
  "ABS": (1, 1), "ROUND": (1, 2), "ROUNDUP": (1, 2), "ROUNDDOWN": (1, 2),
32
  "INT": (1, 1), "MOD": (2, 2), "SQRT": (1, 1), "POWER": (2, 2), "EXP": (1, 1),
@@ -116,6 +119,105 @@ class FormulaError(ValueError):
116
  pass
117
 
118
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
119
  def _rewrite(source):
120
  """Translate Excel punctuation to Python AST punctuation without touching strings."""
121
  out, i, quote = [], 0, None
@@ -138,6 +240,21 @@ def _rewrite(source):
138
  if not re.fullmatch(r"[A-Za-z0-9_]+", key) or len(key) > MAX_FIELD_KEY:
139
  raise FormulaError("a field reference may contain only letters, digits and _")
140
  out.append(f"REF({key!r})"); i = end + 1; continue
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
141
  two = source[i:i + 2]
142
  if two in ("<=", ">=", "!=", "=="):
143
  out.append(two); i += 2; continue
@@ -190,6 +307,16 @@ def _normal(node, depth=0):
190
  if len(node.args) != 1 or not isinstance(node.args[0], ast.Constant):
191
  raise FormulaError("field reference is malformed")
192
  return {"t": "ref", "k": str(node.args[0].value)}
 
 
 
 
 
 
 
 
 
 
193
  if fn not in FN_ARITY or node.keywords:
194
  raise FormulaError(f"{fn} is not a supported function")
195
  lo, hi = FN_ARITY[fn]
@@ -217,14 +344,26 @@ def parse_formula(source):
217
  raise FormulaError(f"formula has more than {MAX_NODES} nodes")
218
  root = _normal(parsed.body)
219
  refs = []
 
 
 
 
 
 
220
  def walk(row):
221
  if row["t"] == "ref" and row["k"] not in refs:
222
  refs.append(row["k"])
 
 
 
 
 
 
223
  for key in ("e", "l", "r"):
224
  if isinstance(row.get(key), dict): walk(row[key])
225
  for child in row.get("args") or (): walk(child)
226
  walk(root)
227
- return {"version": AST_VERSION, "source": source, "ast": root, "refs": refs}
228
 
229
 
230
  def _num(v):
@@ -386,6 +525,20 @@ def _eval(node, row, today, diagnostics=None):
386
  if key not in row:
387
  _diagnose(diagnostics, "unknown_ref")
388
  return row.get(key)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
389
  if kind == "neg":
390
  n = _num(_eval(node["e"], row, today, diagnostics)); return None if n is None else -n
391
  if kind == "bin":
@@ -427,7 +580,19 @@ def _eval(node, row, today, diagnostics=None):
427
  first = None
428
  return first if first is not None else _eval(
429
  node["args"][1], row, today, diagnostics)
430
- args = [_eval(x, row, today, diagnostics) for x in node.get("args") or ()]
 
 
 
 
 
 
 
 
 
 
 
 
431
  return _call(fn, args, today)
432
  raise FormulaError("formula AST node is not supported")
433
 
@@ -594,6 +759,102 @@ def evaluate_fields(definitions, row, *, today=None):
594
  return {"values": {key: values.get(key) for key in definitions}, "errors": errors}
595
 
596
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
597
  def evaluate_batch(definitions, rows, *, consumer, today=None, field_revisions=None):
598
  """Evaluate a bounded set of formula definitions over typed consumer rows.
599
 
 
26
  MAX_BATCH_ROWS = 1000
27
  MANY = 30
28
  AUTHORITY = "server"
29
+ #: ⚠ NOT documentation. `evaluate_batch` refuses any consumer not in this tuple, so `"sheet"`
30
+ #: (wave 49, W49-T03) is required for the Sheet module to call the engine at all. It is also
31
+ #: republished verbatim in `contract_dto()`, which is what the browser reads.
32
+ CONSUMERS = ("preview", "grid", "filter", "export", "automation", "query", "timeseries", "sheet")
33
  FN_ARITY = {
34
  "ABS": (1, 1), "ROUND": (1, 2), "ROUNDUP": (1, 2), "ROUNDDOWN": (1, 2),
35
  "INT": (1, 1), "MOD": (2, 2), "SQRT": (1, 1), "POWER": (2, 2), "EXP": (1, 1),
 
119
  pass
120
 
121
 
122
+ # ── A1 addressing (wave 49, W49-T03, contract C1) ────────────────────────────────────────────
123
+ #
124
+ # ⭐ THE SEAM IS `_rewrite`, AND THAT IS NOT AN ACCIDENT OF CONVENIENCE. `B4`, `B4:B8`, `$B$1` and
125
+ # `Sheet2!C3` are not valid Python expressions: `:` is subscript-only, `!` is not an operator, and a
126
+ # bare `B4` parses as `ast.Name`, which `_normal` refuses. So an A1 token is translated to a
127
+ # synthetic call BEFORE `ast.parse` ever sees it, exactly as `{field}` already becomes `REF('field')`.
128
+ # One rewrite pass, one grammar, no second parser.
129
+ #
130
+ # ⛔⛔ THE COLLISION THAT MAKES THE `(` LOOKAHEAD LOAD-BEARING: a function name can have the SHAPE of
131
+ # a cell reference. `LOG10` is three letters followed by digits, which is exactly `$?[A-Za-z]{1,3}$?
132
+ # [0-9]+`. Without the lookahead, `LOG10(x)` rewrites to `A1REF('LOG10')(x)` and the formula either
133
+ # dies with an unhelpful parse error or, worse, silently resolves a cell nobody wrote. The
134
+ # disambiguator is the character AFTER the token: a `(` means it is a call, never an address.
135
+ MAX_A1_ROW = 9_999_999
136
+ MAX_A1_COL = 3 # AAA, i.e. well past Excel's XFD
137
+ #: A range is materialised into a list of values, so it needs a ceiling for the same reason
138
+ #: `MAX_SOURCE` exists: one cell must not be able to ask for an unbounded amount of work.
139
+ MAX_RANGE_CELLS = 5000
140
+
141
+ _A1_CELL = r"\$?([A-Za-z]{1,3})\$?([1-9][0-9]{0,6})"
142
+ _A1_RE = re.compile(
143
+ r"(?:(?:'([^']{1,64})'|([A-Za-z_][A-Za-z0-9_]{0,63}))!)?"
144
+ + _A1_CELL + r"(?::" + _A1_CELL + r")?"
145
+ )
146
+
147
+
148
+ def col_to_index(letters):
149
+ """`A` -> 1, `Z` -> 26, `AA` -> 27. The spreadsheet base-26 with no zero digit."""
150
+ n = 0
151
+ for ch in str(letters).upper():
152
+ n = n * 26 + (ord(ch) - 64)
153
+ return n
154
+
155
+
156
+ def index_to_col(index):
157
+ """The inverse of `col_to_index`. Refuses a non-positive index rather than emitting nonsense."""
158
+ n = int(index)
159
+ if n < 1:
160
+ raise FormulaError("a column index starts at 1")
161
+ out = ""
162
+ while n:
163
+ n, rem = divmod(n - 1, 26)
164
+ out = chr(65 + rem) + out
165
+ return out
166
+
167
+
168
+ def a1_key(addr, sheet=""):
169
+ """The lookup key for one address: `B4`, or `SHEET2!C3` when it names another tab.
170
+
171
+ ⚠ `$` is NOT part of the key. Anchoring belongs to a formula's TEXT, where it changes how a
172
+ drag-fill shifts the reference; it never changes which cell is being addressed. Keeping it in
173
+ the key would make `$B$1` and `B1` two different cells.
174
+ """
175
+ plain = str(addr or "").replace("$", "").upper()
176
+ return (str(sheet).upper() + "!" + plain) if sheet else plain
177
+
178
+
179
+ def expand_range(first, last, sheet=""):
180
+ """Every address in the rectangle `first:last`, row-major, as lookup keys."""
181
+ c1, r1 = _split_addr(first)
182
+ c2, r2 = _split_addr(last)
183
+ lo_c, hi_c = sorted((col_to_index(c1), col_to_index(c2)))
184
+ lo_r, hi_r = sorted((r1, r2))
185
+ span = (hi_c - lo_c + 1) * (hi_r - lo_r + 1)
186
+ if span > MAX_RANGE_CELLS:
187
+ raise FormulaError(f"a range covers at most {MAX_RANGE_CELLS} cells")
188
+ return [a1_key(index_to_col(c) + str(r), sheet)
189
+ for r in range(lo_r, hi_r + 1)
190
+ for c in range(lo_c, hi_c + 1)]
191
+
192
+
193
+ def _split_addr(addr):
194
+ m = re.fullmatch(r"\$?([A-Za-z]{1,3})\$?([1-9][0-9]{0,6})", str(addr or "").strip())
195
+ if not m:
196
+ raise FormulaError(f"{addr} is not a cell address")
197
+ return m.group(1).upper(), int(m.group(2))
198
+
199
+
200
+ def _a1_at(source, i):
201
+ """`(replacement_text, next_index)` if an A1 token starts at `i`, else None."""
202
+ m = _A1_RE.match(source, i)
203
+ if not m:
204
+ return None
205
+ end = m.end()
206
+ nxt = end
207
+ while nxt < len(source) and source[nxt] == " ":
208
+ nxt += 1
209
+ if nxt < len(source) and source[nxt] == "(":
210
+ return None # a function call, not an address. See the note above.
211
+ if nxt < len(source) and (source[nxt].isalnum() or source[nxt] in "_$!"):
212
+ return None # the token does not end here, so it is not an address
213
+ sheet = m.group(1) or m.group(2) or ""
214
+ first = (m.group(3) or "") + (m.group(4) or "")
215
+ if m.group(5):
216
+ last = m.group(5) + (m.group(6) or "")
217
+ return f"A1RANGE({first!r}, {last!r}, {sheet!r})", end
218
+ return f"A1REF({first!r}, {sheet!r})", end
219
+
220
+
221
  def _rewrite(source):
222
  """Translate Excel punctuation to Python AST punctuation without touching strings."""
223
  out, i, quote = [], 0, None
 
240
  if not re.fullmatch(r"[A-Za-z0-9_]+", key) or len(key) > MAX_FIELD_KEY:
241
  raise FormulaError("a field reference may contain only letters, digits and _")
242
  out.append(f"REF({key!r})"); i = end + 1; continue
243
+ # ⭐ AN A1 TOKEN IS ONLY TRIED AT AN IDENTIFIER BOUNDARY. Without this guard the scanner
244
+ # would happily match the tail of a longer name, so `myB4` would end up holding a reference
245
+ # to cell B4. The previous SOURCE character decides, not the previous emitted one, because
246
+ # a `{field}` just before has already been rewritten into something longer.
247
+ # ⚠ `prev in "_$"` is a TRAP when `prev` is the empty string at position 0: Python answers
248
+ # True, because "" is a substring of every string. That silently disabled A1 addressing for
249
+ # any formula STARTING with a reference, which is most of them, while leaving `SUM(B4:B8)`
250
+ # working because its `B` follows a `(`. Compare against a tuple, which has no such edge.
251
+ prev = source[i - 1] if i else ""
252
+ if (c.isalpha() or c in ("$", "'")) and not (prev.isalnum() or prev in ("_", "$")):
253
+ got = _a1_at(source, i)
254
+ if got:
255
+ text, i = got
256
+ out.append(text)
257
+ continue
258
  two = source[i:i + 2]
259
  if two in ("<=", ">=", "!=", "=="):
260
  out.append(two); i += 2; continue
 
307
  if len(node.args) != 1 or not isinstance(node.args[0], ast.Constant):
308
  raise FormulaError("field reference is malformed")
309
  return {"t": "ref", "k": str(node.args[0].value)}
310
+ if fn in ("A1REF", "A1RANGE"):
311
+ want = 2 if fn == "A1REF" else 3
312
+ if len(node.args) != want or not all(isinstance(x, ast.Constant) for x in node.args):
313
+ raise FormulaError("cell reference is malformed")
314
+ vals = [str(x.value) for x in node.args]
315
+ if fn == "A1REF":
316
+ return {"t": "a1", "k": a1_key(vals[0], vals[1])}
317
+ # The range is expanded HERE, at normalize time, so a malformed or oversized range is a
318
+ # PARSE error the author sees immediately rather than a surprise at evaluation.
319
+ return {"t": "a1range", "keys": expand_range(vals[0], vals[1], vals[2])}
320
  if fn not in FN_ARITY or node.keywords:
321
  raise FormulaError(f"{fn} is not a supported function")
322
  lo, hi = FN_ARITY[fn]
 
344
  raise FormulaError(f"formula has more than {MAX_NODES} nodes")
345
  root = _normal(parsed.body)
346
  refs = []
347
+ # ⭐ `cells` IS A SECOND, SEPARATE LIST AND NOT A MERGE INTO `refs`. `refs` names FIELD keys and
348
+ # is already persisted in every stored definition, read by `evaluate_fields`, `evaluate_batch`
349
+ # and the contract DTO; folding cell addresses into it would hand every one of those consumers
350
+ # a key that is not a field. `cells` is additive, so an existing definition simply carries an
351
+ # empty one.
352
+ cells = []
353
  def walk(row):
354
  if row["t"] == "ref" and row["k"] not in refs:
355
  refs.append(row["k"])
356
+ if row["t"] == "a1" and row["k"] not in cells:
357
+ cells.append(row["k"])
358
+ if row["t"] == "a1range":
359
+ for key in row.get("keys") or ():
360
+ if key not in cells:
361
+ cells.append(key)
362
  for key in ("e", "l", "r"):
363
  if isinstance(row.get(key), dict): walk(row[key])
364
  for child in row.get("args") or (): walk(child)
365
  walk(root)
366
+ return {"version": AST_VERSION, "source": source, "ast": root, "refs": refs, "cells": cells}
367
 
368
 
369
  def _num(v):
 
525
  if key not in row:
526
  _diagnose(diagnostics, "unknown_ref")
527
  return row.get(key)
528
+ if kind == "a1":
529
+ # ⭐ A1 VALUES ARRIVE THROUGH `row`, KEYED BY ADDRESS, and that is deliberately not a new
530
+ # callback parameter. `row` is already threaded through every evaluator path, so a Sheet
531
+ # supplies `{"B4": 42, "SHEET2!C3": 7}` and nothing else in this file changes shape.
532
+ key = node.get("k")
533
+ if key not in row:
534
+ _diagnose(diagnostics, "unknown_ref")
535
+ return row.get(key)
536
+ if kind == "a1range":
537
+ # ⛔ A BARE RANGE IS NOT A VALUE. `=B4:B8` alone has no meaning; a range is only ever an
538
+ # ARGUMENT to an aggregate, and the call dispatch below is what splices it in. Returning
539
+ # the list here would let `=B4:B8*2` silently produce nonsense.
540
+ _diagnose(diagnostics, "range_outside_function")
541
+ return None
542
  if kind == "neg":
543
  n = _num(_eval(node["e"], row, today, diagnostics)); return None if n is None else -n
544
  if kind == "bin":
 
580
  first = None
581
  return first if first is not None else _eval(
582
  node["args"][1], row, today, diagnostics)
583
+ # ⭐ RANGES FLATTEN HERE, INTO THE SAME FLAT LIST `_call` ALREADY TAKES. `SUM`, `AVERAGE`,
584
+ # `COUNT`, `MIN` and `MAX` are declared `(1, MANY)` and simply iterate their argument list,
585
+ # so a range must become MORE ARGUMENTS rather than one list-shaped argument. Doing it here
586
+ # instead of inside `_call` is what keeps all 46 functions unchanged.
587
+ args = []
588
+ for x in node.get("args") or ():
589
+ if isinstance(x, dict) and x.get("t") == "a1range":
590
+ for key in x.get("keys") or ():
591
+ if key not in row:
592
+ _diagnose(diagnostics, "unknown_ref")
593
+ args.append(row.get(key))
594
+ else:
595
+ args.append(_eval(x, row, today, diagnostics))
596
  return _call(fn, args, today)
597
  raise FormulaError("formula AST node is not supported")
598
 
 
759
  return {"values": {key: values.get(key) for key in definitions}, "errors": errors}
760
 
761
 
762
+ def evaluate_sheet(cells, *, today=None):
763
+ """Evaluate a whole SHEET of A1 cells in dependency order (wave 49, W49-T03).
764
+
765
+ `cells` is `{addr_key: {"formula": "=..."} or {"value": v}}` where `addr_key` is what
766
+ `a1_key` produces: `B4` on this tab, `SHEET2!C3` on another. Returns
767
+ `{"values": {addr: value}, "errors": {addr: code}}`.
768
+
769
+ ⛔⛔ **THE REFUSAL IS `circular_reference`, AND IT IS DELIBERATELY NOT THE `"cycle"` THAT
770
+ `evaluate_fields` ALREADY USES.** Renaming that one was considered and rejected on evidence:
771
+ `"cycle"` is a SHIPPED WIRE CODE. It is published in `contract_dto()`'s `errorCodes`, so it is
772
+ on the wire to the browser; `routes_query.py` branches on it behaviourally; and
773
+ `verify_w45_semantic_apps.py` pins the string in two fixtures. Both of those files belong to
774
+ another lane's fence.
775
+
776
+ ⭐ AND THE TWO ARE GENUINELY DIFFERENT GRAPHS, which is what makes keeping both honest rather
777
+ than a dodge. `evaluate_fields`'s cycle is over FIELD MEMBERS within one grid row: every node is
778
+ a column of the same record. A sheet cycle is over CELL ADDRESSES and spans tabs, so its nodes
779
+ are not fields, its edges come from `parse_formula`'s `cells` list rather than `refs`, and a
780
+ range edge expands to many nodes at once. Unifying them would mean one detector walking two
781
+ unrelated graphs. If you are here to merge these names, read this paragraph first: the merge
782
+ breaks `routes_query.py` and a lane C gate in a single edit.
783
+ """
784
+ values, errors, active, resolved = {}, {}, [], set()
785
+ parsed = {}
786
+
787
+ for addr, spec in (cells or {}).items():
788
+ if not isinstance(spec, dict):
789
+ continue
790
+ # ⛔⛔ A CELL THAT ALREADY REFUSED IS CARRIED AS A REFUSAL, NOT AS AN ABSENCE (W49-T09, C2).
791
+ # This is the whole of "refusals propagate". If a refused cell were simply left out of the
792
+ # inputs, a formula over it would answer `unknown_ref` - "this points at a cell that is not
793
+ # filled in" - which is a DIFFERENT and misleading sentence: the cell IS filled in, and the
794
+ # reason it has no value is one the reader needs to see. Worse, `SUM` over an absent cell
795
+ # answers a NUMBER, so the refusal would vanish into a smaller total that looks fine.
796
+ if spec.get("refused"):
797
+ errors[addr] = str(spec["refused"])
798
+ values[addr] = None
799
+ resolved.add(addr)
800
+ continue
801
+ raw = spec.get("formula")
802
+ if isinstance(raw, str) and raw.strip().startswith("="):
803
+ try:
804
+ parsed[addr] = parse_formula(raw.strip()[1:])
805
+ except FormulaError:
806
+ errors[addr] = "bad_formula"
807
+ values[addr] = None
808
+ else:
809
+ values[addr] = spec.get("value")
810
+
811
+ def resolve(addr):
812
+ if addr in resolved:
813
+ return values.get(addr)
814
+ if addr not in parsed:
815
+ return values.get(addr)
816
+ if addr in active:
817
+ # Every member of the loop is refused, not just the one that closed it: a person
818
+ # looking at any cell in the cycle needs to be told it is part of one.
819
+ for member in active[active.index(addr):]:
820
+ errors[member] = "circular_reference"
821
+ values[member] = None
822
+ resolved.add(member)
823
+ return None
824
+ active.append(addr)
825
+ definition = parsed[addr]
826
+ inputs = {}
827
+ inherited = None
828
+ for key in definition.get("cells") or ():
829
+ inputs[key] = resolve(key) if key in parsed else values.get(key)
830
+ # ⭐ THE UPSTREAM REFUSAL WINS, AND THE FIRST ONE FOUND IS THE ONE REPORTED. A formula
831
+ # over two refused cells has two reasons and one place to say them; naming the first is
832
+ # honest and actionable, while inventing a combined sentence is neither. The cell is
833
+ # refused either way, so no number is served.
834
+ if inherited is None and errors.get(key):
835
+ inherited = errors[key]
836
+ if errors.get(addr) == "circular_reference":
837
+ active.pop()
838
+ return None
839
+ if inherited is not None:
840
+ values[addr] = None
841
+ errors[addr] = inherited
842
+ active.pop()
843
+ resolved.add(addr)
844
+ return None
845
+ result = evaluate_result(definition, inputs, today=today)
846
+ active.pop()
847
+ values[addr] = result["value"]
848
+ if result["error"]:
849
+ errors[addr] = result["error"]
850
+ resolved.add(addr)
851
+ return values.get(addr)
852
+
853
+ for addr in list(parsed):
854
+ resolve(addr)
855
+ return {"values": values, "errors": errors}
856
+
857
+
858
  def evaluate_batch(definitions, rows, *, consumer, today=None, field_revisions=None):
859
  """Evaluate a bounded set of formula definitions over typed consumer rows.
860
 
api/main.py CHANGED
@@ -62,6 +62,7 @@ import routes_automation # noqa: E402 (wave 18 C4-AUTO — SESSION D's router,
62
  import routes_changes # noqa: E402 (wave 29 item 20 / C6 — F's change token, mounted by A)
63
  import routes_notes # noqa: E402 (wave 47 instr 19 / W47-T16 — shared-note read state, lane C's router)
64
  import routes_charts # noqa: E402 (wave 47 instr 18 / W47-T30 / R7 — saved charts as records, lane H's router)
 
65
  import routes_customers # noqa: E402
66
  import routes_grid # noqa: E402
67
  import routes_keychain # noqa: E402 (wave 18 C7 — keychain + connectors admin surfaces)
@@ -325,6 +326,10 @@ app.include_router(routes_web_agent.router) # R10 / C5 — E's router, A's lin
325
  # (W47-T30 / R7, saved charts as their own records). Neither lane may edit this file.
326
  app.include_router(routes_notes.router)
327
  app.include_router(routes_charts.router)
 
 
 
 
328
  # ⭐⭐ WAVE 32 (R1 / C5, cross-fence wiring 6) — THE QUERY MODULE. E's router, A's line, and the
329
  # FIFTH consecutive wave in which this exact line is the artifact the protocol nearly loses.
330
  # ⛔ MOUNTED HERE, IN THIS BLOCK, AND NOT AT THE END OF THE FILE — measured by SESSION E in its own
 
62
  import routes_changes # noqa: E402 (wave 29 item 20 / C6 — F's change token, mounted by A)
63
  import routes_notes # noqa: E402 (wave 47 instr 19 / W47-T16 — shared-note read state, lane C's router)
64
  import routes_charts # noqa: E402 (wave 47 instr 18 / W47-T30 / R7 — saved charts as records, lane H's router)
65
+ import routes_sheet # noqa: E402 (wave 49 instr 1 / W49-T02 / C1 — the Sheet workbook doors, lane A's router)
66
  import routes_customers # noqa: E402
67
  import routes_grid # noqa: E402
68
  import routes_keychain # noqa: E402 (wave 18 C7 — keychain + connectors admin surfaces)
 
326
  # (W47-T30 / R7, saved charts as their own records). Neither lane may edit this file.
327
  app.include_router(routes_notes.router)
328
  app.include_router(routes_charts.router)
329
+ # ⭐ WAVE 49 (instruction 1 / C1, W49-T02) — THE SHEET WORKBOOK DOORS. Lane A owns both this file
330
+ # and that router, so this is the one mount in this block that crosses no fence. It is still
331
+ # written HERE rather than at the end, for the reason the block below spells out at length.
332
+ app.include_router(routes_sheet.router)
333
  # ⭐⭐ WAVE 32 (R1 / C5, cross-fence wiring 6) — THE QUERY MODULE. E's router, A's line, and the
334
  # FIFTH consecutive wave in which this exact line is the artifact the protocol nearly loses.
335
  # ⛔ MOUNTED HERE, IN THIS BLOCK, AND NOT AT THE END OF THE FILE — measured by SESSION E in its own
api/odoo_relational.py CHANGED
@@ -265,13 +265,13 @@ def vendor_fields():
265
  {"key": "mobile", "label": "Mobile", "type": "text", "source": "overlay",
266
  "default": False},
267
  {"key": "vat", "label": "Tax ID", "type": "text", "source": "overlay", "default": True,
268
- "description": "Odoo `vat` — the vendor's tax/VAT registration number."},
269
  # ⚠ `vendor_ref`, not `ref`: `ref` is Odoo's own name for it, and the bills grid already
270
  # uses `ref` for the VENDOR'S INVOICE NUMBER on a document. Two different facts, and a
271
  # shared spelling across two linked grids is how a rollup ends up summing the wrong column.
272
  {"key": "vendor_ref", "label": "Vendor reference", "type": "text", "source": "overlay",
273
  "default": False,
274
- "description": "Odoo `res.partner.ref` — our internal reference for this vendor."},
275
  {"key": "website", "label": "Website", "type": "url", "source": "overlay",
276
  "default": False},
277
  {"key": "street", "label": "Street", "type": "text", "source": "overlay",
@@ -579,7 +579,7 @@ def order_line_fields():
579
  "default": False, "description": "The `sale.order.line` id. Also this row's id."},
580
  {"key": "order_id", "label": "Odoo order id", "type": "int", "source": "overlay",
581
  "default": False,
582
- "description": "The `sale.order` id — the key `ut_odoo_orders` is keyed on."},
583
  {"key": "customer", "label": "Customer", "type": "text", "source": "overlay",
584
  "default": True},
585
  {"key": JOIN_KEY, "label": "Odoo partner id", "type": "int", "source": "overlay",
@@ -643,7 +643,7 @@ def gl_line_fields():
643
  "default": True},
644
  {"key": ACCOUNT_JOIN_KEY, "label": "Account code", "type": "text", "source": "overlay",
645
  "default": True,
646
- "description": "The GL code, from the joined chart of accounts — the key "
647
  "`ut_odoo_accounts` is keyed on. Blank on the 1,727 lines with no "
648
  "account."},
649
  {"key": "customer", "label": "Partner", "type": "text", "source": "overlay",
@@ -696,7 +696,7 @@ def product_fields():
696
  {"key": "active", "label": "Active in Odoo", "type": "checkbox", "source": "overlay",
697
  "default": True,
698
  "description": "Unticked = archived. Archived products are kept because they still "
699
- "carry sales history — two of them sold this year."},
700
  # ⚠ TEXT, NOT SELECT. 71 categories exist today and Odoo gains them without telling us; a
701
  # select whose options go stale answers a filter with a list that cannot match a stored
702
  # value (wave-26 item 24). Text filters honestly and never goes out of date.
@@ -767,7 +767,7 @@ def customer_fields():
767
  "default": False},
768
  {"key": "agent", "label": "Sales agent", "type": "text", "source": "overlay",
769
  "default": True,
770
- "description": "The customer's assigned agent (res.partner.agent_ids[0] — the "
771
  "Customers-module convention)."},
772
  # ⭐ WAVE 28 — the agent's ID beside its NAME, because a link joins on an id and this
773
  # table carried only the display string. ⚠ It is `agent_id`, NEVER `partner_id`: both are
@@ -1874,6 +1874,113 @@ def authoritative_schema_snapshot():
1874
  errors.append(f"{model}: {type(exc).__name__}: {exc}")
1875
  return models, errors
1876
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1877
  #: store key -> the REAL-WORLD POPULATION that table presents (`core.registry`'s `subject`
1878
  #: vocabulary, same strings, one namespace). ⭐ W33-T41 / item 12a.
1879
  #:
@@ -2195,7 +2302,7 @@ def plan(cur, rt=None):
2195
  stored = len(((existing.get(key) or {}).get("rows")) or {})
2196
  if stored and len(rows) < stored * MAX_SHRINK:
2197
  problems.append(
2198
- f"{key}: the mirror answered {len(rows)} rows against {stored} stored — a drop of "
2199
  f"more than {int((1 - MAX_SHRINK) * 100)}% is a bad read, not Odoo history "
2200
  f"shrinking; refusing rather than deleting rows that still exist")
2201
  built["problems"] = problems
@@ -2470,7 +2577,14 @@ def refresh(rt, tenant, username="automation", cur=None, today=None):
2470
  # longer built) SAYS SO, with the keys.
2471
  plan_report = {}
2472
  written = apply_plan(rt, built, username=username, today=today, report=plan_report)
 
 
 
 
 
 
2473
  return {"tables": written,
 
2474
  **({"retired": plan_report["retired"]} if plan_report.get("retired") else {}),
2475
  # R6's second sentence: a set that was deliberately not built SAYS SO, with the keys.
2476
  **({"skipped": skipped} if skipped else {}),
 
265
  {"key": "mobile", "label": "Mobile", "type": "text", "source": "overlay",
266
  "default": False},
267
  {"key": "vat", "label": "Tax ID", "type": "text", "source": "overlay", "default": True,
268
+ "description": "Odoo `vat`: the vendor's tax/VAT registration number."},
269
  # ⚠ `vendor_ref`, not `ref`: `ref` is Odoo's own name for it, and the bills grid already
270
  # uses `ref` for the VENDOR'S INVOICE NUMBER on a document. Two different facts, and a
271
  # shared spelling across two linked grids is how a rollup ends up summing the wrong column.
272
  {"key": "vendor_ref", "label": "Vendor reference", "type": "text", "source": "overlay",
273
  "default": False,
274
+ "description": "Odoo `res.partner.ref`: our internal reference for this vendor."},
275
  {"key": "website", "label": "Website", "type": "url", "source": "overlay",
276
  "default": False},
277
  {"key": "street", "label": "Street", "type": "text", "source": "overlay",
 
579
  "default": False, "description": "The `sale.order.line` id. Also this row's id."},
580
  {"key": "order_id", "label": "Odoo order id", "type": "int", "source": "overlay",
581
  "default": False,
582
+ "description": "The `sale.order` id, the key `ut_odoo_orders` is keyed on."},
583
  {"key": "customer", "label": "Customer", "type": "text", "source": "overlay",
584
  "default": True},
585
  {"key": JOIN_KEY, "label": "Odoo partner id", "type": "int", "source": "overlay",
 
643
  "default": True},
644
  {"key": ACCOUNT_JOIN_KEY, "label": "Account code", "type": "text", "source": "overlay",
645
  "default": True,
646
+ "description": "The GL code, from the joined chart of accounts, and the key "
647
  "`ut_odoo_accounts` is keyed on. Blank on the 1,727 lines with no "
648
  "account."},
649
  {"key": "customer", "label": "Partner", "type": "text", "source": "overlay",
 
696
  {"key": "active", "label": "Active in Odoo", "type": "checkbox", "source": "overlay",
697
  "default": True,
698
  "description": "Unticked = archived. Archived products are kept because they still "
699
+ "carry sales history; two of them sold this year."},
700
  # ⚠ TEXT, NOT SELECT. 71 categories exist today and Odoo gains them without telling us; a
701
  # select whose options go stale answers a filter with a list that cannot match a stored
702
  # value (wave-26 item 24). Text filters honestly and never goes out of date.
 
767
  "default": False},
768
  {"key": "agent", "label": "Sales agent", "type": "text", "source": "overlay",
769
  "default": True,
770
+ "description": "The customer's assigned agent (res.partner.agent_ids[0], the "
771
  "Customers-module convention)."},
772
  # ⭐ WAVE 28 — the agent's ID beside its NAME, because a link joins on an id and this
773
  # table carried only the display string. ⚠ It is `agent_id`, NEVER `partner_id`: both are
 
1874
  errors.append(f"{model}: {type(exc).__name__}: {exc}")
1875
  return models, errors
1876
 
1877
+
1878
+ #: ⭐⭐ W49-T25 / C6 — THE COMPILED REGISTRY GRIDS, AND THIS MAP IS WHERE THE WHOLE TICKET LIVES.
1879
+ #:
1880
+ #: `TABLES` above declares the eight mirror grids owned by THIS file. The products and customers
1881
+ #: grids are deliberately NOT among them (W33-T44 retired their spec rows), and their field
1882
+ #: contract belongs to the compiled registry modules `product_data` / `customer_data`, whose
1883
+ #: single source of truth is `platform/aios_grid_fields.json` read through `aios_grid`.
1884
+ #: ⛔ `fba` IS DECLARED IN THAT JSON AND NOWHERE ELSE TREE WIDE. A parity assembler built only
1885
+ #: from `TABLES` would therefore report perfect agreement while the one field this contract was
1886
+ #: written for was missing from the snapshot entirely.
1887
+ #: ⛔ THE KEYS ARE `core.user_tables.LINKABLE_MODULE_KEYS`' OWN STRINGS, not a second vocabulary
1888
+ #: for the same two grids.
1889
+ _REGISTRY_GRID_FIELDS = {
1890
+ "product_data": lambda: _aios_grid().product_fields(),
1891
+ "customer_data": lambda: list(_aios_grid().FIELDS),
1892
+ }
1893
+
1894
+
1895
+ def _aios_grid():
1896
+ """`aios_grid`, imported the same lazy way `_ut` is, and for the same reason: this module is
1897
+ imported by the route layer before `platform/` is necessarily on the path."""
1898
+ import aios_grid
1899
+ return aios_grid
1900
+
1901
+
1902
+ def _declared_from_spec(fields):
1903
+ """One grid's declared field list, reduced to the three keys the snapshot stores.
1904
+
1905
+ ⚠ THE PRESENT/ABSENT SEMANTICS MUST MATCH `core.user_tables._clean_declared_schema` EXACTLY.
1906
+ A key emitted here that the cleaner drops (or the reverse) makes the stored half permanently
1907
+ unequal to the assembled one, and the change detector then re-records the tenant document on
1908
+ every single resync tick with a `flush='sync'` full upload behind it.
1909
+ """
1910
+ return {str(f["key"]): {key: f[key] for key in ("label", "type", "source") if key in f}
1911
+ for f in (fields or [])
1912
+ if isinstance(f, dict) and str(f.get("key") or "").strip()}
1913
+
1914
+
1915
+ def declared_schema_fields():
1916
+ """Every CODE-DECLARED system field: grid key -> field key -> {label, type, source}.
1917
+
1918
+ The mirror grids come from their `TABLES` spec function; the two compiled registry grids come
1919
+ from the JSON contract. Both halves are needed — see `_REGISTRY_GRID_FIELDS` above.
1920
+ """
1921
+ declared = {}
1922
+ for _bucket, key, _label, fields_fn in TABLES:
1923
+ declared[key] = _declared_from_spec(fields_fn())
1924
+ for key, fields_fn in _REGISTRY_GRID_FIELDS.items():
1925
+ declared[key] = _declared_from_spec(fields_fn())
1926
+ return declared
1927
+
1928
+
1929
+ def declared_schema_gaps(stored, declared=None):
1930
+ """C6's parity report: declared fields ABSENT from the stored snapshot, as `grid.field`.
1931
+
1932
+ ⚠ ONE DIRECTIONAL, ON PURPOSE. A stored set that is a SUPERSET of the spec is a field the code
1933
+ RETIRED and the snapshot has not caught up on; that is what the change detector in
1934
+ `_refresh_declared_schema` re-records, and it is not a parity failure. A stored set MISSING a
1935
+ field the code declares is the state C6 was written to catch, because it is the one where a
1936
+ tenant's schema document silently stops describing the product.
1937
+ """
1938
+ declared = declared_schema_fields() if declared is None else declared
1939
+ have_all = stored if isinstance(stored, dict) else {}
1940
+ gaps = []
1941
+ for grid, fields in sorted((declared or {}).items()):
1942
+ have = have_all.get(grid)
1943
+ have = have if isinstance(have, dict) else {}
1944
+ gaps.extend(f"{grid}.{key}" for key in sorted(fields) if key not in have)
1945
+ return gaps
1946
+
1947
+
1948
+ def _refresh_declared_schema(rt):
1949
+ """C6 — the DECLARED half of `odoo_schema_snapshot` RE-RECORDS ITSELF when the code moves.
1950
+
1951
+ ⭐⭐ HOOKED INSIDE `refresh` RATHER THAN AT A CALLER, and that placement is the whole of "no
1952
+ manual sync step". There are exactly two production callers of `refresh`: `api/main.py`'s boot
1953
+ rebuild, which records a snapshot afterwards, and `routes_odoo_tables`' resync route, which
1954
+ records nothing at all today. Hooking a caller would cover one of them; hooking here covers
1955
+ both, including the one that is currently missed entirely.
1956
+
1957
+ ⛔⛔ IT UPDATES THE DECLARED HALF ONLY, through `user_tables.record_declared_odoo_schema`. It
1958
+ cannot flip `complete`, cannot fabricate `models`, and therefore cannot turn a tenant that has
1959
+ never synced into a false "schema complete" — which is the trap, because `complete` is the
1960
+ caller's argument rather than a derived fact and it is the key the 409 in
1961
+ `routes_connectors.odoo_schema_enable` rests on. A never-synced tenant still reports
1962
+ `complete: False` and an empty field list after this runs.
1963
+
1964
+ ⚠ `rt` IS OPTIONAL. `refresh` is called with `rt=None` by the fixture paths, and with no store
1965
+ there is nothing to read or write; the parity step is skipped rather than crashing the spawn.
1966
+ """
1967
+ if rt is None:
1968
+ return None
1969
+ try:
1970
+ declared = declared_schema_fields()
1971
+ except Exception: # noqa: BLE001
1972
+ # A REPORT, NEVER A RAISE, and no exception text on the wire: this runs inside the resync
1973
+ # loop and the boot rebuild, `routes_odoo_tables` returns this dict straight to a client,
1974
+ # and a schema catalogue that cannot be assembled must not stop the tables being written.
1975
+ return {"changed": False, "unavailable": True}
1976
+ ut = _ut()
1977
+ counts = {"grids": len(declared),
1978
+ "fields": sum(len(fields) for fields in declared.values())}
1979
+ if ut.declared_odoo_schema(rt) == declared:
1980
+ return {"changed": False, **counts}
1981
+ ut.record_declared_odoo_schema(declared, st=rt)
1982
+ return {"changed": True, **counts}
1983
+
1984
  #: store key -> the REAL-WORLD POPULATION that table presents (`core.registry`'s `subject`
1985
  #: vocabulary, same strings, one namespace). ⭐ W33-T41 / item 12a.
1986
  #:
 
2302
  stored = len(((existing.get(key) or {}).get("rows")) or {})
2303
  if stored and len(rows) < stored * MAX_SHRINK:
2304
  problems.append(
2305
+ f"{key}: the mirror answered {len(rows)} rows against {stored} stored. A drop of "
2306
  f"more than {int((1 - MAX_SHRINK) * 100)}% is a bad read, not Odoo history "
2307
  f"shrinking; refusing rather than deleting rows that still exist")
2308
  built["problems"] = problems
 
2577
  # longer built) SAYS SO, with the keys.
2578
  plan_report = {}
2579
  written = apply_plan(rt, built, username=username, today=today, report=plan_report)
2580
+ # ⭐⭐ W49-T25 / C6 — THE SCHEMA CATALOGUE FOLLOWS THE CODE WITH NO MANUAL STEP. Runs AFTER the
2581
+ # tables are applied, so the snapshot describes a pass that actually landed. The two early
2582
+ # returns above are respected by construction: a tenant with no Odoo entitlement raised, and a
2583
+ # FROZEN workspace returned before reaching here, so a disconnected connector is not
2584
+ # re-recorded. See `_refresh_declared_schema` for why it writes the declared half only.
2585
+ declared_report = _refresh_declared_schema(rt)
2586
  return {"tables": written,
2587
+ **({"schemaDeclared": declared_report} if declared_report else {}),
2588
  **({"retired": plan_report["retired"]} if plan_report.get("retired") else {}),
2589
  # R6's second sentence: a set that was deliberately not built SAYS SO, with the keys.
2590
  **({"skipped": skipped} if skipped else {}),
api/routes_connectors.py CHANGED
@@ -26,11 +26,33 @@ from fastapi import APIRouter, Body, Depends
26
 
27
  import oauth_connect
28
  from deps import Session, err, require_session
 
 
 
 
 
 
 
29
  #: ⛔ W32-T10 — IMPORTED, NEVER RE-DERIVED. "Does the environment serve THIS tenant's Odoo?" is
30
  #: one question, and this module used to answer it with an unguarded `os.environ.get("ODOO_URL")`
31
  #: while `routes_keychain` answered it correctly. Importing the correct one is the fix; writing a
32
  #: second correct one here would leave the same two-copies shape that produced the defect.
33
  from routes_keychain import TENANT_WIDE_TYPES, env_odoo_available
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
34
 
35
  # ⛔ THE PREFIX IS LOAD-BEARING AND IT WAS MISSING (found at the wave-23 close-out audit).
36
  # This router declared a bare `APIRouter()`, so its one path was served at `/connectors/directory`
@@ -625,6 +647,45 @@ def directory(rt, uname, is_admin=False, incomplete=None):
625
 
626
  contribute("planned", _planned, "the planned-connector list could not be composed",
627
  "the to-do list is missing; every CONNECTED row above is still correct")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
628
  return rows
629
 
630
 
@@ -766,13 +827,42 @@ def connectors_directory(session: Session = Depends(require_session)):
766
  # its cause and a recommended fix. `[]` on a healthy read, so the client can test it directly.
767
  incomplete = []
768
  rows = directory(session.runtime, session.uname, bool(session.admin), incomplete=incomplete)
769
- attach_relationship_graphs(rows, session.user, session.runtime, session.uname,
 
 
 
 
 
 
 
 
 
 
 
770
  bool(session.admin))
771
- return {"connectors": rows,
 
 
 
 
 
 
 
 
 
772
  "incomplete": incomplete,
773
- "counts": {"connected": sum(1 for r in rows if r["state"] == "connected"),
774
- "available": sum(1 for r in rows if r["state"] == "available"),
775
- "planned": sum(1 for r in rows if r["state"] == "planned")}}
 
 
 
 
 
 
 
 
 
776
 
777
 
778
  _ODOO_SCHEMA_ENABLEMENTS = "odoo_schema_enablements"
@@ -786,9 +876,21 @@ def _odoo_admin(session):
786
 
787
  def _schema_catalog(session):
788
  """Rows-free Odoo field catalogue; source fields remain discoverable when every value is empty."""
 
 
 
 
 
 
 
 
 
 
 
 
789
  import core.user_tables as user_tables
790
- enabled = session.runtime.get(_ODOO_SCHEMA_ENABLEMENTS) or {}
791
- snapshot = user_tables.odoo_schema_snapshot(session.runtime)
792
  raw_models = snapshot.get("models") or {}
793
  if raw_models:
794
  rows = []
@@ -857,3 +959,445 @@ def odoo_schema_enable(field_key: str, body: dict = Body(default=None),
857
  session.runtime.pool_cache.pop(cache_key, None)
858
  return {"key": key, "enabled": enabled, "source": "Odoo",
859
  "permissionWall": "normal field permissions"}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
26
 
27
  import oauth_connect
28
  from deps import Session, err, require_session
29
+ #: ⭐⭐ W49-T18 / R27 / C4 — THE TAXONOMY LIVES IN THE DATA LAYER, NOT HERE. `core` is already on
30
+ #: the path by the time this module loads (`deps` imports three of its modules), so this is the
31
+ #: same import shape the rest of the API uses. It is in `platform/core/` rather than beside this
32
+ #: file because the crosswalk is authored CONTENT about connectors, not routing: a second reader
33
+ #: of it (a gate, a future module page) must not have to import FastAPI to ask what category a
34
+ #: connector is in.
35
+ from core import connector_directory
36
  #: ⛔ W32-T10 — IMPORTED, NEVER RE-DERIVED. "Does the environment serve THIS tenant's Odoo?" is
37
  #: one question, and this module used to answer it with an unguarded `os.environ.get("ODOO_URL")`
38
  #: while `routes_keychain` answered it correctly. Importing the correct one is the fix; writing a
39
  #: second correct one here would leave the same two-copies shape that produced the defect.
40
  from routes_keychain import TENANT_WIDE_TYPES, env_odoo_available
41
+ #: ⛔⛔ W49-T16 / C3 — THE DEPENDENTS ROUTER IS MOUNTED FROM HERE, NOT FROM `main.py`. In a
42
+ #: worktree-parallel wave `main.py` lives in exactly ONE lane's fence, so a router built in any
43
+ #: other lane has nowhere to be mounted from (five consecutive waves lost an `include_router`
44
+ #: line for exactly this reason — see `routes_charts.py`'s header). This file is already
45
+ #: included by `main.py`, so mounting the child here puts `/api/v1/dependents` on the app with
46
+ #: no cross-fence edit. The `include_router` call is at the BOTTOM of this file; the import is
47
+ #: here so the module's dependencies read in one place.
48
+ from routes_dependents import router as dependents_router
49
+
50
+ #: ⭐⭐ W49-T19 · R31 / C5 — THE MONID SLICE, MOUNTED THE SAME WAY AND FOR THE SAME REASON.
51
+ #: `routes_monid.py` carries the Amazon reviews pull. It declares NO prefix of its own; the
52
+ #: `include_router` call is at the BOTTOM of this file beside the dependents one, so there is a
53
+ #: single place to read what this router actually serves.
54
+ #: ⛔ NEVER FROM `main.py` (C5). The connectors directory owns its children.
55
+ from routes_monid import router as monid_router
56
 
57
  # ⛔ THE PREFIX IS LOAD-BEARING AND IT WAS MISSING (found at the wave-23 close-out audit).
58
  # This router declared a bare `APIRouter()`, so its one path was served at `/connectors/directory`
 
647
 
648
  contribute("planned", _planned, "the planned-connector list could not be composed",
649
  "the to-do list is missing; every CONNECTED row above is still correct")
650
+
651
+ # ⭐⭐ W49-T18 · R27 / C4 — THE TAXONOMY, AND THE CATALOGUE THAT DEFINES IT. Every row above
652
+ # is filed into one of the fourteen categories, and the authored catalogue is appended beside
653
+ # them so the map covers the things we can reach as well as the things we have wired. R27:
654
+ # *"don't skip Odoo or meta ads, its important to learn how they map the schema for our own
655
+ # benefit."* The crosswalk itself lives in `core.connector_directory`, which explains at
656
+ # length why it cannot be generated from Monid's API.
657
+ #
658
+ # ⛔⛔ ITS `source` IS NOT IN `CONTRIBUTORS`, AND THAT IS DELIBERATE RATHER THAN AN OVERSIGHT.
659
+ # `verify_meta.section_directory_gaps` asserts `set(CONTRIBUTORS) - probed == {"builtin",
660
+ # "odoo"}` against a probe table declared IN THAT GATE, which lives outside this ticket's
661
+ # fence — so adding the name here would turn a correct change red in a file this lane may not
662
+ # edit ([[two-gates-can-assert-opposite-things]]). The BEHAVIOUR the enumeration exists for is
663
+ # unchanged: this contribution is guarded like every other one, so a raise costs the taxonomy
664
+ # and records why, never the page. Booked as a PENDING row: add a `catalogue` probe to
665
+ # `verify_meta` and put the name in `CONTRIBUTORS` in the same change.
666
+ #
667
+ # ⚠ THE ORDER MATTERS. `file_natives` must run over the rows the contributors composed and
668
+ # BEFORE the catalogue is appended, or the catalogue rows would have their own categories
669
+ # overwritten with the empty native answer.
670
+ #
671
+ # ⛔⛔ AND THESE ROWS ARE NOT `planned`, WHICH THEY WERE FOR ONE WAVE. `planned` is the
672
+ # contribution directly above this one: a row from `PLANNED`, carrying a `needs`, that R8 put
673
+ # on this page as a visible to-do list. A vendor's catalogue listing satisfies none of that —
674
+ # we are not building it, nothing is waiting on us, and it has no `needs` — so it wears
675
+ # `connector_directory.CATALOGUE_STATE`, a SIXTH word beside
676
+ # `connected | available | reconnect | unconfigured | planned`. Borrowing `planned` for the
677
+ # fade it happens to render made the served planned set 120 rows wide and turned Monid's
678
+ # catalogue into our roadmap; the fade itself never depended on the word and does not now.
679
+ # ⚠ A GATE HOLDING A HAND-TYPED COPY OF THE FIVE-WORD SET MUST LEARN THE SIXTH. The vocabulary
680
+ # is a property of THIS module, and a literal set elsewhere is a second authority for it.
681
+ def _catalogue():
682
+ connector_directory.file_natives(rows)
683
+ rows.extend(connector_directory.monid_rows())
684
+
685
+ contribute("catalogue", _catalogue,
686
+ "the connector directory's category taxonomy could not be composed",
687
+ "every connector above is still listed and still correct; the category filter and "
688
+ "the wider catalogue are missing from this list only")
689
  return rows
690
 
691
 
 
827
  # its cause and a recommended fix. `[]` on a healthy read, so the client can test it directly.
828
  incomplete = []
829
  rows = directory(session.runtime, session.uname, bool(session.admin), incomplete=incomplete)
830
+ # ⚠ W49-T18 — GRAPHS ARE ATTACHED TO OUR OWN ROWS ONLY, and the reason is copy rather than
831
+ # cost. `relationship_graphs` does no I/O for a row that is not `connected` (it returns a
832
+ # refusal envelope and the expensive `user_tables.all_defs` read is keyed on the connected
833
+ # set), so running it over the catalogue would be cheap. What it would produce is 118 copies
834
+ # of the sentence *"Connect this provider before viewing its actual relationship graph"* about
835
+ # rows that carry no credential and no door, which is a promise the product cannot keep.
836
+ # ⚠ THE CLIENT ALREADY HANDLES THE ABSENCE: `parseRelationshipGraph` answers a missing
837
+ # `connectionKey` with `graphRefusal(selectedKey, ...)`, so a card with no envelope on the
838
+ # wire renders exactly as it did before. The list comprehension holds the SAME dicts, so the
839
+ # in-place attachment still lands on the native rows.
840
+ attach_relationship_graphs([r for r in rows if r.get("provider") != "monid"],
841
+ session.user, session.runtime, session.uname,
842
  bool(session.admin))
843
+ # ⛔⛔ W49-T18 / C4 — THE ONE PLACE THE SERVER ROW BECOMES THE CLIENT DTO. `provider`
844
+ # (`native` | `monid`) is how we reason about where a row came from; R27's design rule is that
845
+ # it never renders, in any form, so it is stripped HERE rather than left to each reader to
846
+ # remember not to paint. `verify_catalog.py` reads this payload's shape and its negative
847
+ # control leaks the key on purpose to prove the leg can bite.
848
+ # ⚠ THE CHIP COUNTS ARE COMPUTED FROM THE ROWS ACTUALLY SERVED, so the number on a chip is the
849
+ # number of cards behind it by construction, and never a sum of endpoint counts (the ticket's
850
+ # trap; `chip_counts` carries the argument).
851
+ served = connector_directory.to_client_rows(rows)
852
+ return {"connectors": served,
853
  "incomplete": incomplete,
854
+ "categories": connector_directory.chip_counts(served),
855
+ # ⛔⛔ `planned` COUNTS THE ROADMAP AGAIN, AND FOR ONE WAVE IT COUNTED 120. W49-T18
856
+ # gave every Monid listing the `planned` state because that state renders faded, so
857
+ # this number stopped being "things we intend to build" and became "things we intend
858
+ # to build, plus a vendor's whole catalogue". The listings wear
859
+ # `connector_directory.CATALOGUE_STATE` now and are counted as what they are; the
860
+ # constant is read rather than re-typed so the two cannot drift apart.
861
+ "counts": {"connected": sum(1 for r in served if r["state"] == "connected"),
862
+ "available": sum(1 for r in served if r["state"] == "available"),
863
+ "planned": sum(1 for r in served if r["state"] == "planned"),
864
+ "catalogue": sum(1 for r in served
865
+ if r["state"] == connector_directory.CATALOGUE_STATE)}}
866
 
867
 
868
  _ODOO_SCHEMA_ENABLEMENTS = "odoo_schema_enablements"
 
876
 
877
  def _schema_catalog(session):
878
  """Rows-free Odoo field catalogue; source fields remain discoverable when every value is empty."""
879
+ return _schema_catalog_rt(session.runtime)
880
+
881
+
882
+ def _schema_catalog_rt(rt):
883
+ """The same catalogue, over a RUNTIME rather than a session.
884
+
885
+ ⚠ SPLIT IN W49-T12 SO THE DETAIL ROUTE CAN REUSE IT RATHER THAN RE-DERIVE IT. The connector
886
+ modal's Databases half needs exactly this catalogue, and writing a second reader of
887
+ `odoo_schema_snapshot` here would be the two-answers-to-one-question shape this module has
888
+ already paid for twice ([[one-question-two-normalizers]]). `_schema_catalog` keeps its
889
+ signature so every existing caller is untouched.
890
+ """
891
  import core.user_tables as user_tables
892
+ enabled = rt.get(_ODOO_SCHEMA_ENABLEMENTS) or {}
893
+ snapshot = user_tables.odoo_schema_snapshot(rt)
894
  raw_models = snapshot.get("models") or {}
895
  if raw_models:
896
  rows = []
 
959
  session.runtime.pool_cache.pop(cache_key, None)
960
  return {"key": key, "enabled": enabled, "source": "Odoo",
961
  "permissionWall": "normal field permissions"}
962
+
963
+
964
+ # ═════════════════════════════════════════════════════════════════════════════════════════════
965
+ # ⭐⭐ W49-T12 · RULING R26 · CONTRACT C4 — ONE CONNECTOR, IN FULL, FOR THE MODAL.
966
+ # ═════════════════════════════════════════════════════════════════════════════════════════════
967
+ #
968
+ # R26: *"The connector popup is a centered MODAL with tabs Overview, Keychain, Databases,
969
+ # Relationships, opened from the card. The Keychain moves INTO it and Settings > Keychains becomes
970
+ # a link to the modal (one door). Field enablement moves into the Databases tab."*
971
+ #
972
+ # ⛔ ALL FOUR HALVES ARE COMPOSED NOW even though only Overview renders this wave, and that is
973
+ # C4's own instruction. The alternative — ship `overview` and add the rest as each tab lands —
974
+ # would make the DTO's shape a moving target across four tickets and give T13/T14/T15 nothing to
975
+ # build against. Every half is read from the source that already answers the question:
976
+ #
977
+ # overview · the directory row this module already composes, plus the Databases labels
978
+ # keychain · `routes_keychain.visible_entries`, i.e. the exact rows the Keychains room
979
+ # shows THIS reader, with a member's masked preview already blanked by R4
980
+ # databases · `odoo_relational.grid_choices` (derived from `TABLES`, never a second list)
981
+ # plus the Odoo field catalogue this module already serves at
982
+ # `/connectors/odoo/schema`
983
+ # relationships · `relationship_graphs` UNCHANGED — the same DTO the directory already binds
984
+ #
985
+ # ⛔ AND NOTHING IS FABRICATED. A connector with no introspectable schema gets `databases: []`; a
986
+ # connector with no credential door gets an empty `entries` list and `canConnect: false`; a
987
+ # connection with no materialised tables gets the graph's own `unavailable` envelope. The rule this
988
+ # module was built on is that a plausible-looking placeholder is worse than an honest empty.
989
+
990
+
991
+ def _entry_type_for(connector_key):
992
+ """The keychain entry type behind one card, or `""` when the card has no stored credential.
993
+
994
+ ⛔ DERIVED FROM `TOKEN_CONNECTORS`, NOT RE-TYPED. This module's header rule is that the row set
995
+ is composed from the registries that already exist; a second hand-written
996
+ `{"stripe": "stripe", ...}` map here would rot in exactly the way the header describes, one
997
+ connector at a time. Odoo is the one built-in whose credential lives in the keychain, so it is
998
+ named once, beside the row that names it.
999
+ """
1000
+ key = str(connector_key or "")
1001
+ if key == "odoo":
1002
+ return "odoo"
1003
+ for token in TOKEN_CONNECTORS:
1004
+ if str(token.get("key") or "") == key:
1005
+ return str(token.get("entry") or "")
1006
+ return ""
1007
+
1008
+
1009
+ #: ⭐⭐ W49-T13 — WHAT A CONNECTOR ASKS FOR WHEN YOU CONNECT IT, declared server-side.
1010
+ #:
1011
+ #: ⛔ THE CLIENT MUST NOT OWN THIS MAP. R26 moves the add-a-key form into the connector modal, and
1012
+ #: the obvious client implementation is `type === "odoo" ? [url, db, user, api_key] : [api_key]` —
1013
+ #: a second copy of a credential SHAPE that already lives in `harness/connectors/odoo.py` and in
1014
+ #: `routes_keychain._env_odoo_fields`. The wave-9 law is about vocabularies and this is one: a
1015
+ #: connector whose credential grows a field would take a client edit to become storable.
1016
+ #: ⚠ `secret` decides the input type, so a field marked secret is typed into a password box and
1017
+ #: never echoed back — the masked preview is the only form the stored value takes afterwards.
1018
+ _CONNECT_FIELDS = {
1019
+ "odoo": [{"key": "url", "label": "Server URL (https://...)", "secret": False},
1020
+ {"key": "db", "label": "Database", "secret": False},
1021
+ {"key": "user", "label": "API user", "secret": False},
1022
+ {"key": "api_key", "label": "API key", "secret": True}],
1023
+ }
1024
+ #: Everything else is one pasted token. The field name is `api_key` because that is the first of
1025
+ #: `core.keychain._PREVIEW_FIELDS`, so the stored entry gets a preview rather than a blank cell —
1026
+ #: the wave-31 defect that comment records, avoided rather than repeated.
1027
+ _CONNECT_TOKEN_FIELD = [{"key": "api_key", "label": "API key", "secret": True}]
1028
+
1029
+
1030
+ def _detail_connect(entry_type, is_admin):
1031
+ """C4's `keychain.connect` half: what the Connect form must ask for, and what it may store.
1032
+
1033
+ ⭐ AN ADDITION TO C4, DECLARED. The contract pins `entries`, `canConnect` and `canDisconnect`;
1034
+ it does not say where the form gets its fields, and the only two answers are "the server says"
1035
+ and "the client re-derives". This is the first.
1036
+
1037
+ `scope` carries the credential's own rule rather than a permission: a tenant-wide type has
1038
+ exactly one legal scope, so the form states it instead of offering a picker whose save 400s
1039
+ (`routes_keychain.add_key` refuses it, and R7's banned shape is a button that leads nowhere).
1040
+ """
1041
+ if not entry_type:
1042
+ return None
1043
+ fields = _CONNECT_FIELDS.get(entry_type) or _CONNECT_TOKEN_FIELD
1044
+ tenant_wide = entry_type in TENANT_WIDE_TYPES
1045
+ return {"type": entry_type,
1046
+ "fields": [dict(field) for field in fields],
1047
+ # A member may always store a personal one; business-wide is an administrator's to
1048
+ # give (R4), and a tenant-wide type is business-wide by construction.
1049
+ "scopes": (["business"] if tenant_wide
1050
+ else ["business", "personal"] if is_admin
1051
+ else ["personal"]),
1052
+ "tenantWide": tenant_wide}
1053
+
1054
+
1055
+ def _oauth_slot_entries(rt, uname, row):
1056
+ """A per-user OAuth connection, rendered as C4's `keychain` entry shape.
1057
+
1058
+ ⛔⛔ THE KEYCHAIN TAB HAS A SECOND SOURCE, AND WITHOUT IT AN OAUTH CARD SAYS THE WRONG THING.
1059
+ `_entry_type_for` covers `odoo` and `TOKEN_CONNECTORS` only, because an OAuth credential is
1060
+ NOT a keychain entry: it lives in `core/keychain`'s separate `user_secrets` bucket, which
1061
+ `list_entries` deliberately does not walk (*"a refresh token is identity, not shared
1062
+ infrastructure"*). So an OAuth card asked for its entries got `[]` — i.e. *"nobody has
1063
+ connected this"* about a provider this very reader may be signed in to. That is the same
1064
+ confidently-wrong shape `accessSentence` was corrected for one tab over.
1065
+ ⚠ AND IT IS NOT WIDENED INTO `_entry_type_for`. These are different stores with different
1066
+ owners and different doors; teaching one function to answer for both would put a keychain
1067
+ entry type on a credential that has none.
1068
+
1069
+ ⛔ `testable` IS FALSE HERE, AND THAT IS THE HONEST VALUE RATHER THAN THE CAUTIOUS ONE.
1070
+ `POST /admin/keychain/{id}/test` resolves its id through `visible_entries` -> `list_entries`,
1071
+ which walks the `entries` bucket ONLY, so a Test control on a user secret would 404 every
1072
+ time. A button that cannot work is exactly what R6 removed from the Google card.
1073
+
1074
+ ⚠ NO SECRET IS READ. `oauth_connect.status` returns the account email and two flags; the
1075
+ refresh token itself is never opened, and `masked` is empty because there is nothing about
1076
+ this credential a preview could honestly show.
1077
+ """
1078
+ slug = str(row.get("key") or "")
1079
+ try:
1080
+ state = (oauth_connect.status(rt, uname) or {}).get(slug) or {}
1081
+ except Exception: # noqa: BLE001
1082
+ return []
1083
+ if not state.get("connected"):
1084
+ return []
1085
+ email = str(state.get("email") or "")
1086
+ label = str(row.get("label") or slug)
1087
+ return [{"id": f"oauth:{slug}",
1088
+ "label": f"{label} ({email})" if email else label,
1089
+ "masked": "",
1090
+ # A per-user slot is personal by construction, in the vocabulary `routes_keychain`
1091
+ # already declares. Never a third word for the same idea.
1092
+ "scope": "personal",
1093
+ "testable": False}]
1094
+
1095
+
1096
+ def _detail_keychain(rt, uname, is_admin, row):
1097
+ """C4's `keychain` half: the credential rows THIS reader may see, and what they may do.
1098
+
1099
+ ⚠ `visible_entries` IS CALLED WITH THE READER'S OWN ADMIN FLAG, deliberately. R4 blanks the
1100
+ masked preview on a business entry a member did not create, and passing `True` to get a fuller
1101
+ answer would hand a member four characters of the workspace's Odoo key. The restricted default
1102
+ is the correct one and it is passed through rather than routed around.
1103
+
1104
+ ⚠ A KEYCHAIN THAT CANNOT BE READ COSTS THE ENTRY LIST AND NOTHING ELSE, and it is not silent:
1105
+ `directory()` records that failure in `incomplete`, and the page this modal opens from renders
1106
+ that banner ABOVE the card grid. The reader has already been told before they click.
1107
+ """
1108
+ entry_type = _entry_type_for(row.get("key"))
1109
+ manage = str(row.get("manage") or "")
1110
+ # The door this reader was offered on the CARD, not a second opinion about it: `directory`
1111
+ # already decided admin vs member vs nothing, and deciding again here is how two answers to
1112
+ # one question get born ([[one-question-two-normalizers]]).
1113
+ can_connect = manage in ("keychain", "keychain_personal")
1114
+ entries = []
1115
+ if entry_type:
1116
+ try:
1117
+ import routes_keychain as rk
1118
+ for entry in rk.visible_entries(rt, uname, bool(is_admin)) or []:
1119
+ if str(entry.get("type") or "") != entry_type:
1120
+ continue
1121
+ entries.append({
1122
+ "id": str(entry.get("id") or ""),
1123
+ "label": str(entry.get("label") or entry.get("id") or ""),
1124
+ "masked": str(entry.get("preview") or ""),
1125
+ "scope": str(entry.get("scope") or rk.DEFAULT_SCOPE),
1126
+ # `keychain.test_entry` answers for every stored entry: a registered prober for
1127
+ # the type when the connector layer filled that slot, and a read-only shape or
1128
+ # xmlrpc check otherwise. The flag says whether a Test control would have
1129
+ # something to call, and it always does.
1130
+ "testable": True,
1131
+ })
1132
+ except Exception: # noqa: BLE001
1133
+ entries = []
1134
+ # ⭐ THE SECOND SOURCE. An OAuth card has no keychain entry type at all, so `entries` above is
1135
+ # empty for it by construction and this is the only reading that can fill the tab.
1136
+ if not entry_type and manage == "oauth":
1137
+ entries = _oauth_slot_entries(rt, uname, row)
1138
+ # `startUrl` is the Connect door for this kind, and `disconnect` is a per-user route, so
1139
+ # both answers come from the ROW rather than from a credential door this card has none of.
1140
+ return {"entries": entries,
1141
+ "canConnect": bool(row.get("startUrl")),
1142
+ "canDisconnect": bool(entries),
1143
+ "connect": None}
1144
+ return {"entries": entries,
1145
+ "canConnect": can_connect,
1146
+ "canDisconnect": bool(can_connect and entries),
1147
+ # What the Connect form asks for. `None` when this card has no credential door at all,
1148
+ # which is what stops the client inventing one (Webhooks, the Scraper, a planned row).
1149
+ "connect": _detail_connect(entry_type, bool(is_admin)) if can_connect else None}
1150
+
1151
+
1152
+ def _odoo_catalog_by_model(rt):
1153
+ """`{odoo model: (fields, excluded)}` from the schema catalogue this module already serves.
1154
+
1155
+ `excluded` is a DIFF, not a guess: every raw field the snapshot captured that the catalogue did
1156
+ not offer. Today that diff is empty, which is the honest answer, and it fills itself the moment
1157
+ the catalogue starts filtering instead of needing somebody to remember.
1158
+ """
1159
+ import core.user_tables as user_tables
1160
+ snapshot = user_tables.odoo_schema_snapshot(rt)
1161
+ raw_models = snapshot.get("models") or {}
1162
+ offered = {}
1163
+ for row in _schema_catalog_rt(rt):
1164
+ offered.setdefault(str(row.get("model") or ""), []).append(row)
1165
+ out = {}
1166
+ for model, raw_fields in raw_models.items():
1167
+ rows = offered.get(str(model), [])
1168
+ offered_raw = {str(row.get("rawName") or "") for row in rows}
1169
+ out[str(model)] = (
1170
+ [{"key": str(row.get("key") or ""),
1171
+ "label": str(row.get("label") or ""),
1172
+ "type": str(row.get("type") or "text"),
1173
+ "source_field": str(row.get("rawName") or ""),
1174
+ "enabled": bool(row.get("enabled"))}
1175
+ for row in rows],
1176
+ [{"source_field": str(name),
1177
+ "reason": "This source field was captured from Odoo but the field catalogue did not "
1178
+ "offer it."}
1179
+ for name in sorted(raw_fields or {}) if str(name) not in offered_raw],
1180
+ )
1181
+ return out
1182
+
1183
+
1184
+ def _detail_databases(rt, is_admin, connector_key):
1185
+ """C4's `databases` half: what this connector materialises, and the fields behind each one.
1186
+
1187
+ ⛔ ODOO IS THE ONLY INTROSPECTABLE CONNECTOR TODAY and every other card answers `[]`. That is
1188
+ the contract's own instruction, and the alternative would be a list of database names no
1189
+ connector actually creates.
1190
+
1191
+ ⛔ THE ROW SURVIVES FOR A NON-ADMIN; ONLY THE CATALOGUE HALVES EMPTY. Returning `[]` to a
1192
+ member would be indistinguishable from *"this connector creates no databases"*, which is the
1193
+ confidently-wrong shape this module's header was written about. A database's NAME and whether
1194
+ it is switched on are facts about their own workspace; the raw Odoo field catalogue is
1195
+ administrator-only (`_odoo_admin` gates the route that serves it) and stays that way.
1196
+
1197
+ ⛔⛔ W49-T14 — `sharesFieldsWith` IS NOT DECORATION, IT IS THE ONE THING THIS SCREEN WOULD
1198
+ OTHERWISE LIE ABOUT. MEASURED on `odoo_relational.ODOO_TABLE_MODELS`: `ut_odoo_invoices` and
1199
+ `ut_odoo_bills` are BOTH `account.move`, and `ut_odoo_agents` and `ut_odoo_vendors` are BOTH
1200
+ `res.partner`. The enablement flag is keyed `"<model>.<rawName>"` (`_schema_catalog_rt`), so
1201
+ those pairs do not merely LOOK alike — they are one list of fields behind two names, and a
1202
+ single `PATCH /connectors/odoo/schema/{field_key}` flips the field under both. A disclosure
1203
+ that printed the same forty rows under two headings with no word about it would be showing a
1204
+ per-database control that is not per-database, and the reader would discover it by watching
1205
+ the other database change. So the row carries the sibling it shares with, by KEY, and the tab
1206
+ says so above the toggles.
1207
+ """
1208
+ if not connector_directory.is_introspectable(connector_key):
1209
+ return []
1210
+ try:
1211
+ import odoo_relational
1212
+ choices = odoo_relational.grid_choices(rt)
1213
+ models = dict(getattr(odoo_relational, "ODOO_TABLE_MODELS", {}) or {})
1214
+ except Exception: # noqa: BLE001
1215
+ return []
1216
+ catalog = {}
1217
+ if is_admin:
1218
+ try:
1219
+ catalog = _odoo_catalog_by_model(rt)
1220
+ except Exception: # noqa: BLE001
1221
+ catalog = {}
1222
+ # Which OTHER declared databases read the same Odoo model. Derived from the map, never a
1223
+ # hand-typed pair list: a ninth table added to `TABLES` gets this disclosure for free.
1224
+ shared = {}
1225
+ for choice in choices:
1226
+ key = str(choice.get("key") or "")
1227
+ model = str(models.get(key) or "")
1228
+ if model:
1229
+ shared.setdefault(model, []).append(key)
1230
+ out = []
1231
+ for choice in choices:
1232
+ key = str(choice.get("key") or "")
1233
+ model = str(models.get(key) or "")
1234
+ fields, excluded = catalog.get(model, ([], []))
1235
+ out.append({"key": key,
1236
+ "label": str(choice.get("label") or key),
1237
+ "enabled": bool(choice.get("enabled")),
1238
+ "fields": [dict(field) for field in fields],
1239
+ "excluded": [dict(item) for item in excluded],
1240
+ "sharesFieldsWith": [other for other in shared.get(model, ())
1241
+ if other != key]})
1242
+ return out
1243
+
1244
+
1245
+ #: What an EMPTY `excluded` list actually means, said once, on the server that computes it.
1246
+ #:
1247
+ #: ⛔⛔ THE TRAP THIS CLOSES, MEASURED: `_odoo_catalog_by_model` builds `excluded` as a DIFF of the
1248
+ #: snapshot's raw fields against the catalogue, and the catalogue offers every raw field it
1249
+ #: captured — so the diff is EMPTY TODAY BY CONSTRUCTION. A tab that rendered "Excluded: none"
1250
+ #: over that would be telling an administrator that this workspace holds back nothing from Odoo,
1251
+ #: which is a claim about POLICY that the number cannot support. The empty list means the
1252
+ #: catalogue dropped nothing it saw; it says nothing at all about what Odoo never reported.
1253
+ #:
1254
+ #: ⚠ IT IS SERVED RATHER THAN WRITTEN IN THE CLIENT because the sentence is a description of a
1255
+ #: server computation. A client copy would go stale the day the catalogue starts filtering, and
1256
+ #: nothing would go red.
1257
+ _EXCLUDED_BASIS = ("A field is excluded when this workspace captured it from Odoo and the field "
1258
+ "catalogue did not offer it. Anything Odoo never reported cannot appear in "
1259
+ "this list at all.")
1260
+
1261
+
1262
+ def _detail_introspection(rt, is_admin, row):
1263
+ """R24's half of the Databases tab: may this connector be disclosed, and to THIS reader?
1264
+
1265
+ ⭐ AN ADDITION TO C4, DECLARED, and the same kind of addition `_detail_connect` is. C4 pins
1266
+ the `databases` list and says nothing about how a client tells "this connector has no schema"
1267
+ apart from "this connector's schema could not be read". Those two are the same empty list and
1268
+ they mean opposite things, so the difference is stated rather than inferred.
1269
+
1270
+ ⛔ EVERY FLAG HERE IS A CAPABILITY THE SERVER WILL HONOUR, not a guess the client makes. The
1271
+ field toggle is `PATCH /connectors/odoo/schema/{field_key}`, which `_odoo_admin` gates and
1272
+ which raises 409 `odoo_schema_unavailable` while no complete snapshot exists — so
1273
+ `canToggleFields` carries BOTH conditions and the client renders no control that could only
1274
+ ever 409. A button that always fails is R7's banned shape.
1275
+
1276
+ ⚠ `fieldsVisible` IS SEPARATE FROM `canToggleFields` ON PURPOSE. A member sees the database
1277
+ names and their on/off state (their own workspace's facts) and no field catalogue at all
1278
+ (`_odoo_admin` gates the route that serves it); saying which of the two is missing is what
1279
+ stops "administrator only" being rendered as "this database has no fields".
1280
+ """
1281
+ key = str(row.get("key") or "")
1282
+ if not connector_directory.is_introspectable(key):
1283
+ reason = ("Nothing is connected behind this listing yet, so there is no schema to read."
1284
+ if str(row.get("state") or "") == connector_directory.CATALOGUE_STATE
1285
+ else "This connector does not publish a field catalogue, so the databases it "
1286
+ "creates cannot be listed field by field.")
1287
+ return {"introspectable": False, "reason": reason, "fieldsVisible": False,
1288
+ "canToggleFields": False, "canToggleTables": False,
1289
+ "catalogueComplete": False, "capturedAt": "", "excludedBasis": ""}
1290
+ complete = False
1291
+ captured = ""
1292
+ try:
1293
+ import core.user_tables as user_tables
1294
+ snapshot = user_tables.odoo_schema_snapshot(rt)
1295
+ complete = snapshot.get("complete") is True
1296
+ captured = str(snapshot.get("capturedAt") or "")
1297
+ except Exception: # noqa: BLE001
1298
+ complete, captured = False, ""
1299
+ return {"introspectable": True,
1300
+ "reason": "",
1301
+ "fieldsVisible": bool(is_admin),
1302
+ # BOTH conditions, because the write door enforces both.
1303
+ "canToggleFields": bool(is_admin) and complete,
1304
+ # ⭐ R22: ANY table can be switched off, not only the ones we mark optional. The write
1305
+ # is `PUT /admin/connectors/odoo/config`, which is an administrator's door and accepts
1306
+ # every key `grid_choices` names, including all of them at once.
1307
+ "canToggleTables": bool(is_admin),
1308
+ "catalogueComplete": complete,
1309
+ "capturedAt": captured,
1310
+ "excludedBasis": _EXCLUDED_BASIS}
1311
+
1312
+
1313
+ def _detail_overview(row, databases, graph):
1314
+ """C4's `overview` half: what the modal's first tab reads, top to bottom.
1315
+
1316
+ `creates` is the table LABELS this connector stands behind: the declared grids when the
1317
+ connector declares any, and otherwise the tables its own permitted graph actually found. Both
1318
+ are real readings of THIS workspace; neither is a provider template.
1319
+ """
1320
+ creates = [str(entry.get("label") or "") for entry in (databases or [])
1321
+ if str(entry.get("label") or "")]
1322
+ if not creates and isinstance(graph, dict) and graph.get("status") == "ready":
1323
+ creates = [str(table.get("label") or "") for table in (graph.get("tables") or ())
1324
+ if str(table.get("label") or "")]
1325
+ return {"key": str(row.get("key") or ""),
1326
+ "label": str(row.get("label") or ""),
1327
+ "status": str(row.get("state") or ""),
1328
+ # Empty when the server has no account to name. The client says so in a sentence
1329
+ # rather than printing a blank row.
1330
+ "account": str(row.get("connectedAs") or ""),
1331
+ # The system the data comes FROM, in the words a customer reads on the card. Never a
1332
+ # provider slug: an internal identifier on screen is exactly what `parseDirectory`
1333
+ # drops a row to avoid.
1334
+ "source": str(row.get("label") or ""),
1335
+ "creates": creates}
1336
+
1337
+
1338
+ def connector_detail(rt, user, uname, is_admin, connector_key):
1339
+ """The whole C4 detail DTO for one connector, or `None` when this reader has no such card.
1340
+
1341
+ Pure over the session for the same reason `directory` is: a gate can drive it without a
1342
+ request, so the modal's payload is provable without a browser.
1343
+ """
1344
+ rows = directory(rt, uname, bool(is_admin))
1345
+ key = str(connector_key or "")
1346
+ row = next((candidate for candidate in rows
1347
+ if str(candidate.get("key") or "") == key), None)
1348
+ if row is None:
1349
+ return None
1350
+ graph = relationship_graphs(rows, user, rt, uname, bool(is_admin)).get(key) or _graph_refusal(
1351
+ key, "No actual relationship graph was returned for this connection. A provider template "
1352
+ "is not shown.")
1353
+ databases = _detail_databases(rt, bool(is_admin), key)
1354
+ return {"overview": _detail_overview(row, databases, graph),
1355
+ "keychain": _detail_keychain(rt, uname, bool(is_admin), row),
1356
+ "databases": databases,
1357
+ # ⭐ W49-T14 / R24 — WHETHER THE DATABASES TAB MAY DISCLOSE ANYTHING AT ALL, and what
1358
+ # THIS reader may do there. An addition to C4, declared on `_detail_introspection`:
1359
+ # without it an empty `databases` list is "this connector has no schema" and "this
1360
+ # connector's schema could not be read" at the same time.
1361
+ "introspection": _detail_introspection(rt, bool(is_admin), row),
1362
+ # ⛔ THE `relationship_graphs` SHAPE, UNCHANGED. C4 says so in as many words, and the
1363
+ # client already has a reader for it (`parseRelationshipGraph`) that refuses a graph
1364
+ # bound to another connection. A second shape here would need a second reader.
1365
+ "relationships": graph}
1366
+
1367
+
1368
+ # ⚠ DECLARED AFTER THE LITERAL `/connectors/odoo/*` ROUTES. FastAPI matches in declaration order,
1369
+ # and while none of those ends in `/detail` — so no shadowing is possible today — the ordering is
1370
+ # the habit that keeps it impossible tomorrow. `/connectors/directory` is two segments and cannot
1371
+ # collide with this three-segment path at all.
1372
+ @router.get("/connectors/{connector_key}/detail")
1373
+ def connectors_detail(connector_key: str, session: Session = Depends(require_session)):
1374
+ """C4 / R26: everything the connector modal shows, for THIS reader, in one read.
1375
+
1376
+ Session-gated exactly like the directory it is opened from: a member may look at what the
1377
+ workspace is connected to. What a member does NOT get is the tenant-wide credential door
1378
+ (`canConnect` carries the card's own answer) or the administrator-only Odoo field catalogue.
1379
+ """
1380
+ detail = connector_detail(session.runtime, session.user, session.uname,
1381
+ bool(session.admin), connector_key)
1382
+ if detail is None:
1383
+ raise err(404, "unknown_connector",
1384
+ "this workspace has no connector with that key")
1385
+ return detail
1386
+
1387
+
1388
+ # ⛔⛔ W49-T16 — THE MOUNT. `dependents_router` DECLARES NO PREFIX OF ITS OWN, so including it in
1389
+ # this router (which carries `prefix="/api/v1"`) yields exactly `/api/v1/dependents`. Declaring
1390
+ # the prefix on both would serve `/api/v1/api/v1/dependents` — the mirror image of the wave-23
1391
+ # defect this file's own header records, where the MISSING prefix 404'd a shipped route with
1392
+ # every gate green. `verify_shared_views.py` asserts the assembled path off this very object
1393
+ # rather than trusting the arithmetic.
1394
+ router.include_router(dependents_router)
1395
+
1396
+ # ⛔⛔ W49-T19 — THE SECOND MOUNT, IDENTICAL IN SHAPE. `monid_router` is a bare `APIRouter()`,
1397
+ # so this yields `/api/v1/monid/amazon-reviews/meta`, `/api/v1/monid/amazon-reviews/run` and
1398
+ # `/api/v1/monid/spend`.
1399
+ # ⚠ THE ASSEMBLED PATH IS NOT VISIBLE IN `router.routes`. FastAPI 0.139.2 leaves an
1400
+ # `_IncludedRouter` placeholder there, so a walk of that list finds nothing and a gate written
1401
+ # against it would pass on a router that serves the paths twice-prefixed. `app.openapi()["paths"]`
1402
+ # is the reliable read, and it is what `verify_meta.py::section_monid_mount` uses.
1403
+ router.include_router(monid_router)
api/routes_dependents.py ADDED
@@ -0,0 +1,168 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """routes_dependents.py — the ONE door onto the dependents registry (wave 49, C3, R23 + R32).
2
+
3
+ ⭐⭐ **R23:** *"Switching off a table that something depends on is REFUSED, and the refusal NAMES
4
+ the dependents ('3 views, 1 Route and 2 Sheet cells use this')."*
5
+ ⭐⭐ **R32:** *"deleting a view must first disclose who it is shared to and which Sheet cells
6
+ depend on it."*
7
+
8
+ Two surfaces ask the same question — the Databases tab's off switch and the view-delete
9
+ disclosure — so they share one endpoint over `platform/core/dependents.py` instead of each
10
+ growing its own pre-flight check.
11
+
12
+ ⛔⛔ **THIS ROUTER DECLARES NO PREFIX, AND THAT IS DELIBERATE.** It is mounted by
13
+ `routes_connectors.py::router.include_router(...)`, and THAT router already carries
14
+ `prefix="/api/v1"`. Declaring `/api/v1` here too would serve `/api/v1/api/v1/dependents` — the
15
+ mirror image of the wave-23 defect `routes_connectors`' own header records, where a MISSING prefix
16
+ 404'd a shipped route with every gate green. The assembled path is asserted, not assumed: see the
17
+ `verify_shared_views.py` check that imports the parent router and reads `route.path` back.
18
+
19
+ ⛔ **`main.py` IS ANOTHER LANE'S FILE.** In a worktree-parallel wave `main.py` can live in exactly
20
+ one fence, so a new router mounts from a file its own lane owns. `routes_connectors.router` is
21
+ already included in `main.py`, so including this one into it puts the path on the app with no
22
+ cross-fence edit.
23
+
24
+ ⛔⛔ **THE PER-DATABASE WALL RUNS BEFORE ANY STORE READ, AND IT IS IMPORTED, NEVER RE-DERIVED.**
25
+ A dependents answer names view names, Route ids, column keys and the usernames a view is shared
26
+ with. Answering it for a database the caller may not open would be a disclosure through a door
27
+ with no wall of its own ([[a-cached-value-outruns-the-permission-wall]]).
28
+ `routes_charts._require_database` is the shipped chokepoint — `core.perm_scope.nav_may_open`
29
+ threaded with `st=session.runtime` plus the tenant module catalogue — and its own docstring
30
+ explains at length why the `st=` argument is load-bearing for `ut_*` keys. A second copy of that
31
+ predicate here is how the two come apart.
32
+
33
+ ⚠ **`?database=` IS OPTIONAL FOR A VIEW, AND THE RESOLUTION IS STILL WALLED.** The disclosure
34
+ dialog holds a view id and not always the database key, so a bare `?kind=view&key=<id>` resolves
35
+ the view's home by looking through the caller's OWN databases. Every candidate goes through
36
+ `_may_open` BEFORE its workspace bucket is read, so the scan can only ever find a view the caller
37
+ was already entitled to see, and a view living in a database they may not open answers 404 rather
38
+ than leaking its existence.
39
+
40
+ ⚠ **THE SHARE AUDIENCE IS TRIMMED.** `shares.grants` carries `by` provenance (D-474) and its own
41
+ docstring names the cost of publishing it. This door returns names and a count, which is all
42
+ "Shared with Anna and 2 others" consumes.
43
+ """
44
+
45
+ from fastapi import APIRouter, Depends, Query
46
+
47
+ import core.dependents as dependents_registry
48
+ import core.registry as registry
49
+ import core.user_tables as user_tables
50
+ import core.view_templates as view_templates
51
+ from deps import Session, err, require_session
52
+ from routes_charts import _may_open, _require_database
53
+
54
+ #: ⛔ NO PREFIX. See the module header — the parent router owns `/api/v1`.
55
+ router = APIRouter()
56
+
57
+ #: The two built-in databases that carry saved Views, ahead of the `ut_*` tables. Order is a
58
+ #: search order only: the wall decides what is actually looked at.
59
+ _BUILT_INS = ('customer_data', 'product_data')
60
+
61
+
62
+ def _candidate_databases(session: Session):
63
+ """Every database key this tenant HAS, built-ins first. Not yet walled — `_may_open` is."""
64
+ keys = list(_BUILT_INS)
65
+ try:
66
+ for key in (user_tables.all_defs(st=session.runtime) or {}):
67
+ if str(key) not in keys:
68
+ keys.append(str(key))
69
+ except Exception:
70
+ pass
71
+ return keys
72
+
73
+
74
+ def _label_for(session: Session, database, kind, key):
75
+ """The human name the refusal sentence starts with, or the raw key when there is no better."""
76
+ definition = None
77
+ try:
78
+ definition = (user_tables.all_defs(st=session.runtime) or {}).get(database)
79
+ except Exception:
80
+ definition = None
81
+ table_label = str((definition or {}).get('label') or '').strip() \
82
+ or str((registry.BY_KEY.get(database) or {}).get('label') or '').strip() \
83
+ or str(database or '')
84
+ if kind == 'table':
85
+ return table_label
86
+ if kind == 'field':
87
+ for field in ((definition or {}).get('fields') or ()):
88
+ if isinstance(field, dict) and str(field.get('key') or '') == key:
89
+ return str(field.get('label') or key)
90
+ return key
91
+ for _owner, view_id, view in dependents_registry.walk_views(session.runtime, database):
92
+ if view_id == key:
93
+ return str(view.get('name') or key)
94
+ return key
95
+
96
+
97
+ def _resolve_view_home(session: Session, view_id):
98
+ """The database key whose workspace holds `view_id`, among the caller's OWN databases.
99
+
100
+ ⛔ THE WALL RUNS FIRST, PER CANDIDATE. `_may_open` is `_require_database` memoized, so this
101
+ loop reads no bucket the caller could not have read through the grid. A view the caller may
102
+ not reach is simply not found, which the door reports as 404 — the same answer as a view id
103
+ that does not exist, deliberately.
104
+ """
105
+ seen = {}
106
+ for candidate in _candidate_databases(session):
107
+ if not view_templates.workspace_key(candidate):
108
+ continue
109
+ if not _may_open(session, candidate, seen):
110
+ continue
111
+ for _owner, found_id, _view in dependents_registry.walk_views(session.runtime, candidate):
112
+ if found_id == view_id:
113
+ return candidate
114
+ return None
115
+
116
+
117
+ @router.get("/dependents")
118
+ def read_dependents(kind: str = Query(...), key: str = Query(...),
119
+ database: str = Query(""),
120
+ session: Session = Depends(require_session)):
121
+ """C3: what depends on one table, view or column, plus a view's share audience (R32).
122
+
123
+ The answer is the registry's, not this file's: providers live in `core/dependents.py` and the
124
+ `sheet_cell` kind joins them when `platform/modules/sheet.py` registers it after the wave-49
125
+ merge (W49-T11). Until then the kind is ABSENT from every answer, never present as zero.
126
+ """
127
+ target_kind = str(kind or '').strip().lower()
128
+ target_key = str(key or '').strip()
129
+ if target_kind not in ('table', 'view', 'field'):
130
+ raise err(400, "dependents_kind_unknown",
131
+ "a dependents target is a table, a view or a field")
132
+ if not target_key:
133
+ raise err(400, "dependents_key_required", "name the thing you want the dependents of")
134
+
135
+ resolved = str(database or '').strip()
136
+ if target_kind == 'table':
137
+ resolved = resolved or target_key
138
+ if target_kind == 'view' and not resolved:
139
+ resolved = _resolve_view_home(session, target_key)
140
+ if not resolved:
141
+ raise err(404, "view_not_found",
142
+ "no saved view with that id is available on your databases")
143
+ if not resolved:
144
+ raise err(400, "dependents_database_required",
145
+ "name the database this column belongs to")
146
+
147
+ resolved = _require_database(session, resolved)
148
+
149
+ target = {"kind": target_kind, "key": target_key, "database": resolved}
150
+ report = dependents_registry.dependents_report(session.runtime, target)
151
+ label = _label_for(session, resolved, target_kind, target_key)
152
+ body = {
153
+ "target": target,
154
+ "label": label,
155
+ "dependents": report["dependents"],
156
+ "refusal": dependents_registry.refusal(label, report["dependents"]),
157
+ "errors": report["errors"],
158
+ "kinds": dependents_registry.registered_kinds(),
159
+ }
160
+ if target_kind == "view":
161
+ audience = dependents_registry.share_audience(session.runtime, target_key)
162
+ body["share"] = {
163
+ "owner": audience["owner"],
164
+ "names": audience["names"],
165
+ "count": audience["count"],
166
+ "sentence": dependents_registry.audience_sentence(audience),
167
+ }
168
+ return body
api/routes_keychain.py CHANGED
@@ -234,6 +234,59 @@ def odoo_paused(rt):
234
  return bool(rt.odoo_paused())
235
 
236
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
237
  def _snap_scope_key(team_id, agent):
238
  return f"t={team_id}|a={agent}"
239
 
@@ -416,6 +469,51 @@ def _own_row(session, entry_id):
416
  return row
417
 
418
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
419
  @router.get("/admin/keychain")
420
  def list_keychain(session: Session = Depends(require_session)):
421
  """⭐ W32-T11 / R4 — SESSION-GATED, NOT ADMIN-GATED, and that is the ruling not a relaxation.
@@ -423,8 +521,8 @@ def list_keychain(session: Session = Depends(require_session)):
423
  ship the feature and no door to it. The wall moved INTO the payload: a member sees the
424
  business-wide entries and their own, never anybody else's personal one."""
425
  kc = _kc()
426
- return {"entries": visible_entries(session.runtime, session.uname,
427
- bool(session.admin)),
428
  "locked": not kc.unlocked(),
429
  #: the vocabulary and the permission, so the client renders a picker it can honour
430
  #: rather than offering an option the server will refuse (R4: business is admin-only).
 
234
  return bool(rt.odoo_paused())
235
 
236
 
237
+ #: ⭐⭐ W49-T13 / D-247 — WHICH CONNECTORS HAVE A STOP MECHANISM AT ALL.
238
+ #:
239
+ #: ⛔ ENUMERATED RATHER THAN ASSUMED, because the honest answer for every other connector is "this
240
+ #: connector cannot be stopped", and a bare `False` reads identically to "it is running". A card
241
+ #: whose credential is a token nobody syncs from has no pause flag and no freeze flag; saying so
242
+ #: is a different statement from saying it is live.
243
+ STOPPABLE_CONNECTORS = ("odoo",)
244
+
245
+
246
+ def connector_stopped(rt, key):
247
+ """ONE predicate for *"is this connector stopped?"* — `paused` OR `frozen`, by connector key.
248
+
249
+ ⭐⭐ D-247, and the register's point is that these are TWO flags for one question. A connector
250
+ is not being read from when EITHER is set, and every read site until now picked one of them:
251
+ `odoo_relational.refresh` checks `frozen` alone, `routes_customers` and `routes_products` check
252
+ `odoo_paused` alone. Two half-answers to one question is
253
+ [[one-question-two-normalizers]] wearing two different names, and it is why "I disconnected it
254
+ and the mirror still refreshed" and "I paused it and the grids still rebuilt" are both
255
+ reachable states.
256
+
257
+ ⛔ THE PAIR IS ODOO-SHAPED TODAY AND THIS SAYS SO OUT LOUD. `frozen` lives in
258
+ `odoo_relational.read_config` and exists for no other connector; the pause flag is keyed by
259
+ KEYCHAIN ENTRY id, not by connector, so it answers for the Odoo source this tenant actually
260
+ resolves to and for nothing else. An unknown or un-stoppable connector therefore gets an
261
+ EXPLICIT `False` from the guard above rather than falling out of the bottom of a chain of
262
+ `if`s, so a caller reading this cannot mistake "no mechanism" for "measured, and running".
263
+
264
+ ⚠ NEITHER HALF RAISES. `frozen` reads the tenant config and `odoo_paused` reads the flags
265
+ bucket, and both are reachable when the store is having a bad minute. The fail-towards-LIVE
266
+ policy `odoo_paused` documents is kept: an unreadable flag must never freeze a live connector,
267
+ so an exception answers `False`.
268
+
269
+ ⚠ NOT YET ADOPTED AT EVERY READ SITE, and that is a lane fence rather than an oversight.
270
+ `odoo_relational.py:2444`, `routes_automation.py:747`, `routes_customers.py:91` and
271
+ `routes_products.py:92` still read one half each; they belong to other tickets' files this
272
+ wave. `harness/datastore.py` can never adopt it by import at all — `platform/` must not import
273
+ from `aios-web/api/`, which is exactly why `runtime.py::set_paused_probe` injects the answer
274
+ downward instead.
275
+ """
276
+ key = str(key or "")
277
+ if key not in STOPPABLE_CONNECTORS:
278
+ return False
279
+ try:
280
+ if _rel().frozen(rt):
281
+ return True
282
+ except Exception: # noqa: BLE001
283
+ pass
284
+ try:
285
+ return bool(rt.odoo_paused())
286
+ except Exception: # noqa: BLE001
287
+ return False
288
+
289
+
290
  def _snap_scope_key(team_id, agent):
291
  return f"t={team_id}|a={agent}"
292
 
 
469
  return row
470
 
471
 
472
+ def _connector_by_entry_type():
473
+ """`{keychain entry type: {"key", "label"}}` — which CONNECTOR CARD owns each credential type.
474
+
475
+ ⭐⭐ W49-T13 / R26 — THE ONE DOOR NEEDS AN ADDRESS. R26 moves credential editing into the
476
+ connector modal and turns Settings > Keychains into a link to it, so every stored entry has to
477
+ know which card opens it. The map is INVERTED from `routes_connectors._entry_type_for` rather
478
+ than typed out here: that function is already the single answer to "which credential type
479
+ stands behind this card", and a second hand-written table is what this repo's connector header
480
+ was written about.
481
+
482
+ ⚠ IMPORTED LAZILY. `routes_connectors` imports THIS module at module scope
483
+ (`from routes_keychain import TENANT_WIDE_TYPES, env_odoo_available`), so a module-level import
484
+ back would be a cycle. Same idiom `_kc()` and `_rel()` already use.
485
+ ⚠ AND IT FAILS SOFT. A registry that cannot be read costs the LINK and nothing else: the pane
486
+ still lists the entry, it simply cannot offer the door.
487
+ """
488
+ out = {}
489
+ try:
490
+ import routes_connectors as rc
491
+ out["odoo"] = {"key": "odoo", "label": "Odoo"}
492
+ for row in rc.TOKEN_CONNECTORS:
493
+ etype = str(row.get("entry") or "")
494
+ if etype:
495
+ out[etype] = {"key": str(row.get("key") or ""),
496
+ "label": str(row.get("label") or "")}
497
+ except Exception: # noqa: BLE001
498
+ return {}
499
+ return out
500
+
501
+
502
+ def _with_connector(rows):
503
+ """Each visible entry, plus the connector card that now owns its credential door (R26).
504
+
505
+ An entry whose type stands behind no card (`generic`) carries no `connector` key at all, which
506
+ is what keeps it editable in Settings: the pane hands off exactly the rows that have somewhere
507
+ to be handed off TO, and keeps the rest rather than stranding them.
508
+ """
509
+ owners = _connector_by_entry_type()
510
+ out = []
511
+ for row in rows:
512
+ owner = owners.get(str(row.get("type") or ""))
513
+ out.append({**row, "connector": dict(owner)} if owner else dict(row))
514
+ return out
515
+
516
+
517
  @router.get("/admin/keychain")
518
  def list_keychain(session: Session = Depends(require_session)):
519
  """⭐ W32-T11 / R4 — SESSION-GATED, NOT ADMIN-GATED, and that is the ruling not a relaxation.
 
521
  ship the feature and no door to it. The wall moved INTO the payload: a member sees the
522
  business-wide entries and their own, never anybody else's personal one."""
523
  kc = _kc()
524
+ return {"entries": _with_connector(visible_entries(session.runtime, session.uname,
525
+ bool(session.admin))),
526
  "locked": not kc.unlocked(),
527
  #: the vocabulary and the permission, so the client renders a picker it can honour
528
  #: rather than offering an option the server will refuse (R4: business is admin-only).
api/routes_monid.py ADDED
@@ -0,0 +1,300 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """routes_monid.py — the Amazon reviews slice over Monid. W49-T19, ruling R31, contract C5.
2
+
3
+ ⭐⭐ R31, verbatim: *"Monid's one working slice is Amazon reviews for our ASINs, landing as a
4
+ database linkable to Odoo products."*
5
+
6
+ ⛔⛔ MOUNTED FROM `routes_connectors.py`, NEVER FROM `main.py` (C5). This router declares NO
7
+ prefix; the parent owns `/api/v1`. Declaring it on both silently serves `/api/v1/api/v1/monid/...`
8
+ and every call 404s while `tsc`, the build and every source scan stay green — which is the trap
9
+ W49-T16 paid for when it mounted `routes_dependents` the same way.
10
+
11
+ ⚠ FastAPI 0.139.2 leaves `_IncludedRouter` PLACEHOLDERS in `router.routes`, so a walk of
12
+ `[r.path for r in router.routes]` cannot see a child router's assembled path at all. The reliable
13
+ read of what is actually served is `app.openapi()["paths"]`. Do not rediscover this.
14
+
15
+ ⛔⛔ EVERY POST TO `/monid/amazon-reviews/run` SPENDS REAL MONEY. There is no dry run and no
16
+ sandbox key at Monid. The two GETs here are free: `meta` reads constants and one free wallet
17
+ probe, `spend` reads our own ledger. Only the POST debits, only an administrator may call it, and
18
+ it says what it will cost before it is confirmed.
19
+
20
+ ⛔ THE TABLE DOORS ARE CALLED, NOT REIMPLEMENTED (C5). `routes_tables.create_table` and
21
+ `routes_tables.import_rows` are the only way rows land, and `routes_tables.py` belongs to another
22
+ lane — nothing here edits it. They are plain synchronous functions taking a raw dict body and a
23
+ `Session`, so they are called in process; what that costs is that FastAPI's exception machinery
24
+ is not around them, so `HTTPException` is caught here rather than allowed to escape as a 500.
25
+ """
26
+ import sys as _monid_sys
27
+ from pathlib import Path as _MonidPath
28
+
29
+ from fastapi import APIRouter, Body, Depends, HTTPException
30
+
31
+ from deps import Session, err, require_session
32
+
33
+ _PLATFORM = _MonidPath(__file__).resolve().parents[2] / "platform"
34
+ if str(_PLATFORM) not in _monid_sys.path:
35
+ _monid_sys.path.insert(0, str(_PLATFORM))
36
+
37
+ import core.monid as monid # noqa: E402
38
+ import core.user_tables as ut # noqa: E402
39
+
40
+ #: ⛔ NO PREFIX. See the module docstring; the parent owns `/api/v1`.
41
+ router = APIRouter()
42
+
43
+ #: The most ASINs one pull may name. Not a data cap in the sense standing rule 1 forbids: Monid
44
+ #: is a METERED third party and every ASIN is a separate debit, so this bounds a SPEND, not a
45
+ #: read from a connected source. The rule's own test is `records_mutable(key)`, and the records
46
+ #: here are minted by a paid call rather than mirrored from a connector.
47
+ MAX_ASINS = 25
48
+
49
+ #: How long we wait on an asynchronous run before answering "still going". A 202 gives us a run
50
+ #: id; polling forever inside a request would hold a worker for the p95 of 51.5 seconds and then
51
+ #: some, so the ceiling is explicit and the answer names the run id either way.
52
+ POLL_ATTEMPTS = 12
53
+ POLL_SLEEP = 5
54
+
55
+
56
+ def _require_admin(session: Session):
57
+ """⛔ THE PAID DOOR IS ADMIN ONLY, and the check reads `session.admin`.
58
+
59
+ ⚠ NOT `getattr(session, "is_admin", False)` — that attribute does not exist, so the guard
60
+ would read False for everyone and refuse the administrator too. `routes_connectors.py` carries
61
+ the same warning at its own directory route; this is the same trap, one file over.
62
+ """
63
+ if not session.admin:
64
+ raise err(403, "not_admin",
65
+ "Only an administrator can pull Amazon reviews, because the pull spends this "
66
+ "workspace's Monid balance.")
67
+
68
+
69
+ def _monid_http(exc: monid.MonidError):
70
+ """A Monid refusal as our one error shape (X2).
71
+
72
+ ⛔ 402 IS 402 AND ITS SENTENCE IS EXACT (C5). "Monid wallet is empty", authored once in
73
+ `core/monid.py`, printed here, printed by the dialog. Nothing retries it.
74
+ """
75
+ if isinstance(exc, monid.MonidWalletEmpty):
76
+ return err(402, "wallet_empty", monid.WALLET_EMPTY_MESSAGE)
77
+ return err(502, exc.code, exc.message)
78
+
79
+
80
+ @router.get("/monid/amazon-reviews/meta")
81
+ def amazon_reviews_meta(session: Session = Depends(require_session)):
82
+ """What the dialog needs before it can ask for anything, and it costs nothing.
83
+
84
+ ⭐ `canRun` IS THE ADMIN GATE, SERVED RATHER THAN COMPUTED ON THE CLIENT. This directory's
85
+ own rule is that an empty `manage` renders NO control instead of one that would 403, and the
86
+ client has no notion of who is an administrator. So the button exists only when the server
87
+ says the caller may press it.
88
+
89
+ ⚠ THE BALANCE IS A FREE PROBE AND IT IS ALLOWED TO FAIL. A wallet read that times out must
90
+ not stop an operator seeing the price, so `balance` is reported as `null` and the dialog says
91
+ the balance is unknown rather than inventing one.
92
+ """
93
+ bal = None
94
+ if monid.configured():
95
+ try:
96
+ b = monid.balance() or {}
97
+ v = (b.get("balance") or {}) if isinstance(b, dict) else {}
98
+ bal = {"value": v.get("value"), "currency": v.get("currency")}
99
+ except monid.MonidError:
100
+ bal = None
101
+ return {
102
+ "canRun": bool(session.admin),
103
+ "configured": monid.configured(),
104
+ "provider": monid.AMAZON_REVIEWS_PROVIDER,
105
+ "endpoint": monid.AMAZON_REVIEWS_ENDPOINT,
106
+ "priceKind": monid.AMAZON_REVIEWS_PRICE_KIND,
107
+ "unitPrice": monid.AMAZON_REVIEWS_UNIT_PRICE,
108
+ "currency": monid.AMAZON_REVIEWS_CURRENCY,
109
+ "maxAsins": MAX_ASINS,
110
+ "tableKey": monid.TABLE_KEY,
111
+ "tableLabel": monid.TABLE_LABEL,
112
+ "balance": bal,
113
+ # ⭐ WHERE THE ASINs COME FROM, MEASURED RATHER THAN ASSUMED. `fields_get` on
114
+ # `product.template` and `product.product` was read on 2026-09-02: the only Amazon field
115
+ # either model carries is `x_studio_amazon_sku` ("Amazon SKU"), and its 162 populated
116
+ # values are merchant SKUs such as `RI-SHR-09_BLK`, not ten-character ASINs. So Odoo has
117
+ # no ASIN to offer and the operator pastes them. Saying so here keeps the sentence the
118
+ # user reads and the fact behind it in one place.
119
+ "asinSource": "paste",
120
+ "asinNote": "Odoo has no ASIN field. The nearest one, Amazon SKU, holds merchant SKUs "
121
+ "such as RI-SHR-09_BLK, so paste the ASINs you want reviews for.",
122
+ }
123
+
124
+
125
+ @router.get("/monid/spend")
126
+ def monid_spend(session: Session = Depends(require_session)):
127
+ """The ledger C5 names, newest last. Every paid run is in here or it did not happen."""
128
+ _require_admin(session)
129
+ rows = monid.spend_rows(st=session.runtime)
130
+ return {"runs": rows,
131
+ "total": round(sum(float(r.get("cost") or 0) for r in rows), 6),
132
+ "currency": monid.AMAZON_REVIEWS_CURRENCY}
133
+
134
+
135
+ @router.post("/monid/amazon-reviews/run", status_code=201)
136
+ def amazon_reviews_run(body: dict = Body(default=None),
137
+ session: Session = Depends(require_session)):
138
+ """⛔⛔ THE ONE PAID DOOR. One call, one debit, one ledger row.
139
+
140
+ The shape of the work, in the order it has to happen:
141
+
142
+ 1. REFUSE FIRST, SPEND SECOND. Not an administrator, no key, no valid ASIN: every one of
143
+ those is answered before a request reaches Monid, because a refusal after the debit is
144
+ a refusal the wallet already paid for.
145
+ 2. RUN. `run()` answers 200 with the result inline or 202 with a run id, because the
146
+ endpoint's own p95 run time is 51.5 seconds and the sync window is shorter than that.
147
+ A 202 is polled here, up to a stated ceiling, and then reported honestly as pending with
148
+ its run id rather than as a failure.
149
+ 3. LEDGER BEFORE LANDING. `record_spend` is called as soon as the run is accepted. The money
150
+ is gone whether or not the table write succeeds, so a ledger written after the import
151
+ would under-report every run that failed to land.
152
+ 4. LAND. Columns are derived from the RECORDS THAT CAME BACK (`columns_from_rows`), because
153
+ `inspect` returns no output schema; then `create_table` and `import_rows` are CALLED.
154
+ """
155
+ _require_admin(session)
156
+ if not monid.configured():
157
+ raise err(503, "not_configured",
158
+ "Monid is not connected in this workspace. An administrator adds the key "
159
+ "before a pull can run.")
160
+ payload = body if isinstance(body, dict) else {}
161
+ asins, rejected = monid.clean_asins(payload.get("asins"), limit=MAX_ASINS)
162
+ if not asins:
163
+ raise err(400, "no_asins",
164
+ "Enter at least one ASIN. An ASIN is ten characters, letters and digits, and "
165
+ "it is printed on the product page.")
166
+ if rejected:
167
+ raise err(400, "bad_asins",
168
+ "These are not ASINs: " + ", ".join(rejected[:5]) +
169
+ ". An ASIN is ten characters, letters and digits.")
170
+ domain = str(payload.get("domainCode") or "com")
171
+ sort_by = str(payload.get("sortBy") or "recent")
172
+ try:
173
+ max_pages = max(1, min(10, int(payload.get("maxPages") or 1)))
174
+ except (TypeError, ValueError):
175
+ max_pages = 1
176
+
177
+ run_input = monid.amazon_reviews_input(asins, domain, sort_by, max_pages)
178
+ try:
179
+ status, answer = monid.run(monid.AMAZON_REVIEWS_PROVIDER,
180
+ monid.AMAZON_REVIEWS_ENDPOINT, run_input)
181
+ except monid.MonidError as exc:
182
+ raise _monid_http(exc)
183
+
184
+ run_id = ""
185
+ if isinstance(answer, dict):
186
+ run_id = str(answer.get("runId") or answer.get("run_id") or answer.get("id") or "")
187
+
188
+ # ⛔⛔ THE LEDGER RECORDS WHAT WAS CHARGED, NOT WHAT WE GUESSED, and this is a CORRECTION
189
+ # paid for by a live run. The first version wrote `estimate_cost(len(asins))` on the vendor's
190
+ # own pricing note; that note is false, 2 ASINs billed 20 units, and the ledger would have
191
+ # said 0.0027 about a charge of 0.027. A completed run carries an authoritative
192
+ # `cost: {"value", "currency"}` that matched the wallet delta exactly, so it wins.
193
+ #
194
+ # ⚠ THE FLOOR IS STILL WRITTEN WHEN NOTHING IS REPORTED, because the money moved whether or
195
+ # not Monid told us how much. It is stamped `estimated` so nobody reads it as measured.
196
+ cost = monid.payload_cost(answer)
197
+ estimated = cost is None
198
+ if estimated:
199
+ cost = monid.estimate_cost(len(asins))
200
+ # ⛔ WRITTEN HERE, BEFORE THE POLL AND BEFORE THE TABLE. The debit already happened, and a
201
+ # crash between here and the import must not lose the spend.
202
+ monid.record_spend(session.tenant, monid.AMAZON_REVIEWS_PROVIDER,
203
+ monid.AMAZON_REVIEWS_ENDPOINT, cost, run_id,
204
+ st=session.runtime, estimated=estimated)
205
+
206
+ if status == 202:
207
+ import time
208
+ for _ in range(POLL_ATTEMPTS):
209
+ time.sleep(POLL_SLEEP)
210
+ try:
211
+ answer = monid.poll(run_id)
212
+ except monid.MonidError as exc:
213
+ raise _monid_http(exc)
214
+ state = str((answer or {}).get("status") or "").lower() if isinstance(answer, dict) else ""
215
+ if state in ("succeeded", "success", "done", "completed", "finished"):
216
+ break
217
+ if state in ("failed", "error", "cancelled", "canceled"):
218
+ raise err(502, "run_failed",
219
+ "The Monid run finished without a result. The spend is recorded as "
220
+ "run " + (run_id or "with no id") + ".")
221
+ if monid.extract_records(answer):
222
+ break
223
+ else:
224
+ return {"pending": True, "runId": run_id, "cost": cost, "costEstimated": estimated,
225
+ "asins": asins, "records": 0, "tableKey": "",
226
+ "message": "The run is still going at Monid. It is recorded in the spend "
227
+ "ledger as run " + (run_id or "with no id") + "."}
228
+
229
+ # ⭐ THE 202 PATH REPORTS ITS COST ONLY WHEN IT COMPLETES, so the estimated row written above
230
+ # is amended here rather than left as a guess for a run we now have the real figure for.
231
+ if estimated:
232
+ settled = monid.payload_cost(answer)
233
+ if settled is not None and monid.settle_spend(run_id, settled, st=session.runtime):
234
+ cost, estimated = settled, False
235
+
236
+ records = monid.extract_records(answer)
237
+ if not records:
238
+ return {"pending": False, "runId": run_id, "cost": cost,
239
+ "costEstimated": estimated, "asins": asins,
240
+ "records": 0, "tableKey": "",
241
+ "message": "Monid returned no review records for those ASINs. The run is "
242
+ "recorded in the spend ledger."}
243
+
244
+ # ⛔ THE TWO DOORS, IMPORTED WHERE THEY ARE USED. A top-level import would run
245
+ # `routes_tables` while `routes_connectors` is still importing THIS module, and a cycle at
246
+ # boot is an ImportError with a traceback that names neither cause. `routes_tables.py` uses
247
+ # exactly this local-import style itself (`from routes_grid import govern_date_recurrence`,
248
+ # inside `create_table`), so this is the file's own convention rather than a workaround.
249
+ from routes_tables import create_table, import_rows
250
+
251
+ fields = monid.columns_from_rows(records)
252
+ # ⚠ THE DERIVED `type` IS A DISPLAY DECISION, NOT A STORAGE ONE, and that is the existing
253
+ # door's behaviour rather than this ticket's choice: `user_tables.add_rows` writes every cell
254
+ # as `str(v)` and drops any key the table has no column for. So an `int` column holds the
255
+ # string "12345" and sorts as the grid's own column type says, which is what every other
256
+ # imported database in this workspace already does. Recorded here because a reader who expects
257
+ # a typed cell will otherwise think the derivation lost the type.
258
+ rows = monid.rows_for_import(records, fields)
259
+
260
+ existing = ut.all_defs(session.runtime) or {}
261
+ table_key = monid.TABLE_KEY
262
+ created = False
263
+ unmapped = []
264
+ if table_key not in (existing or {}):
265
+ # ⚠ CALLED, NOT REIMPLEMENTED (C5). `create_table` slugifies the label, so
266
+ # "Amazon reviews" mints exactly `ut_amazon_reviews` the first time — and `_2` every time
267
+ # after, which is why this branch is guarded rather than run on every pull.
268
+ try:
269
+ made = create_table({"label": monid.TABLE_LABEL, "fields": fields}, session)
270
+ except HTTPException as exc:
271
+ raise exc
272
+ table_key = (made or {}).get("key") or ""
273
+ created = True
274
+ if not table_key:
275
+ raise err(503, "table_refused",
276
+ "The reviews arrived and the database could not be created. The run is "
277
+ "recorded in the spend ledger.")
278
+ else:
279
+ # ⛔ AN EXISTING TABLE KEEPS ITS COLUMNS. Adding one is a field door that lives in
280
+ # `routes_tables.py`, which belongs to another lane, so a key the first pull never saw is
281
+ # NAMED in the answer rather than dropped in silence.
282
+ have = {str(f.get("key")) for f in (existing[table_key].get("fields") or [])}
283
+ unmapped = sorted({f["key"] for f in fields} - have)
284
+
285
+ try:
286
+ landed = import_rows(table_key, {"rows": rows}, session)
287
+ except HTTPException as exc:
288
+ raise exc
289
+ return {"pending": False,
290
+ "runId": run_id,
291
+ "cost": cost,
292
+ "costEstimated": estimated,
293
+ "asins": asins,
294
+ "records": len(records),
295
+ "imported": int((landed or {}).get("imported") or 0),
296
+ "tableKey": table_key,
297
+ "tableCreated": created,
298
+ "columns": [f["key"] for f in fields],
299
+ "unmappedColumns": unmapped,
300
+ "message": "The reviews landed in " + monid.TABLE_LABEL + "."}
api/routes_query.py CHANGED
@@ -1451,6 +1451,47 @@ def _semantic_authorize(session, database, *, require_answerable=False):
1451
  return status
1452
 
1453
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1454
  @router.get("/query/semantics/{database}")
1455
  def semantic_catalog(database: str, session: Session = Depends(require_session)):
1456
  # Permission is resolved by the same source boundary Query uses. An empty field selection is
@@ -1599,15 +1640,40 @@ def _metric_dtos(offer, catalog):
1599
  return out
1600
 
1601
 
1602
- def _compatible_metric_dtos(session, database):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1603
  from core import perm_scope
1604
  if not perm_scope.may_metrics(session.user, database):
1605
- return []
1606
  from harness import semantic as sem
1607
  topic = sem.topic_for_grid(database)
1608
  if not topic:
1609
- return []
1610
- return _metric_dtos(sem.entity_measures(topic), sem.metrics())
 
 
 
 
 
1611
 
1612
 
1613
  @router.get("/query/metrics")
@@ -1615,9 +1681,22 @@ def query_metrics(database: str = "", session: Session = Depends(require_session
1615
  database = str(database or "").strip()
1616
  if not database:
1617
  raise err(400, "bad_request", "a database is required")
1618
- _semantic_authorize(session, database)
1619
- _semantic_records(session, database) # The same governed semantic source wall as Query.
1620
- return {"metrics": _compatible_metric_dtos(session, database)}
 
 
 
 
 
 
 
 
 
 
 
 
 
1621
 
1622
 
1623
  def _tool_spec(body, requested):
 
1451
  return status
1452
 
1453
 
1454
+ def _semantic_authorize_schema_only(session, database):
1455
+ """The RECORD wall, widened for a door that reads no record. W49-T22 / D-276.
1456
+
1457
+ ⛔⛔ THIS IS A SEPARATE FUNCTION ON PURPOSE, AND IT MUST STAY ONE. `_semantic_authorize` is
1458
+ the wall every record-reading door keeps and nothing here may soften it: `_semantic_records`,
1459
+ `profile_semantic_field`, `query_tool` and every `require_answerable=True` caller go on
1460
+ calling that one. Naming this path separately is what stops a later reader from taking the
1461
+ widening for the record boundary.
1462
+
1463
+ ⭐ WHAT IT WIDENS, AND WHY THAT IS HONEST. MEASURED on tenant #0: an ADMIN asking
1464
+ `GET /query/metrics?database=product_data` got 403 `assistant_forbidden` for a database the
1465
+ same account opens from the nav. The cause is D-276 and is still open —
1466
+ `deps.assistant_source_status` sets `permitted=False` when `perm_scope.assistant_entry` finds
1467
+ no `entry()` dict, even for a caller whose `may_access` is True. That branch already
1468
+ computes the honest second fact beside it, `visible`, described in its own comment as true
1469
+ "only when the ordinary product wall already lets them open it, i.e. when the silence was
1470
+ incoherent rather than protective".
1471
+
1472
+ ⛔ SO `permitted` IS NOT TOUCHED. Widening it would resurrect stored artefacts the read
1473
+ boundary refuses. This door returns metric NAMES and nothing else — it discloses the shape of
1474
+ a database the caller can already open, never a value from inside it, which is the rule
1475
+ `semantic_catalog` states for itself ("An empty field selection is a schema-only authorization
1476
+ check and never widens to records"). It admits exactly the incoherent case and nothing else:
1477
+ a caller with neither `permitted` nor `visible` still gets the same 403.
1478
+
1479
+ ⚠ EXACTLY ONE DOOR CALLS THIS, AND THAT IS DELIBERATE, NOT AN OVERSIGHT. `GET /query/metrics`
1480
+ is the surface W49-T22's contract (C7) names, and it is the whole of this function's warrant.
1481
+ `GET /query/semantics/{database}` is schema-only by the same argument and keeps the STRICT
1482
+ wall, so the same admin can get 200 from the catalogue and 403 from the field contract on one
1483
+ database. That asymmetry is real and is booked as a follow-up rather than closed here: the
1484
+ field contract carries per-field `purpose`, `synonyms` and `sensitivity`, which is a wider
1485
+ disclosure than a list of metric names, and widening it needs its own ruling. ⛔ Do not
1486
+ "finish the job" by adding call sites without one.
1487
+ """
1488
+ status = assistant_source_status(session, [database]).get(database) or {}
1489
+ if not (status.get("permitted") or status.get("visible")):
1490
+ raise err(403, "assistant_forbidden",
1491
+ "your current permissions do not allow this database")
1492
+ return status
1493
+
1494
+
1495
  @router.get("/query/semantics/{database}")
1496
  def semantic_catalog(database: str, session: Session = Depends(require_session)):
1497
  # Permission is resolved by the same source boundary Query uses. An empty field selection is
 
1640
  return out
1641
 
1642
 
1643
+ #: ⭐⭐ W49-T22 / CONTRACT C7 — THE THREE CAUSES AN EMPTY CATALOGUE CAN HAVE, and they are a
1644
+ #: CLOSED SET so the picker never has to guess which sentence is true. Declared here, next to the
1645
+ #: only code that can distinguish them, rather than in the client: the browser can see that the
1646
+ #: list is empty and cannot see WHY.
1647
+ #:
1648
+ #: ⛔ A FOURTH CAUSE EXISTS AND IS DELIBERATELY NOT IN THIS SET. The panel also falls idle when
1649
+ #: the row set is empty (`!pids.length`), which is neither of these three; stretching one of these
1650
+ #: sentences over it would print a false statement on a database that has a topic and a filled
1651
+ #: catalogue. It is reported as a contract gap instead.
1652
+ METRIC_CATALOGUE_REASONS = ("no_metrics", "refused", "no_topic")
1653
+
1654
+
1655
+ def _metric_catalogue(session, database):
1656
+ """`(metrics, reason)` for one database. `reason` is "" when something was offered.
1657
+
1658
+ ⛔ THE REASON IS COMPUTED WHERE THE REFUSAL HAPPENS. Each branch below is the ONLY place its
1659
+ cause is knowable: the metrics capability lives in `perm_scope`, the topic binding lives in
1660
+ `semantic.topic_for_grid`, and an empty offer is `entity_measures` refusing every declared
1661
+ key for its own stated reasons (`entity_measure_refusals` carries those). A client that saw
1662
+ only `[]` would have to invent one of the three, and two of the three would be a lie.
1663
+ """
1664
  from core import perm_scope
1665
  if not perm_scope.may_metrics(session.user, database):
1666
+ return [], "refused"
1667
  from harness import semantic as sem
1668
  topic = sem.topic_for_grid(database)
1669
  if not topic:
1670
+ return [], "no_topic"
1671
+ metrics = _metric_dtos(sem.entity_measures(topic), sem.metrics())
1672
+ return metrics, ("" if metrics else "no_metrics")
1673
+
1674
+
1675
+ def _compatible_metric_dtos(session, database):
1676
+ return _metric_catalogue(session, database)[0]
1677
 
1678
 
1679
  @router.get("/query/metrics")
 
1681
  database = str(database or "").strip()
1682
  if not database:
1683
  raise err(400, "bad_request", "a database is required")
1684
+ # ⭐ SCHEMA-ONLY. This door returns metric NAMES and never a value, so it takes the widened
1685
+ # wall (see `_semantic_authorize_schema_only` for exactly what that widens and what it does
1686
+ # not). Before W49-T22 an admin asking about `product_data` got 403 here for a database the
1687
+ # same account opens from the nav.
1688
+ _semantic_authorize_schema_only(session, database)
1689
+ metrics, reason = _metric_catalogue(session, database)
1690
+ # ⛔⛔ THE GOVERNED SOURCE WALL STAYS, BUT IT CANNOT BE THE FIRST THING ASKED.
1691
+ # `_semantic_records` resolves `_semantic_baseline`, which raises 404 `semantic_source_unknown`
1692
+ # for a database no topic declares — and `ut_odoo_order_lines` / `ut_odoo_gl_lines` are exactly
1693
+ # that: read-through grains with no entity topic. A 404 carries no body the picker can read,
1694
+ # so the reader was told nothing at all where C7 promises a sentence. The wall is therefore
1695
+ # asked only once a topic is known to exist, which is the only case where it has a contract to
1696
+ # enforce; a topic-less database answers 200 with `reason: no_topic`, and that IS its answer.
1697
+ if reason != "no_topic":
1698
+ _semantic_records(session, database)
1699
+ return {"metrics": metrics, "reason": reason}
1700
 
1701
 
1702
  def _tool_spec(body, requested):
api/routes_shares.py CHANGED
@@ -891,17 +891,31 @@ def get_share(kind: str, oid: str, session: Session = Depends(require_session)):
891
 
892
  def _people(tenant):
893
  """[{username, name}] for this tenant — same population as `assignable_people`, with the
894
- BINDING identity alongside the display one."""
 
 
 
 
 
 
 
 
 
 
 
 
895
  try:
896
  reg = users.registry() or {}
897
  except Exception:
898
  return []
899
  want = str(tenant or '').strip().lower()
 
 
900
  out = []
901
  for uname, u in reg.items():
902
  if not isinstance(u, dict) or u.get('active') is False:
903
  continue
904
- if want and str(u.get('tenant') or 'royal-imports').strip().lower() != want:
905
  continue
906
  out.append({"username": str(uname), "name": str(u.get('name') or uname)})
907
  return sorted(out, key=lambda p: p["name"].lower())
 
891
 
892
  def _people(tenant):
893
  """[{username, name}] for this tenant — same population as `assignable_people`, with the
894
+ BINDING identity alongside the display one.
895
+
896
+ ⛔⛔ W49-T23 / D-235 — A BLANK TENANT RETURNS NOBODY, NOT EVERYBODY. This read
897
+ `if want and str(u.get('tenant') …) != want`, so a blank or `None` slug skipped the filter
898
+ entirely and handed one workspace every tenant's roster: the exact `if want and …` fail-OPEN
899
+ that W33-T37 closed in `core.users.assignable_people` / `avatar_map` one layer down, left
900
+ behind in the copy that lives here. The three callers all pass `session.tenant`, which is
901
+ `claims["t"]` and is already proven non-blank by `require_session` (an unresolvable slug is a
902
+ 401 before any route runs), so this changes no answer any live caller gets today — it removes
903
+ the shape, before a fourth caller arrives that does not carry that proof. Fail-closed, because
904
+ from this function a blank slug and "every tenant at once" are the same observation, and one
905
+ of the two callers below turns this roster into who may be GRANTED access.
906
+ """
907
  try:
908
  reg = users.registry() or {}
909
  except Exception:
910
  return []
911
  want = str(tenant or '').strip().lower()
912
+ if not want:
913
+ return []
914
  out = []
915
  for uname, u in reg.items():
916
  if not isinstance(u, dict) or u.get('active') is False:
917
  continue
918
+ if str(u.get('tenant') or 'royal-imports').strip().lower() != want:
919
  continue
920
  out.append({"username": str(uname), "name": str(u.get('name') or uname)})
921
  return sorted(out, key=lambda p: p["name"].lower())
api/routes_sheet.py ADDED
@@ -0,0 +1,502 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """routes_sheet.py — the Sheet workbook doors (wave 49, instruction 1, ticket W49-T02).
2
+
3
+ WHAT GOES HERE:
4
+
5
+ Contract C1's routes over `platform/core/sheets.py`: list, create, read, replace, plus the three
6
+ doors that RESOLVE something and are therefore built by later tickets in this lane.
7
+
8
+ ⭐ **THE WALL HERE IS THE ORDINARY SESSION, AND THAT IS THE WHOLE POINT OF THE SPLIT.** Any signed
9
+ in user may own a workbook, so a workbook needs no per-database permission. A CELL is different: it
10
+ names a database, and W49-T04 puts the per-database wall on the doors that read one, per contract
11
+ C2 and ruling R16.
12
+
13
+ ⛔⛔ **WHEN THAT WALL ARRIVES IT IS `routes_charts.py::_require_database`, COPIED, NEVER
14
+ `deps.Session.require`.** `Session.require` calls `nav_may_open(user, key)` with no `st=` argument,
15
+ so the `ut_*` leg of that predicate resolves against the PROCESS-DEFAULT tenant store instead of
16
+ this session's runtime. Measured on the running app, same user and same table: 403 with the process
17
+ default pointing elsewhere, 200 once it happened to match. D-612 is open at HEAD and lane C repairs
18
+ it; this file must not inherit it in the meantime.
19
+
20
+ ⛔ **THIS FILE IS MOUNTED BEFORE IT SERVES ITS FULL SURFACE, ON PURPOSE.** See the identical note in
21
+ `routes_charts.py` and `routes_notes.py`: five consecutive waves lost the `include_router` line, and
22
+ in a worktree-parallel wave that is structural rather than careless, because `main.py` lives in
23
+ exactly one lane's fence. The mount lands with the first ticket so no later ticket can reach BUILT
24
+ while its surface is a 404.
25
+
26
+ ⚠ Every message in this file reaches a screen, so none carries an em dash or an en dash
27
+ (standing rule 2), and each names both the cause and the subject.
28
+ """
29
+
30
+ from fastapi import APIRouter, Body, Depends, HTTPException
31
+
32
+ from deps import Session, err, require_session
33
+
34
+ router = APIRouter(prefix="/api/v1")
35
+
36
+ #: What a door answers while the ticket that resolves it is still open. It is a REFUSAL with a
37
+ #: named code, not an empty success: a stub that answered `{"value": null}` would be indexed,
38
+ #: charted and believed, and nothing downstream could tell it from a real answer.
39
+ _NOT_YET = "sheet_resolution_not_built"
40
+
41
+
42
+ def _require_database(session: Session, database) -> str:
43
+ """THE per-database wall, COPIED from `routes_charts.py::_require_database` (contract C2).
44
+
45
+ ⛔⛔ IT IS COPIED RATHER THAN `deps.Session.require`, AND THAT IS THE WHOLE POINT.
46
+ `Session.require` calls `nav_may_open(user, key)` with NO `st=` argument, so the `ut_*` leg of
47
+ that predicate resolves the table against the PROCESS-DEFAULT tenant store instead of THIS
48
+ session's runtime. Measured on the running app, same user and same table: 403 with the process
49
+ default pointing elsewhere, 200 once it happened to match. D-612 is open at HEAD and lane C
50
+ repairs it; until then every new door that passes a `ut_*` key must thread `st=session.runtime`
51
+ itself or inherit the bug.
52
+
53
+ ⚠ It runs the SAME two legs as the nav rail, so it can only ever agree with what the caller is
54
+ already offered. It widens nothing.
55
+ """
56
+ key = str(database or "").strip()
57
+ if not key:
58
+ raise err(400, "sheet_database_required", "That cell does not name a database.")
59
+ import core.perm_scope as perm_scope
60
+ if not perm_scope.nav_may_open(session.user, key, st=session.runtime):
61
+ raise err(403, "database_unreadable", f"You cannot read {key}.")
62
+ tcfg = getattr(session.runtime.tenant, "config", None) or {}
63
+ tmods = tcfg.get("modules", "all")
64
+ if tmods != "all" and key not in {str(k) for k in (tmods or [])}:
65
+ raise err(403, "database_unreadable", f"This workspace does not include {key}.")
66
+ return key
67
+
68
+
69
+ def _mirror(session: Session):
70
+ """`(cursor, spec, columns)` for one read-through database, or the refusal that names why.
71
+
72
+ ⛔ THE TWO MIRROR FAILURES MEAN OPPOSITE ACTIONS AND ARE KEPT APART HERE, exactly as the rows
73
+ door keeps them apart. `DatastoreMismatch` means this process has ANOTHER TENANT'S FILE open;
74
+ it never becomes un-mis-pinned by waiting, so it is a 409 and never a retry. A plain
75
+ `RuntimeError` means the mirror is completing its first sync, so it is a 503 the caller may
76
+ retry. `DatastoreMismatch` SUBCLASSES `RuntimeError`, so the guard must run ABOVE the try, and
77
+ collapsing them would turn the loudest refusal in the system into a spinner.
78
+ """
79
+ import routes_odoo_tables as rot
80
+ import odoo_relational as rel
81
+
82
+ def _for(table_key):
83
+ fields = None
84
+ for _bucket, key, _label, mk_fields in rel.TABLES:
85
+ if key == table_key:
86
+ fields = mk_fields()
87
+ break
88
+ if fields is None:
89
+ raise err(404, "not_connected", f"{table_key} is not a connected Odoo database.")
90
+ try:
91
+ cur, mismatch = rot._mirror_cur(session)
92
+ except RuntimeError as exc:
93
+ raise err(503, "store_not_ready", str(exc))
94
+ if mismatch:
95
+ raise err(409, "cross_tenant_store", mismatch)
96
+ spec = rot._source_for(cur, table_key)
97
+ if spec is None:
98
+ raise err(409, "not_read_through",
99
+ f"{table_key} is still served from its stored copy, so a cell cannot read "
100
+ "through to it on this deployment yet.")
101
+ return cur, spec, rot._filter_columns(spec, fields)
102
+
103
+ return _for
104
+
105
+
106
+ def _view_filter(session: Session, database: str, view_id: str, view_name: str = ""):
107
+ """`(nodes, conj)` for a saved view's filter, or a `view_missing` refusal that NAMES it.
108
+
109
+ ⛔⛔ `prefer_owner=session.uname` IS LOAD-BEARING AND OMITTING IT IS A SILENT CROSS-USER READ.
110
+ The system view id `all-customers` is pinned on every database, and every user who has ever
111
+ touched that view's config holds their OWN record under the same id, so a bare first-hit scan
112
+ answers whichever stratum the dict happens to yield first. Measured in the wave-48 go-live QA
113
+ (W48C-T02): starring `All products` wrote onto a COLLEAGUE's overlay record while the caller's
114
+ own rail never changed, with a 200 and nothing red. A bound cell that inherits that bug
115
+ computes somebody else's number and reports it as this person's.
116
+
117
+ ⚠ The refusal names the view, which is why `clean_binding` keeps `view_name` on the binding:
118
+ once the record is deleted there is nothing left to look a name up from.
119
+ """
120
+ from core import table_store
121
+ # ⚠ `TableStore(table_key, st=...)`, in that order. `st` is the STORE HANDLE, and passing the
122
+ # session's runtime is what makes the lookup read THIS tenant's bucket rather than tenant #0's.
123
+ store = table_store.TableStore(database, st=session.runtime)
124
+ found = store.find_view(view_id, prefer_owner=session.uname)
125
+ if not found:
126
+ raise err(409, "view_missing", f"View {view_name or view_id} no longer exists.")
127
+ _owner, view = found
128
+ import routes_odoo_tables as rot
129
+ return rot._fe().tree_parts((view or {}).get("filters"))
130
+
131
+
132
+ def _refuse(exc):
133
+ """Turn a `SheetRefusal` into the HTTP answer that names it."""
134
+ status = 404 if exc.code == "workbook_missing" else 409 if exc.code.endswith("_stale") else 400
135
+ return err(status, exc.code, exc.message)
136
+
137
+
138
+ def _store(session: Session):
139
+ return session.runtime
140
+
141
+
142
+ @router.get("/sheets")
143
+ def list_sheets(session: Session = Depends(require_session)):
144
+ """The workbook list, identity only. Cells never ride this door."""
145
+ from core import sheets
146
+ return {"workbooks": sheets.list_workbooks(_store(session))}
147
+
148
+
149
+ @router.post("/sheets", status_code=201)
150
+ def create_sheet(body: dict = Body(default=None), session: Session = Depends(require_session)):
151
+ """Create a workbook with exactly one tab (R7)."""
152
+ from core import sheets
153
+ raw = dict(body or {})
154
+ try:
155
+ book = sheets.create_workbook(_store(session),
156
+ name=raw.get("name") or "",
157
+ created_by=session.uname)
158
+ except sheets.SheetRefusal as exc:
159
+ raise _refuse(exc)
160
+ return {"workbook": book}
161
+
162
+
163
+ @router.get("/sheets/{workbook_id}")
164
+ def read_sheet(workbook_id: str, session: Session = Depends(require_session)):
165
+ from core import sheets
166
+ try:
167
+ return {"workbook": sheets.get_workbook(_store(session), workbook_id)}
168
+ except sheets.SheetRefusal as exc:
169
+ raise _refuse(exc)
170
+
171
+
172
+ @router.put("/sheets/{workbook_id}")
173
+ def write_sheet(workbook_id: str, body: dict = Body(default=None),
174
+ session: Session = Depends(require_session)):
175
+ """Persist name and sheets in the C1 cell shape, bumping `rev`.
176
+
177
+ ⚠ `rev` in the body makes the write CONDITIONAL. Omit it and the last writer wins; send the
178
+ `rev` you read and a concurrent change answers `workbook_revision_stale` instead of being
179
+ silently overwritten.
180
+ """
181
+ from core import sheets
182
+ raw = dict(body or {})
183
+ try:
184
+ # `rev` inside the body IS the expectation; `core.sheets.put_workbook` reads it. This door
185
+ # does not translate it into a second argument, because two ways to say the same thing is
186
+ # how one of them ends up ignored.
187
+ book = sheets.put_workbook(_store(session), workbook_id, raw)
188
+ except sheets.SheetRefusal as exc:
189
+ raise _refuse(exc)
190
+ return {"workbook": book}
191
+
192
+
193
+ @router.delete("/sheets/{workbook_id}")
194
+ def drop_sheet(workbook_id: str, session: Session = Depends(require_session)):
195
+ from core import sheets
196
+ try:
197
+ removed = sheets.delete_workbook(_store(session), workbook_id)
198
+ except sheets.SheetRefusal as exc:
199
+ raise _refuse(exc)
200
+ return {"deleted": bool(removed)}
201
+
202
+
203
+ # ── the doors that RESOLVE, and are therefore later tickets ──────────────────────────────────
204
+ #
205
+ # ⭐ Each is declared here so the surface exists and `main.py` needs no second edit, and each
206
+ # REFUSES with a named code until its ticket lands. W49-T04 replaces `preview`, `refresh` and
207
+ # `drill` with real resolution through the mirror seam; W49-T03 supplies formula evaluation.
208
+
209
+
210
+ @router.post("/sheets/{workbook_id}/refresh")
211
+ def refresh_sheet(workbook_id: str, session: Session = Depends(require_session)):
212
+ """R10: recompute every bound cell, then every formula, and restamp `refreshed_at`.
213
+
214
+ ⭐ THE WALL RUNS PER DISTINCT DATABASE, ON OPEN, NOT ONLY PER CELL (R16). A workbook that binds
215
+ forty cells to one database asks once; a reader who has lost access to that database gets a
216
+ refusal on every one of its cells rather than a stale number quietly repainting.
217
+
218
+ ⚠ Each distinct `view_id` is resolved ONCE. `table_store.find_view` runs a legacy migration on
219
+ every call, so resolving per cell would make a forty-cell refresh do forty migrations.
220
+ """
221
+ from core import sheets
222
+ from modules import sheet as sheet_mod
223
+ import formula_runtime as fr
224
+
225
+ try:
226
+ book = sheets.get_workbook(_store(session), workbook_id)
227
+ except sheets.SheetRefusal as exc:
228
+ raise _refuse(exc)
229
+
230
+ stamp = _now_iso()
231
+ seen_db = {}
232
+ for tab in book.get("sheets") or ():
233
+ for addr, cell in (tab.get("cells") or {}).items():
234
+ if not isinstance(cell, dict) or cell.get("kind") != "bound":
235
+ continue
236
+ binding = cell.get("binding") or {}
237
+ db = str(binding.get("database") or "")
238
+ if db not in seen_db:
239
+ try:
240
+ _require_database(session, db)
241
+ seen_db[db] = None
242
+ except Exception as exc: # noqa: BLE001
243
+ seen_db[db] = exc
244
+ failure = seen_db.get(db)
245
+ if failure is not None:
246
+ cell["state"] = "refused"
247
+ cell["value"] = None
248
+ cell["refusal"] = {"code": "database_unreadable",
249
+ "message": f"You cannot read {db}."}
250
+ continue
251
+ try:
252
+ out = _resolve_binding(session, binding)
253
+ except HTTPException as exc:
254
+ detail = getattr(exc, "detail", None) or {}
255
+ info = detail.get("error") if isinstance(detail, dict) else None
256
+ cell["state"] = "refused"
257
+ cell["value"] = None
258
+ cell["refusal"] = {
259
+ "code": (info or {}).get("code", "sheet_unresolved"),
260
+ "message": (info or {}).get("message", "This cell could not be refreshed."),
261
+ }
262
+ continue
263
+ cell["state"] = "fresh"
264
+ cell["value"] = out["value"]
265
+ cell["display"] = "" if out["value"] is None else str(out["value"])
266
+ cell["refreshed_at"] = stamp
267
+ cell.pop("refusal", None)
268
+ if out["limits"]:
269
+ cell["limits"] = out["limits"]
270
+ else:
271
+ cell.pop("limits", None)
272
+
273
+ _recompute_formulas(book, fr, sheet_mod)
274
+ try:
275
+ saved = sheets.put_workbook(_store(session), workbook_id,
276
+ {"name": book.get("name"), "sheets": book.get("sheets"),
277
+ "refreshed_at": stamp, "rev": book.get("rev")})
278
+ except sheets.SheetRefusal as exc:
279
+ raise _refuse(exc)
280
+ return {"workbook": saved}
281
+
282
+
283
+ def _now_iso():
284
+ from datetime import datetime, timezone
285
+ return datetime.now(timezone.utc).replace(microsecond=0).isoformat()
286
+
287
+
288
+ def _recompute_formulas(book, fr, sheet_mod):
289
+ """Re-evaluate every formula cell across the workbook, per tab, in dependency order.
290
+
291
+ ⛔ A REFUSED INPUT PROPAGATES; IT DOES NOT BECOME ZERO (C2, and W49-T09 hardens it further).
292
+ A cell whose value is None because the database refused is handed to the engine as absent, so
293
+ arithmetic over it stays None rather than silently counting it as nothing.
294
+ """
295
+ for tab in book.get("sheets") or ():
296
+ cells = tab.get("cells") or {}
297
+ spec = {}
298
+ for addr, cell in cells.items():
299
+ if not isinstance(cell, dict):
300
+ continue
301
+ if cell.get("kind") == "formula" and cell.get("formula"):
302
+ spec[addr] = {"formula": cell["formula"]}
303
+ elif cell.get("state") == "refused":
304
+ # ⛔⛔ CARRIED AS A REFUSAL, NOT DROPPED (W49-T09, C2). Leaving a refused cell OUT
305
+ # of the inputs is the defect, not the safe option: MEASURED, `=SUM(B4:B8)` with B4
306
+ # merely absent answers **3.0 with no error**, while the same range with B4 REFUSED
307
+ # answers None and names the cause. Dropping it turns a refusal into a smaller
308
+ # total that looks entirely reasonable.
309
+ spec[addr] = {"refused": (cell.get("refusal") or {}).get("code") or "refused"}
310
+ else:
311
+ spec[addr] = {"value": cell.get("value")}
312
+ if not any("formula" in v for v in spec.values()):
313
+ continue
314
+ out = fr.evaluate_sheet(spec)
315
+ for addr, cell in cells.items():
316
+ if not isinstance(cell, dict) or cell.get("kind") != "formula":
317
+ continue
318
+ code = (out.get("errors") or {}).get(addr)
319
+ if code:
320
+ cell["state"] = "refused"
321
+ cell["value"] = None
322
+ cell["refusal"] = {"code": code, "message": _formula_message(code)}
323
+ else:
324
+ cell["state"] = "fresh"
325
+ cell["value"] = (out.get("values") or {}).get(addr)
326
+ cell["display"] = "" if cell["value"] is None else str(cell["value"])
327
+ cell.pop("refusal", None)
328
+
329
+
330
+ def _formula_message(code, subject=""):
331
+ """The sentence a refused formula wears.
332
+
333
+ ⭐ AN INHERITED REFUSAL KEEPS ITS OWN WORDS (C2, R16). When a formula inherits
334
+ `database_unreadable` from an input, the reader is told the CAUSE - a database they cannot read
335
+ - rather than a generic "this could not be calculated", which would send them looking at the
336
+ formula instead of at their access. So C2's vocabulary is answered here by the same sentences
337
+ `modules/sheet.py::REFUSALS` uses, and only the formula-specific codes get their own.
338
+ """
339
+ from modules.sheet import REFUSALS
340
+ if code in REFUSALS:
341
+ return REFUSALS[code].format(subject=subject or "that database")
342
+ return {
343
+ "circular_reference": "This formula refers back to itself, so it has no value.",
344
+ "bad_formula": "This formula could not be read.",
345
+ "unknown_ref": "This formula points at a cell that is not filled in.",
346
+ "div_zero": "This formula divides by zero.",
347
+ }.get(code, "This formula could not be calculated.")
348
+
349
+
350
+ def _resolve_binding(session: Session, raw_binding, *, today=None):
351
+ """Evaluate ONE C2 binding and return `{value, limits, sql_columns}`.
352
+
353
+ The order below is the contract, not a preference:
354
+ 1. the per-database wall, per DISTINCT database, on every read (R16);
355
+ 2. the mirror cursor, whose two failures mean opposite things;
356
+ 3. the ROW wall, fail-closed, refusing 409 when it names a column the mirror cannot answer;
357
+ 4. the binding's own scope, whose unanswerable columns are REPORTED rather than dropped.
358
+ """
359
+ from modules import sheet as sheet_mod
360
+ import core.perm_scope as perm_scope
361
+
362
+ try:
363
+ binding = sheet_mod.clean_binding(raw_binding)
364
+ except sheet_mod.SheetRefusal as exc:
365
+ raise err(400, exc.code, exc.message)
366
+
367
+ database = _require_database(session, binding["database"])
368
+ cur, spec, cols = _mirror(session)(database)
369
+
370
+ # ── the ROW wall, fail-closed ────────────────────────────────────────────────────────────
371
+ wall_tree = ((perm_scope.entry(session.user, database) or {}).get("filter")
372
+ if perm_scope.row_scope_applies(session.user, database) else None)
373
+ wall_nodes, wall_conj = _fe_parts(wall_tree)
374
+ if wall_nodes:
375
+ unknown = sorted(sheet_mod.filter_columns_named(wall_nodes) - set(cols))
376
+ if unknown:
377
+ # ⛔ 409, NOT a silently unapplied wall. A restriction that cannot be compiled here
378
+ # must stop the read; serving the number without it would hand a scoped reader the
379
+ # whole database and look exactly like success.
380
+ raise err(409, "scope_not_applicable",
381
+ "an administrator restricted your view of this database using "
382
+ + ", ".join(unknown)
383
+ + ", and that column cannot be read on this database's live connection, so "
384
+ "the restriction cannot be applied here. Ask an administrator to restrict "
385
+ "you on a column this database carries")
386
+
387
+ # ── the binding's own scope ──────────────────────────────────────────────────────────────
388
+ scope = binding["scope"]
389
+ if scope.get("view_id"):
390
+ scope_nodes, scope_conj = _view_filter(session, database, scope["view_id"],
391
+ scope.get("view_name", ""))
392
+ else:
393
+ scope_nodes, scope_conj = _fe_parts(scope.get("filter"))
394
+
395
+ # ⚠ NOTHING IS DONE HERE ABOUT `needs_excluded`. `_source_for` has already resolved it into the
396
+ # spec's column expressions; applying it a second time would double-count the exclusion and
397
+ # break every joined spec, whose partner column is `sol.order_partner_id` or `aml.partner_id`.
398
+ try:
399
+ sql, params, limits = sheet_mod.build_aggregate_query(
400
+ spec, binding, cols, scope_nodes=scope_nodes, scope_conj=scope_conj,
401
+ wall_nodes=wall_nodes, wall_conj=wall_conj, today=today)
402
+ except sheet_mod.SheetRefusal as exc:
403
+ raise err(400, exc.code, exc.message)
404
+
405
+ row = cur.execute(sql, params).fetchone()
406
+ value = row[0] if row else None
407
+ return {"value": value, "limits": limits, "database": database, "binding": binding}
408
+
409
+
410
+ def _fe_parts(tree):
411
+ """`(nodes, conj)` for a stored `{conj, nodes}` filter, through the ONE reader of that shape."""
412
+ from modules import sheet as sheet_mod
413
+ return sheet_mod.stored_tree_parts(tree)
414
+
415
+
416
+ @router.post("/sheets/{workbook_id}/cells/{addr}/preview")
417
+ def preview_cell(workbook_id: str, addr: str, body: dict = Body(default=None),
418
+ session: Session = Depends(require_session)):
419
+ """Evaluate a C2 binding WITHOUT saving it (contract C1).
420
+
421
+ ⭐ It takes the binding from the BODY rather than from the stored cell, which is what lets the
422
+ binding editor show a number before anyone commits to it, and what lets this door be exercised
423
+ on a tenant whose store is read-only.
424
+ """
425
+ raw = dict(body or {})
426
+ out = _resolve_binding(session, raw.get("binding"))
427
+ return {"value": out["value"], "display": "" if out["value"] is None else str(out["value"]),
428
+ "limits": out["limits"]}
429
+
430
+
431
+ @router.get("/sheets/{workbook_id}/cells/{addr}/drill")
432
+ def drill_cell(workbook_id: str, addr: str, session: Session = Depends(require_session)):
433
+ """`{database, view_id?, filter?, record_ids, count}` for `LinkGridModal` (R6, R13, R17).
434
+
435
+ ⛔ A FORMULA CELL REFUSES BY NAME AND DOES NOT DRILL TO ONE OPERAND (R17). Picking an input
436
+ would be a guess presented as an answer: `=B4-B8` has two, and neither is what the person
437
+ clicked on.
438
+
439
+ ⭐ THE IDS ARE READ LIVE, NOT TAKEN FROM THE CELL (R13). A stale cell opens the same popup with
440
+ no comparison text, and the count beside those ids is the LIVE count, because `LinkGridModal`
441
+ prints the length of what it is handed and runs no query of its own.
442
+ """
443
+ from core import sheets
444
+ from modules import sheet as sheet_mod
445
+ import core.perm_scope as perm_scope
446
+
447
+ try:
448
+ book = sheets.get_workbook(_store(session), workbook_id)
449
+ except sheets.SheetRefusal as exc:
450
+ raise _refuse(exc)
451
+
452
+ key = str(addr or "").replace("$", "").upper()
453
+ cell = None
454
+ for tab in book.get("sheets") or ():
455
+ if key in (tab.get("cells") or {}):
456
+ cell = tab["cells"][key]
457
+ break
458
+ if not isinstance(cell, dict):
459
+ raise err(404, "cell_missing", f"Cell {key} is not filled in.")
460
+ if cell.get("kind") == "formula":
461
+ raise err(409, "formula_no_drill",
462
+ "A formula cell cannot drill; view one of its inputs.")
463
+ if cell.get("kind") != "bound":
464
+ raise err(409, "literal_no_drill",
465
+ "A hand typed value has no rows behind it.")
466
+
467
+ try:
468
+ binding = sheet_mod.clean_binding(cell.get("binding"))
469
+ except sheet_mod.SheetRefusal as exc:
470
+ raise err(400, exc.code, exc.message)
471
+
472
+ database = _require_database(session, binding["database"])
473
+ cur, spec, cols = _mirror(session)(database)
474
+
475
+ wall_tree = ((perm_scope.entry(session.user, database) or {}).get("filter")
476
+ if perm_scope.row_scope_applies(session.user, database) else None)
477
+ wall_nodes, wall_conj = _fe_parts(wall_tree)
478
+
479
+ scope = binding["scope"]
480
+ if scope.get("view_id"):
481
+ scope_nodes, scope_conj = _view_filter(session, database, scope["view_id"],
482
+ scope.get("view_name", ""))
483
+ else:
484
+ scope_nodes, scope_conj = _fe_parts(scope.get("filter"))
485
+
486
+ count_sql, count_params, limits = sheet_mod.build_aggregate_query(
487
+ spec, {"aggregate": {"fn": "count"}}, cols, scope_nodes=scope_nodes,
488
+ scope_conj=scope_conj, wall_nodes=wall_nodes, wall_conj=wall_conj)
489
+ total = (cur.execute(count_sql, count_params).fetchone() or [0])[0]
490
+
491
+ ids_sql, ids_params, _ = sheet_mod.build_ids_query(
492
+ spec, cols, scope_nodes=scope_nodes, scope_conj=scope_conj,
493
+ wall_nodes=wall_nodes, wall_conj=wall_conj)
494
+ record_ids = [int(r[0]) for r in cur.execute(ids_sql, ids_params).fetchall() if r and r[0]]
495
+
496
+ out = {"database": database, "record_ids": record_ids, "count": int(total or 0),
497
+ "limits": limits}
498
+ if scope.get("view_id"):
499
+ out["view_id"] = scope["view_id"]
500
+ else:
501
+ out["filter"] = scope.get("filter")
502
+ return out
platform/aios_grid_fields.json CHANGED
@@ -18,7 +18,7 @@
18
  "source": "odoo",
19
  "derived": true,
20
  "default": false,
21
- "description": "The Odoo res.partner id — the key every Odoo document joins on. DERIVED: this row's pid IS the partner id, so a stored copy would be a second source."
22
  },
23
  {
24
  "key": "odoo_status",
@@ -59,7 +59,7 @@
59
  "type": "select",
60
  "source": "odoo",
61
  "default": false,
62
- "description": "Who keyed in most of this customer's orders — not the Agent, who owns the account."
63
  },
64
  {
65
  "key": "street",
@@ -148,7 +148,7 @@
148
  "type": "select",
149
  "source": "odoo",
150
  "default": false,
151
- "description": "Payment terms on this customer's account — Net 30, for example."
152
  },
153
  {
154
  "key": "last_order",
@@ -192,7 +192,7 @@
192
  "type": "currency",
193
  "source": "odoo",
194
  "default": false,
195
- "description": "Invoiced money past due — same basis as the Collections page."
196
  },
197
  {
198
  "_note": "wave 21 R1 — the TOTAL, added beside the rename above. AR current $ + AR overdue $, i.e. what most people mean by 'open AR'. Composed from the same ar.credit_exposure rows the siblings use, so it is transitively reconciled by ar.validate()'s residual read_group tie — no second oracle.",
@@ -329,7 +329,7 @@
329
  "source": "odoo",
330
  "pinned": true,
331
  "default": true,
332
- "description": "The SKU code — the product's real business key. `pid` is a stable CRC32 of it because the grid keys on an integer."
333
  },
334
  {
335
  "key": "product_id",
@@ -611,7 +611,7 @@
611
  "label": "Revenue LY",
612
  "type": "currency",
613
  "source": "odoo",
614
- "description": "Same period last year — seasonal wholesale compares like for like."
615
  },
616
  {
617
  "key": "yoy_pct",
@@ -639,7 +639,14 @@
639
  "label": "On hand",
640
  "type": "int",
641
  "source": "odoo",
642
- "description": "Units in stock. CONSOLIDATED — one physical warehouse, not brand-tagged, so this column is ABSENT for a BU-scoped caller rather than silently company-wide."
 
 
 
 
 
 
 
643
  },
644
  {
645
  "key": "unit_cost",
 
18
  "source": "odoo",
19
  "derived": true,
20
  "default": false,
21
+ "description": "The Odoo res.partner id, the key every Odoo document joins on. DERIVED: this row's pid IS the partner id, so a stored copy would be a second source."
22
  },
23
  {
24
  "key": "odoo_status",
 
59
  "type": "select",
60
  "source": "odoo",
61
  "default": false,
62
+ "description": "Who keyed in most of this customer's orders. Not the Agent, who owns the account."
63
  },
64
  {
65
  "key": "street",
 
148
  "type": "select",
149
  "source": "odoo",
150
  "default": false,
151
+ "description": "Payment terms on this customer's account. Net 30, for example."
152
  },
153
  {
154
  "key": "last_order",
 
192
  "type": "currency",
193
  "source": "odoo",
194
  "default": false,
195
+ "description": "Invoiced money past due, on the same basis as the Collections page."
196
  },
197
  {
198
  "_note": "wave 21 R1 — the TOTAL, added beside the rename above. AR current $ + AR overdue $, i.e. what most people mean by 'open AR'. Composed from the same ar.credit_exposure rows the siblings use, so it is transitively reconciled by ar.validate()'s residual read_group tie — no second oracle.",
 
329
  "source": "odoo",
330
  "pinned": true,
331
  "default": true,
332
+ "description": "The SKU code, the product's real business key. `pid` is a stable CRC32 of it because the grid keys on an integer."
333
  },
334
  {
335
  "key": "product_id",
 
611
  "label": "Revenue LY",
612
  "type": "currency",
613
  "source": "odoo",
614
+ "description": "Same period last year, because seasonal wholesale compares like for like."
615
  },
616
  {
617
  "key": "yoy_pct",
 
639
  "label": "On hand",
640
  "type": "int",
641
  "source": "odoo",
642
+ "description": "Units in stock. Consolidated: one physical warehouse, not brand-tagged, so every caller sees the same company-wide figure, a BU-scoped one included."
643
+ },
644
+ {
645
+ "key": "fba",
646
+ "label": "FBA",
647
+ "type": "int",
648
+ "source": "odoo",
649
+ "description": "Units held in the Amazon FBA warehouse, read live from Odoo under that warehouse's own context. These units are already counted in On hand; this column says how many of them sit at Amazon. Warehouse wide and never a business unit allocation, and blank rather than zero when the tenant has no FBA warehouse."
650
  },
651
  {
652
  "key": "unit_cost",
platform/core/connector_directory.py ADDED
@@ -0,0 +1,464 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """THE CONNECTOR DIRECTORY'S TAXONOMY (W49-T18, ruling R27, contract C4).
2
+
3
+ ⭐⭐ WHAT R27 ASKED FOR, verbatim: *"don't skip Odoo or meta ads, its important to learn how they
4
+ map the schema for our own benefit."* So this module imports the FULL Monid tool catalogue as our
5
+ directory's taxonomy, files OUR OWN connectors into the same 14 categories, and keeps the four
6
+ overlapping providers (Facebook, Instagram, TikTok, Amazon) beside ours, distinguished only by a
7
+ label nothing renders.
8
+
9
+ ⛔⛔ THE CROSSWALK BELOW IS AUTHORED AND IT CANNOT BE GENERATED. That is the centre of the ticket
10
+ and the reason for this paragraph: the next reader WILL go looking for the script that produced
11
+ it, and there is nothing to find. Measured against the live Monid API on 2026-09-02:
12
+
13
+ · `POST /v1/discover` returns results whose `tags` are VERIFICATION BADGES: `["verified"]` or
14
+ `[]`. Nothing else. `tags` is not the category taxonomy, whatever the PRD's finding F-T says.
15
+ · `POST /v1/inspect` returns `categories: ["amazon", "apify"]` for the Amazon reviews scraper,
16
+ i.e. PROVIDER-LEVEL SLUGS, not the 14 sidebar categories. Its whole top-level key set is
17
+ `provider, providerName, endpoint, description, summary, method, input, price, docUrl, notes,
18
+ tags, categories, metrics, hints`, and none of those carries a sidebar name.
19
+
20
+ So the 14 categories are reachable only from Monid's WEB UI SIDEBAR, which is what
21
+ `.claude/wiki/waves/wave49/proto/monid-catalogue.md` captured by hand. `MONID_PROVIDERS` is
22
+ regenerated by re-reading that file, not by calling an endpoint.
23
+
24
+ ⚠ AND THE CATALOGUE IS A FLOOR, NOT A CENSUS. `discover` returns providers absent from the proto
25
+ capture (`mrscraper` came back twice in eight results), because the proto list is the SIDEBAR's
26
+ and the sidebar is not the whole set. Nothing in this module or on the screen it feeds claims to
27
+ be complete, and nothing should be made to.
28
+
29
+ ⭐ THE COUNT RULE, and it is the ticket's named trap. Categories OVERLAP: one provider carries
30
+ several, so `sum(endpoints)` over a category double counts and cannot be reconciled with anything.
31
+ A chip's number is therefore THE NUMBER OF CARDS CARRYING THAT CATEGORY, computed from the tag
32
+ lists in `chip_counts`, never a sum of endpoint counts. The endpoint count stays where it means
33
+ something: on the card, about one provider.
34
+
35
+ ⛔ `provider` IS SERVER-SIDE ONLY (C4). The row a contributor composes says whether it is `native`
36
+ or `monid`; `to_client_row` strips it before the route answers, and `verify_catalog.py` reads the
37
+ CLIENT-facing payload to prove the key is gone. The label exists so we can reason about where a
38
+ row came from, and R27's design rule is that it never renders: no badge, no tooltip, nothing.
39
+
40
+ ⛔ THIS MODULE IS PURE. No I/O, no network, no runtime, no store. It is data plus four small
41
+ functions, which is what lets a gate drive it with no FastAPI app and no session.
42
+ """
43
+ from __future__ import annotations
44
+
45
+ import re
46
+
47
+ #: ⭐ MONID'S SIDEBAR, VERBATIM AND IN ITS ORDER, INCLUDING `All`. The proto capture lists `All`
48
+ #: as a sidebar row with a count of its own (1831), so it is one of the fourteen rather than a
49
+ #: control we invented; it is simply the one that selects everything. `TAG_CATEGORIES` below is
50
+ #: the thirteen a provider can actually be filed under.
51
+ #:
52
+ #: ⚠ THESE ARE PROPER NOUNS AS MONID WRITES THEM and they reach a screen, so they are neither
53
+ #: re-cased nor re-spelled. "Search & SEO", "Crypto & DeFi", "E-commerce" and "AI" are names, not
54
+ #: chrome, and DESIGN.md's no-ALL-CAPS rule is about chrome.
55
+ ALL = "All"
56
+ CATEGORIES = (
57
+ ALL,
58
+ "Social Media",
59
+ "Lead Gen",
60
+ "Search & SEO",
61
+ "News",
62
+ "E-commerce",
63
+ "Crypto & DeFi",
64
+ "Finance",
65
+ "AI",
66
+ "Phone & Messaging",
67
+ "Web Tools",
68
+ "Data",
69
+ "Utilities",
70
+ "Scrapers",
71
+ )
72
+
73
+ #: The thirteen a row can be tagged with. `All` is the everything chip and tags nothing.
74
+ TAG_CATEGORIES = tuple(c for c in CATEGORIES if c != ALL)
75
+
76
+ #: ⚠ PROVENANCE ONLY, AND DELIBERATELY NOT ON A SCREEN. These are MONID's own endpoint totals per
77
+ #: sidebar category, copied from the proto capture. They sum to 2,894 against a stated total of
78
+ #: 1,831, which is the overlap made arithmetic and the clearest possible statement of why a chip
79
+ #: must not add endpoint counts up. Kept so a future reader can re-check the capture against the
80
+ #: sidebar without re-reading the sidebar.
81
+ MONID_CATEGORY_ENDPOINTS = {
82
+ "All": 1831, "Social Media": 957, "Lead Gen": 301, "Search & SEO": 68, "News": 26,
83
+ "E-commerce": 20, "Crypto & DeFi": 293, "Finance": 70, "AI": 58, "Phone & Messaging": 14,
84
+ "Web Tools": 34, "Data": 79, "Utilities": 6, "Scrapers": 968,
85
+ }
86
+
87
+ #: ⭐⭐ THE AUTHORED CROSSWALK: (provider name, endpoint count, the categories it is filed under).
88
+ #:
89
+ #: REGENERATION, because there is no generator: re-read the `PROVIDERS` line of
90
+ #: `.claude/wiki/waves/wave49/proto/monid-catalogue.md`, which is `name count` pairs separated by
91
+ #: the middle dot. The NAME and the COUNT come from there unchanged and `verify_catalog.py` proves
92
+ #: it, pair by pair, so a typo here goes red rather than quiet. The CATEGORIES are the authored
93
+ #: half: a judgement about which sidebar rows a provider sits under, made once, here.
94
+ #:
95
+ #: ⚠ THE FOUR OVERLAPS ARE IN THIS LIST ON PURPOSE (R27). Facebook, Instagram, TikTok and Amazon
96
+ #: all have a native counterpart of ours, and both cards ship. A directory that hid the catalogue
97
+ #: entry because we already scrape that platform would be answering a question nobody asked: the
98
+ #: two rows describe different things we can reach, and only the hidden label says which is which.
99
+ MONID_PROVIDERS = (
100
+ ("3D Generation", 4, ("AI",)),
101
+ ("AAA Gas Prices", 12, ("Data",)),
102
+ ("AccuWeather", 3, ("Data",)),
103
+ ("Agentic Phone", 12, ("Phone & Messaging", "AI")),
104
+ ("Ahrefs", 36, ("Search & SEO",)),
105
+ ("Akta", 6, ("Crypto & DeFi",)),
106
+ ("Alibaba", 10, ("E-commerce", "Scrapers")),
107
+ ("Amazon", 5, ("E-commerce", "Scrapers")),
108
+ ("Apify", 44, ("Scrapers", "Web Tools")),
109
+ ("Apollo", 8, ("Lead Gen",)),
110
+ ("Artificial Analysis", 9, ("AI", "Data")),
111
+ ("Audio Tools", 2, ("AI", "Utilities")),
112
+ ("Automotive", 45, ("Data", "Scrapers")),
113
+ ("Bid.Cars", 10, ("Data", "Scrapers")),
114
+ ("Bilibili", 42, ("Social Media", "Scrapers")),
115
+ ("BlockRun", 55, ("Crypto & DeFi",)),
116
+ ("Browser Automation", 8, ("Web Tools", "Scrapers")),
117
+ ("Browserbase", 8, ("Web Tools", "Scrapers")),
118
+ ("Built In", 3, ("Lead Gen", "Data")),
119
+ ("ByteDance", 4, ("Social Media", "AI")),
120
+ ("Capterra", 5, ("Lead Gen", "Data")),
121
+ ("Carfax", 11, ("Data", "Scrapers")),
122
+ ("Cars.com", 3, ("Data", "Scrapers")),
123
+ ("Clay", 10, ("Lead Gen",)),
124
+ ("Clutch", 6, ("Lead Gen", "Data")),
125
+ ("Company Search & Enrichment", 199, ("Lead Gen", "Data")),
126
+ ("Company News", 4, ("News", "Lead Gen")),
127
+ ("Company Reviews", 17, ("Lead Gen", "Data")),
128
+ ("Compensation", 8, ("Data", "Lead Gen")),
129
+ ("Context.dev", 21, ("AI", "Data")),
130
+ ("Market Signals", 7, ("Finance", "Data")),
131
+ ("DeFi", 93, ("Crypto & DeFi",)),
132
+ ("DefiLlama", 127, ("Crypto & DeFi", "Data")),
133
+ ("Derivatives & Perps", 21, ("Crypto & DeFi", "Finance")),
134
+ ("Douyin", 315, ("Social Media", "Scrapers")),
135
+ ("Edmunds", 3, ("Data", "Scrapers")),
136
+ ("ElevenLabs", 9, ("AI", "Phone & Messaging")),
137
+ ("Embeddings", 1, ("AI",)),
138
+ ("Stocks & Funds", 54, ("Finance",)),
139
+ ("Exa", 2, ("Search & SEO", "AI")),
140
+ ("Facebook", 6, ("Social Media", "Scrapers")),
141
+ ("Finviz", 5, ("Finance", "Data")),
142
+ ("Funding & Investors", 7, ("Finance", "Lead Gen")),
143
+ ("G2", 6, ("Lead Gen", "Data")),
144
+ ("GetApp", 11, ("Lead Gen", "Data")),
145
+ ("Gloria", 5, ("News",)),
146
+ ("Google Shopping", 2, ("E-commerce", "Search & SEO")),
147
+ ("Homes.com", 5, ("Data", "Scrapers")),
148
+ ("Hunter", 13, ("Lead Gen",)),
149
+ ("Idealist", 9, ("Lead Gen", "Data")),
150
+ ("Image Generation", 5, ("AI",)),
151
+ ("Indeed", 5, ("Lead Gen", "Data")),
152
+ ("Insider & Institutional", 16, ("Finance",)),
153
+ ("Instagram", 61, ("Social Media", "Scrapers")),
154
+ ("IQAir", 4, ("Data",)),
155
+ ("Jobs", 36, ("Lead Gen", "Data")),
156
+ ("Kelley Blue Book", 6, ("Data", "Scrapers")),
157
+ ("Kuaishou", 38, ("Social Media", "Scrapers")),
158
+ ("Lemon8", 16, ("Social Media", "Scrapers")),
159
+ ("Levels.fyi", 8, ("Data", "Lead Gen")),
160
+ ("LinkedIn", 16, ("Social Media", "Lead Gen")),
161
+ ("LMArena", 13, ("AI", "Data")),
162
+ ("LoopNet", 4, ("Data", "Scrapers")),
163
+ ("Maps & Places", 2, ("Data", "Search & SEO")),
164
+ ("MarketBeat", 14, ("Finance",)),
165
+ ("MiniMax", 5, ("AI",)),
166
+ ("Model Benchmarks", 22, ("AI", "Data")),
167
+ ("Music Generation", 2, ("AI",)),
168
+ ("Nasdaq", 20, ("Finance",)),
169
+ ("News Search", 17, ("News", "Search & SEO")),
170
+ ("Octen", 4, ("Web Tools",)),
171
+ ("On-chain Data", 83, ("Crypto & DeFi", "Data")),
172
+ ("People Data Labs", 4, ("Lead Gen", "Data")),
173
+ ("People Search & Enrichment", 25, ("Lead Gen", "Data")),
174
+ ("PiPiXia", 17, ("Social Media", "Scrapers")),
175
+ ("Prediction Markets", 24, ("Crypto & DeFi", "Finance")),
176
+ ("QuickNode (x402)", 2, ("Crypto & DeFi",)),
177
+ ("Real Estate", 17, ("Data", "Scrapers")),
178
+ ("Reddit", 27, ("Social Media", "Scrapers")),
179
+ ("Saperly", 14, ("Lead Gen",)),
180
+ ("SECForm4", 11, ("Finance", "Data")),
181
+ ("SEO", 36, ("Search & SEO",)),
182
+ ("Simple FS", 6, ("Utilities",)),
183
+ ("SMS", 2, ("Phone & Messaging",)),
184
+ ("Snapchat", 2, ("Social Media", "Scrapers")),
185
+ ("Software Reviews", 22, ("Lead Gen", "Data")),
186
+ ("Speech & Voice", 7, ("AI", "Phone & Messaging")),
187
+ ("Stablecoins", 7, ("Crypto & DeFi",)),
188
+ ("StockAnalysis", 7, ("Finance",)),
189
+ ("Strale", 160, ("Social Media", "Scrapers")),
190
+ ("Surf", 105, ("Web Tools", "Scrapers")),
191
+ ("Suzanne", 4, ("AI",)),
192
+ ("Telegram", 7, ("Social Media", "Phone & Messaging")),
193
+ ("Threads", 11, ("Social Media", "Scrapers")),
194
+ ("TikHub", 924, ("Social Media", "Scrapers")),
195
+ ("TikTok", 155, ("Social Media", "Scrapers")),
196
+ ("TikTok Shop", 13, ("E-commerce", "Social Media")),
197
+ ("TinyFish", 2, ("Web Tools", "Scrapers")),
198
+ ("Token Prices", 22, ("Crypto & DeFi", "Finance")),
199
+ ("Toutiao", 7, ("News", "Social Media")),
200
+ ("Trustpilot", 7, ("Lead Gen", "Data")),
201
+ ("Video Generation", 12, ("AI",)),
202
+ ("Weather", 17, ("Data",)),
203
+ ("Weather Underground", 10, ("Data",)),
204
+ ("Content Extraction", 16, ("Web Tools", "Scrapers")),
205
+ ("Web Search", 6, ("Search & SEO", "Web Tools")),
206
+ ("Web3 Career", 9, ("Crypto & DeFi", "Lead Gen")),
207
+ ("WeChat", 23, ("Social Media", "Scrapers")),
208
+ ("Weibo", 67, ("Social Media", "Scrapers")),
209
+ ("Wellfound", 7, ("Lead Gen", "Data")),
210
+ ("X402 Atlas", 4, ("Crypto & DeFi",)),
211
+ ("Xiaohongshu", 45, ("Social Media", "Scrapers")),
212
+ ("Xigua", 7, ("Social Media", "Scrapers")),
213
+ ("Yahoo Finance", 5, ("Finance",)),
214
+ ("Yields", 14, ("Crypto & DeFi", "Finance")),
215
+ ("YouTube", 41, ("Social Media", "Scrapers")),
216
+ ("Zhihu", 41, ("Social Media", "Scrapers")),
217
+ ("Zillow", 8, ("Data", "Scrapers")),
218
+ )
219
+
220
+ #: ⭐⭐ OUR OWN CONNECTORS, FILED INTO THE SAME FOURTEEN. R27's first clause is *"file our native
221
+ #: connectors into it"*, and the point of doing so is that one taxonomy covers both halves: a
222
+ #: reader looking for a way to reach commerce data finds Odoo and Shopify beside Alibaba, rather
223
+ #: than a catalogue on one side of the page and the things we actually built on the other.
224
+ #:
225
+ #: ⛔ THERE IS NO FALLBACK CATEGORY, DELIBERATELY. C4 says no native connector may be left
226
+ #: uncategorised; a default would satisfy that sentence while filing a new connector under a name
227
+ #: nobody chose, which is exactly the rot this directory exists to prevent. An unlisted key gets
228
+ #: NO category, appears only under `All`, and `verify_catalog.py` names it and goes red.
229
+ NATIVE_CATEGORIES = {
230
+ "odoo": ("Data", "Finance", "E-commerce"),
231
+ "webhooks": ("Utilities", "Web Tools"),
232
+ "scraper": ("Scrapers", "Social Media"),
233
+ "stripe": ("Finance", "E-commerce"),
234
+ "shopify": ("E-commerce", "Data"),
235
+ "meta_ads": ("Social Media", "Data"),
236
+ "slack": ("Phone & Messaging", "Utilities"),
237
+ "hubspot": ("Lead Gen", "Data"),
238
+ "quickbooks": ("Finance", "Data"),
239
+ "xero": ("Finance", "Data"),
240
+ "outlook": ("Phone & Messaging", "Utilities"),
241
+ # The OAuth registry's one slug. Hidden today (R6, D-45) and filed anyway: the blocker is
242
+ # money, not code, so the row comes back with a category already on it.
243
+ "google": ("Phone & Messaging", "Utilities"),
244
+ "google_sheets": ("Data", "Utilities"),
245
+ "google_drive": ("Data", "Utilities"),
246
+ "google_calendar": ("Utilities",),
247
+ }
248
+
249
+ #: ⭐⭐ W49-T19 — THE CATALOGUE ROWS THAT ARE NOT A TO-DO LIST, AND TODAY THERE IS EXACTLY ONE.
250
+ #:
251
+ #: A key here names the DIRECT ACTION its card offers. `md_amazon` carries `amazon_reviews`
252
+ #: because Monid can pull Amazon reviews for this workspace right now: `core/monid.py` is written,
253
+ #: `POST /api/v1/monid/amazon-reviews/run` answers, one live run has been paid for, and the result
254
+ #: lands in a database. Leaving that row at `planned` said the opposite of what is true, and a
255
+ #: directory that describes a working integration as unbuilt is the same lie as one that offers a
256
+ #: door with nothing behind it, told backwards.
257
+ #:
258
+ #: ⛔ THIS MAP IS THE WHOLE PERMISSION TO BE INTERACTIVE, AND IT IS DELIBERATELY ALMOST EMPTY. The
259
+ #: other 117 rows have nothing behind them: no client, no route, no detail composer. They wear
260
+ #: `CATALOGUE_STATE` and their cards stay non-interactive, which is the rule R8 set and the lead
261
+ #: accepted. An entry added here without a route behind it is an affordance that cannot
262
+ #: work, and `verify_catalog.py` pins the count at one so the second one has to be argued for.
263
+ #:
264
+ #: ⚠ THE ACTION NAME IS THE CLIENT'S CONTRACT, not a display string. `ConnectorsPage.tsx` matches
265
+ #: on `amazon_reviews` to decide which card gets a button; both sides are read by the gate.
266
+ MONID_ACTIONS = {
267
+ "md_amazon": "amazon_reviews",
268
+ }
269
+
270
+ #: The state a row with a direct action wears. `available` is already in the server's vocabulary
271
+ #: (`connected | available | reconnect | unconfigured | planned | catalogue`), already tinted by
272
+ #: `ConnectorsPage.stateTone`, and it means precisely what is true here: there is something you
273
+ #: can use. Inventing a fifteenth word would have made every reader of that vocabulary wrong.
274
+ #:
275
+ #: ⚠ IT DOES NOT CLAIM A KEY EXISTS. This module is pure and cannot know whether the workspace has
276
+ #: a Monid credential, so it does not say `unconfigured` either. Whether the caller may run, and
277
+ #: whether a key is stored, are answered by `GET /monid/amazon-reviews/meta` at the moment of use.
278
+ MONID_ACTION_STATE = "available"
279
+
280
+ #: ⭐⭐ THE STATE A CATALOGUE LISTING WEARS, AND IT IS THE WHOLE OF THIS REPAIR.
281
+ #:
282
+ #: ⛔⛔ `planned` WAS ALREADY A WORD WITH A CONTRACT, AND T18 OVERLOADED IT. In this product a
283
+ #: PLANNED row means three things at once: it is a connector we intend to BUILD, it is enumerated
284
+ #: in `routes_connectors.PLANNED`, and it carries a `needs` naming what it is waiting on. That is
285
+ #: what makes it R8's visible to-do list, and `verify_automation` asserts all three — the served
286
+ #: planned set IS `PLANNED`, and every planned row has a `needs`.
287
+ #:
288
+ #: ⛔ A CATALOGUE LISTING IS NONE OF THOSE THINGS. It is not on our roadmap, nobody is waiting on
289
+ #: anything for it, and it has no `needs` to give. The 117 rows were handed `planned` only because
290
+ #: that state happened to render faded and non-interactive, which is a rendering fact borrowed to
291
+ #: carry a roadmap claim — and it made `verify_automation` read the whole Monid catalogue as our
292
+ #: to-do list. So the listing gets its OWN word and `planned` goes back to meaning what it meant.
293
+ #:
294
+ #: ⚠ THE FADE IS NOT THIS WORD'S JOB. `ConnectorsPage.ConnectorCard` no longer keys the faded,
295
+ #: `aria-disabled`, non-openable treatment on the literal `planned` — it keys on "this row has no
296
+ #: door", which both words satisfy. The card renders exactly as it did; only what it CLAIMS moved.
297
+ #:
298
+ #: ⛔ AND IT IS A SIXTH WORD IN THE SERVER'S STATE VOCABULARY (`connected | available | reconnect
299
+ #: | unconfigured | planned | catalogue`). `ConnectorsPage.stateTone` already answers an unknown
300
+ #: state with the neutral tone by construction (the wave-9 law: no client union over a server
301
+ #: vocabulary), so the client renders it without a change. Any gate holding a HAND-TYPED copy of
302
+ #: the five-word set has to learn the sixth.
303
+ CATALOGUE_STATE = "catalogue"
304
+
305
+ #: ⭐⭐ W49-T14 · RULINGS R21 + R24 — WHICH CONNECTORS HAVE A FIELD CATALOGUE, AUTHORED IN CODE.
306
+ #:
307
+ #: ⭐⭐ R21, verbatim: *"the table list stays AUTHORED IN CODE; the screen DISCLOSES it, it does
308
+ #: not DERIVE it."* R24, verbatim: *"ONLY introspectable connectors get this screen. Scrapers,
309
+ #: Meta Ads and anything without a field catalogue keep today's connector card."*
310
+ #:
311
+ #: ⛔ THE ANSWER IS A DECLARATION, NEVER A PROBE. The tempting implementation is "introspectable
312
+ #: means `_detail_databases` came back non-empty", and that is precisely the confidently-wrong
313
+ #: shape the composer's own header was written about: an Odoo connection whose store read failed,
314
+ #: or whose grids are all switched off, returns the same empty list as Meta Ads — so the tab would
315
+ #: tell an administrator that Odoo has no schema on the one day the schema mattered. A connector
316
+ #: either publishes a field catalogue or it does not, and that fact is ours to state.
317
+ #:
318
+ #: ⛔ A CATALOGUE ROW IS NEVER IN HERE, and that is `CATALOGUE_STATE`'s whole point one paragraph
319
+ #: up: the 117 Monid listings have no client, no route and no detail composer, so there is nothing
320
+ #: behind them to introspect. Membership is by KEY, and every catalogue key wears
321
+ #: `MONID_KEY_PREFIX`, so the two sets cannot overlap by construction.
322
+ #:
323
+ #: ⚠ ONE ENTRY TODAY, AND ADDING A SECOND IS A REAL DECISION. A connector named here promises the
324
+ #: Databases tab a field catalogue AND a route that can enable one of its fields; without both,
325
+ #: the tab renders toggles that lead nowhere, which is R8's fake affordance.
326
+ INTROSPECTABLE_CONNECTORS = ("odoo",)
327
+
328
+
329
+ def is_introspectable(connector_key) -> bool:
330
+ """Does this connector publish a field catalogue the Databases tab can disclose (R24)?
331
+
332
+ Pure and total: an unknown key is not introspectable, which is the fail-closed direction.
333
+ """
334
+ return str(connector_key or "") in INTROSPECTABLE_CONNECTORS
335
+
336
+
337
+ #: ⛔ THE KEYS A ROW CARRIES FOR US AND NEVER FOR THE CLIENT (C4). One tuple, read by
338
+ #: `to_client_row` and by the gate's negative control, so "which keys are server-only" has one
339
+ #: answer wherever it is asked.
340
+ SERVER_ONLY_KEYS = ("provider",)
341
+
342
+ #: The prefix every catalogue row's key wears. Internal, never on a screen, and it exists because
343
+ #: `Instagram` and `TikTok` are already directory keys of ours: two cards for two different things
344
+ #: must not collide, and `verify_meta` asserts no key appears twice in the served set.
345
+ MONID_KEY_PREFIX = "md_"
346
+
347
+
348
+ def slug(name: str) -> str:
349
+ """A provider name to its key fragment. Lowercase, and every run of non-alphanumerics
350
+ becomes one underscore, so `Bid.Cars` and `QuickNode (x402)` both land somewhere stable."""
351
+ return re.sub(r"_+", "_", re.sub(r"[^a-z0-9]+", "_", str(name).lower())).strip("_")
352
+
353
+
354
+ def monid_rows():
355
+ """The authored catalogue as directory rows.
356
+
357
+ ⛔⛔ ALL BUT ONE ROW IS `catalogue`, AND IT USED TO BE `planned`, WHICH WAS THE DEFECT. The
358
+ first draft of this docstring argued that a catalogue entry IS a to-do item, and it was wrong
359
+ in the one way that matters: `planned` is not a look, it is a claim with a registry
360
+ (`routes_connectors.PLANNED`) and a `needs` behind it, and 117 listings we have never planned
361
+ to build were therefore served as our roadmap. `CATALOGUE_STATE` carries the argument in full.
362
+
363
+ ⚠ THE CARD IS UNCHANGED. A catalogue row still has no detail route behind it, so it is still
364
+ faded, `aria-disabled` and not openable — the client keys that on the row having no door
365
+ rather than on the literal word `planned`, which is why the word could move at all.
366
+
367
+ ⭐⭐ W49-T19 AMENDS THAT SENTENCE FOR EXACTLY THE ROWS IN `MONID_ACTIONS`, AND THE AMENDMENT
368
+ IS THE POINT OF THE TICKET. `md_amazon` is neither: Monid pulls Amazon reviews today, the
369
+ route behind it answers, and a real run has been paid for. So that row carries `action` and
370
+ the `available` state, and its card offers ONE named control ("Pull reviews") that opens the
371
+ run dialog IN PLACE. It is still not modal-openable, because the 404 above is still true:
372
+ `action` buys a button, never a door to a detail route that does not exist.
373
+
374
+ ⚠ `action` IS ON EVERY ROW, EMPTY FOR 117 OF THEM, and that is deliberate. One shape means the
375
+ client asks `row.action === "amazon_reviews"` rather than probing for a key's presence, and it
376
+ means the gate can assert an ordinary row's answer is `""` rather than merely absent. An
377
+ absent key and an empty key read the same in JavaScript and differently in a test.
378
+
379
+ ⚠ NO `desc`. DESIGN.md forbids over-explaining, and 118 invented sentences would be 118
380
+ guesses about somebody else's product. The card carries the name, the category and the
381
+ endpoint count, all three of which are measured.
382
+ """
383
+ rows = []
384
+ for name, endpoints, cats in MONID_PROVIDERS:
385
+ key = MONID_KEY_PREFIX + slug(name)
386
+ action = MONID_ACTIONS.get(key, "")
387
+ rows.append({
388
+ "key": key,
389
+ "label": name,
390
+ "kind": "catalogue",
391
+ "desc": "",
392
+ "state": MONID_ACTION_STATE if action else CATALOGUE_STATE,
393
+ "manage": "",
394
+ "endpoints": int(endpoints),
395
+ "category": cats[0],
396
+ "categories": list(cats),
397
+ # ⭐ THE DIRECT ACTION, AND IT CROSSES TO THE CLIENT (unlike `provider`). The card can
398
+ # only offer a control it is told about; a client-side list of which providers are
399
+ # special would be a second authority for one fact, in the layer least able to know.
400
+ "action": action,
401
+ # ⛔ SERVER-SIDE ONLY (C4). `to_client_row` removes it; nothing renders it.
402
+ "provider": "monid",
403
+ })
404
+ return rows
405
+
406
+
407
+ def file_natives(rows):
408
+ """Tag every row already composed by `routes_connectors.directory` with its category.
409
+
410
+ Mutates in place, because that is what the composer holds. A key with no entry in
411
+ `NATIVE_CATEGORIES` gets an EMPTY category rather than a guessed one: it still renders, under
412
+ `All` only, and the gate names it.
413
+ """
414
+ for row in rows:
415
+ cats = NATIVE_CATEGORIES.get(str(row.get("key") or ""), ())
416
+ row["categories"] = list(cats)
417
+ row["category"] = cats[0] if cats else ""
418
+ row["provider"] = "native"
419
+ return rows
420
+
421
+
422
+ def unfiled_native_keys(keys):
423
+ """The native connector keys nobody filed. The gate's subject, and it takes the key set from
424
+ the caller so that a gate can build it from the composer's own registries rather than from a
425
+ second list here (one question, one answer)."""
426
+ return sorted(k for k in keys if k not in NATIVE_CATEGORIES)
427
+
428
+
429
+ def chip_counts(rows):
430
+ """The filter rail: one entry per category, in `CATEGORIES` order, with what its chip shows.
431
+
432
+ ⭐⭐ A CHIP'S NUMBER IS A COUNT OF CARDS, NOT A SUM OF ENDPOINTS, and that is the ticket's
433
+ named trap answered in one line of code. Categories overlap, so a provider carrying three of
434
+ them would contribute its endpoint total three times and the rail would add up to more
435
+ endpoints than Monid has. Counting cards also makes the number mean what a reader assumes it
436
+ means: press the chip and that many cards remain.
437
+
438
+ `All` counts every row, which is the one place the number is both a card count and the whole
439
+ set.
440
+ """
441
+ out = []
442
+ for name in CATEGORIES:
443
+ if name == ALL:
444
+ out.append({"name": ALL, "count": len(rows)})
445
+ continue
446
+ out.append({"name": name,
447
+ "count": sum(1 for r in rows if name in (r.get("categories") or []))})
448
+ return out
449
+
450
+
451
+ def to_client_row(row):
452
+ """One row as the client is allowed to see it.
453
+
454
+ ⛔ C4's NEGATIVE CONTROL LIVES ON THIS FUNCTION. `provider` says whether a row is ours or the
455
+ catalogue's, we reason with it on the server, and R27's design rule is that it never reaches a
456
+ screen in any form. Stripping it here rather than at each composer means there is ONE place to
457
+ read to know what the wire carries, and one place for the gate to break.
458
+ """
459
+ return {k: v for k, v in row.items() if k not in SERVER_ONLY_KEYS}
460
+
461
+
462
+ def to_client_rows(rows):
463
+ """The whole served set, stripped. The route calls this and nothing else."""
464
+ return [to_client_row(r) for r in rows]
platform/core/dependents.py ADDED
@@ -0,0 +1,515 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """dependents.py — THE ONE REGISTRY THAT ANSWERS "what breaks if I remove this?" (wave 49, C3).
2
+
3
+ ⭐⭐ **OWNER RULING R23, verbatim:** *"Switching off a table that something depends on is REFUSED,
4
+ and the refusal NAMES the dependents ('3 views, 1 Route and 2 Sheet cells use this')."*
5
+ ⭐⭐ **OWNER RULING R32, second half:** *"deleting a view must first disclose who it is shared to
6
+ and which Sheet cells depend on it."*
7
+
8
+ Both rulings ask the same question of different targets, so there is ONE answer path here rather
9
+ than a bespoke pre-flight check per surface. A surface (the Databases tab's off switch, the view
10
+ delete dialog, a Sheet cell binding) calls `dependents(st, target)` and renders what comes back.
11
+
12
+ CONTRACT C3, copied so it cannot drift:
13
+
14
+ register(kind: str, fn)
15
+ dependents(st, target) -> list[Dependent]
16
+ target = {"kind": "table"|"view"|"field", "key": str, "database"?: str}
17
+ Dependent = {"kind": "view"|"route"|"link"|"rollup"|"grant"|"chart"|"sheet_cell",
18
+ "label": str, "count": int, "ids": list[str]}
19
+
20
+ ⛔⛔ **A ZERO-COUNT KIND IS OMITTED, NEVER REPORTED AS ZERO, AND THAT IS THE WHOLE POINT OF THE
21
+ REGISTRY BEING OPEN.** "used by 0 Routes" is noise; worse, it is a claim. `sheet_cell` is
22
+ registered by `platform/modules/sheet.py` AFTER the wave-49 lane merge (W49-T11, a declared
23
+ handover), so until that line lands this module has no opinion about Sheet cells at all — and
24
+ saying "0 Sheet cells" would be an assertion it cannot support. An unregistered kind is UNKNOWN,
25
+ not empty, and the only honest rendering of unknown is silence.
26
+
27
+ ⛔⛔ **A PROVIDER THAT RAISES OMITS ITS KIND. IT NEVER CONTRIBUTES A ZERO.** Same reason, arriving
28
+ by a different road: a store read that failed knows nothing, and "nothing" must not be spelled the
29
+ same way as "none". `dependents_report` hands the omitted kinds back to the caller as `errors` so
30
+ the omission is visible rather than swallowed.
31
+
32
+ ⛔ **LAYERING.** This file lives in `core/` and imports only `core/` siblings and stdlib, so
33
+ `modules -> core` still points one way. In particular it does NOT copy
34
+ `core/grid_events.py::_tops`, which reaches UP into `modules.customer_data` (tolerated wave-25 debt
35
+ carrying a tenant-#0-only fallback bug). `core.table_store.TableStore` is instantiated directly,
36
+ and the page-key -> workspace-bucket mapping comes from `core.view_templates.workspace_key`, which
37
+ is already the one place that mapping lives.
38
+
39
+ ⛔ **AND `TableStore.find_view` IS DELIBERATELY NOT USED HERE.** It calls
40
+ `migrate_legacy_shared_views()` first — a side-effecting read that WRITES the store and can raise
41
+ `LegacySharedViewMigrationError` on a malformed legacy record. A disclosure dialog is a GET; a GET
42
+ that migrates data, or 500s on data it only meant to describe, is a defect. The table document is
43
+ walked directly instead, exactly as the shape allows.
44
+
45
+ ⚠ **THE `'link'` KEY CARRIES TWO SHAPES AND THIS IS WHERE THAT BITES.** On a field of
46
+ `type == 'link'` it is a DICT (`{'table': ..., 'inverse': ...}`); on a rollup bag it is the bare
47
+ FIELD KEY (a string) of the link the rollup traverses. A rollup may also carry no `link` at all
48
+ (the `{'source': {...}}` shape, which joins through a topic dim). Every walker below branches on
49
+ `field['type']` first and on which key is present second.
50
+ """
51
+ import core.chart_system as chart_system
52
+ import core.route_system as route_system
53
+ import core.shares as shares
54
+ import core.user_tables as user_tables
55
+ import core.view_templates as view_templates
56
+ from core.table_store import ASSIGNED_KEY, SHARED_KEY
57
+
58
+ #: The reading order of a refusal sentence. `sheet_cell` is listed even though nothing in this
59
+ #: file registers it: the ORDER is a presentation fact and it must not depend on which lane
60
+ #: happened to register first (W49-T11 registers `sheet_cell` after the merge).
61
+ KIND_ORDER = ('view', 'route', 'link', 'rollup', 'grant', 'chart', 'sheet_cell')
62
+
63
+ #: Singular / plural noun phrase per kind. ⛔ THE CASING IS R23's OWN — lowercase `views`, capital
64
+ #: `Route`, capital `Sheet cells` — because the ruling quotes the sentence the user reads.
65
+ _NOUNS = {
66
+ 'view': ('view', 'views'),
67
+ 'route': ('Route', 'Routes'),
68
+ 'link': ('Link field', 'Link fields'),
69
+ 'rollup': ('rollup', 'rollups'),
70
+ 'grant': ('share', 'shares'),
71
+ 'chart': ('chart', 'charts'),
72
+ 'sheet_cell': ('Sheet cell', 'Sheet cells'),
73
+ }
74
+
75
+ _PROVIDERS = {}
76
+
77
+
78
+ def noun(kind, count):
79
+ """The noun phrase for `count` of `kind`, agreeing in number."""
80
+ pair = _NOUNS.get(str(kind or ''))
81
+ if not pair:
82
+ base = str(kind or '').replace('_', ' ').strip() or 'dependent'
83
+ pair = (base, base + 's')
84
+ return pair[0] if int(count or 0) == 1 else pair[1]
85
+
86
+
87
+ def register(kind, fn):
88
+ """Register `fn(st, target) -> Dependent | list[Dependent] | None` for one dependent kind.
89
+
90
+ ⚠ RE-REGISTERING A KIND REPLACES IT rather than adding a second answer to one question. The
91
+ combine session registers `sheet_cell` once; a module imported twice must not double-count.
92
+
93
+ ⚠ THE RETURN SHAPE IS DELIBERATELY LOOSE (one dict, a list, or None). Lane A wrote
94
+ `modules/sheet.py::sheet_dependents` without ever seeing this file, so the seam accepts either
95
+ spelling instead of demanding the lanes agreed on something neither could read.
96
+ """
97
+ key = str(kind or '').strip()
98
+ if not key or not callable(fn):
99
+ raise ValueError('dependents.register: a kind and a callable are both required')
100
+ _PROVIDERS[key] = fn
101
+ return key
102
+
103
+
104
+ def registered_kinds():
105
+ """Every kind that currently has a provider, in `KIND_ORDER`."""
106
+ known = [k for k in KIND_ORDER if k in _PROVIDERS]
107
+ return known + sorted(k for k in _PROVIDERS if k not in KIND_ORDER)
108
+
109
+
110
+ def clean_target(target):
111
+ """`{'kind', 'key', 'database'}` with kind restricted to the C3 vocabulary, else None."""
112
+ target = target if isinstance(target, dict) else {}
113
+ kind = str(target.get('kind') or '').strip().lower()
114
+ key = str(target.get('key') or '').strip()
115
+ if kind not in ('table', 'view', 'field') or not key:
116
+ return None
117
+ database = str(target.get('database') or '').strip()
118
+ if kind == 'table' and not database:
119
+ database = key
120
+ return {'kind': kind, 'key': key, 'database': database}
121
+
122
+
123
+ def _dependent(kind, ids):
124
+ """A Dependent, or None when nothing depends. ⛔ NONE IS THE ZERO CASE — never `count: 0`."""
125
+ seen, out = set(), []
126
+ for raw in ids or ():
127
+ value = str(raw or '').strip()
128
+ if value and value not in seen:
129
+ seen.add(value)
130
+ out.append(value)
131
+ if not out:
132
+ return None
133
+ return {'kind': kind, 'label': noun(kind, len(out)), 'count': len(out), 'ids': out}
134
+
135
+
136
+ def dependents(st, target):
137
+ """Every registered kind that depends on `target`, in `KIND_ORDER`. C3's shape, exactly.
138
+
139
+ Zero-count kinds are absent. A provider that RAISES is absent too — see the module note; use
140
+ `dependents_report` when the caller needs to know which kinds could not be answered.
141
+ """
142
+ return dependents_report(st, target)['dependents']
143
+
144
+
145
+ def dependents_report(st, target):
146
+ """`{'dependents': [...], 'errors': {kind: message}}` — `dependents()` plus what it could not
147
+ answer. The route returns `errors` so an unanswerable kind is visible rather than swallowed."""
148
+ clean = clean_target(target)
149
+ if clean is None:
150
+ return {'dependents': [], 'errors': {}}
151
+ found, errors = [], {}
152
+ for kind in registered_kinds():
153
+ try:
154
+ produced = _PROVIDERS[kind](st, dict(clean))
155
+ except Exception as exc: # noqa: BLE001 — an unanswerable kind is omitted, never zeroed
156
+ errors[kind] = f'{type(exc).__name__}: {exc}'
157
+ continue
158
+ for item in (produced if isinstance(produced, (list, tuple)) else [produced]):
159
+ if not isinstance(item, dict):
160
+ continue
161
+ ids = item.get('ids') or []
162
+ count = int(item.get('count') or len(ids) or 0)
163
+ if count <= 0:
164
+ continue
165
+ found.append({'kind': str(item.get('kind') or kind),
166
+ 'label': str(item.get('label') or noun(kind, count)),
167
+ 'count': count,
168
+ 'ids': [str(i) for i in ids]})
169
+ order = {kind: index for index, kind in enumerate(KIND_ORDER)}
170
+ found.sort(key=lambda item: (order.get(item['kind'], len(order)), item['kind']))
171
+ return {'dependents': found, 'errors': errors}
172
+
173
+
174
+ def refusal(label, found):
175
+ """R23's sentence: `"<label> is used by 2 views and 1 Route"`, or `''` when nothing depends.
176
+
177
+ ⛔ ZERO-COUNT KINDS ARE ABSENT BY CONSTRUCTION, because `dependents()` never emitted one. The
178
+ empty string is the "nothing depends on this" answer: a caller renders a refusal only when
179
+ this is truthy, so there is no sentence that can accidentally say "used by nothing".
180
+ """
181
+ parts = [f"{item['count']} {item['label']}" for item in (found or ())
182
+ if int(item.get('count') or 0) > 0]
183
+ if not parts:
184
+ return ''
185
+ if len(parts) == 1:
186
+ listed = parts[0]
187
+ else:
188
+ listed = ', '.join(parts[:-1]) + ' and ' + parts[-1]
189
+ name = str(label or '').strip() or 'This database'
190
+ return f'{name} is used by {listed}'
191
+
192
+
193
+ # ═══════════════════════════════════════════════ the store readers the providers share
194
+
195
+
196
+ def _table_doc(st, database):
197
+ """The raw `<key>_table_workspace` document, or `{}`. Never migrates — see the module note."""
198
+ bucket = view_templates.workspace_key(str(database or '').strip())
199
+ if not bucket:
200
+ return {}
201
+ try:
202
+ return dict(st.get(bucket) or {})
203
+ except Exception:
204
+ return {}
205
+
206
+
207
+ def walk_views(st, database):
208
+ """`[(owner, view_id, view)]` for every PERSONAL saved View on one database.
209
+
210
+ ⛔ THE RESERVED STRATA ARE SKIPPED. `__shared__` holds field annotations (and, before wave 48,
211
+ a retired legacy view map); `__assigned__` holds recipient projections, which are counted by
212
+ `_assigned_ids` as dependents OF a source view rather than as views in their own right.
213
+ """
214
+ out = []
215
+ for owner, workspace in _table_doc(st, database).items():
216
+ if owner in (SHARED_KEY, ASSIGNED_KEY) or not isinstance(workspace, dict):
217
+ continue
218
+ for view_id, view in (workspace.get('views') or {}).items():
219
+ if isinstance(view, dict):
220
+ out.append((str(owner), str(view_id), view))
221
+ return out
222
+
223
+
224
+ def _assigned_ids(st, database, source_view_id):
225
+ """Ids of the recipient ASSIGNMENTS minted from one source view.
226
+
227
+ These are real dependents: `grid_events`' owner-delete path removes them with the source, so
228
+ a disclosure that omitted them would understate what the delete destroys.
229
+ """
230
+ stratum = _table_doc(st, database).get(ASSIGNED_KEY)
231
+ if not isinstance(stratum, dict):
232
+ return []
233
+ found = []
234
+ for recipient, workspace in stratum.items():
235
+ if not isinstance(workspace, dict):
236
+ continue
237
+ for view_id, view in (workspace.get('views') or {}).items():
238
+ if not isinstance(view, dict):
239
+ continue
240
+ source = view.get('sourceViewId') or view.get('sourceId') or view.get('source')
241
+ if str(source or '').strip() == str(source_view_id):
242
+ found.append(f'{recipient}:{view_id}')
243
+ return found
244
+
245
+
246
+ def _defs(st):
247
+ """`{table_key: definition-without-rows}`. `all_defs` falls back to the whole read itself."""
248
+ try:
249
+ return dict(user_tables.all_defs(st=st) or {})
250
+ except Exception:
251
+ return {}
252
+
253
+
254
+ def _fields(definition):
255
+ return [f for f in ((definition or {}).get('fields') or []) if isinstance(f, dict)]
256
+
257
+
258
+ def _link_bag(field):
259
+ """The link DICT of a link field, else None. ⛔ Branches on `type` before touching `link`."""
260
+ if str((field or {}).get('type') or '') != 'link':
261
+ return None
262
+ bag = (field or {}).get('link')
263
+ return bag if isinstance(bag, dict) else None
264
+
265
+
266
+ def _rollup_bag(field):
267
+ """The rollup bag of a rollup field, else None."""
268
+ if str((field or {}).get('type') or '') != 'rollup':
269
+ return None
270
+ bag = (field or {}).get('rollup')
271
+ return bag if isinstance(bag, dict) else None
272
+
273
+
274
+ def _routes(st):
275
+ try:
276
+ return [r for r in (route_system.list_routes(st) or ()) if isinstance(r, dict)]
277
+ except Exception:
278
+ return []
279
+
280
+
281
+ def _zones(st, table_key):
282
+ try:
283
+ return [z for z in (route_system.list_zones(st, table_key=table_key) or ())
284
+ if isinstance(z, dict)]
285
+ except Exception:
286
+ return []
287
+
288
+
289
+ def _charts(st):
290
+ try:
291
+ return [c for c in (chart_system.list_charts(st) or ()) if isinstance(c, dict)]
292
+ except Exception:
293
+ return []
294
+
295
+
296
+ def share_audience(st, view_id):
297
+ """`{'owner': str|None, 'names': [...], 'count': n}` for one saved View — R32's first half.
298
+
299
+ ⛔ `by` PROVENANCE IS STRIPPED HERE ON PURPOSE. `shares.grants` carries *who placed* each grant
300
+ (D-474), and its own docstring names the cost of returning that verbatim: it widens "who has
301
+ this?" into "who let them in?". A delete dialog needs only the audience, so this door hands
302
+ back names and a count and nothing else.
303
+ """
304
+ record = shares.grants('view', str(view_id or ''), st=st)
305
+ names = [str(entry.get('user') or '') for entry in (record.get('entries') or ())
306
+ if str(entry.get('user') or '')]
307
+ return {'owner': record.get('owner'), 'names': names, 'count': len(names)}
308
+
309
+
310
+ def audience_sentence(audience):
311
+ """`"Shared with anna and 2 others"`, `"Shared with anna"`, or `''`. No dash, ever."""
312
+ names = [str(n) for n in ((audience or {}).get('names') or ()) if str(n or '').strip()]
313
+ if not names:
314
+ return ''
315
+ everyone = [n for n in names if n == shares.EVERYONE]
316
+ if everyone:
317
+ return 'Shared with everyone in this workspace'
318
+ if len(names) == 1:
319
+ return f'Shared with {names[0]}'
320
+ if len(names) == 2:
321
+ return f'Shared with {names[0]} and 1 other'
322
+ return f'Shared with {names[0]} and {len(names) - 1} others'
323
+
324
+
325
+ # ═══════════════════════════════════════════════ the six providers this lane owns
326
+
327
+
328
+ def view_dependents(st, target):
329
+ """Saved Views that depend on the target.
330
+
331
+ * table -> every personal saved View filed on that database
332
+ * view -> the recipient ASSIGNMENTS minted from it (deleting the source deletes them)
333
+ * field -> every View whose config NAMES the column (visible / filter leaf / sort / group)
334
+ """
335
+ kind, key, database = target['kind'], target['key'], target['database']
336
+ if kind == 'table':
337
+ return _dependent('view', [vid for _owner, vid, _v in walk_views(st, key)])
338
+ if kind == 'view':
339
+ if not database:
340
+ return None
341
+ return _dependent('view', _assigned_ids(st, database, key))
342
+ hits = []
343
+ for _owner, view_id, view in walk_views(st, database):
344
+ if _view_names_field(view, key):
345
+ hits.append(view_id)
346
+ return _dependent('view', hits)
347
+
348
+
349
+ def _view_names_field(view, field_key):
350
+ """Does one saved View's config reference this column anywhere a delete would break?"""
351
+ config = (view or {}).get('config')
352
+ if not isinstance(config, dict):
353
+ return False
354
+ wanted = str(field_key)
355
+ if wanted in [str(c) for c in (config.get('visible') or ())]:
356
+ return True
357
+ if str(config.get('groupBy') or '') == wanted:
358
+ return True
359
+ for sort in (config.get('sorts') or ()):
360
+ if isinstance(sort, dict) and str(sort.get('colId') or sort.get('field') or '') == wanted:
361
+ return True
362
+ return _filters_name_field(config.get('filters'), wanted)
363
+
364
+
365
+ def _filters_name_field(node, wanted, depth=0):
366
+ """A filter tree is nested groups of leaves; a leaf names its column as `colId`/`field`."""
367
+ if depth > 8:
368
+ return False
369
+ if isinstance(node, (list, tuple)):
370
+ return any(_filters_name_field(item, wanted, depth + 1) for item in node)
371
+ if not isinstance(node, dict):
372
+ return False
373
+ if str(node.get('colId') or node.get('field') or '') == wanted:
374
+ return True
375
+ return _filters_name_field(node.get('items') or node.get('children'), wanted, depth + 1)
376
+
377
+
378
+ def route_dependents(st, target):
379
+ """Routes and Zones built ON the target.
380
+
381
+ A Route pins the saved View it was planned from (`sourceViewId`), so deleting that View or
382
+ switching off its database leaves the Route pointing at nothing. Zones carry the same pin plus
383
+ a `geographicField`, which is what makes them a FIELD dependent too.
384
+ """
385
+ kind, key, database = target['kind'], target['key'], target['database']
386
+ routes, hits = _routes(st), []
387
+ if kind == 'view':
388
+ hits += [str(r.get('id')) for r in routes if str(r.get('sourceViewId') or '') == key]
389
+ hits += [str(z.get('id')) for z in _zones(st, database or None)
390
+ if str(z.get('sourceViewId') or '') == key]
391
+ return _dependent('route', hits)
392
+ if kind == 'table':
393
+ view_ids = {vid for _owner, vid, _v in walk_views(st, key)}
394
+ hits += [str(r.get('id')) for r in routes
395
+ if str(r.get('sourceViewId') or '') in view_ids]
396
+ hits += [str(z.get('id')) for z in _zones(st, key)]
397
+ return _dependent('route', hits)
398
+ hits += [str(z.get('id')) for z in _zones(st, database)
399
+ if str(z.get('geographicField') or '') == key]
400
+ return _dependent('route', hits)
401
+
402
+
403
+ def link_dependents(st, target):
404
+ """INBOUND Link fields: the columns on OTHER databases that point at the target.
405
+
406
+ ⚠ A link field the target itself owns is not a dependent, it is part of the thing being
407
+ removed. What breaks is the column on the far side, which is why only `link['table']` (and,
408
+ for a field target, `link['inverse']`) is matched.
409
+ """
410
+ kind, key = target['kind'], target['key']
411
+ if kind == 'view':
412
+ return None
413
+ hits = []
414
+ for table_key, definition in _defs(st).items():
415
+ for field in _fields(definition):
416
+ bag = _link_bag(field)
417
+ if bag is None:
418
+ continue
419
+ if kind == 'table' and str(bag.get('table') or '') == key and str(table_key) != key:
420
+ hits.append(f'{table_key}:{field.get("key")}')
421
+ elif kind == 'field' and str(bag.get('inverse') or '') == key \
422
+ and str(bag.get('table') or '') == str(target['database']):
423
+ hits.append(f'{table_key}:{field.get("key")}')
424
+ return _dependent('link', hits)
425
+
426
+
427
+ def rollup_dependents(st, target):
428
+ """Rollups that would stop resolving.
429
+
430
+ ⛔ THREE SHAPES, NOT TWO. `{'link': <field key str>, 'fn': ...}` traverses a Link column on its
431
+ own table; `{'source': {'topic', 'on', 'groupBy', ...}}` joins through a topic dim and carries
432
+ NO `link` at all; and a malformed bag carries neither. Each is matched separately, and the
433
+ `link` value is read as a STRING here because a rollup's `link` is never the link field's dict.
434
+ """
435
+ kind, key = target['kind'], target['key']
436
+ if kind == 'view':
437
+ return None
438
+ hits = []
439
+ for table_key, definition in _defs(st).items():
440
+ fields = _fields(definition)
441
+ by_key = {str(f.get('key') or ''): f for f in fields}
442
+ for field in fields:
443
+ bag = _rollup_bag(field)
444
+ if bag is None:
445
+ continue
446
+ source = bag.get('source') if isinstance(bag.get('source'), dict) else None
447
+ hop = str(bag.get('link') or '') if not isinstance(bag.get('link'), dict) else ''
448
+ hop_field = by_key.get(hop) if hop else None
449
+ hop_bag = _link_bag(hop_field) if hop_field else None
450
+ if kind == 'table':
451
+ if source and str(source.get('topic') or '') == key:
452
+ hits.append(f'{table_key}:{field.get("key")}')
453
+ elif hop_bag is not None and str(hop_bag.get('table') or '') == key:
454
+ hits.append(f'{table_key}:{field.get("key")}')
455
+ continue
456
+ if str(target['database']) and str(table_key) != str(target['database']):
457
+ continue
458
+ if hop == key or str(bag.get('field') or '') == key:
459
+ hits.append(f'{table_key}:{field.get("key")}')
460
+ elif source and key in (str(source.get('on') or ''), str(source.get('groupBy') or ''),
461
+ str(source.get('measure') or '')):
462
+ hits.append(f'{table_key}:{field.get("key")}')
463
+ return _dependent('rollup', hits)
464
+
465
+
466
+ def grant_dependents(st, target):
467
+ """People who would lose access, read straight off the grant registry.
468
+
469
+ * view -> `shares.grants('view', <id>)` — R32's "who it is shared to"
470
+ * table -> the `database` grant plus every `field` grant on that database's columns
471
+ * field -> the `field` grant on `<database>:<key>`
472
+ """
473
+ kind, key, database = target['kind'], target['key'], target['database']
474
+ if kind == 'view':
475
+ return _dependent('grant', share_audience(st, key)['names'])
476
+ if kind == 'field':
477
+ if not database:
478
+ return None
479
+ record = shares.grants('field', shares.field_oid(database, key), st=st)
480
+ return _dependent('grant', [str(e.get('user') or '') for e in (record.get('entries') or ())])
481
+ holders = [str(e.get('user') or '')
482
+ for e in (shares.grants('database', key, st=st).get('entries') or ())]
483
+ try:
484
+ field_oids = shares.granted_oids('field', st=st)
485
+ except Exception:
486
+ field_oids = ()
487
+ for oid in field_oids:
488
+ table_key, field_key = shares.split_field_oid(oid)
489
+ if table_key != key or not field_key:
490
+ continue
491
+ for entry in (shares.grants('field', oid, st=st).get('entries') or ()):
492
+ holders.append(str(entry.get('user') or ''))
493
+ return _dependent('grant', holders)
494
+
495
+
496
+ def chart_dependents(st, target):
497
+ """Saved charts filed against the target DATABASE.
498
+
499
+ ⛔ A CHART NEVER DEPENDS ON A VIEW, and that is `chart_system`'s stated contract rather than an
500
+ omission here: a chart's `config` is OPAQUE and this file must not start reading keys out of
501
+ it to guess at a reference. Deleting a view cannot delete a chart, so it must not disclose one.
502
+ """
503
+ kind, key = target['kind'], target['key']
504
+ if kind != 'table':
505
+ return None
506
+ return _dependent('chart', [str(c.get('id')) for c in _charts(st)
507
+ if str(c.get('database') or '') == key])
508
+
509
+
510
+ register('view', view_dependents)
511
+ register('route', route_dependents)
512
+ register('link', link_dependents)
513
+ register('rollup', rollup_dependents)
514
+ register('grant', grant_dependents)
515
+ register('chart', chart_dependents)
platform/core/grid_events.py CHANGED
@@ -1570,7 +1570,7 @@ def handle_one(event, ctx):
1570
  import core.shares as _shares
1571
  if _shares.role_for('view', view_id, uname,
1572
  st=getattr(_tops(ctx), 'st', None)) != 'edit':
1573
- ctx.out.toast = ('That view is shared with you read-only — ask its '
1574
  'owner for edit access.')
1575
  return False
1576
  view['createdBy'] = _stored.get('createdBy', _o_uname)
 
1570
  import core.shares as _shares
1571
  if _shares.role_for('view', view_id, uname,
1572
  st=getattr(_tops(ctx), 'st', None)) != 'edit':
1573
+ ctx.out.toast = ('That view is shared with you read-only. Ask its '
1574
  'owner for edit access.')
1575
  return False
1576
  view['createdBy'] = _stored.get('createdBy', _o_uname)
platform/core/keychain.py CHANGED
@@ -221,6 +221,13 @@ def odoo_creds(rt):
221
  def meta_creds(rt):
222
  """W31 (R2): the FIRST `meta_ads` entry's fields, else None — the Meta connector's resolver.
223
 
 
 
 
 
 
 
 
224
  ⛔ IT IS DELIBERATELY THE SAME SHAPE AS `odoo_creds` AND SHARES ITS IMPLEMENTATION, because
225
  "which stored credential serves this connector?" is ONE question and this module was one
226
  copy-paste away from having two answers to it ([[one-question-two-normalizers]]). The
 
221
  def meta_creds(rt):
222
  """W31 (R2): the FIRST `meta_ads` entry's fields, else None — the Meta connector's resolver.
223
 
224
+ ⭐⭐ W49-T13 / D-202 — IT HAS A PRODUCTION CALLER NOW, AND THAT WAS THE WHOLE DEFECT.
225
+ `harness/meta_store.py::token` read `META_ADS_ACCESS_TOKEN` unconditionally, so this resolver
226
+ existed, was correct, and was reached by nothing: a tenant's stored Meta credential was
227
+ accepted, previewed and testable while every sync ran on the deployment's own token. The
228
+ loader now asks here FIRST and falls back to the environment only. Deleting this function
229
+ because "nothing calls it" would have been the wrong repair to the same reading.
230
+
231
  ⛔ IT IS DELIBERATELY THE SAME SHAPE AS `odoo_creds` AND SHARES ITS IMPLEMENTATION, because
232
  "which stored credential serves this connector?" is ONE question and this module was one
233
  copy-paste away from having two answers to it ([[one-question-two-normalizers]]). The
platform/core/monid.py ADDED
@@ -0,0 +1,651 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """core/monid.py — the Monid aggregated-connection client. W49-T19, ruling R31, contract C5.
2
+
3
+ ⭐⭐ R31, verbatim: *"Monid's one working slice is Amazon reviews for our ASINs, landing as a
4
+ database linkable to Odoo products."*
5
+
6
+ Monid (https://api.monid.ai) is a paid AGGREGATOR: one key, one wallet, and several hundred
7
+ third-party endpoints behind five verbs. This module is the whole of our side of it.
8
+
9
+ ⛔⛔ EVERY `run()` SPENDS REAL MONEY, AND THE WALLET HELD $1.00 WHEN THIS WAS WRITTEN.
10
+ `discover`, `inspect` and `balance` are FREE and may be called freely. `run` and `poll` are not,
11
+ and `run` is the only one that debits. There is no dry-run mode and no sandbox key, so the only
12
+ honest way to build against this is a RECORDED FIXTURE plus a deterministic mapping — which is
13
+ what `columns_from_rows` below is, and what `verify_meta.py` exercises.
14
+
15
+ ⛔⛔ THE KEY NEVER LEAVES THIS MODULE. `MONID_API_KEY` is read from `platform/.env` inside
16
+ `_key()`, put straight into an Authorization header, and never returned, logged, formatted into a
17
+ message or stored. `MonidError` carries the server's own `{code, message}` and nothing else;
18
+ `_headers()` is deliberately private and is never handed to a caller. `verify_meta.py`'s
19
+ `section_monid_secret` proves the negative by stuffing a sentinel into the environment and
20
+ asserting it is absent from `json.dumps` of every payload this module hands upward.
21
+
22
+ ⛔ 402 IS A REFUSAL, NOT A RETRY (C5). An empty wallet is a fact about the account, not a
23
+ transient fault: retrying it spends nothing and tells the operator nothing, so it raises
24
+ `MonidWalletEmpty` whose message is exactly "Monid wallet is empty" and stops.
25
+
26
+ ⚠ THE ENDPOINT IS RECORDED, NOT REDISCOVERED. `discover("amazon reviews")` chose
27
+ `apify /axesso_data/amazon-reviews-scraper` on 2026-09-02 and the losing candidates are written
28
+ down in `.claude/wiki/waves/wave49/proto/monid-research.md`. Re-running discover at request time
29
+ would let a ranking change silently move which vendor we pay; the constants below are the
30
+ decision, and `discover` remains available for the next slice.
31
+
32
+ ⚠ `inspect` RETURNS NO OUTPUT SCHEMA. Its complete top-level key set, measured, is
33
+ `provider providerName endpoint description summary method input price docUrl notes tags
34
+ categories metrics hints` — `input` only. C5's sentence about deriving columns from "inspect's
35
+ output schema" describes something the API does not have, so the derivation is
36
+ `columns_from_rows`: a deterministic key union over the rows the run actually returned.
37
+
38
+ ⚠ A RUN CAN OUTLIVE THE SYNC WINDOW. The endpoint's own `metrics` put `runTimeMs` p50 at 25,092
39
+ and p95 at 51,550, so `run()` handles BOTH a 200 with the result inline and a 202 with a run id
40
+ to poll. A client written only for the sync answer works in testing and times out in use.
41
+ """
42
+ import datetime as _dt
43
+ import os
44
+ import re
45
+ from pathlib import Path
46
+
47
+ import requests
48
+ from dotenv import load_dotenv
49
+
50
+ load_dotenv(Path(__file__).resolve().parents[1] / '.env')
51
+
52
+ #: The API root. http would work; https is what we send.
53
+ BASE = 'https://api.monid.ai'
54
+
55
+ #: Read timeouts. A run can take a minute (p95 51.5s), a free probe cannot.
56
+ PROBE_TIMEOUT = 30
57
+ RUN_TIMEOUT = 90
58
+
59
+ # ── THE RECORDED SLICE (R31). Measured 2026-09-02 by `POST /v1/discover
60
+ # {"query":"amazon reviews","limit":8}` and confirmed by `POST /v1/inspect`.
61
+ AMAZON_REVIEWS_PROVIDER = 'apify'
62
+ AMAZON_REVIEWS_ENDPOINT = '/axesso_data/amazon-reviews-scraper'
63
+ #: PER_RESULT at this price per RESULT. The unit price is real and measured. What a "result" IS
64
+ #: was not, and that is the whole of what follows.
65
+ #:
66
+ #: ⛔⛔ THE VENDOR'S OWN `price.notes` IS FALSE, AND THE FIRST LIVE RUN PROVED IT. The note
67
+ #: reads "One result is returned per input query. Total results and cost scale with the number of
68
+ #: queries provided." Measured 2026-09-02 on run `01M1H28SAG2RHBJ4JNCJX1P2V2`: TWO ASINs returned
69
+ #: `resultCount: 20` and `billedUnits: 20`, and the wallet went 1.000 to 0.973, a charge of USD
70
+ #: 0.027. That is TEN TIMES what "one result per query" predicts. A result is one REVIEW RETURNED,
71
+ #: and how many reviews an ASIN carries is not knowable before the call.
72
+ #:
73
+ #: ⛔ SO NOTHING MAY QUOTE A TOTAL IN ADVANCE. `estimate_cost` is a FLOOR, the dialog states the
74
+ #: per-review price instead of an arithmetic total, and the ledger records the charge the RUN
75
+ #: reports rather than one we computed. A confident wrong number costs the owner money in the one
76
+ #: direction that matters.
77
+ AMAZON_REVIEWS_UNIT_PRICE = 0.00135
78
+ AMAZON_REVIEWS_CURRENCY = 'USD'
79
+ #: There is NO result-limit parameter and no `maxResults` on this endpoint, so nothing on our side
80
+ #: bounds the charge. `maxPages` bounds the pages fetched per ASIN and is the only lever we hold.
81
+ AMAZON_REVIEWS_PRICE_KIND = 'PER_RESULT'
82
+
83
+ #: The landing database R31 names. `user_tables._slug("Amazon reviews")` is `amazon_reviews`, so
84
+ #: `create_table` mints exactly this key the first time and `<key>_2` every time after — which is
85
+ #: why the route reuses an existing table instead of asking for a second one.
86
+ TABLE_KEY = 'ut_amazon_reviews'
87
+ TABLE_LABEL = 'Amazon reviews'
88
+
89
+ #: The tenant store document C5 names. One list of runs, appended to, never overwritten.
90
+ SPEND_DOC = 'monid_spend'
91
+
92
+ #: ⛔ THE ONE SENTENCE FOR AN EMPTY WALLET (C5), and it is exact. The dialog prints what the
93
+ #: server sends, so this string is the only place it is authored.
94
+ WALLET_EMPTY_MESSAGE = 'Monid wallet is empty'
95
+
96
+
97
+ class MonidError(RuntimeError):
98
+ """A refusal from Monid, carrying its own `{code, message}` and nothing of ours.
99
+
100
+ ⛔ NO REQUEST ECHO. An exception that repeated the request would carry the Authorization
101
+ header into a traceback, and a traceback is a log line.
102
+ """
103
+
104
+ def __init__(self, code, message, status=0):
105
+ self.code = str(code or 'monid_error')
106
+ self.message = str(message or 'Monid refused the request.')
107
+ self.status = int(status or 0)
108
+ super().__init__(self.message)
109
+
110
+
111
+ class MonidWalletEmpty(MonidError):
112
+ """402. Never retried, never invented (C5)."""
113
+
114
+ def __init__(self, message=None):
115
+ super().__init__('wallet_empty', message or WALLET_EMPTY_MESSAGE, 402)
116
+
117
+
118
+ def _key():
119
+ """The API key, or '' when nobody has provisioned one.
120
+
121
+ ⛔ THE ONLY READER OF THE SECRET. It is returned to `_headers` and to `configured()`'s
122
+ truth test, and to nothing else. It is never printed and never put in a message.
123
+ """
124
+ return str(os.environ.get('MONID_API_KEY') or '').strip()
125
+
126
+
127
+ def configured():
128
+ """Whether a key exists. A BOOLEAN, deliberately: the caller needs to know whether the door
129
+ is usable, never what is behind it."""
130
+ return bool(_key())
131
+
132
+
133
+ def _headers():
134
+ """Private, and it stays private. Handing this dict to a caller would hand out the key."""
135
+ return {'Authorization': 'Bearer ' + _key(), 'Content-Type': 'application/json'}
136
+
137
+
138
+ def _call(method, path, body=None, timeout=PROBE_TIMEOUT):
139
+ """One request, one error shape.
140
+
141
+ ⛔ THE RESPONSE IS THE ONLY THING THAT COMES BACK. No headers, no request, no key.
142
+ """
143
+ if not configured():
144
+ raise MonidError('not_configured',
145
+ 'Monid is not connected in this workspace. An administrator adds the '
146
+ 'key before a pull can run.')
147
+ url = BASE + path
148
+ try:
149
+ res = requests.request(method, url, headers=_headers(), json=body, timeout=timeout)
150
+ except requests.RequestException:
151
+ # ⚠ THE EXCEPTION IS SWALLOWED ON PURPOSE. `requests` puts the full URL in its own
152
+ # message and, on some transports, the request headers in `__context__`.
153
+ raise MonidError('unreachable', 'Cannot reach Monid.')
154
+ if res.status_code == 402:
155
+ raise MonidWalletEmpty()
156
+ try:
157
+ payload = res.json()
158
+ except ValueError:
159
+ payload = None
160
+ if res.status_code >= 400:
161
+ err = (payload or {}).get('error') if isinstance(payload, dict) else None
162
+ if isinstance(err, dict):
163
+ raise MonidError(err.get('code'), err.get('message'), res.status_code)
164
+ if isinstance(payload, dict) and ('code' in payload or 'message' in payload):
165
+ raise MonidError(payload.get('code'), payload.get('message'), res.status_code)
166
+ raise MonidError('http_' + str(res.status_code),
167
+ 'Monid answered ' + str(res.status_code) + '.', res.status_code)
168
+ return res.status_code, (payload if payload is not None else {})
169
+
170
+
171
+ # ── THE FIVE VERBS C5 NAMES ───────────────────────────────────────────────────────────────────
172
+
173
+ def discover(query, limit=8):
174
+ """FREE. Rank endpoints against a plain-language query. Returns the payload as sent."""
175
+ _, payload = _call('POST', '/v1/discover',
176
+ {'query': str(query or ''), 'limit': int(limit or 8)})
177
+ return payload
178
+
179
+
180
+ def inspect(provider, endpoint):
181
+ """FREE. One endpoint's description, input schema, price, metrics and hints.
182
+
183
+ ⚠ There is no output schema in the answer. See the module docstring.
184
+ """
185
+ _, payload = _call('POST', '/v1/inspect',
186
+ {'provider': str(provider), 'endpoint': str(endpoint)})
187
+ return payload
188
+
189
+
190
+ def run(provider, endpoint, input): # noqa: A002 - `input` is Monid's own field name
191
+ """⛔⛔ PAID. One call, one debit. Returns `(status, payload)`.
192
+
193
+ `input` WRAPS the body; it is not the body. The endpoint's own hint is
194
+ `{"provider":..., "endpoint":..., "input":{"body":<BODY>, "queryParams":..., "pathParams":...}}`
195
+ and getting that wrong sends an empty request to a paid endpoint.
196
+
197
+ `status` is 200 when the result came back inline and 202 when Monid answered with a run id to
198
+ poll. The caller branches on it; this function never polls on its own, because a poll loop
199
+ hidden inside a paid call is a spend nobody chose.
200
+
201
+ ⛔⛔ IF YOU LOSE THIS RETURN VALUE, THE MONEY IS ALREADY GONE. The two-tuple has been
202
+ mishandled once for real: the first live run's payload was dropped by a caller-side error
203
+ AFTER the wallet had been debited. DO NOT CALL THIS AGAIN to recover it. `runs(limit)` is
204
+ free, lists recent runs with their ids and provider responses, and is the recovery path.
205
+
206
+ ⚠ The completed payload carries `cost`, `billedUnits` and `resultCount`. `cost` is the
207
+ authority on what was charged; read it with `payload_cost` and never recompute it.
208
+ """
209
+ return _call('POST', '/v1/run',
210
+ {'provider': str(provider), 'endpoint': str(endpoint), 'input': input},
211
+ timeout=RUN_TIMEOUT)
212
+
213
+
214
+ def poll(run_id):
215
+ """The state of a run started earlier. Returns the payload as sent."""
216
+ _, payload = _call('GET', '/v1/runs/' + str(run_id), timeout=RUN_TIMEOUT)
217
+ return payload
218
+
219
+
220
+ def balance():
221
+ """FREE. `{"balance": {"value", "currency"}, "held": {...}}`."""
222
+ _, payload = _call('GET', '/v1/wallet/balance')
223
+ return payload
224
+
225
+
226
+ def runs(limit=20):
227
+ """⭐⭐ FREE, UNDOCUMENTED, AND THE ONLY WAY BACK FROM A LOST PAID RESPONSE.
228
+
229
+ `GET /v1/runs?limit=N` answers `{"items": [{runId, caller, provider, providerName, endpoint,
230
+ status, providerResponse, price, ...}]}`. It is in no documentation and no `hints` block; it
231
+ was found on 2026-09-02 by the lead, after a caller-side error dropped the response to a run
232
+ that had ALREADY BEEN CHARGED.
233
+
234
+ ⛔ THAT IS WHY IT LIVES HERE RATHER THAN IN A NOTE. Without it, a dropped response means
235
+ paying for the same reviews twice: the money is gone, the run id is gone, and the only way to
236
+ get the rows is to run again. With it, the run is recoverable for nothing. Reach for this
237
+ BEFORE ever re-running a call that failed on our side rather than at Monid.
238
+ """
239
+ _, payload = _call('GET', '/v1/runs?limit=' + str(int(limit or 20)))
240
+ return payload
241
+
242
+
243
+ # ── THE SPEND LEDGER (C5) ─────────────────────────────────────────────────────────────────────
244
+
245
+ def record_spend(tenant, provider, endpoint, cost, run_id, st=None, estimated=False):
246
+ """Append one run to the tenant store document `monid_spend`.
247
+
248
+ ⛔ APPEND, NEVER OVERWRITE, AND THE APPEND HAPPENS INSIDE THE UPDATE FUNCTION. The store
249
+ retries `fn` against the freshest document on a conflict, so a row built from a document read
250
+ outside `fn` would be written on top of a concurrent run's row
251
+ ([[a-test-double-must-carry-the-strict-reader]] is the sibling lesson: the doubles have to
252
+ carry the real read).
253
+
254
+ ⚠ NO KEY, NO INPUT, NO RESULT. The ledger answers "what did we pay and for what", which is
255
+ five fields. Storing the request would put ASINs and, worse, a header into a document that
256
+ gets served.
257
+ """
258
+ import core.store as store
259
+
260
+ row = {
261
+ 'ts': _dt.datetime.now().strftime('%Y-%m-%dT%H:%M:%S'),
262
+ 'tenant': str(tenant or ''),
263
+ 'provider': str(provider or ''),
264
+ 'endpoint': str(endpoint or ''),
265
+ 'cost': round(float(cost or 0), 6),
266
+ 'run_id': str(run_id or ''),
267
+ # ⭐⭐ THE SEVENTH FIELD, AND IT IS A DELIBERATE DEPARTURE FROM C5's SIX.
268
+ #
269
+ # C5 specifies `{ts, tenant, provider, endpoint, cost, run_id}`. That shape assumed our
270
+ # arithmetic WAS the charge, and the first live run destroyed the assumption: the vendor's
271
+ # pricing note is false, 2 ASINs billed 20 units, and the computed figure was wrong by
272
+ # 10x. A ledger that cannot distinguish a cost the run REPORTED from one we GUESSED is a
273
+ # ledger whose every row has to be treated as a guess, which is worse than no ledger. So
274
+ # `False` means the run reported this number and it reconciles to the wallet; `True` means
275
+ # nothing was reported and this is `estimate_cost`'s FLOOR, which is known to under-read.
276
+ 'estimated': bool(estimated),
277
+ }
278
+
279
+ def _append(cur):
280
+ doc = cur if isinstance(cur, dict) else {}
281
+ runs = doc.get('runs')
282
+ doc['runs'] = (list(runs) if isinstance(runs, list) else []) + [row]
283
+ return doc
284
+
285
+ target = st if st is not None else store
286
+ target.update(SPEND_DOC, _append, flush='sync')
287
+ return row
288
+
289
+
290
+ def settle_spend(run_id, cost, st=None):
291
+ """⭐⭐ REPLACE AN ESTIMATED LEDGER ROW WITH THE CHARGE THE RUN FINALLY REPORTED.
292
+
293
+ ⛔ THE TWO WRITES EXIST BECAUSE THE MONEY AND THE NUMBER ARRIVE AT DIFFERENT TIMES. A 202
294
+ debits the wallet immediately and reports no `cost` until it completes, so the row has to be
295
+ written at once (or a crash mid-poll loses the spend entirely) and CORRECTED when the real
296
+ figure lands. Writing only after the poll would be a ledger that is accurate exactly when
297
+ nothing went wrong.
298
+
299
+ ⚠ IT AMENDS, IT DOES NOT APPEND. Matching on `run_id` and clearing `estimated` keeps one
300
+ row per run; a second row would double-count the charge, which is the same lie as missing it.
301
+ Returns True when a row was amended.
302
+ """
303
+ import core.store as store
304
+
305
+ value = round(float(cost), 6)
306
+ hit = [False]
307
+
308
+ def _settle(cur):
309
+ doc = cur if isinstance(cur, dict) else {}
310
+ rows = doc.get('runs')
311
+ rows = list(rows) if isinstance(rows, list) else []
312
+ for row in rows:
313
+ if isinstance(row, dict) and str(row.get('run_id') or '') == str(run_id or ''):
314
+ row['cost'] = value
315
+ row['estimated'] = False
316
+ hit[0] = True
317
+ doc['runs'] = rows
318
+ return doc
319
+
320
+ (st if st is not None else store).update(SPEND_DOC, _settle, flush='sync')
321
+ return hit[0]
322
+
323
+
324
+ def spend_rows(st=None):
325
+ """The ledger, oldest first. A read for the operator, and it carries no secret to redact."""
326
+ import core.store as store
327
+
328
+ doc = (st if st is not None else store).get(SPEND_DOC) or {}
329
+ runs = doc.get('runs') if isinstance(doc, dict) else None
330
+ return list(runs) if isinstance(runs, list) else []
331
+
332
+
333
+ # ── THE MAPPING C5 ASKS FOR, AND THE REASON IT LOOKS LIKE THIS ────────────────────────────────
334
+
335
+ #: Keys we never make a column of. `_` prefixed keys are Apify's own bookkeeping and a column
336
+ #: made of one is a column nobody asked for on every row.
337
+ _SKIP_KEYS = ('#debug',)
338
+
339
+ #: Anything longer than this is prose, not a cell, and it lands as `text` anyway. The constant
340
+ #: exists so the choice is visible rather than a magic number inside a branch.
341
+ _LONG_TEXT = 200
342
+
343
+
344
+ #: The words that read wrong in lower case. Small on purpose: a growing list of exceptions is a
345
+ #: sign the rule is wrong, and these three are the ones this endpoint actually returns.
346
+ _ACRONYMS = {'asin', 'url', 'id'}
347
+
348
+
349
+ def _words(raw):
350
+ """A vendor key to its words. ⚠ THE CAMEL SPLIT HAPPENS BEFORE THE LOWERCASE, and that order
351
+ is the whole function: lowering first turns `variationList` into one word, so the column key
352
+ comes out `variationlist` and the header reads `Variationlist`. Measured on the recorded
353
+ fixture, not reasoned about."""
354
+ spaced = re.sub(r'([a-z0-9])([A-Z])', r'\1 \2', str(raw or ''))
355
+ spaced = re.sub(r'([A-Z]+)([A-Z][a-z])', r'\1 \2', spaced)
356
+ return [w for w in re.split(r'[^A-Za-z0-9]+', spaced) if w]
357
+
358
+
359
+ def _column_key(raw):
360
+ """A record key to a stable column key: lower snake case, capped the way `user_tables._slug`
361
+ caps a table key, so a column key and a table key are built by one rule rather than two."""
362
+ s = '_'.join(w.lower() for w in _words(raw))
363
+ return (s or 'field')[:40]
364
+
365
+
366
+ def _column_label(raw):
367
+ """`variationList` to `Variation list`. SENTENCE CASE (DESIGN.md §2), which means every word
368
+ after the first goes lower unless it is one of the three acronyms above. Title Case headers
369
+ are the ALL-CAPS chrome rule's quieter cousin and this grid would have been full of them."""
370
+ words = _words(raw)
371
+ if not words:
372
+ return 'Field'
373
+ out = []
374
+ for i, w in enumerate(words):
375
+ low = w.lower()
376
+ if low in _ACRONYMS:
377
+ out.append(low.upper())
378
+ elif i == 0:
379
+ out.append(low[0].upper() + low[1:])
380
+ else:
381
+ out.append(low)
382
+ return ' '.join(out)
383
+
384
+
385
+ def _column_type(values):
386
+ """The narrowest `user_tables` type every observed value fits.
387
+
388
+ ⛔⛔ A WRONG TYPE HERE REFUSES THE WHOLE IMPORT AFTER THE MONEY IS ALREADY SPENT, and that is
389
+ not a hypothetical: the first version of this function typed a 0-to-5 decimal as `rating`, the
390
+ vendor's `rating` came back as `5.0`, and `user_tables.cell_type_refusal` answered *"'5.0' is
391
+ not a whole number, and 'Rating' holds a rating. Nothing was imported"*. The run had already
392
+ been paid for. So the rule below is not about tidiness, it is about never handing the import
393
+ door a column it will reject.
394
+
395
+ ⚠ FAIL-WIDE, NOT FAIL-NARROW, and two types are never derived at all:
396
+ * `rating` takes a WHOLE number from 1 to 5, and a vendor's average is a decimal.
397
+ * `date` demands a `YYYY-MM-DD` prefix, and this vendor sends "Reviewed on August 1, 2026".
398
+ Both would refuse a paid import. `checkbox`, `json`, `url` and `text` cannot refuse anything;
399
+ `int` is checked below against the door's own validator rather than trusted.
400
+ """
401
+ seen = [v for v in values if v is not None and v != '']
402
+ if not seen:
403
+ return 'text'
404
+ if all(isinstance(v, bool) for v in seen):
405
+ return 'checkbox'
406
+ if all(isinstance(v, int) and not isinstance(v, bool) for v in seen):
407
+ return 'int'
408
+ if all(isinstance(v, (int, float)) and not isinstance(v, bool) for v in seen):
409
+ # ⛔ NO FLOAT TYPE EXISTS IN `user_tables`, and the two candidates both lie: `rating` is
410
+ # refused outright, and `int` would call 4.7 a whole number. `text` keeps the value.
411
+ return 'text'
412
+ if all(isinstance(v, str) and v.startswith(('http://', 'https://')) for v in seen):
413
+ return 'url'
414
+ if all(isinstance(v, (dict, list)) for v in seen):
415
+ return 'json'
416
+ return 'text'
417
+
418
+
419
+ def _survives_the_door(ftype, label, values):
420
+ """⭐⭐ ONE AUTHORITY ON WHAT A CELL MAY BE, AND IT IS THE DOOR'S OWN.
421
+
422
+ `core.user_tables.cell_type_refusal` is the function the import actually runs. Mirroring its
423
+ rules here would be a second engine for one question, and a disagreement between two engines
424
+ is accepted on write and refused on read with nothing having gone red
425
+ ([[two-gates-can-assert-opposite-things]] is the same shape one layer up). So this CALLS it,
426
+ against the STRINGIFIED value `add_rows` will really write, and any refusal downgrades the
427
+ column to `text` before the table is ever created.
428
+
429
+ ⚠ Both modules live in `core/`, so this is a sideways import and not a layer violation.
430
+ """
431
+ try:
432
+ from core import user_tables as _ut
433
+ except Exception: # pragma: no cover - a caller without the data layer keeps the guess
434
+ return True
435
+ field = {'type': ftype, 'label': label}
436
+ for v in values:
437
+ if v is None or v == '' or isinstance(v, (dict, list)):
438
+ continue
439
+ if _ut.cell_type_refusal(field, str(v)):
440
+ return False
441
+ return True
442
+
443
+
444
+ def columns_from_rows(rows, max_columns=60):
445
+ """⭐⭐ THE COLUMN DERIVATION, AND IT IS A KEY UNION OVER REAL ROWS BECAUSE THERE IS NO
446
+ OUTPUT SCHEMA TO DERIVE FROM.
447
+
448
+ C5 says the landing table's columns come from `inspect`'s output schema. Measured, `inspect`
449
+ returns no output schema at all: its answer describes the INPUT and the price. So the columns
450
+ come from the run's own records, by a rule with three properties that matter:
451
+
452
+ 1. DETERMINISTIC. The order is FIRST-SEEN across the records in the order they arrived, so
453
+ the same result set always builds the same table and a re-import lands in the same
454
+ columns. Sorting alphabetically instead would reorder the grid every time a vendor added
455
+ a field.
456
+ 2. TOTAL. Every key any record carries becomes a column, so a field present on one review
457
+ in a thousand is not silently dropped. That is the failure mode a schema would have
458
+ protected us from and a "columns of the first row" rule would reintroduce.
459
+ 3. TYPED FROM EVIDENCE. `_column_type` looks at every observed value, not the first.
460
+
461
+ Returns the `fields` list `routes_tables.create_table` takes. The identity column comes first
462
+ and is always `text`: `user_tables.create` gives a blank table a `name` column for exactly
463
+ this reason, and a review needs one thing to be listed by.
464
+ """
465
+ order = []
466
+ values = {}
467
+ for rec in (rows or []):
468
+ if not isinstance(rec, dict):
469
+ continue
470
+ for raw in rec.keys():
471
+ if raw in _SKIP_KEYS or str(raw).startswith('_'):
472
+ continue
473
+ key = _column_key(raw)
474
+ if key not in values:
475
+ if len(order) >= max_columns:
476
+ continue
477
+ order.append((key, raw))
478
+ values[key] = []
479
+ values[key].append(rec.get(raw))
480
+ fields = []
481
+ for key, raw in order:
482
+ label = _column_label(raw)
483
+ ftype = _column_type(values[key])
484
+ # ⛔⛔ THE LAST GUARD BEFORE MONEY BECOMES A REFUSAL. Whatever the rule above decided, the
485
+ # column only ships with that type if the import door itself accepts every value we have
486
+ # seen for it. Anything else falls back to `text`, which the door never refuses.
487
+ if not _survives_the_door(ftype, label, values[key]):
488
+ ftype = 'text'
489
+ fields.append({
490
+ 'key': key,
491
+ 'label': label,
492
+ 'type': ftype,
493
+ # ⛔ THE PROVENANCE IS NOT DECORATION. `origin` and `valueAuthority` are what tell the
494
+ # grid these cells are a vendor's record rather than something a colleague typed, and
495
+ # they are what a later read-only rule would key on.
496
+ 'origin': 'loopable',
497
+ 'valueAuthority': 'source',
498
+ 'scope': 'source',
499
+ })
500
+ if not fields:
501
+ fields = [{'key': 'name', 'label': 'Name', 'type': 'text',
502
+ 'origin': 'loopable', 'valueAuthority': 'source', 'scope': 'source'}]
503
+ return fields
504
+
505
+
506
+ def rows_for_import(rows, fields):
507
+ """The records reshaped onto the derived column keys.
508
+
509
+ ⚠ A VALUE THAT IS NOT A SCALAR IS SERIALISED, NOT DROPPED. A nested `variant` object is data
510
+ the vendor charged us for; losing it to keep the cell tidy is the quiet half of C5's
511
+ "never invented".
512
+
513
+ ⛔ A KEY THE RECORD DOES NOT CARRY IS ABSENT, NOT NULL, and the difference is not cosmetic.
514
+ The columns are a UNION over every record, so most records are missing some of them. Writing
515
+ an explicit `None` into each would make "the vendor sent no badge for this review" and "the
516
+ vendor sent an empty badge" the same cell, and the grid has no way back from that.
517
+ """
518
+ import json as _json
519
+
520
+ by_key = {}
521
+ for rec in (rows or []):
522
+ if isinstance(rec, dict):
523
+ for raw in rec.keys():
524
+ by_key.setdefault(_column_key(raw), raw)
525
+ out = []
526
+ for rec in (rows or []):
527
+ if not isinstance(rec, dict):
528
+ continue
529
+ row = {}
530
+ for f in fields:
531
+ raw = by_key.get(f['key'])
532
+ if raw is None or raw not in rec:
533
+ continue
534
+ v = rec.get(raw)
535
+ if isinstance(v, (dict, list)):
536
+ v = _json.dumps(v, ensure_ascii=False)[:2000]
537
+ row[f['key']] = v
538
+ out.append(row)
539
+ return out
540
+
541
+
542
+ def extract_records(payload):
543
+ """The list of records inside whatever shape Monid wrapped the result in.
544
+
545
+ ⚠ THE WRAPPER IS NOT PROMISED. `inspect` describes the input and says nothing about the
546
+ envelope, so this reads the four shapes an aggregator plausibly sends and, failing all four,
547
+ returns an empty list rather than guessing. An empty list is visible in the response as
548
+ `"records": 0`; a guess would be a table full of the envelope's own keys.
549
+ """
550
+ if isinstance(payload, list):
551
+ return [r for r in payload if isinstance(r, dict)]
552
+ if not isinstance(payload, dict):
553
+ return []
554
+ for key in ('result', 'results', 'data', 'items', 'output', 'records'):
555
+ v = payload.get(key)
556
+ if isinstance(v, list):
557
+ return [r for r in v if isinstance(r, dict)]
558
+ if isinstance(v, dict):
559
+ inner = extract_records(v)
560
+ if inner:
561
+ return inner
562
+ return []
563
+
564
+
565
+ def estimate_cost(asin_count):
566
+ """⛔⛔ A FLOOR, NOT A PRICE, AND THE NAME IS THE ONLY HONEST PART OF IT.
567
+
568
+ This was written as exact arithmetic on the vendor's own pricing note, and the first live run
569
+ showed the note is false: 2 ASINs billed 20 units, so this function under-reported the real
570
+ charge by 10x. It survives as the LOWER BOUND (a run returns at least one result per ASIN, or
571
+ it returned nothing at all) and as the FALLBACK the ledger uses only when a run reports no
572
+ cost of its own. When it is used, the ledger row is stamped `estimated: True`, so a reader can
573
+ always tell a measured charge from a guessed one.
574
+
575
+ ⛔ IT MUST NOT BE SHOWN AS A TOTAL. `MonidRunDialog` states the per-review price instead.
576
+ """
577
+ return round(max(0, int(asin_count or 0)) * AMAZON_REVIEWS_UNIT_PRICE, 6)
578
+
579
+
580
+ def payload_cost(answer):
581
+ """⭐⭐ THE CHARGE THE RUN ITSELF REPORTS, or None when it reported none.
582
+
583
+ A completed run carries `cost: {"value": 0.027, "currency": "USD"}` beside `billedUnits` and
584
+ `resultCount`, and on the measured run that value matched the wallet delta EXACTLY. That makes
585
+ it the authority and our arithmetic the guess, which is the reverse of how this module was
586
+ first written.
587
+
588
+ ⚠ None IS A REAL ANSWER, NOT A ZERO. A run still going, or one whose envelope changes shape,
589
+ reports no cost; the caller then falls back to the floor and marks the row estimated, rather
590
+ than writing 0.00 into a ledger about money that certainly moved.
591
+ """
592
+ if not isinstance(answer, dict):
593
+ return None
594
+ cost = answer.get('cost')
595
+ if isinstance(cost, dict):
596
+ cost = cost.get('value')
597
+ if isinstance(cost, bool) or not isinstance(cost, (int, float)):
598
+ return None
599
+ return round(float(cost), 6)
600
+
601
+
602
+ #: An ASIN is ten characters, alphanumeric, and Amazon's own are uppercase.
603
+ _ASIN_RE = re.compile(r'^[A-Z0-9]{10}$')
604
+
605
+
606
+ def clean_asins(raw, limit=25):
607
+ """Pasted text to a de-duplicated ASIN list, order preserved.
608
+
609
+ ⛔ IT REFUSES RATHER THAN CORRECTS. A string that is not an ASIN is returned in the second
610
+ list so the dialog can name it; silently dropping it would let an operator pay for nine ASINs
611
+ believing they had asked for ten.
612
+ """
613
+ if isinstance(raw, (list, tuple)):
614
+ parts = [str(x) for x in raw]
615
+ else:
616
+ parts = re.split(r'[\s,;]+', str(raw or ''))
617
+ good, bad, seen = [], [], set()
618
+ for p in parts:
619
+ token = p.strip().upper()
620
+ if not token:
621
+ continue
622
+ if not _ASIN_RE.match(token):
623
+ bad.append(p.strip())
624
+ continue
625
+ if token in seen:
626
+ continue
627
+ seen.add(token)
628
+ if len(good) < limit:
629
+ good.append(token)
630
+ return good, bad
631
+
632
+
633
+ def amazon_reviews_body(asins, domain_code='com', sort_by='recent', max_pages=1):
634
+ """The exact `body` for the recorded endpoint, from `inspect`'s own input schema.
635
+
636
+ The schema is `{"input": [ {asin, domainCode, sortBy, maxPages, filterByStar,
637
+ filterByKeyword, reviewerType, formatType, mediaType} ]}` with `required: ["input"]` and
638
+ `bodyType: json`. One entry per ASIN, one paid result per entry.
639
+ """
640
+ return {'input': [{'asin': a,
641
+ 'domainCode': str(domain_code or 'com'),
642
+ 'sortBy': str(sort_by or 'recent'),
643
+ 'maxPages': int(max_pages or 1)} for a in (asins or [])]}
644
+
645
+
646
+ def amazon_reviews_input(asins, domain_code='com', sort_by='recent', max_pages=1):
647
+ """The `input` envelope `run()` takes. ⚠ `input` WRAPS `body`; passing the body straight
648
+ through is the trap the endpoint's hint exists to prevent, and it is a paid mistake."""
649
+ return {'body': amazon_reviews_body(asins, domain_code, sort_by, max_pages),
650
+ 'queryParams': {},
651
+ 'pathParams': {}}
platform/core/perm_scope.py CHANGED
@@ -138,6 +138,22 @@ def nav_may_open(user, key, st=None):
138
  3. a `ut_*` key with no explicit deny defers to `user_tables.may_open` — creator, admin or
139
  a `core.shares` grant — and **an `access: true` entry may NEVER widen past it**. The
140
  editor must not become a way to hand somebody another user's private table;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
141
  4. a REGISTRY TOPIC with an explicit entry takes that entry, grant included. Here the
142
  editor IS the authority: `_clean_perms` writes an entry for every governed topic on
143
  every save, so an entry means an administrator decided;
 
138
  3. a `ut_*` key with no explicit deny defers to `user_tables.may_open` — creator, admin or
139
  a `core.shares` grant — and **an `access: true` entry may NEVER widen past it**. The
140
  editor must not become a way to hand somebody another user's private table;
141
+ ⛔⛔ **AND LEG 3 IS THE ONE THAT NEEDS `st`. A CALLER THAT OMITS IT ASKS ABOUT THE WRONG
142
+ TENANT** (D-612, W49-T23). `user_tables._st(None)` falls back to the PROCESS-DEFAULT
143
+ store, so `nav_may_open(user, 'ut_x')` with no `st` answers against whichever tenant that
144
+ process happened to load — right only by coincidence, and wrong in BOTH directions:
145
+ it 403s a table the caller demonstrably owns, and it admits one that exists only in
146
+ another tenant's document under the same key. Legs 1, 2, 4 and 5 read the USER record
147
+ and are unaffected, which is precisely why the omission was invisible for every
148
+ registry topic and fatal for exactly one key family. Every door that can be handed a
149
+ `ut_*` key now threads its session's own runtime: `deps.Session.require`,
150
+ `routes_charts._require_database`, `routes_nav.nav` and `routes_tables` (both lending
151
+ the rows-free projection) and `routes_admin.get_perms`. The two callers that still omit
152
+ `st` are `perms.nav_pages`, which iterates `core.registry.REGISTRY` (a compiled literal
153
+ carrying no `ut_` key — `verify_perm_scope.py` section K pins that, so the fence can go
154
+ red rather than merely being asserted here), and `routes_admin`'s surface DEFAULT, which
155
+ its own `m.get("surface")` test fences to registry rows. Neither can reach this leg;
156
+
157
  4. a REGISTRY TOPIC with an explicit entry takes that entry, grant included. Here the
158
  editor IS the authority: `_clean_perms` writes an entry for every governed topic on
159
  every save, so an entry means an administrator decided;
platform/core/sheets.py ADDED
@@ -0,0 +1,418 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """core/sheets.py — the Sheet WORKBOOK record (wave 49, instruction 1, ticket W49-T02).
2
+
3
+ WHAT GOES HERE:
4
+
5
+ A workbook is a store document per contract C1: key `sheet_workbook_<id>`, shape
6
+ `{id, name, sheets:[{id, name, cells:{"B4": Cell}}], rev, refreshed_at}`. This module owns the
7
+ document, its `rev`, and the CELL VOCABULARY that every later Sheet ticket consumes. It resolves
8
+ nothing: no aggregate, no formula, no permission decision.
9
+
10
+ ⭐ **THE VOCABULARY IS FROZEN HERE AND `verify_api.py` PROVES THE CLIENT AGREES.** `CELL_KINDS` and
11
+ `CELL_STATES` are the whole of it, name for name, and `web/src/sheet/types.ts` carries the same two
12
+ lists. A parity check compares them so the two halves cannot drift; adding a name on one side only
13
+ is what that check exists to catch.
14
+
15
+ ⛔ **THERE IS NO `chart` KIND, AND ADDING ONE IS A CONTRACT CHANGE, NOT A CONVENIENCE.** W49-T08
16
+ stores a chart as a sibling `charts:[{range, anchor, kind}]` array on the SHEET, precisely so a
17
+ chart never has to pretend to be a cell. Only the ROOT may amend C1.
18
+
19
+ ⭐ **WHY A PER-WORKBOOK DOCUMENT NEEDS AN INDEX.** C1 names the document key, which makes a
20
+ workbook cheap to read and cheap to write without touching its neighbours. It also means nothing
21
+ can enumerate workbooks, and two later tickets must: `GET /api/v1/sheets` lists them, and
22
+ W49-T10's dependents provider has to scan every one of them to answer "which Sheet cells bind to
23
+ this table". So this module keeps a companion index document, `sheet_workbooks`, holding only the
24
+ identity of each workbook. The index is a POINTER LIST, never a second copy of the content: if it
25
+ ever disagrees with a document, the document wins and `list_workbooks` simply omits what it cannot
26
+ read.
27
+
28
+ ⚠ ONE STORE (standing rule 5). Every write goes through `st.update(...)`, the store's own
29
+ read-modify-write under its lock. There is no file writer here and there must never be one.
30
+
31
+ ⚠ R10, the snapshot rule: `value` and `display` are stored as LAST COMPUTED and this module never
32
+ recomputes them. A cell goes stale by being marked stale, not by being read.
33
+ """
34
+
35
+ from __future__ import annotations
36
+
37
+ import copy
38
+ import json
39
+ import re
40
+ import uuid
41
+ from datetime import datetime, timezone
42
+
43
+ #: C1's document key. `<id>` is the workbook id.
44
+ WORKBOOK_KEY_PREFIX = "sheet_workbook_"
45
+
46
+ #: The companion pointer list. See the module note for why a per-document key needs one.
47
+ INDEX_KEY = "sheet_workbooks"
48
+
49
+ #: ⛔ THE FROZEN VOCABULARY (contract C1). `verify_api.py` asserts `web/src/sheet/types.ts` carries
50
+ #: exactly these, name for name.
51
+ CELL_KINDS = ("literal", "formula", "bound")
52
+ CELL_STATES = ("fresh", "stale", "typed", "refused")
53
+
54
+ #: A literal is ALWAYS this state (R19). Stated once, here, so no caller has to remember it.
55
+ LITERAL_STATE = "typed"
56
+
57
+ _MAX_NAME = 120
58
+ _MAX_ID = 80
59
+ _MAX_TEXT = 4000
60
+ _MAX_FORMULA = 4000
61
+ _MAX_DISPLAY = 400
62
+ _MAX_SHEETS = 50
63
+ _MAX_CELLS_PER_SHEET = 20000
64
+
65
+ #: A client may not park an unbounded blob in the tenant store. A BYTE CAP is not interpretation:
66
+ #: it never looks at a key, only at the serialized length. Mirrors `chart_system.MAX_CONFIG_BYTES`.
67
+ MAX_WORKBOOK_BYTES = 4 * 1024 * 1024
68
+
69
+ #: A stored address is plain A1 with no `$`. Anchoring is a property of a FORMULA's text, not of
70
+ #: the cell it lands in, so a `$` here would be a second way to say the same thing.
71
+ _ADDR = re.compile(r"^[A-Z]{1,3}[1-9][0-9]{0,6}$")
72
+
73
+ _ID_CLEAN = re.compile(r"[^a-z0-9_-]+")
74
+
75
+
76
+ class SheetRefusal(Exception):
77
+ """A named refusal, so a route can answer with a code instead of a stack trace.
78
+
79
+ ⚠ `message` reaches a screen, so it carries no em dash and no en dash (standing rule 2) and
80
+ names both the cause and the subject.
81
+ """
82
+
83
+ def __init__(self, code, message):
84
+ super().__init__(message)
85
+ self.code = code
86
+ self.message = message
87
+
88
+
89
+ def _now():
90
+ return datetime.now(timezone.utc).replace(microsecond=0).isoformat()
91
+
92
+
93
+ def workbook_key(workbook_id):
94
+ """C1's document key for one workbook."""
95
+ return WORKBOOK_KEY_PREFIX + _slug_id(workbook_id)
96
+
97
+
98
+ def _slug_id(raw):
99
+ slug = _ID_CLEAN.sub("", str(raw or "").strip().lower())[:_MAX_ID]
100
+ if not slug:
101
+ raise SheetRefusal("workbook_id_invalid", "That workbook id is not a valid id.")
102
+ return slug
103
+
104
+
105
+ def _text(raw, limit):
106
+ return str(raw if raw is not None else "").strip()[:limit]
107
+
108
+
109
+ def _read(st, key):
110
+ """One document, projected when the runtime offers a projection (never the whole store)."""
111
+ try:
112
+ projected = getattr(st, "get_projection", None)
113
+ if callable(projected):
114
+ return dict(projected(key, drop=()) or {})
115
+ return dict(st.get(key) or {})
116
+ except Exception:
117
+ return {}
118
+
119
+
120
+ def _persist(st, key, mutate, seed=None):
121
+ """Read-modify-write under the store's own lock, mirroring `chart_system._persist`."""
122
+ result = {}
123
+
124
+ def apply(current):
125
+ state = copy.deepcopy(current) if isinstance(current, dict) else {}
126
+ if seed:
127
+ for k, v in seed.items():
128
+ state.setdefault(k, copy.deepcopy(v))
129
+ next_state, value = mutate(state)
130
+ result["value"] = copy.deepcopy(value)
131
+ return next_state
132
+
133
+ st.update(key, apply, flush="sync")
134
+ return result.get("value")
135
+
136
+
137
+ def _json_safe(payload, what):
138
+ """Strictly JSON-serializable and under the byte cap, or a named refusal.
139
+
140
+ No `default=` coercion: the store persists JSON, and a value that only stringifies would be a
141
+ write that fails later, somewhere else.
142
+ """
143
+ try:
144
+ blob = json.dumps(payload)
145
+ except (TypeError, ValueError):
146
+ raise SheetRefusal("workbook_not_serializable",
147
+ "That " + what + " holds a value the store cannot save.")
148
+ if len(blob.encode("utf-8")) > MAX_WORKBOOK_BYTES:
149
+ raise SheetRefusal("workbook_too_large",
150
+ "That workbook is larger than the tenant store accepts.")
151
+ return payload
152
+
153
+
154
+ # ── the cell ─────────────────────────────────────────────────────────────────────────────────
155
+
156
+ def clean_cell(raw, addr=""):
157
+ """Normalize ONE cell, or raise `SheetRefusal` with a named code.
158
+
159
+ ⛔ THE REFUSAL IS NAMED AND THE UNKNOWN NAME IS NOT ECHOED BACK INTO THE DOCUMENT. An unknown
160
+ `kind` or `state` is refused rather than dropped, because dropping it would store a cell that
161
+ silently means something other than what the caller sent, and the caller would have no way to
162
+ know. That is the shape of a defect a gate cannot see.
163
+
164
+ ⚠ R19: a literal is `state:"typed"`, always, whatever the caller asked for. That is not a
165
+ correction of the caller, it is the definition of a literal.
166
+ """
167
+ if not isinstance(raw, dict):
168
+ raise SheetRefusal("cell_not_an_object", "A cell must be an object.")
169
+
170
+ kind = _text(raw.get("kind"), 40)
171
+ if kind not in CELL_KINDS:
172
+ raise SheetRefusal(
173
+ "cell_kind_unknown",
174
+ "A cell kind must be one of " + ", ".join(CELL_KINDS) + ".")
175
+
176
+ state = _text(raw.get("state"), 40) or ("typed" if kind == "literal" else "stale")
177
+ if state not in CELL_STATES:
178
+ raise SheetRefusal(
179
+ "cell_state_unknown",
180
+ "A cell state must be one of " + ", ".join(CELL_STATES) + ".")
181
+
182
+ if kind == "literal":
183
+ state = LITERAL_STATE
184
+
185
+ cell = {"kind": kind, "state": state}
186
+
187
+ if raw.get("text") is not None:
188
+ cell["text"] = _text(raw.get("text"), _MAX_TEXT)
189
+ if raw.get("formula") is not None:
190
+ cell["formula"] = _text(raw.get("formula"), _MAX_FORMULA)
191
+ if raw.get("display") is not None:
192
+ cell["display"] = _text(raw.get("display"), _MAX_DISPLAY)
193
+
194
+ #: R10: stored as last computed. This module does not look inside `value` and does not
195
+ #: recompute it; it only refuses what the store could not persist.
196
+ if "value" in raw:
197
+ cell["value"] = _json_safe(raw.get("value"), "cell value")
198
+
199
+ for key in ("binding", "source", "refusal"):
200
+ blob = raw.get(key)
201
+ if blob is None:
202
+ continue
203
+ if not isinstance(blob, dict):
204
+ raise SheetRefusal("cell_" + key + "_invalid",
205
+ "A cell " + key + " must be an object.")
206
+ cell[key] = _json_safe(copy.deepcopy(blob), "cell " + key)
207
+
208
+ if raw.get("refreshed_at") is not None:
209
+ cell["refreshed_at"] = _text(raw.get("refreshed_at"), 120)
210
+
211
+ return cell
212
+
213
+
214
+ def _clean_cells(raw, sheet_name=""):
215
+ if raw is None:
216
+ return {}
217
+ if not isinstance(raw, dict):
218
+ raise SheetRefusal("cells_not_an_object", "A sheet's cells must be an object.")
219
+ if len(raw) > _MAX_CELLS_PER_SHEET:
220
+ raise SheetRefusal("sheet_too_many_cells",
221
+ "That sheet holds more cells than one sheet accepts.")
222
+ out = {}
223
+ for addr, cell in raw.items():
224
+ key = _text(addr, 12).upper()
225
+ if not _ADDR.match(key):
226
+ raise SheetRefusal("cell_address_invalid",
227
+ "Cell address " + (key or str(addr)) + " is not an A1 address.")
228
+ out[key] = clean_cell(cell, addr=key)
229
+ return out
230
+
231
+
232
+ def _clean_sheet(raw, index=0):
233
+ if not isinstance(raw, dict):
234
+ raise SheetRefusal("sheet_not_an_object", "A sheet must be an object.")
235
+ name = _text(raw.get("name"), _MAX_NAME) or ("Sheet" + str(index + 1))
236
+ sid = _text(raw.get("id"), _MAX_ID) or uuid.uuid4().hex[:12]
237
+ return {"id": sid, "name": name, "cells": _clean_cells(raw.get("cells"), sheet_name=name)}
238
+
239
+
240
+ def _clean_sheets(raw):
241
+ if raw is None:
242
+ return []
243
+ if not isinstance(raw, list):
244
+ raise SheetRefusal("sheets_not_a_list", "A workbook's sheets must be a list.")
245
+ if len(raw) > _MAX_SHEETS:
246
+ raise SheetRefusal("workbook_too_many_sheets",
247
+ "That workbook holds more tabs than one workbook accepts.")
248
+ return [_clean_sheet(s, i) for i, s in enumerate(raw)]
249
+
250
+
251
+ # ── the workbook ─────────────────────────────────────────────────────────────────────────────
252
+
253
+ def new_workbook(name="", created_by="", workbook_id=""):
254
+ """The in-memory shape of a fresh workbook with ONE tab (R7: a workbook has tabs)."""
255
+ wid = _slug_id(workbook_id) if workbook_id else uuid.uuid4().hex[:12]
256
+ stamp = _now()
257
+ return {
258
+ "id": wid,
259
+ "name": _text(name, _MAX_NAME) or "Untitled workbook",
260
+ "sheets": [{"id": uuid.uuid4().hex[:12], "name": "Sheet1", "cells": {}}],
261
+ "rev": 1,
262
+ "refreshed_at": None,
263
+ "created_by": _text(created_by, _MAX_ID),
264
+ "created_at": stamp,
265
+ "updated_at": stamp,
266
+ }
267
+
268
+
269
+ def create_workbook(st, name="", created_by=""):
270
+ """Write a new `sheet_workbook_<id>` document and register it in the index."""
271
+ book = new_workbook(name=name, created_by=created_by)
272
+ _json_safe(book, "workbook")
273
+
274
+ def _apply(state):
275
+ return copy.deepcopy(book), book
276
+
277
+ _persist(st, workbook_key(book["id"]), _apply)
278
+ _index_upsert(st, book)
279
+ return book
280
+
281
+
282
+ def get_workbook(st, workbook_id):
283
+ """One workbook, or a named refusal when the document is not there."""
284
+ wid = _slug_id(workbook_id)
285
+ doc = _read(st, workbook_key(wid))
286
+ if not doc or not doc.get("id"):
287
+ raise SheetRefusal("workbook_missing",
288
+ "That workbook no longer exists.")
289
+ return doc
290
+
291
+
292
+ def put_workbook(st, workbook_id, raw, expect_rev=None):
293
+ """Replace a workbook's name and sheets, bumping `rev`.
294
+
295
+ ⛔ `id`, `created_by` and `created_at` are PRIOR-WINS: a client may not reassign a workbook by
296
+ sending a different id, and a client that never read the document cannot blank its provenance.
297
+
298
+ ⚠ `expect_rev` makes the write CONDITIONAL, and when it is not passed explicitly the `rev`
299
+ inside `raw` is used instead. That fallback is the safe default rather than a convenience: a
300
+ client that round-trips the document it read is carrying the rev it saw, and silently ignoring
301
+ it would turn every full-document save into last-writer-wins. Measured before it was written
302
+ this way: passing `{"rev": 1}` in the body against a document already at rev 2 was accepted and
303
+ overwrote it. Pass `expect_rev=False` to opt out deliberately.
304
+ """
305
+ wid = _slug_id(workbook_id)
306
+ if not isinstance(raw, dict):
307
+ raise SheetRefusal("workbook_not_an_object", "A workbook must be an object.")
308
+
309
+ if expect_rev is None:
310
+ expect_rev = raw.get("rev")
311
+ if expect_rev is False:
312
+ expect_rev = None
313
+
314
+ sheets = _clean_sheets(raw.get("sheets"))
315
+ name = _text(raw.get("name"), _MAX_NAME)
316
+ refreshed_at = raw.get("refreshed_at")
317
+ saved = {}
318
+
319
+ def _apply(state):
320
+ prior = state if state.get("id") else None
321
+ if prior is None:
322
+ raise SheetRefusal("workbook_missing", "That workbook no longer exists.")
323
+ if expect_rev is not None and int(prior.get("rev") or 0) != int(expect_rev):
324
+ raise SheetRefusal(
325
+ "workbook_revision_stale",
326
+ "That workbook changed somewhere else, so this save was not applied.")
327
+ book = dict(prior)
328
+ book["name"] = name or _text(prior.get("name"), _MAX_NAME) or "Untitled workbook"
329
+ book["sheets"] = sheets
330
+ book["rev"] = int(prior.get("rev") or 0) + 1
331
+ if refreshed_at is not None:
332
+ book["refreshed_at"] = _text(refreshed_at, 120) or None
333
+ book["updated_at"] = _now()
334
+ _json_safe(book, "workbook")
335
+ saved.update(book)
336
+ return book, book
337
+
338
+ _persist(st, workbook_key(wid), _apply)
339
+ _index_upsert(st, saved)
340
+ return saved
341
+
342
+
343
+ def delete_workbook(st, workbook_id):
344
+ """Empty the document and drop its index row. Returns True when something was there."""
345
+ wid = _slug_id(workbook_id)
346
+ existed = {}
347
+
348
+ def _apply(state):
349
+ existed["yes"] = bool(state.get("id"))
350
+ return {}, None
351
+
352
+ _persist(st, workbook_key(wid), _apply)
353
+ _index_drop(st, wid)
354
+ return bool(existed.get("yes"))
355
+
356
+
357
+ # ── the index ────────────────────────────────────────────────────────────────────────────────
358
+
359
+ def _index_row(book):
360
+ return {
361
+ "id": book.get("id") or "",
362
+ "name": book.get("name") or "",
363
+ "created_by": book.get("created_by") or "",
364
+ "created_at": book.get("created_at") or "",
365
+ "updated_at": book.get("updated_at") or "",
366
+ "rev": int(book.get("rev") or 0),
367
+ "refreshed_at": book.get("refreshed_at"),
368
+ }
369
+
370
+
371
+ def _index_upsert(st, book):
372
+ if not book or not book.get("id"):
373
+ return
374
+
375
+ def _apply(state):
376
+ rows = [r for r in (state.get("workbooks") or [])
377
+ if isinstance(r, dict) and r.get("id") != book["id"]]
378
+ rows.append(_index_row(book))
379
+ rows.sort(key=lambda r: str(r.get("created_at") or ""))
380
+ state["workbooks"] = rows
381
+ return state, rows
382
+
383
+ _persist(st, INDEX_KEY, _apply, seed={"workbooks": []})
384
+
385
+
386
+ def _index_drop(st, workbook_id):
387
+ def _apply(state):
388
+ rows = [r for r in (state.get("workbooks") or [])
389
+ if isinstance(r, dict) and r.get("id") != workbook_id]
390
+ state["workbooks"] = rows
391
+ return state, rows
392
+
393
+ _persist(st, INDEX_KEY, _apply, seed={"workbooks": []})
394
+
395
+
396
+ def list_workbooks(st):
397
+ """The index rows, identity only.
398
+
399
+ ⚠ This is a POINTER LIST. It carries no cells, so it can never be mistaken for the content and
400
+ can never go stale in a way that changes a number on a screen.
401
+ """
402
+ rows = _read(st, INDEX_KEY).get("workbooks") or []
403
+ return [dict(r) for r in rows if isinstance(r, dict) and r.get("id")]
404
+
405
+
406
+ def iter_workbooks(st):
407
+ """Every workbook DOCUMENT the index points at, skipping any it cannot read.
408
+
409
+ ⭐ This is what W49-T10's dependents provider scans. It yields documents rather than index
410
+ rows, because a dependent question ("which cells bind to this table") can only be answered
411
+ from cells. An index row whose document is gone is SKIPPED rather than raising: the index is a
412
+ pointer list and the document is the truth.
413
+ """
414
+ for row in list_workbooks(st):
415
+ try:
416
+ yield get_workbook(st, row["id"])
417
+ except SheetRefusal:
418
+ continue
platform/core/user_tables.py CHANGED
@@ -4292,8 +4292,51 @@ def _utc_now():
4292
  return _dt.datetime.now(_dt.timezone.utc).replace(microsecond=0)
4293
 
4294
 
4295
- def record_odoo_schema_snapshot(models, *, complete, errors=(), st=None):
4296
- """Store an authoritative fields_get snapshot supplied by the sync lifecycle."""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4297
  clean_models = {}
4298
  for model, fields in (models or {}).items():
4299
  if not isinstance(fields, dict):
@@ -4307,11 +4350,52 @@ def record_odoo_schema_snapshot(models, *, complete, errors=(), st=None):
4307
  ('string', 'type', 'required', 'readonly', 'relation') if key in meta
4308
  }
4309
  clean_models[str(model)] = clean_fields
4310
- row = {'models': clean_models, 'complete': bool(complete),
4311
- 'errors': [str(error)[:500] for error in errors][:50],
4312
- 'capturedAt': _utc_now().isoformat()}
4313
- _st(st).update(ODOO_SCHEMA_SNAPSHOT_KEY, lambda _current: row, flush='sync')
4314
- return row
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4315
 
4316
 
4317
  def odoo_schema_snapshot(st=None):
@@ -4319,6 +4403,19 @@ def odoo_schema_snapshot(st=None):
4319
  return dict(row) if isinstance(row, dict) else {}
4320
 
4321
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4322
  def enabled_odoo_schema_fields(st=None, model=None):
4323
  """Product assembly seam: enabled raw metadata, still subject to its normal field wall."""
4324
  enabled = _st(st).get(ODOO_SCHEMA_ENABLEMENTS_KEY) or {}
 
4292
  return _dt.datetime.now(_dt.timezone.utc).replace(microsecond=0)
4293
 
4294
 
4295
+ #: ⭐⭐ W49-T25 / CONTRACT C6 — the row key carrying the CODE-DECLARED half of the schema snapshot.
4296
+ #:
4297
+ #: ⛔⛔ A SIBLING OF `models`, NEVER MERGED INTO IT, and that separation is a security boundary
4298
+ #: rather than tidiness. `routes_connectors._schema_catalog` builds its field catalogue out of
4299
+ #: `models` ALONE and stamps every row `source: "Odoo"`; `routes_connectors.odoo_schema_enable`
4300
+ #: then treats exactly that catalogue as the set of PATCH-enablable raw fields. Our declared
4301
+ #: columns are grid declarations, and some of them (`fba`, a `qty_available` read under a
4302
+ #: warehouse context) are DERIVED and are not fields on any Odoo model at all. Injected into
4303
+ #: `models` they would become enablable as though a `fields_get` had returned them.
4304
+ ODOO_SCHEMA_DECLARED = 'declared'
4305
+
4306
+
4307
+ def _clean_declared_schema(declared):
4308
+ """Clean the CODE-DECLARED field set: grid key -> field key -> {label, type, source}.
4309
+
4310
+ ⛔ NOT the `fields_get` cleaner above, and it must not be folded into it. A declared grid spec
4311
+ carries `label`/`type`/`source`; a `fields_get` entry carries
4312
+ `string`/`type`/`required`/`readonly`/`relation`. Sharing one cleaner would silently drop
4313
+ every key each side actually has and leave two documents of `{'type': ...}` singletons.
4314
+ """
4315
+ clean = {}
4316
+ for grid, fields in (declared or {}).items():
4317
+ if not isinstance(fields, dict):
4318
+ continue
4319
+ clean_fields = {}
4320
+ for name, meta in fields.items():
4321
+ if not str(name).strip() or not isinstance(meta, dict):
4322
+ continue
4323
+ clean_fields[str(name)] = {
4324
+ key: meta.get(key) for key in ('label', 'type', 'source') if key in meta
4325
+ }
4326
+ clean[str(grid)] = clean_fields
4327
+ return clean
4328
+
4329
+
4330
+ def record_odoo_schema_snapshot(models, *, complete, errors=(), declared=None, st=None):
4331
+ """Store an authoritative fields_get snapshot supplied by the sync lifecycle.
4332
+
4333
+ ⭐⭐ W49-T25 / C6 — `declared` is the CODE-DECLARED half, and passing None CARRIES THE STORED
4334
+ ONE FORWARD rather than dropping it. That carry is load-bearing, not defensive: `api/main.py`'s
4335
+ boot rebuild calls `odoo_relational.refresh` (which records the declared half) and then
4336
+ re-records THIS document unconditionally from `authoritative_schema_snapshot()`. Without the
4337
+ carry, every container start would erase the declared set that had just been written, and the
4338
+ parity would be re-derived from scratch on the next resync tick forever.
4339
+ """
4340
  clean_models = {}
4341
  for model, fields in (models or {}).items():
4342
  if not isinstance(fields, dict):
 
4350
  ('string', 'type', 'required', 'readonly', 'relation') if key in meta
4351
  }
4352
  clean_models[str(model)] = clean_fields
4353
+ base = {'models': clean_models, 'complete': bool(complete),
4354
+ 'errors': [str(error)[:500] for error in errors][:50],
4355
+ 'capturedAt': _utc_now().isoformat()}
4356
+ written = {}
4357
+
4358
+ def _apply(current):
4359
+ row = dict(base)
4360
+ if declared is None:
4361
+ carried = (current or {}).get(ODOO_SCHEMA_DECLARED) if isinstance(current, dict) else None
4362
+ if isinstance(carried, dict):
4363
+ row[ODOO_SCHEMA_DECLARED] = carried
4364
+ else:
4365
+ row[ODOO_SCHEMA_DECLARED] = _clean_declared_schema(declared)
4366
+ written.clear()
4367
+ written.update(row)
4368
+ return row
4369
+
4370
+ _st(st).update(ODOO_SCHEMA_SNAPSHOT_KEY, _apply, flush='sync')
4371
+ return written
4372
+
4373
+
4374
+ def record_declared_odoo_schema(declared, st=None):
4375
+ """Re-record the CODE-DECLARED half ONLY (C6), leaving the fields_get half byte for byte.
4376
+
4377
+ ⛔⛔ THE SURGICAL WRITER EXISTS SO THE PARITY REFRESH CANNOT LIE ABOUT ODOO, and this is the
4378
+ trap the ticket names. `complete` is NOT derived from "has a sync ever run" — it is literally
4379
+ whatever the last caller passed — so a parity path that rebuilt the whole row could hand a
4380
+ never-synced tenant `complete: True` and a fabricated `models`, and that one boolean is the
4381
+ ONLY thing standing between such a tenant and raw-field enablement
4382
+ (`routes_connectors.odoo_schema_enable` refuses 409 on exactly this key).
4383
+
4384
+ This updater copies the current row and replaces ONE key, so `models`, `complete`, `errors`
4385
+ and `capturedAt` survive untouched: a tenant that has never synced still reports
4386
+ `complete: False`, an empty field list and a null `capturedAt` after the parity write, and
4387
+ `capturedAt` keeps meaning "when Odoo was actually read" rather than "when we last compared
4388
+ two dicts".
4389
+ """
4390
+ clean = _clean_declared_schema(declared)
4391
+
4392
+ def _apply(current):
4393
+ row = dict(current) if isinstance(current, dict) else {}
4394
+ row[ODOO_SCHEMA_DECLARED] = clean
4395
+ return row
4396
+
4397
+ _st(st).update(ODOO_SCHEMA_SNAPSHOT_KEY, _apply, flush='sync')
4398
+ return clean
4399
 
4400
 
4401
  def odoo_schema_snapshot(st=None):
 
4403
  return dict(row) if isinstance(row, dict) else {}
4404
 
4405
 
4406
+ def declared_odoo_schema(st=None):
4407
+ """The code-declared field set last recorded, or None when none ever was.
4408
+
4409
+ ⛔ `None` IS NOT `{}`, and collapsing the two is the backward-compatibility bug waiting here.
4410
+ Every snapshot written before C6 carries no declared key at all; reading that absence as an
4411
+ empty declared set would read as AGREEMENT with a spec that declares nothing, so the refresh
4412
+ would compare `{}` against the real spec, or worse, compare `{}` against `{}` and never
4413
+ record anything at all.
4414
+ """
4415
+ declared = odoo_schema_snapshot(st).get(ODOO_SCHEMA_DECLARED)
4416
+ return declared if isinstance(declared, dict) else None
4417
+
4418
+
4419
  def enabled_odoo_schema_fields(st=None, model=None):
4420
  """Product assembly seam: enabled raw metadata, still subject to its normal field wall."""
4421
  enabled = _st(st).get(ODOO_SCHEMA_ENABLEMENTS_KEY) or {}
platform/harness/meta_store.py CHANGED
@@ -193,13 +193,15 @@ class MetaError(RuntimeError):
193
  """A Graph refusal carrying Meta's own words. Safe to print: no token ever reaches it."""
194
 
195
 
196
- def token():
197
- """The Meta token from the environment or gitignored `platform/.env`; "" when absent.
 
 
198
 
199
- ⚠ Same resolver `aios-web/api/connectors_meta.py` uses. Duplicated deliberately and minimally:
200
- `platform/` must not import from `aios-web/api/`, which is the layering rule this repo keeps
201
- (`core` never imports up). Fifteen lines is the price of that boundary.
202
- """
203
  tok = os.environ.get("META_ADS_ACCESS_TOKEN") or ""
204
  if tok:
205
  return tok.strip()
@@ -212,6 +214,53 @@ def token():
212
  return ""
213
 
214
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
215
  def _get(path, tok, **params):
216
  params["access_token"] = tok
217
  url = f"{GRAPH}/{path.lstrip('/')}?" + urllib.parse.urlencode(params)
@@ -393,13 +442,31 @@ def _upsert(con, table, fields, rows):
393
  return len(rows)
394
 
395
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
396
  def sync(tenant_key="royal-imports", tok=None, log=print, insights=True, insights_days=None):
397
  """Pull every level into the tenant's mirror. -> a report dict; raises only on a bad token.
398
 
399
  Idempotent: re-running updates rows in place. Safe to call at boot and on the resync loop,
400
  exactly as `odoo_relational.refresh` is.
401
  """
402
- tok = tok or token()
 
 
 
 
403
  # ⛔ THE WINDOW IS A PARAMETER, NOT AN ENVIRONMENT READ AT CALL TIME — and the difference cost a
404
  # live deploy. `INSIGHTS_DAYS` binds at IMPORT (module scope), so `main._pull_meta`'s
405
  # `os.environ.setdefault("META_INSIGHTS_DAYS", "7")` executed AFTER this module was already
 
193
  """A Graph refusal carrying Meta's own words. Safe to print: no token ever reaches it."""
194
 
195
 
196
+ #: The stored field a Meta credential may arrive under, in the order `connectors_meta.py:453`
197
+ #: already resolves them. ONE order, written once: a second precedence here would be
198
+ #: [[one-question-two-normalizers]] on the field that carries the secret itself.
199
+ _META_TOKEN_FIELDS = ("access_token", "token", "api_key")
200
 
201
+
202
+ def _env_token():
203
+ """The Meta token from the process environment or the gitignored `platform/.env`; "" when
204
+ absent. This is the DEPLOYMENT's token, which is why it is only ever a fallback."""
205
  tok = os.environ.get("META_ADS_ACCESS_TOKEN") or ""
206
  if tok:
207
  return tok.strip()
 
214
  return ""
215
 
216
 
217
+ def token(rt=None):
218
+ """The Meta token for `rt`: **the tenant's stored keychain credential first, the environment
219
+ only as a fallback**; "" when neither answers.
220
+
221
+ ⭐⭐ W49-T13 / D-202 — THE PRECEDENCE IS THE WHOLE DEFECT, NOT THE CALL. This module read
222
+ `META_ADS_ACCESS_TOKEN` unconditionally, so a tenant whose administrator had stored a Meta
223
+ credential on the keychain was synced with the OWNER's measurement token instead — the stored
224
+ key was accepted, previewed, testable, and never used by the loader it was stored for. A gate
225
+ that merely proves `keychain.meta_creds` is CALLED cannot see that; the assertion has to drive
226
+ both sources at once and name which one won.
227
+
228
+ ⛔ IT FAILS CLOSED ON THE TENANT QUESTION. With no `rt` there is no tenant to read a keychain
229
+ for, so this answers from the environment ALONE rather than resolving a default runtime.
230
+ Resolving one would read tenant #0's stored credential on behalf of whatever tenant is
231
+ actually syncing, which is the precise elevation `core/keychain.meta_creds` refuses an env
232
+ fallback for in the first place.
233
+
234
+ ⚠ THE ENV FALLBACK SURVIVES BECAUSE D-202 ASKS FOR IT (*"with the env variable as fallback
235
+ only"*) and because removing it would take tenant #0's live Meta sync offline. It is the
236
+ weaker half of the pair: a tenant with no stored entry still reaches the deployment token, and
237
+ that residual is booked rather than silently kept.
238
+
239
+ ⚠ THE FIELD NAME IS RESOLVED, NOT ASSUMED. A Meta credential is conventionally stored under
240
+ `access_token`, but `token` and `api_key` are both accepted by the connector that stores it,
241
+ so an entry using either is honoured here. An entry of the right TYPE carrying none of the
242
+ three yields "" from the keychain and the environment answers — an unreadable credential must
243
+ not be quieter than a missing one, so `sync` reports the empty token in as many words.
244
+
245
+ ⛔ NO CREDENTIAL IS PRINTED, LOGGED OR RAISED FROM HERE. The return value is the only place
246
+ the secret exists, and every failure path returns "" rather than echoing what it read.
247
+ """
248
+ if rt is not None:
249
+ try:
250
+ import core.keychain as _keychain
251
+ fields = _keychain.meta_creds(rt) or {}
252
+ for name in _META_TOKEN_FIELDS:
253
+ stored = str(fields.get(name) or "").strip()
254
+ if stored:
255
+ return stored
256
+ except Exception: # noqa: BLE001
257
+ # A locked or unreadable keychain costs the STORED credential and nothing else. It
258
+ # must not take the sync down, and it must not carry the exception outward: the
259
+ # message could quote a field this function exists to keep out of a log.
260
+ pass
261
+ return _env_token()
262
+
263
+
264
  def _get(path, tok, **params):
265
  params["access_token"] = tok
266
  url = f"{GRAPH}/{path.lstrip('/')}?" + urllib.parse.urlencode(params)
 
442
  return len(rows)
443
 
444
 
445
+ def _runtime_for(tenant_key):
446
+ """The tenant runtime for `tenant_key`, or None when this process cannot resolve one.
447
+
448
+ ⚠ IMPORTED LAZILY AND GUARDED. `harness/runtime.py` reads the tenant registry and the store;
449
+ a loader that could not be imported without one would make `--status` (which needs no
450
+ credential at all) depend on a store being reachable.
451
+ """
452
+ try:
453
+ from harness import runtime as _rt
454
+ return _rt.get_runtime(str(tenant_key or ""))
455
+ except Exception: # noqa: BLE001
456
+ return None
457
+
458
+
459
  def sync(tenant_key="royal-imports", tok=None, log=print, insights=True, insights_days=None):
460
  """Pull every level into the tenant's mirror. -> a report dict; raises only on a bad token.
461
 
462
  Idempotent: re-running updates rows in place. Safe to call at boot and on the resync loop,
463
  exactly as `odoo_relational.refresh` is.
464
  """
465
+ # ⭐ W49-T13 / D-202 — THE TENANT IS PASSED, which is what makes "the tenant's stored
466
+ # credential first" true of this loader rather than of a helper nobody calls with one. A
467
+ # runtime that cannot be resolved (an unregistered slug, an unavailable store) leaves `rt`
468
+ # None and `token()` answers from the environment exactly as it did before this ticket.
469
+ tok = tok or token(_runtime_for(tenant_key))
470
  # ⛔ THE WINDOW IS A PARAMETER, NOT AN ENVIRONMENT READ AT CALL TIME — and the difference cost a
471
  # live deploy. `INSIGHTS_DAYS` binds at IMPORT (module scope), so `main._pull_meta`'s
472
  # `os.environ.setdefault("META_INSIGHTS_DAYS", "7")` executed AFTER this module was already
platform/model/metrics/gl.yml CHANGED
@@ -10,6 +10,12 @@ metrics:
10
  field: balance
11
  store_filter_sql: "a.account_type IN ('expense', 'expense_depreciation')"
12
  format: usd
 
 
 
 
 
 
13
  description: "Posted operating expense from the GL (all expense-type accounts; COGS excluded) — the Expenses dashboard's basis."
14
  ai_context: "Company-level; includes payroll JEs/depreciation/fees that never hit vendor bills. Watch close-lag: the newest month is often still being booked."
15
  validate:
 
10
  field: balance
11
  store_filter_sql: "a.account_type IN ('expense', 'expense_depreciation')"
12
  format: usd
13
+ # W49-T22 — C1's empty-window family, and it is what admits `opex` as an ENTITY measure.
14
+ # `agg: sum` is ADDITIVE, so a group with no posted expense line in the window genuinely
15
+ # measured zero; that is a fact, not an absence. Without this declaration
16
+ # `semantic._one_binding_offer` refuses the key outright (refusal 3), which is why the GL
17
+ # account and vendor registries offered nothing at all.
18
+ empty: zero
19
  description: "Posted operating expense from the GL (all expense-type accounts; COGS excluded) — the Expenses dashboard's basis."
20
  ai_context: "Company-level; includes payroll JEs/depreciation/fees that never hit vendor bills. Watch close-lag: the newest month is often still being booked."
21
  validate:
platform/model/metrics/receivables.yml CHANGED
@@ -7,6 +7,9 @@ metrics:
7
  agg: sum
8
  field: amount_residual_signed
9
  format: usd
 
 
 
10
  description: "Total unpaid customer balance: signed residual over posted invoices and credit notes (credit notes net against invoices)."
11
  ai_context: "Ask WITHOUT a date window for the current balance (a window filters by invoice date, not by 'as of')."
12
  validate:
 
7
  agg: sum
8
  field: amount_residual_signed
9
  format: usd
10
+ # W49-T22 — same C1 rule as `opex`. A signed residual sum is additive, so an invoice with
11
+ # nothing outstanding is a measured zero and renders as 0.00 rather than as a blank cell.
12
+ empty: zero
13
  description: "Total unpaid customer balance: signed residual over posted invoices and credit notes (credit notes net against invoices)."
14
  ai_context: "Ask WITHOUT a date window for the current balance (a window filters by invoice date, not by 'as of')."
15
  validate:
platform/model/topics/odoo_accounts.yml CHANGED
@@ -22,6 +22,30 @@ store:
22
  dims:
23
  account_type: {label: "Account type"}
24
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
25
  # key / label / type / kind, derived from the grid contract. `kind` says where the
26
  # value COMES FROM: a `data` column is stored on the row; a `rollup` is computed
27
  # from another topic; a `link` points at another database.
 
22
  dims:
23
  account_type: {label: "Account type"}
24
 
25
+ # ⭐⭐ W49-T22 (R28) — THE MEASURE BINDING. The chart of accounts is the registry `gl_lines`
26
+ # posts against, so the natural measure is what was posted TO each account.
27
+ #
28
+ # ⛔ ONE KEY, AND IT IS THE VALIDATED ONE. `opex` carries `validate: {method: gl_opex}`, which
29
+ # reconciles the store aggregate against the live Odoo posted expense-line total to the cent.
30
+ # `gl_cogs` and `gl_revenue` resolve here and are left out for want of a contract.
31
+ #
32
+ # ⚠ THE KEY IS THE INTEGER `account_id`, NOT THE ACCOUNT CODE. A cross-table link on this grid
33
+ # joins on `account_code` (text), and reusing that here would have produced a column of nulls
34
+ # reading as "nothing was ever posted". `gl_lines.account` is `l.account_id` and
35
+ # `read_accounts` uses `account.account.id` as the pid; MEASURED, 136 groups, all 136 present
36
+ # in `account_account`.
37
+ #
38
+ # ⚠ A row that reads $0.00 is a MEASUREMENT here, not a gap: 56 of the 192 accounts carry no
39
+ # posted expense line at all, and `empty: zero` says that is a real zero.
40
+ measures:
41
+ source: gl_lines
42
+ dim: account
43
+ keys: [opex]
44
+ not_yet:
45
+ - key: gl_cogs / gl_revenue
46
+ cause: "no `validate:` contract, so neither reconciles to an independent Odoo aggregate (standing rule 8)"
47
+ fix: "add the validate method + a `_v_*` reconciliation, then add the key here"
48
+
49
  # key / label / type / kind, derived from the grid contract. `kind` says where the
50
  # value COMES FROM: a `data` column is stored on the row; a `rollup` is computed
51
  # from another topic; a `link` points at another database.
platform/model/topics/odoo_bills.yml CHANGED
@@ -24,6 +24,33 @@ store:
24
  payment_state: {label: "Payment state"}
25
  move_type: {label: "Document type"}
26
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
27
  # key / label / type / kind, derived from the grid contract. `kind` says where the
28
  # value COMES FROM: a `data` column is stored on the row; a `rollup` is computed
29
  # from another topic; a `link` points at another database.
 
24
  payment_state: {label: "Payment state"}
25
  move_type: {label: "Document type"}
26
 
27
+ # ⛔⛔ W49-T22 (R28) — NO `measures:` BLOCK, AND THE ABSENCE IS THE FINDING, NOT AN OVERSIGHT.
28
+ # Its four siblings (orders, invoices, accounts, vendors) each gained one in this ticket; this
29
+ # one could not, and offering a wrongly-keyed column would have been worse than offering none
30
+ # (`semantic.entity_measures`: an offer is a promise).
31
+ #
32
+ # THE MODEL CARRIES NO AP FACT TOPIC AT ALL. The topic list is commission_lines, credit_notes,
33
+ # customer_invoices, gl_lines, invoice_lines, odoo_*, receivables, sales_lines, sales_orders,
34
+ # stock_moves. `receivables` looks like the answer and is not: its `scope_sql` is
35
+ # `move_type IN ('out_invoice','out_refund')`, i.e. CUSTOMER documents only.
36
+ #
37
+ # AND THE ONE EXISTING BINDING THAT COULD KEY HERE IS ARITHMETICALLY OUT OF REACH. A `move` dim
38
+ # on `gl_lines` (`l.move_id`) WOULD key to `account.move.id`, which is this grid's pid — but
39
+ # `store_query` groups over the topic's whole scope, and tenant #0 has **234,364 distinct posted
40
+ # `move_id`** against `semantic.MAX_GROUPS = 200_000`. `entity_measure_values` refuses a
41
+ # truncated group set outright, so that binding raises rather than answering.
42
+ # (`gl_lines.partner` groups by PARTNER, so it keys a vendor, never a bill.)
43
+ #
44
+ # THE FIX, and it is its own ticket: a `payables` topic — table `account_move`, alias `m`,
45
+ # `scope_sql: m.state = 'posted' AND m.move_type IN ('in_invoice','in_refund')`,
46
+ # `date_col: m.invoice_date`, dims `vendor`/`payment_state`/`move`, an `ap_outstanding` metric
47
+ # (`agg: sum`, `field: amount_residual_signed`, `empty: zero`) and a `_v_ap_outstanding`
48
+ # reconciliation in `harness/semantic.py::_VALIDATORS`. MEASURED as viable: 6,538 posted vendor
49
+ # documents, so a `move` dim there returns 6,538 groups, far inside MAX_GROUPS.
50
+ # EXIT CONDITION: `entity_measures("odoo_bills")` is non-empty under `strict=True` and
51
+ # `entity_measure_values("odoo_bills", ["ap_outstanding"])` returns integer keys that are
52
+ # `account.move.id` values in the posted vendor-document population.
53
+
54
  # key / label / type / kind, derived from the grid contract. `kind` says where the
55
  # value COMES FROM: a `data` column is stored on the row; a `rollup` is computed
56
  # from another topic; a `link` points at another database.
platform/model/topics/odoo_invoices.yml CHANGED
@@ -24,6 +24,25 @@ store:
24
  payment_state: {label: "Payment state"}
25
  move_type: {label: "Document type"}
26
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
27
  # key / label / type / kind, derived from the grid contract. `kind` says where the
28
  # value COMES FROM: a `data` column is stored on the row; a `rollup` is computed
29
  # from another topic; a `link` points at another database.
 
24
  payment_state: {label: "Payment state"}
25
  move_type: {label: "Document type"}
26
 
27
+ # ⭐⭐ W49-T22 (R28) — THE MEASURE BINDING, on the AR side. `receivables` is already one row per
28
+ # posted customer document, so grouping it by its own `m.id` gives exactly one group per invoice.
29
+ #
30
+ # ⛔ ONE KEY, AND IT IS THE VALIDATED ONE. `ar_outstanding` carries
31
+ # `validate: {method: ar_outstanding}`, which reconciles the store's signed-residual sum against
32
+ # the live Odoo aggregate over the same domain, to the cent. `ar_overdue` and `open_invoices`
33
+ # resolve here too and are left out: neither declares an independent contract.
34
+ #
35
+ # ⚠ KEYING PROVEN: 31,418 groups on tenant #0, every one an `account.move.id` in the posted
36
+ # customer-document population — the same integer `read_invoices` uses as a row's pid.
37
+ measures:
38
+ source: receivables
39
+ dim: move
40
+ keys: [ar_outstanding]
41
+ not_yet:
42
+ - key: ar_overdue / open_invoices
43
+ cause: "no `validate:` contract, so neither ties to an independent Odoo aggregate (standing rule 8)"
44
+ fix: "add the validate method + a `_v_*` reconciliation, then add the key here"
45
+
46
  # key / label / type / kind, derived from the grid contract. `kind` says where the
47
  # value COMES FROM: a `data` column is stored on the row; a `rollup` is computed
48
  # from another topic; a `link` points at another database.
platform/model/topics/odoo_orders.yml CHANGED
@@ -25,6 +25,32 @@ store:
25
  state: {label: "State"}
26
  invoice_status: {label: "Invoice status"}
27
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
28
  # key / label / type / kind, derived from the grid contract. `kind` says where the
29
  # value COMES FROM: a `data` column is stored on the row; a `rollup` is computed
30
  # from another topic; a `link` points at another database.
 
25
  state: {label: "State"}
26
  invoice_status: {label: "Invoice status"}
27
 
28
+ # ⭐⭐ W49-T22 (R28) — THE MEASURE BINDING. Joel Pal opened this database, opened Time series,
29
+ # and had nothing to choose; `entity_measures` answered `[]` because this file declared no
30
+ # `measures:` block at all. It does now, and the offer is deliberately ONE key.
31
+ #
32
+ # ⛔ ONLY A VALIDATE-BACKED METRIC IS OFFERED, which is standing rule 8 read as a catalogue
33
+ # rule: `revenue` carries `validate: {method: order_level_revenue}`, so the number in this column
34
+ # reconciles line-level price_subtotal against Odoo's own order-level amount_untaxed. `units`,
35
+ # `margin`, `cogs`, `margin_pct`, `asp` and `customers` all resolve here and are all left out,
36
+ # because none of them has an independent Odoo aggregate to tie to and an unverifiable aggregate
37
+ # does not reach a screen.
38
+ #
39
+ # ⚠ THE JOIN KEY IS THE WHOLE TRAP, and it was proven rather than assumed: `sales_lines.order`
40
+ # groups by `l.order_id`, `read_orders` sets a row's pid to `sale_order.id`, and all 26,948
41
+ # groups measured on tenant #0 are ids that exist in `sale_order`.
42
+ measures:
43
+ source: sales_lines
44
+ dim: order
45
+ keys: [revenue]
46
+ not_yet:
47
+ - key: units / margin / cogs / margin_pct / asp / customers
48
+ cause: "each resolves cleanly on `sales_lines` under this dim, but none declares a `validate:` contract, so no independent Odoo aggregate reconciles it (standing rule 8)"
49
+ fix: "declare a validate method for the metric in `model/metrics/sales.yml` and add a `_v_*` reconciliation to `harness/semantic.py::_VALIDATORS`, then add the key here"
50
+ - key: revenue, for an order outside the wholesale fence
51
+ cause: "`sales_lines.scope_sql` keeps teams 5/6 and excludes the GIFTWARE DEALS partner, so the 6,145 confirmed orders outside it group nothing and zero-fill to $0.00 — which reads as 'this order sold nothing' rather than 'this order is out of scope'"
52
+ fix: "the grid already carries `wholesale_scope`; either bind a second `scope_variant: all_channels` block once a channel-aware label exists, or teach the caller to leave an out-of-scope row blank instead of zero-filling it"
53
+
54
  # key / label / type / kind, derived from the grid contract. `kind` says where the
55
  # value COMES FROM: a `data` column is stored on the row; a `rollup` is computed
56
  # from another topic; a `link` points at another database.
platform/model/topics/odoo_vendors.yml CHANGED
@@ -24,6 +24,28 @@ store:
24
  dims:
25
  country: {label: "Country"}
26
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
27
  # key / label / type / kind, derived from the grid contract. `kind` says where the
28
  # value COMES FROM: a `data` column is stored on the row; a `rollup` is computed
29
  # from another topic; a `link` points at another database.
 
24
  dims:
25
  country: {label: "Country"}
26
 
27
+ # ⭐⭐ W49-T22 (R28) — THE MEASURE BINDING. A vendor's own number is what we booked as expense
28
+ # against it, and `gl_lines` already carries a `partner` dim keyed on `l.partner_id`.
29
+ #
30
+ # ⛔ ONE KEY, AND IT IS THE VALIDATED ONE (`opex`, `validate: {method: gl_opex}`).
31
+ #
32
+ # ⚠ KEYING PROVEN: 2,335 partner groups on tenant #0, 2,334 of them present in `res_partner`;
33
+ # the one miss is a partner the mirror does not carry, and it simply keys no grid row rather
34
+ # than mis-keying one. `read_vendors` uses `res.partner.id` as the pid, which is the same
35
+ # integer this dim groups by.
36
+ #
37
+ # ⚠ THIS IS THE GL BASIS, NOT THE BILL BASIS, and the two are deliberately different numbers:
38
+ # payroll journals and depreciation reach `opex` without ever passing through a vendor bill.
39
+ # Read it beside the Bills link, never as a restatement of it.
40
+ measures:
41
+ source: gl_lines
42
+ dim: partner
43
+ keys: [opex]
44
+ not_yet:
45
+ - key: gl_cogs / gl_revenue
46
+ cause: "no `validate:` contract (standing rule 8)"
47
+ fix: "add the validate method + a `_v_*` reconciliation, then add the key here"
48
+
49
  # key / label / type / kind, derived from the grid contract. `kind` says where the
50
  # value COMES FROM: a `data` column is stored on the row; a `rollup` is computed
51
  # from another topic; a `link` points at another database.
platform/model/topics/receivables.yml CHANGED
@@ -21,6 +21,12 @@ store:
21
  dims:
22
  partner: {col: "m.partner_id", name_col: "m.partner_name", label: "Customer"}
23
  payment_state: {col: "m.payment_state", name_col: null, label: "Payment state"}
 
 
 
 
 
 
24
 
25
  ai_context: >
26
  Customer receivables at document grain. "Outstanding" = the signed residual (credit notes net
 
21
  dims:
22
  partner: {col: "m.partner_id", name_col: "m.partner_name", label: "Customer"}
23
  payment_state: {col: "m.payment_state", name_col: null, label: "Payment state"}
24
+ # ⭐⭐ W49-T22 — THE DOCUMENT DIM, the receivables analogue of `sales_lines.order`. This
25
+ # topic's grain already IS one row per posted customer document, so grouping by `m.id`
26
+ # returns exactly one group per invoice; `account.move.id` is the pid
27
+ # `odoo_relational.read_invoices` gives a `ut_odoo_invoices` row. MEASURED: 31,418 groups,
28
+ # all 31,418 present in the invoice population.
29
+ move: {col: "m.id", name_col: "m.name", label: "Invoice"}
30
 
31
  ai_context: >
32
  Customer receivables at document grain. "Outstanding" = the signed residual (credit notes net
platform/model/topics/sales_lines.yml CHANGED
@@ -82,6 +82,15 @@ store:
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.
 
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
+ # ⭐⭐ W49-T22 — THE ORDER-DOCUMENT DIM, and it exists so a metric can key to a row of the
86
+ # `ut_odoo_orders` database. Every other dim here groups by an ATTRIBUTE of the order
87
+ # (customer, team, product); this one groups by the order ITSELF, which is what
88
+ # `semantic.entity_measure_values` needs when the entity being measured is the document.
89
+ # ⚠ `o` IS ALREADY JOINED by this topic's own `join:` (JOIN sale_order o ON o.id =
90
+ # l.order_id), so `o.name` costs no extra table — and `l.order_id` IS `sale_order.id`, which
91
+ # is the integer `odoo_relational.read_orders` uses as a grid row's pid. MEASURED on tenant
92
+ # #0's mirror: 26,948 groups, every one of them an id present in `sale_order`.
93
+ order: {col: "l.order_id", name_col: "o.name", label: "Order"}
94
 
95
  ai_context: >
96
  The wholesale sales dataset of Royal Imports / Fisch Floral Supply, at order-LINE grain.
platform/modules/product_data.py CHANGED
@@ -16,7 +16,11 @@ template and this deliberately mirrors its signature and its row shape.
16
  of that anyone would notice.
17
 
18
  2. **THE SCOPE RULE — inventory columns are CONSOLIDATED and are therefore OMITTED for a
19
- BU-scoped caller.** `products.directory(t, team_id)` is brand-shaped; `inventory.sku_inventory`
 
 
 
 
20
  is explicitly NOT (its own docstring: "on-hand stock is one physical warehouse, not
21
  brand-tagged"). Joining them for a Fisch-only user would put BU-shaped revenue beside
22
  company-wide stock IN THE SAME ROW — the mixed-scope value defect wave 15's amendment 3 exists
@@ -354,7 +358,7 @@ def _assert_no_pid_collision(rows):
354
  prior = seen.get(r["pid"])
355
  if prior is not None and prior != r["code"]:
356
  raise ValueError(
357
- f"product_data: pid collision — {prior!r} and {r['code']!r} both hash to "
358
  f"{r['pid']}. Downstream set operations would merge them silently; widen the id "
359
  f"before shipping this catalogue.")
360
  seen[r["pid"]] = r["code"]
@@ -586,6 +590,51 @@ def _catalogue_by_code():
586
  return products.catalogue()
587
 
588
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
589
  def pool(team_id=None, t=None, raw_fields=()):
590
  """One row per ACTIVE product — the PRODUCT analogue of `customer_data.pool`.
591
 
@@ -631,6 +680,11 @@ def pool(team_id=None, t=None, raw_fields=()):
631
  # does not carry belongs to a product no ACTIVE record claims — archived, and R12 keeps those
632
  # out. `validate()` asserts that of Odoo rather than assuming it, and reports the revenue
633
  # that therefore sits outside the grid (MEASURED 2026-08-11: 3 codes, $0.00 YTD / $294.50 LY).
 
 
 
 
 
634
  rev = {r["code"]: r for r in products.directory(t=t, team_id=team_id)}
635
  raw_by_code = {(p.get("default_code") or f"pid:{p.get('id')}"): p
636
  for p in (_prods or []) if p.get("default_code") or p.get("id")}
@@ -766,6 +820,14 @@ def pool(team_id=None, t=None, raw_fields=()):
766
  row.update({
767
  # UNSCOPED on purpose (owner 2026-08-11): one warehouse, no per-brand shelf.
768
  "on_hand": e.get("on_hand"),
 
 
 
 
 
 
 
 
769
  "unit_cost": e.get("unit_cost"),
770
  "inv_value": e.get("inv_value"),
771
  # W48C-T09 — this is not `unit_cost`. The older field falls back to LTM COGS when
@@ -1104,7 +1166,7 @@ def validate(team_id=None, t=None):
1104
  # built. NC: drop one row from `pool()` and this goes red; that is the whole point of it.
1105
  n_active = products.catalogue_count()
1106
  checks = [{
1107
- "check": "the pool holds one row per ACTIVE product (R12) — row count == an INDEPENDENT "
1108
  "Odoo search_count('product.product', active=True)",
1109
  "ours": len(rows), "theirs": n_active, "ok": len(rows) == n_active,
1110
  }]
@@ -1141,7 +1203,7 @@ def validate(team_id=None, t=None):
1141
  if coded_outside else 0)
1142
  checks.append({
1143
  "check": "every SKU with revenue but NO grid row is genuinely ARCHIVED (R12: archived "
1144
- "stay out) — asked of Odoo, never of the catalogue that did the dropping",
1145
  "ours": still_active, "theirs": 0, "ok": still_active == 0,
1146
  "detail": {"codes": coded_outside[:10], "n_codes": len(outside)},
1147
  })
@@ -1368,6 +1430,153 @@ def validate(team_id=None, t=None):
1368
  pool_codes={r["code"] for r in rows}))
1369
  checks.extend(validate_price_and_unit_cells(rows))
1370
  checks.extend(validate_stock_measures(t=t))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1371
  return checks
1372
 
1373
 
 
16
  of that anyone would notice.
17
 
18
  2. **THE SCOPE RULE — inventory columns are CONSOLIDATED and are therefore OMITTED for a
19
+ BU-scoped caller.** ⛔ **SUPERSEDED as to the OMISSION half by the owner ruling of
20
+ 2026-08-11 recorded below (search `THIS SET IS NOW EMPTY`): `on_hand` / `unit_cost` /
21
+ `inv_value` are set on EVERY pull, warehouse wide and never re-scoped (`pool()` L818-820),
22
+ so nothing is withheld from a BU-scoped caller. The CONSOLIDATED half still holds; the
23
+ reasoning below is kept because it is why the SPLIT, not the omission, is the shipped rule.** `products.directory(t, team_id)` is brand-shaped; `inventory.sku_inventory`
24
  is explicitly NOT (its own docstring: "on-hand stock is one physical warehouse, not
25
  brand-tagged"). Joining them for a Fisch-only user would put BU-shaped revenue beside
26
  company-wide stock IN THE SAME ROW — the mixed-scope value defect wave 15's amendment 3 exists
 
358
  prior = seen.get(r["pid"])
359
  if prior is not None and prior != r["code"]:
360
  raise ValueError(
361
+ f"product_data: pid collision. {prior!r} and {r['code']!r} both hash to "
362
  f"{r['pid']}. Downstream set operations would merge them silently; widen the id "
363
  f"before shipping this catalogue.")
364
  seen[r["pid"]] = r["code"]
 
590
  return products.catalogue()
591
 
592
 
593
+ def _fba_by_code(cat):
594
+ """`({code: units} | None, report)` — the FBA column's source, keyed like the pool's rows.
595
+
596
+ ⭐ W49-T24. A `pd`-level seam for exactly the reason `_inventory_by_code` and
597
+ `_catalogue_by_code` are: it is what `verify_product_pool.py` stubs to build a pool with no
598
+ Odoo behind it. The READ itself lives in `modules/warehouse.py` (`fba_qty_by_product_id`),
599
+ which owns the warehouse-code resolution and the batching; this function only re-keys its
600
+ answer from Odoo product ids onto the pool's own code key.
601
+
602
+ ⚠ DEGRADES TO `(None, report)` ON ANY FAILURE, like every other COLUMN source in `pool()`.
603
+ FBA is a column, not the row set: a warehouse read that fails must blank one column, never
604
+ take the product grid down. The cause travels in `report` and `validate_fba()` fails its leg
605
+ on it, so an outage is a NAMED refusal rather than an all-blank column that quietly passes.
606
+
607
+ ⚠ ONE ID PER CODE, AND THE LEFTOVERS ARE ACCOUNTED FOR RATHER THAN SUMMED AWAY. A code can own
608
+ more than one `product.product` (re-SKU and merge history), and `products.catalogue()` carries
609
+ ONE id per code, so this column reads only that id's units. The others land in
610
+ `validate_fba()`'s `outside_the_grid` residual, which is exactly why its total leg is
611
+ DECOMPOSED instead of a bare equality. The loop below is shaped to sum a code's ids so it
612
+ stays correct the day the catalogue carries more than one, but it is not what makes the
613
+ reconciliation tie today. MEASURED live 2026-09-02: 1 active duplicate code, holding no FBA
614
+ stock, and a zero residual.
615
+ """
616
+ try:
617
+ import modules.warehouse as warehouse
618
+ ids_by_code = {}
619
+ for code, meta in (cat or {}).items():
620
+ pid = (meta or {}).get('id')
621
+ if pid is not None:
622
+ ids_by_code.setdefault(code, []).append(pid)
623
+ wanted = [pid for ids in ids_by_code.values() for pid in ids]
624
+ by_pid, report = warehouse.fba_qty_by_product_id(wanted)
625
+ except Exception as e: # noqa: BLE001
626
+ return None, {'available': False,
627
+ 'cause': 'the FBA warehouse read failed: ' + type(e).__name__}
628
+ if by_pid is None:
629
+ return None, report
630
+ out = {}
631
+ for code, ids in ids_by_code.items():
632
+ seen = [by_pid[pid] for pid in ids if pid in by_pid]
633
+ if seen:
634
+ out[code] = sum(seen)
635
+ return out, report
636
+
637
+
638
  def pool(team_id=None, t=None, raw_fields=()):
639
  """One row per ACTIVE product — the PRODUCT analogue of `customer_data.pool`.
640
 
 
680
  # does not carry belongs to a product no ACTIVE record claims — archived, and R12 keeps those
681
  # out. `validate()` asserts that of Odoo rather than assuming it, and reports the revenue
682
  # that therefore sits outside the grid (MEASURED 2026-08-11: 3 codes, $0.00 YTD / $294.50 LY).
683
+ # ⭐⭐ W49-T24 — THE AMAZON FBA SHELF, beside the consolidated one. Read AFTER the catalogue
684
+ # because it is keyed off it, and UNSCOPED for the same reason `on_hand` is: a warehouse holds
685
+ # units, not brands, and pro-rating them onto a BU would print a number no Odoo query could
686
+ # reproduce. Blank, never zero, when the tenant has no FBA warehouse.
687
+ fba_by_code, _fba_report = _fba_by_code(cat)
688
  rev = {r["code"]: r for r in products.directory(t=t, team_id=team_id)}
689
  raw_by_code = {(p.get("default_code") or f"pid:{p.get('id')}"): p
690
  for p in (_prods or []) if p.get("default_code") or p.get("id")}
 
820
  row.update({
821
  # UNSCOPED on purpose (owner 2026-08-11): one warehouse, no per-brand shelf.
822
  "on_hand": e.get("on_hand"),
823
+ # ⭐⭐ W49-T24 — of those units, the ones sitting at Amazon. SAME BU BEHAVIOUR AS
824
+ # `on_hand` DELIBERATELY: set on every pull, warehouse wide, never re-scoped.
825
+ # ⚠ A REAL 0.0 IS AN OBSERVED ZERO, exactly like `pre_book_qty` above: the warehouse
826
+ # context read answers for every product it is asked about, so "this SKU holds nothing
827
+ # at Amazon" is measured. BLANK means the source could not answer at all, which is
828
+ # `fba_by_code is None` (no FBA warehouse, or the read failed) or a code carrying no
829
+ # Odoo product id. Those are different sentences and only one of them is a number.
830
+ "fba": (fba_by_code or {}).get(code),
831
  "unit_cost": e.get("unit_cost"),
832
  "inv_value": e.get("inv_value"),
833
  # W48C-T09 — this is not `unit_cost`. The older field falls back to LTM COGS when
 
1166
  # built. NC: drop one row from `pool()` and this goes red; that is the whole point of it.
1167
  n_active = products.catalogue_count()
1168
  checks = [{
1169
+ "check": "the pool holds one row per ACTIVE product (R12): row count == an INDEPENDENT "
1170
  "Odoo search_count('product.product', active=True)",
1171
  "ours": len(rows), "theirs": n_active, "ok": len(rows) == n_active,
1172
  }]
 
1203
  if coded_outside else 0)
1204
  checks.append({
1205
  "check": "every SKU with revenue but NO grid row is genuinely ARCHIVED (R12: archived "
1206
+ "stay out), asked of Odoo, never of the catalogue that did the dropping",
1207
  "ours": still_active, "theirs": 0, "ok": still_active == 0,
1208
  "detail": {"codes": coded_outside[:10], "n_codes": len(outside)},
1209
  })
 
1430
  pool_codes={r["code"] for r in rows}))
1431
  checks.extend(validate_price_and_unit_cells(rows))
1432
  checks.extend(validate_stock_measures(t=t))
1433
+ checks.extend(validate_fba(rows))
1434
+ return checks
1435
+
1436
+
1437
+ def fba_quant_oracle():
1438
+ """`(warehouse | None, {product_id: units}, detail)` — the FBA column's INDEPENDENT oracle.
1439
+
1440
+ ⛔⛔ A DIFFERENT MODEL, READ A DIFFERENT WAY, AND THAT IS THE WHOLE POINT OF THIS FUNCTION.
1441
+ The COLUMN is `product.product.qty_available` read under `{'warehouse': id}`; this is a
1442
+ `stock.quant` `read_group` summed over the same warehouse. Computing both from one read would
1443
+ reconcile a number to ITSELF and satisfy STANDING RULE 8 on paper only
1444
+ ([[no-unverifiable-aggregates]]).
1445
+
1446
+ ⛔ THE WAREHOUSE IS RE-RESOLVED HERE RATHER THAN BORROWED from `warehouse.fba_warehouse()`,
1447
+ for the same reason. A shared resolver would make "both sides name the same warehouse" true by
1448
+ construction, and naming the WRONG warehouse is one of the two ways this column can be wrong.
1449
+ The duplication is four lines and is deliberate.
1450
+
1451
+ MEASURED live 2026-09-02 on tenant #0: warehouse id 8 code FBA, 66,007.01 units over 582
1452
+ products, tying to the context read to the cent with zero per-product disagreement.
1453
+ """
1454
+ o = O.get_odoo()
1455
+ found = o.search_read('stock.warehouse', [('code', '=', 'FBA')], ['id', 'name', 'code'])
1456
+ if not found:
1457
+ return None, {}, {'available': False,
1458
+ 'cause': "no stock.warehouse carries the code FBA"}
1459
+ wh = found[0]
1460
+ by_pid = {}
1461
+ for g in o.read_group('stock.quant',
1462
+ [('warehouse_id', '=', wh['id']),
1463
+ ('location_id.usage', '=', 'internal')],
1464
+ ['quantity:sum'], ['product_id'], lazy=False):
1465
+ if g.get('product_id'):
1466
+ by_pid[O.m2o_id(g['product_id'])] = g.get('quantity') or 0.0
1467
+ return wh, by_pid, {'available': True, 'warehouse_id': wh['id'],
1468
+ 'warehouse_code': wh.get('code'),
1469
+ 'source': "stock.quant quantity:sum over warehouse_id, internal usage",
1470
+ 'products': len(by_pid),
1471
+ 'units': round(sum(by_pid.values()), 2)}
1472
+
1473
+
1474
+ def validate_fba(rows, oracle=None, sample=10):
1475
+ """⭐⭐ W49-T24 — the FBA column against a `stock.quant` aggregate it cannot borrow from.
1476
+
1477
+ Four legs, and each answers a different way the column can be wrong:
1478
+ 1. the warehouse was resolved AT RUNTIME by its code, and the id is reported rather than
1479
+ asserted, because the id is a tenant fact;
1480
+ 2. the TOTAL, DECOMPOSED. `Σ FBA in the grid + Σ FBA units on product ids no grid row
1481
+ carries == the quant total`. Not a bare equality: FBA can legitimately hold stock on an
1482
+ ARCHIVED product, which the catalogue-first pool keeps out by design (R12), and a bare
1483
+ total would then red a correct build. MEASURED live 2026-09-02: that residual is 0.00
1484
+ today, so the decomposition is a guard against drift rather than a standing excuse;
1485
+ 3. every SKU's own cell ties to the quant sum for its Odoo product id;
1486
+ 4. `on_hand >= fba` per row, REPORTED not tolerated. FBA units are a SUBSET of On hand, so a
1487
+ violation means a negative stock position outside FBA and is a real finding. MEASURED
1488
+ live 2026-09-02: zero violations over all 582 products holding FBA stock.
1489
+
1490
+ ⚠ RUN ON `pool()` ROWS, NEVER ON `rows_from_pool` OUTPUT. `fba` is an `int` field, so the wire
1491
+ projection rounds it and a fractional quant would read as a spurious sub-unit gap.
1492
+ """
1493
+ wh, by_pid, detail = oracle if oracle is not None else fba_quant_oracle()
1494
+ rows = list(rows or ())
1495
+ valued = [r for r in rows if isinstance(r.get('fba'), (int, float))
1496
+ and not isinstance(r.get('fba'), bool)]
1497
+
1498
+ if wh is None:
1499
+ # A tenant with no FBA warehouse holds no opinion about FBA stock. The honest state is a
1500
+ # BLANK column on every row, and that is asserted rather than assumed.
1501
+ return [{
1502
+ "check": "this tenant has NO warehouse with code FBA, so the FBA column is blank on "
1503
+ "every row (blank, never a fabricated zero)",
1504
+ "ours": len(valued), "theirs": 0, "ok": not valued,
1505
+ "detail": {**detail, "rows": len(rows),
1506
+ "rows_with_a_number": [r.get("code") for r in valued][:sample]},
1507
+ }]
1508
+
1509
+ checks = [{
1510
+ "check": "the FBA warehouse is resolved AT RUNTIME from stock.warehouse.code, never a "
1511
+ "pinned id (the id is a TENANT fact and is reported, not asserted)",
1512
+ "ours": {"warehouse_id": wh.get("id"), "warehouse_code": wh.get("code"),
1513
+ "warehouse_name": wh.get("name")},
1514
+ "theirs": "code == FBA", "ok": wh.get("code") == "FBA", "detail": detail,
1515
+ }]
1516
+
1517
+ if not valued:
1518
+ checks.append({
1519
+ "check": "⛔ REFUSAL: the FBA warehouse EXISTS and yet no row carries a number, so "
1520
+ "the column is blank for a reason nobody measured",
1521
+ "ours": 0, "theirs": ">0", "ok": False,
1522
+ "detail": {"source_refusal": "the warehouse-context read returned nothing for any "
1523
+ "product; see modules/warehouse.fba_qty_by_product_id",
1524
+ "rows": len(rows), **detail},
1525
+ })
1526
+ return checks
1527
+
1528
+ in_grid_ids = {r.get("product_id") for r in rows if r.get("product_id") is not None}
1529
+ outside = {pid: q for pid, q in by_pid.items() if pid not in in_grid_ids}
1530
+ ours = round(sum(float(r["fba"]) for r in valued), 2)
1531
+ dropped = round(sum(outside.values()), 2)
1532
+ theirs = round(sum(by_pid.values()), 2)
1533
+ checks.append({
1534
+ "check": "Σ FBA units in the grid + Σ FBA units on product ids NO grid row carries == an "
1535
+ "INDEPENDENT stock.quant read_group over the FBA warehouse. Decomposed rather "
1536
+ "than compared loosely: FBA may hold stock on an ARCHIVED product, which R12 "
1537
+ "keeps out of the pool, and that residual is a number here instead of slack",
1538
+ "ours": round(ours + dropped, 2), "theirs": theirs,
1539
+ "ok": abs((ours + dropped) - theirs) <= 0.01,
1540
+ "detail": {"in_the_grid": ours, "outside_the_grid": dropped,
1541
+ "product_ids_outside": len(outside),
1542
+ "skus_with_a_number": len(valued), "rows": len(rows), **detail},
1543
+ })
1544
+
1545
+ off = []
1546
+ for r in valued:
1547
+ pid = r.get("product_id")
1548
+ if pid is None:
1549
+ continue
1550
+ want = by_pid.get(pid, 0.0)
1551
+ if abs(float(r["fba"]) - want) > 0.01:
1552
+ off.append({"sku": r.get("code"), "product_id": pid,
1553
+ "ours": round(float(r["fba"]), 2), "odoo": round(want, 2)})
1554
+ checks.append({
1555
+ "check": "each SKU's own FBA cell ties to the quant sum for ITS Odoo product id, so a "
1556
+ "correct total cannot hide two SKUs swapped",
1557
+ "ours": len(off), "theirs": 0, "ok": not off,
1558
+ "detail": {"mismatched": off[:sample], "skus_compared": len(valued)},
1559
+ })
1560
+
1561
+ viol = []
1562
+ for r in valued:
1563
+ oh = r.get("on_hand")
1564
+ if isinstance(oh, bool) or not isinstance(oh, (int, float)):
1565
+ continue
1566
+ if float(oh) + 0.01 < float(r["fba"]):
1567
+ viol.append({"sku": r.get("code"), "on_hand": round(float(oh), 2),
1568
+ "fba": round(float(r["fba"]), 2)})
1569
+ checks.append({
1570
+ "check": "⛔ On hand >= FBA on every row: On hand is the UNSCOPED read and already "
1571
+ "INCLUDES these units, so a violation is a negative stock position outside FBA "
1572
+ "and is a real finding, never something a tolerance should absorb",
1573
+ "ours": len(viol), "theirs": 0, "ok": not viol,
1574
+ "detail": {"violations": viol[:sample],
1575
+ "rows_with_both_numbers": sum(
1576
+ 1 for r in valued
1577
+ if isinstance(r.get("on_hand"), (int, float))
1578
+ and not isinstance(r.get("on_hand"), bool))},
1579
+ })
1580
  return checks
1581
 
1582
 
platform/modules/sheet.py ADDED
@@ -0,0 +1,421 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """modules/sheet.py — bound cell resolution over the mirror seam (wave 49, W49-T04, contract C2).
2
+
3
+ WHAT GOES HERE, AND WHAT DELIBERATELY DOES NOT:
4
+
5
+ Here: the SHAPE of a binding, the SQL a binding compiles to, and the honest accounting of what
6
+ that SQL could not answer. This module is the THIRD consumer of the mirror seam, after the grid
7
+ and `assistant_mirror.py`.
8
+
9
+ Not here: any permission decision. ⛔⛔ Contract C2 is explicit — "no permission decision inside
10
+ `routes_sheet.py` or `platform/modules/sheet.py`". The per-database wall is
11
+ `routes_charts.py::_require_database`, copied into the route layer and called per DISTINCT
12
+ database on OPEN, and the ROW wall is the caller's `perm_scope` entry handed in as
13
+ `wall_nodes`. A module that started deciding access would be a second answer to a question the
14
+ nav rail already answers, and the two would diverge.
15
+
16
+ Also not here: the cursor. The route hands one in, because choosing between
17
+ `DatastoreMismatch` (this process has another tenant's file open, never self-heals) and a plain
18
+ `RuntimeError` (mid first sync, retry) is a ROUTE's decision about status codes, and
19
+ `_mirror_cur` already makes it.
20
+
21
+ ⭐⭐ **THE RULE THIS FILE EXISTS TO KEEP: A NUMBER THAT COULD NOT BE FULLY ANSWERED SAYS SO.**
22
+ Standing rule 1's second half — a limit that genuinely cannot be removed must be REPORTED, with its
23
+ cause and a recommended fix, never silently enforced. Every way a bound cell's answer can come out
24
+ WIDER than the binding asked for is collected in `limits` and travels with the value. The failure
25
+ this prevents is not a crash; it is a plausible bigger number that nobody questions.
26
+
27
+ ⛔ **AN OPERATOR INSIDE A STRING IS THE FORBIDDEN SECOND DIALECT (C2).** Every predicate in this
28
+ file comes from `harness.filter_sql.compile_filter_tree`. Nothing here concatenates a comparison.
29
+ The only SQL this module writes itself is the aggregate wrapper and the spec's own fixed scope.
30
+ """
31
+
32
+ from __future__ import annotations
33
+
34
+ #: C2's aggregate vocabulary. `metric_key` is the other arm of that union and is resolved by the
35
+ #: route against the same catalogue `routes_query.py::_compatible_metric_dtos` serves.
36
+ AGGREGATE_FNS = ("sum", "count", "avg", "min", "max")
37
+
38
+ #: C2's refusal codes, spelled once. ⚠ Each message reaches a screen, so none carries an em dash or
39
+ #: an en dash (standing rule 2) and each names both the cause and the subject.
40
+ REFUSALS = {
41
+ "database_unreadable": "You cannot read {subject}.",
42
+ "view_missing": "View {subject} no longer exists.",
43
+ "result_too_large": "This result does not fit in one cell.",
44
+ "formula_no_drill": "A formula cell cannot drill; view one of its inputs.",
45
+ "mirror_mismatch": "This deployment is reading another tenant's data, so {subject} cannot be "
46
+ "answered here.",
47
+ "mirror_not_ready": "The data mirror is still loading, so {subject} cannot be answered yet.",
48
+ "binding_invalid": "That cell's source is not set up correctly.",
49
+ "aggregate_unknown": "{subject} is not an aggregate this cell can compute.",
50
+ "field_unknown": "{subject} is not a column on this database.",
51
+ }
52
+
53
+
54
+ class SheetRefusal(Exception):
55
+ """A named refusal. `code` is C2 vocabulary; `message` is the sentence a person reads."""
56
+
57
+ def __init__(self, code, subject=""):
58
+ template = REFUSALS.get(code) or "{subject} could not be answered."
59
+ self.code = code
60
+ self.subject = str(subject or "")
61
+ self.message = template.format(subject=self.subject or "this database")
62
+ super().__init__(self.message)
63
+
64
+
65
+ def clean_binding(raw):
66
+ """Normalize a C2 `Binding`, or raise `SheetRefusal`.
67
+
68
+ `Binding = {database, aggregate:{fn, field?} | {metric_key}, scope:{view_id} | {filter},
69
+ period?: {ref} | {window}}`
70
+ """
71
+ if not isinstance(raw, dict):
72
+ raise SheetRefusal("binding_invalid")
73
+ database = str(raw.get("database") or "").strip()
74
+ if not database:
75
+ raise SheetRefusal("binding_invalid")
76
+
77
+ agg = raw.get("aggregate")
78
+ if not isinstance(agg, dict):
79
+ raise SheetRefusal("binding_invalid")
80
+ out_agg = {}
81
+ if agg.get("metric_key"):
82
+ out_agg = {"metric_key": str(agg["metric_key"]).strip()}
83
+ else:
84
+ fn = str(agg.get("fn") or "").strip().lower()
85
+ if fn not in AGGREGATE_FNS:
86
+ raise SheetRefusal("aggregate_unknown", agg.get("fn") or "That")
87
+ out_agg = {"fn": fn}
88
+ # ⚠ COUNT is the one aggregate with no field, and defaulting a field for it would quietly
89
+ # turn `count` into `count(<some column>)`, which skips NULLs and answers a smaller number.
90
+ if fn != "count":
91
+ field = str(agg.get("field") or "").strip()
92
+ if not field:
93
+ raise SheetRefusal("binding_invalid")
94
+ out_agg["field"] = field
95
+ elif agg.get("field"):
96
+ out_agg["field"] = str(agg["field"]).strip()
97
+
98
+ scope = raw.get("scope")
99
+ if not isinstance(scope, dict):
100
+ raise SheetRefusal("binding_invalid")
101
+ if scope.get("view_id"):
102
+ out_scope = {"view_id": str(scope["view_id"]).strip()}
103
+ # ⭐ THE VIEW'S NAME IS STORED AT BIND TIME, ON PURPOSE. C2's `view_missing` refusal has to
104
+ # NAME the view ("View Top accounts no longer exists"), and once the record is deleted
105
+ # there is nothing left to look a name up from. Carrying it is the only way that sentence
106
+ # can still be written after the thing it names is gone.
107
+ if scope.get("view_name"):
108
+ out_scope["view_name"] = str(scope["view_name"]).strip()
109
+ elif scope.get("filter") is not None:
110
+ out_scope = {"filter": scope["filter"]}
111
+ else:
112
+ raise SheetRefusal("binding_invalid")
113
+
114
+ out = {"database": database, "aggregate": out_agg, "scope": out_scope}
115
+
116
+ period = raw.get("period")
117
+ if isinstance(period, dict) and (period.get("ref") or period.get("window")):
118
+ out["period"] = ({"ref": str(period["ref"]).strip()} if period.get("ref")
119
+ else {"window": period["window"]})
120
+ return out
121
+
122
+
123
+ def filter_columns_named(nodes):
124
+ """Every `colId` a filter tree names, at any depth, including a right-hand column reference.
125
+
126
+ ⚠ A mirror of `routes_odoo_tables._leaf_cols`, and it must stay one: it is how this module
127
+ learns which columns a predicate DEPENDS ON, and therefore which of them the compiler will
128
+ silently skip. Missing a nesting shape here means missing a widen.
129
+ """
130
+ seen = set()
131
+ for node in (nodes or ()):
132
+ if not isinstance(node, dict):
133
+ continue
134
+ if node.get("children") is not None:
135
+ seen |= filter_columns_named(node.get("children"))
136
+ elif node.get("colId"):
137
+ seen.add(str(node["colId"]))
138
+ rhs = node.get("rhs")
139
+ if isinstance(rhs, dict) and rhs.get("colId"):
140
+ seen.add(str(rhs["colId"]))
141
+ return seen
142
+
143
+
144
+ def widen_limits(nodes, columns, compiled=None):
145
+ """The `limits` rows for every part of a filter that did NOT reach the SQL.
146
+
147
+ ⛔⛔ THIS IS THE HALF OF STANDING RULE 1 THAT KEEPS GETTING DROPPED. A condition that does not
148
+ compile is SKIPPED, and a skipped condition WIDENS the answer. The number still comes back, and
149
+ it is bigger than the binding asked for. Returning it without this list is how a cell reports a
150
+ wider number as fact.
151
+
152
+ ⭐⭐ **IT IS MEASURED AGAINST WHAT THE COMPILER ACTUALLY USED, NOT AGAINST WHAT LOOKED
153
+ ANSWERABLE.** The first version of this function compared the tree's column names against the
154
+ offered `columns` and stopped there, which catches an unknown COLUMN and nothing else. Measured
155
+ on the live orders mirror: a leaf whose OPERATOR is not in `filter_sql.FILTER_OPS` (`is` rather
156
+ than `eq`) compiled to no predicate at all, so a bound cell answered 33,093 for a filter whose
157
+ true answer was 24,920 — **a third more rows than asked for, with an empty `limits` list.** The
158
+ column was known, so a column-only check reported nothing. Comparing against
159
+ `Compiled.columns_used` catches every reason a leaf can fall out: unknown column, unknown
160
+ operator, a value the leaf could not use, a rank op this compiler deliberately refuses.
161
+
162
+ ⚠ `routes_odoo_tables.py`'s docstring names a helper `_unpushable` as the thing that does this.
163
+ That helper DOES NOT EXIST anywhere in the repo (2026-09-02); the live mechanism is an inline
164
+ `limits.append` on the rows door, and it is column-only, so it carries the same blind spot.
165
+ """
166
+ named = filter_columns_named(nodes)
167
+ if not named:
168
+ return []
169
+ used = set(getattr(compiled, "columns_used", None) or ()) if compiled is not None else set()
170
+ dropped = sorted(named - used)
171
+ if not dropped:
172
+ return []
173
+ unknown = sorted(named - set(columns or {}))
174
+ known_but_dropped = [c for c in dropped if c not in unknown]
175
+ out = []
176
+ if unknown:
177
+ out.append({
178
+ "subject": ", ".join(unknown),
179
+ "effect": "filter_ignored",
180
+ "cause": "these columns have no expression in the mirror (a link, a rollup, or a "
181
+ "column this deployment's mirror has not backfilled), so a condition on them "
182
+ "cannot be answered in SQL",
183
+ "recommendation": "filter on the id column the link is built from, or open the linked "
184
+ "database directly",
185
+ })
186
+ if known_but_dropped:
187
+ out.append({
188
+ "subject": ", ".join(known_but_dropped),
189
+ "effect": "filter_ignored",
190
+ "cause": "the mirror knows these columns, but the condition on them could not be "
191
+ "turned into SQL, so it was not applied and this number covers more rows "
192
+ "than the filter asked for",
193
+ "recommendation": "check the operator on that condition, then open the database "
194
+ "directly to confirm the number",
195
+ })
196
+ return out
197
+
198
+
199
+ def compile_scope(nodes, conj, columns, *, today=None, cohort_sets=None):
200
+ """The predicate for one filter tree, or None when nothing is active.
201
+
202
+ ⛔ None MEANS NO PREDICATE, NOT A FALSE ONE. `compile_filter_tree`'s own docstring says so, and
203
+ treating None as "match nothing" inverts the filter: the cell would show 0 for a binding that
204
+ should have counted the whole database. The caller must add nothing to its WHERE in that case.
205
+
206
+ ⚠ `today` and `cohort_sets` REFUSE when they are needed and missing; neither defaults. `today`
207
+ is what a relative date condition needs, and it is exactly the value R14's `period.ref` feeds.
208
+ """
209
+ from harness.filter_sql import compile_filter_tree
210
+ return compile_filter_tree(list(nodes or ()), conj=conj or "and", columns=columns or {},
211
+ today=today, cohort_sets=cohort_sets)
212
+
213
+
214
+ def stored_tree_parts(tree):
215
+ """`(nodes, conj)` for a stored `{conj, nodes}` filter.
216
+
217
+ ⛔ READ IT THROUGH THIS, NEVER BY HAND. A stored wall or view filter is `{conj, nodes}` while
218
+ both consumers take a BARE NODE LIST plus a separate conj. Handing the dict straight to
219
+ `_leaf_cols` or `compile_filter_tree` is SILENTLY EMPTY rather than an error: the dict's KEYS
220
+ are iterated, no dict is found among them, and the answer is "this names no columns" - so an
221
+ unanswerable wall compiles to NO WALL AT ALL, on the one path where that serves the whole
222
+ database to somebody who may not see it.
223
+ """
224
+ from harness import filter_eval
225
+ return filter_eval.tree_parts(tree)
226
+
227
+
228
+ def aggregate_sql(spec, aggregate, columns):
229
+ """The SELECT expression for a C2 aggregate, and the column it reads.
230
+
231
+ ⭐ The column expression comes from the mirror SPEC, never from the binding's text. A binding
232
+ names a column KEY; only the spec knows the SQL behind that key, and letting a key reach SQL
233
+ unmapped is how an injection or a silent wrong column happens.
234
+ """
235
+ fn = aggregate.get("fn")
236
+ if fn == "count":
237
+ return "COUNT(*)", None
238
+ key = aggregate.get("field") or ""
239
+ col = (columns or {}).get(key)
240
+ if not col or not col.get("sql"):
241
+ raise SheetRefusal("field_unknown", key or "That column")
242
+ return f"{fn.upper()}({col['sql']})", key
243
+
244
+
245
+ def build_aggregate_query(spec, binding, columns, *, scope_nodes, scope_conj,
246
+ wall_nodes=None, wall_conj="and", today=None, cohort_sets=None):
247
+ """`(sql, params, limits)` for one bound cell.
248
+
249
+ ⛔⛔ **THE SPEC'S OWN `where` IS NOT OPTIONAL AND IT IS NOT AN OPTIMISATION.** It carries the
250
+ FIXED wholesale scope (`state IN ('sale','done') AND partner_id IS NOT NULL` for orders), which
251
+ is the project's standing "scope is fixed" convention expressed as SQL. A query built from
252
+ `cols` alone counts DRAFT and CANCELLED rows, so it returns a bigger number that looks entirely
253
+ reasonable and disagrees with every grid and module reading the same data. That is the worst
254
+ class of defect this ticket can ship, because nothing goes red.
255
+
256
+ ⭐⭐ **THE EXCLUDED PARTNER SET IS ALREADY BAKED IN AND MUST NOT BE APPLIED AGAIN HERE.**
257
+ `routes_odoo_tables._source_for` resolves `needs_excluded` BEFORE this function ever sees the
258
+ spec: it reads `excluded_ids(cur)` and substitutes them into any column expression carrying
259
+ `{excluded}`, then returns `{**spec, "cols": <resolved>}`. Adding a second `partner_id NOT IN
260
+ (...)` clause here would double-apply it, and worse, it would be WRONG on every joined spec:
261
+ order lines address the column as `sol.order_partner_id` and GL lines as `aml.partner_id`, so a
262
+ bare `partner_id` would either match nothing or fail to compile. The spec arrives resolved; use
263
+ it as given.
264
+
265
+ ⚠ `from_sql` beats `table` where a spec declares it. The joined specs (order lines, GL lines)
266
+ carry `from_sql` plus a `tables` alias map, and reading `table` alone would query one side of
267
+ the join with column expressions written for both.
268
+ """
269
+ select, _read = aggregate_sql(spec, binding["aggregate"], columns)
270
+ where = []
271
+ params = []
272
+
273
+ base = str(spec.get("where") or "").strip()
274
+ if base:
275
+ where.append(f"({base})")
276
+
277
+ scope_compiled = None
278
+ for nodes, conj, is_scope in ((wall_nodes, wall_conj, False),
279
+ (scope_nodes, scope_conj, True)):
280
+ compiled = compile_scope(nodes, conj, columns, today=today, cohort_sets=cohort_sets)
281
+ if is_scope:
282
+ scope_compiled = compiled
283
+ if compiled is None: # nothing active: add NOTHING. See `compile_scope`.
284
+ continue
285
+ where.append(f"({compiled.sql})")
286
+ params.extend(list(compiled.params))
287
+
288
+ source = str(spec.get("from_sql") or "").strip() or str(spec.get("table") or "").strip()
289
+ if not source:
290
+ raise SheetRefusal("binding_invalid")
291
+ sql = f"SELECT {select} FROM {source}"
292
+ if where:
293
+ sql += " WHERE " + " AND ".join(where)
294
+ # ⭐ The limits are measured against what the compiler REALLY used, so a leaf that fell out for
295
+ # any reason is reported. See `widen_limits` for the measurement that made this necessary.
296
+ return sql, params, widen_limits(scope_nodes, columns, scope_compiled)
297
+
298
+
299
+ #: A drill hands `LinkGridModal` a list of record ids. It is capped because the popup renders them,
300
+ #: and because an uncapped list is a way to pull a whole database through one cell.
301
+ #: ⚠ THIS IS A CAP ON A DRILL POPUP, NOT ON A CONNECTOR READ. Standing rule 1 forbids capping the
302
+ #: data pulled from a connected source; the AGGREGATE above reads the whole scope with no limit.
303
+ #: This bounds only how many ids one popup is handed, and the true `count` is returned beside them
304
+ #: so the caller can say "showing 500 of 24,920" rather than quietly showing 500.
305
+ MAX_DRILL_IDS = 500
306
+
307
+
308
+ def build_ids_query(spec, columns, *, scope_nodes, scope_conj, wall_nodes=None, wall_conj="and",
309
+ today=None, cohort_sets=None, limit=MAX_DRILL_IDS):
310
+ """`(sql, params, limits)` for the ROW IDS behind a bound cell (R6, R13).
311
+
312
+ Same WHERE as the aggregate, by construction: it is built by the same function so the popup
313
+ cannot disagree with the number that opened it.
314
+ """
315
+ id_expr = str(spec.get("id") or "").strip()
316
+ if not id_expr:
317
+ raise SheetRefusal("binding_invalid")
318
+ probe = {"aggregate": {"fn": "count"}}
319
+ sql, params, limits = build_aggregate_query(
320
+ spec, probe, columns, scope_nodes=scope_nodes, scope_conj=scope_conj,
321
+ wall_nodes=wall_nodes, wall_conj=wall_conj, today=today, cohort_sets=cohort_sets)
322
+ sql = sql.replace("SELECT COUNT(*) FROM", f"SELECT {id_expr} FROM", 1)
323
+ return f"{sql} LIMIT {int(limit)}", params, limits
324
+
325
+
326
+ # ── W49-T10: the dependents provider (contract C3) ───────────────────────────────────────────
327
+
328
+ def sheet_dependents(st, target):
329
+ """Which Sheet cells depend on `target`, as C3 `Dependent` rows.
330
+
331
+ `target = {"kind": "table"|"view"|"field", "key": str, "database"?: str}`.
332
+
333
+ ⛔ RETURNS A LIST, ALWAYS, AND NEVER A GENERATOR. R23 refuses to switch off a table that
334
+ something depends on, and the refusal NAMES the dependents. An under-count here does not read
335
+ as an error: it reads as permission to switch the table off while a Sheet cell still binds to
336
+ it. So every workbook is materialised, and one whose document cannot be read is COUNTED as
337
+ unreadable rather than silently skipped.
338
+
339
+ ⭐ REGISTERED with `platform/core/dependents.py` at the bottom of this module (W49-T11,
340
+ completed by the wave-49 combine). Until that merge this file could not import it at all --
341
+ it is lane B's, and it did not exist in lane A's worktree.
342
+ """
343
+ from core import sheets as sheet_store
344
+
345
+ kind = str((target or {}).get("kind") or "")
346
+ key = str((target or {}).get("key") or "")
347
+ database = str((target or {}).get("database") or "")
348
+ if not kind or not key:
349
+ return []
350
+
351
+ hits, unreadable = [], 0
352
+ for row in sheet_store.list_workbooks(st):
353
+ try:
354
+ book = sheet_store.get_workbook(st, row["id"])
355
+ except sheet_store.SheetRefusal:
356
+ unreadable += 1
357
+ continue
358
+ for tab in book.get("sheets") or ():
359
+ for addr, cell in (tab.get("cells") or {}).items():
360
+ if _cell_depends_on(cell, kind, key, database):
361
+ hits.append(f"{book.get('name') or book.get('id')} / "
362
+ f"{tab.get('name') or tab.get('id')}!{addr}")
363
+
364
+ out = []
365
+ if hits:
366
+ # ⛔ NO `label` KEY, DELIBERATELY. `dependents.dependents_report` defaults it to
367
+ # `noun("sheet_cell", count)`, which AGREES IN NUMBER; a static "Sheet cells" renders
368
+ # the user-facing refusal "Leads is used by 1 Sheet cells". Enforced, not merely
369
+ # written down: `verify_shared_views.py`'s `(W49-T11b)` leg reds on a static label.
370
+ out.append({"kind": "sheet_cell", "count": len(hits), "ids": hits})
371
+ if unreadable:
372
+ # ⚠ REPORTED, never folded into the count above. "3 cells depend on this" and "3 cells
373
+ # depend on this and 2 workbooks could not be read" are different answers, and only the
374
+ # second one lets a person decide whether to proceed.
375
+ out.append({"kind": "sheet_unreadable",
376
+ "label": ("Workbook that could not be read" if unreadable == 1
377
+ else "Workbooks that could not be read"),
378
+ "count": unreadable, "ids": []})
379
+ return out
380
+
381
+
382
+ # ── W49-T11 (combine-owned): register the provider with the dependents registry ────────────
383
+ #
384
+ # ⛔ THIS ONE LINE IS THE WHOLE TICKET, AND IT COULD NOT EXIST IN LANE A.
385
+ # `platform/core/dependents.py` is lane B's file and was absent from lane A's worktree, so the
386
+ # provider above was built, gated and observed without ever being reachable. Registering it is
387
+ # what makes R23 refuse to switch off a table a Sheet cell binds to.
388
+ # ⚠ `register()` REPLACES a kind rather than adding a second answer, so importing this module
389
+ # twice cannot double-count.
390
+ from core import dependents as _dependents # noqa: E402 - after the provider it registers
391
+
392
+ _dependents.register("sheet_cell", sheet_dependents)
393
+
394
+
395
+ def _cell_depends_on(cell, kind, key, database):
396
+ if not isinstance(cell, dict) or cell.get("kind") != "bound":
397
+ return False
398
+ binding = cell.get("binding")
399
+ if not isinstance(binding, dict):
400
+ return False
401
+ db = str(binding.get("database") or "")
402
+ scope = binding.get("scope") if isinstance(binding.get("scope"), dict) else {}
403
+ agg = binding.get("aggregate") if isinstance(binding.get("aggregate"), dict) else {}
404
+
405
+ if kind == "table":
406
+ return db == key
407
+ if kind == "view":
408
+ return str(scope.get("view_id") or "") == key
409
+ if kind == "field":
410
+ if database and db != database:
411
+ return False
412
+ # ⭐ A field target matches the AGGREGATE's column AND any column the filter tree names.
413
+ # Matching only the aggregate would miss a cell that filters on the field it is about to
414
+ # lose, which is the more common shape.
415
+ if str(agg.get("field") or "") == key:
416
+ return True
417
+ nodes = scope.get("filter")
418
+ if isinstance(nodes, dict):
419
+ nodes = nodes.get("nodes")
420
+ return key in filter_columns_named(nodes)
421
+ return False
platform/modules/warehouse.py CHANGED
@@ -721,6 +721,87 @@ def untrusted_counts(t=None):
721
  return codes
722
 
723
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
724
  def program_health(adj):
725
  """Counting-program health: gross corrections (12m, layer-valued) as a share of inventory
726
  value. Inventory value here is qty x CURRENT standard cost — an approximation used only for
 
721
  return codes
722
 
723
 
724
+ # --- W49-T24 — THE AMAZON FBA WAREHOUSE ----------------------------------------------------
725
+ #
726
+ # ⭐⭐ FBA IS A WAREHOUSE, NOT A LOCATION NAME, AND THAT DISTINCTION IS THE WHOLE TICKET.
727
+ # MEASURED 2026-09-02 on tenant #0: `stock.warehouse` code 'FBA' (id 8) with one active internal
728
+ # location `FBA/Stock`, 66,007.01 units over 604 quants and 582 products.
729
+ #
730
+ # ⛔ `DITM/Stock/AMZN` (location 14533) IS NOT FBA. It is a DOMESTIC Amazon prep zone inside the
731
+ # Ditmas warehouse, so a scope built by matching a location NAME against /amzn|amazon/ sweeps it
732
+ # in and silently overstates the column. Scoping by the WAREHOUSE CODE does not, which is why
733
+ # every read below starts from `fba_warehouse()` and never from a location name.
734
+ #
735
+ # ⛔ THE ID IS RESOLVED AT RUNTIME, NEVER PINNED. 8 is a TENANT fact measured on tenant #0, not a
736
+ # platform fact; the moment a second tenant onboards, a literal here is a cross-tenant wrong
737
+ # number that no gate can see. `verify_product_pool.py`'s fixture deliberately hands back a
738
+ # DIFFERENT id so a hard-coded 8 would go red rather than pass by coincidence.
739
+ FBA_WAREHOUSE_CODE = 'FBA'
740
+ #: ⭐ STANDING RULE 1 — A BATCH SIZE, NOT A CAP. Every requested product id is read; the loop
741
+ #: below simply asks Odoo for them 5,000 at a time, matching `untrusted_counts` above. Nothing
742
+ #: is dropped, and the report each reader returns states the requested/read counts so a short
743
+ #: pull is visible as a number instead of as a plausible smaller total.
744
+ _FBA_BATCH = 5000
745
+
746
+
747
+ def fba_warehouse():
748
+ """The `stock.warehouse` whose short code is FBA, or `None` when the tenant has no such
749
+ warehouse.
750
+
751
+ ⚠ `None` IS THE BLANK-NOT-ZERO SIGNAL for everything downstream. A tenant with no Amazon
752
+ warehouse holds no FBA stock and holds no OPINION about FBA stock, and printing 0 units on
753
+ 5,873 rows would be a measurement nobody made.
754
+ """
755
+ found = O.search_read('stock.warehouse', [('code', '=', FBA_WAREHOUSE_CODE)],
756
+ ['id', 'name', 'code'])
757
+ return found[0] if found else None
758
+
759
+
760
+ def fba_qty_by_product_id(product_ids=None, wh=None):
761
+ """`({product_id: units}, report)` — units held in the FBA warehouse, per `product.product`.
762
+
763
+ ⭐⭐ THIS IS NOT A SECOND DEFINITION OF ON HAND. It is the SAME `product.product.qty_available`
764
+ field, read under Odoo's own `warehouse` context, which is exactly what makes the two columns
765
+ reconcile by construction: the unscoped read INCLUDES these units, so On hand is unchanged and
766
+ `on_hand >= fba` holds for every row. MEASURED live 2026-09-02: the context read totals
767
+ 66,007.01, tying to the `stock.quant` sum over the same warehouse to the cent, with zero
768
+ per-product disagreement over all 582 products and zero rows where On hand fell below it.
769
+
770
+ ⛔ `execute_kw`, NOT `search_read`. `OdooClient.search_read` takes no `context` argument and
771
+ the client's write guard sits on `execute_kw`, so this stays inside STANDING RULE 4: the
772
+ method asked for is `search_read`, which the guard passes and no write path can reach.
773
+
774
+ ⚠ `(None, report)` — not `({}, report)` — when the tenant has no FBA warehouse. An empty map
775
+ would read as "every SKU holds zero", and the caller must be able to tell the two apart.
776
+ """
777
+ wh = wh if wh is not None else fba_warehouse()
778
+ if not wh:
779
+ return None, {'available': False,
780
+ 'cause': "no stock.warehouse carries the code " + FBA_WAREHOUSE_CODE,
781
+ 'recommended_fix': "give the Amazon warehouse the short code "
782
+ + FBA_WAREHOUSE_CODE + " in Odoo, or leave the column "
783
+ "blank if this tenant sells nothing through FBA"}
784
+ o = O.get_odoo()
785
+ ctx = {'warehouse': wh['id']}
786
+ if product_ids is None:
787
+ ids = [p['id'] for p in O.search_read('product.product', [('active', '=', True)], ['id'])]
788
+ else:
789
+ ids = [int(i) for i in product_ids if i is not None]
790
+ out, batches = {}, 0
791
+ for i in range(0, len(ids), _FBA_BATCH):
792
+ batches += 1
793
+ chunk = ids[i:i + _FBA_BATCH]
794
+ for r in o.execute_kw('product.product', 'search_read', [[('id', 'in', chunk)]],
795
+ {'fields': ['id', 'qty_available'], 'context': ctx}):
796
+ out[r['id']] = r.get('qty_available') or 0.0
797
+ return out, {'available': True, 'warehouse_id': wh['id'],
798
+ 'warehouse_code': wh.get('code'), 'warehouse_name': wh.get('name'),
799
+ 'resolved_by': 'stock.warehouse.code at runtime, never a pinned id',
800
+ 'products_requested': len(ids), 'products_read': len(out),
801
+ 'batches': batches, 'batch_size': _FBA_BATCH,
802
+ 'cap': 'none: every requested product id is read, 5000 per round trip'}
803
+
804
+
805
  def program_health(adj):
806
  """Counting-program health: gross corrections (12m, layer-valued) as a share of inventory
807
  value. Inventory value here is qty x CURRENT standard cost — an approximation used only for
web/public/sample_customers.json CHANGED
@@ -16,7 +16,7 @@
16
  "source": "odoo",
17
  "derived": true,
18
  "default": false,
19
- "description": "The Odoo res.partner id — the key every Odoo document joins on. DERIVED: this row's pid IS the partner id, so a stored copy would be a second source."
20
  },
21
  {
22
  "key": "odoo_status",
@@ -57,7 +57,7 @@
57
  "type": "select",
58
  "source": "odoo",
59
  "default": false,
60
- "description": "Who keyed in most of this customer's orders — not the Agent, who owns the account."
61
  },
62
  {
63
  "key": "street",
@@ -146,7 +146,7 @@
146
  "type": "select",
147
  "source": "odoo",
148
  "default": false,
149
- "description": "Payment terms on this customer's account — Net 30, for example."
150
  },
151
  {
152
  "key": "last_order",
@@ -190,7 +190,7 @@
190
  "type": "currency",
191
  "source": "odoo",
192
  "default": false,
193
- "description": "Invoiced money past due — same basis as the Collections page."
194
  },
195
  {
196
  "_note": "wave 21 R1 — the TOTAL, added beside the rename above. AR current $ + AR overdue $, i.e. what most people mean by 'open AR'. Composed from the same ar.credit_exposure rows the siblings use, so it is transitively reconciled by ar.validate()'s residual read_group tie — no second oracle.",
 
16
  "source": "odoo",
17
  "derived": true,
18
  "default": false,
19
+ "description": "The Odoo res.partner id, the key every Odoo document joins on. DERIVED: this row's pid IS the partner id, so a stored copy would be a second source."
20
  },
21
  {
22
  "key": "odoo_status",
 
57
  "type": "select",
58
  "source": "odoo",
59
  "default": false,
60
+ "description": "Who keyed in most of this customer's orders. Not the Agent, who owns the account."
61
  },
62
  {
63
  "key": "street",
 
146
  "type": "select",
147
  "source": "odoo",
148
  "default": false,
149
+ "description": "Payment terms on this customer's account. Net 30, for example."
150
  },
151
  {
152
  "key": "last_order",
 
190
  "type": "currency",
191
  "source": "odoo",
192
  "default": false,
193
+ "description": "Invoiced money past due, on the same basis as the Collections page."
194
  },
195
  {
196
  "_note": "wave 21 R1 — the TOTAL, added beside the rename above. AR current $ + AR overdue $, i.e. what most people mean by 'open AR'. Composed from the same ar.credit_exposure rows the siblings use, so it is transitively reconciled by ar.validate()'s residual read_group tie — no second oracle.",
web/src/connectors/ConnectorModal.tsx ADDED
@@ -0,0 +1,698 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // ---------------------------------------------------------------------------
2
+ // connectors/ConnectorModal.tsx — W49-T12, ruling R26, contract C4.
3
+ //
4
+ // ⭐⭐ R26, verbatim: *"The connector popup is a centered MODAL with tabs Overview,
5
+ // Keychain, Databases, Relationships, opened from the card. The Keychain moves
6
+ // INTO it and Settings > Keychains becomes a link to the modal (one door). Field
7
+ // enablement moves into the Databases tab."*
8
+ //
9
+ // W49-T12 SHIPPED THE SHELL AND THE OVERVIEW TAB, and the other three tabs each
10
+ // rendered a named placeholder component so a later ticket could swap ONE name.
11
+ // All three swaps have now landed: `KeychainTabPlaceholder` (W49-T13),
12
+ // `RelationshipsTabPlaceholder` (W49-T15) and `DatabasesTabPlaceholder`
13
+ // (W49-T14). Every tab is now DATA, so every tab renders below the load guard,
14
+ // and `renderTab` has no branch left above it.
15
+ //
16
+ // ⛔ NO REUSABLE MODAL COMPONENT EXISTS IN THIS REPO. `CustomerGrid.tsx`'s
17
+ // `LinkGridModal` owns the portal-plus-focus-trap pattern and is NOT exported, so
18
+ // it is READ as the model and never imported. What IS shared is the layer
19
+ // contract underneath it, `customer-grid/OverlaySurface`, which already carries
20
+ // the four behaviours the done-when names: focus trap, Escape, outside-pointer
21
+ // dismiss, and focus restored to whatever was focused when the overlay mounted.
22
+ // Re-implementing those here would be a second answer to one question.
23
+ //
24
+ // ⛔⛔ TWO TRAPS, BOTH PAID FOR ALREADY, BOTH RESOLVED IN `styles/wave49/connectors.css`:
25
+ // (a) a portalled overlay paints its OWN background, or it renders transparent
26
+ // over whatever it covers ([[a-portal-overlay-carries-its-own-surface]]);
27
+ // (b) z-order is a THREE-WAY order, so the modal sits on the DIALOG step
28
+ // (`--cg-z-record`) and the portal step (`--cg-z-overlay`) stays above it
29
+ // ([[z-layering-is-a-three-way-order]]). Tokens, never a number.
30
+ //
31
+ // ⚠ NO CLIENT UNION OVER A SERVER VOCABULARY (the wave-9 law, and this directory's
32
+ // own header). `status` and `scope` arrive as STRINGS: a state the server adds
33
+ // later renders in the neutral tone instead of dropping the panel.
34
+ // ---------------------------------------------------------------------------
35
+
36
+ import { useCallback, useEffect, useRef, useState } from "react";
37
+ import { API_V1, CREDENTIALS } from "../apiContract";
38
+ import { BodyPortal, useOverlayLayer } from "../customer-grid/OverlaySurface";
39
+ import { brandForConnector } from "./brandMarks";
40
+ import DatabasesTab from "./DatabasesTab";
41
+ import KeychainTab from "./KeychainTab";
42
+ import MonidRunDialog from "./MonidRunDialog";
43
+ import RelationshipDiagram from "./RelationshipDiagram";
44
+ import { stateTone, tileText } from "./ConnectorsPage";
45
+ import type { ConnectorRelationshipGraph, ConnectorRow } from "./ConnectorsPage";
46
+ import { parseRelationshipGraph } from "./ConnectorsPage";
47
+ import "../styles/wave49/connectors.css";
48
+
49
+ /** The four tabs R26 names, in the ruling's own order. */
50
+ export type ConnectorTab = "overview" | "keychain" | "databases" | "relationships";
51
+
52
+ /** Sentence case exactly, and no ALL-CAPS chrome (DESIGN.md §2). */
53
+ export const CONNECTOR_TABS: ReadonlyArray<{ key: ConnectorTab; label: string }> = [
54
+ { key: "overview", label: "Overview" },
55
+ { key: "keychain", label: "Keychain" },
56
+ { key: "databases", label: "Databases" },
57
+ { key: "relationships", label: "Relationships" },
58
+ ];
59
+
60
+ export interface ConnectorOverview {
61
+ key: string;
62
+ label: string;
63
+ /** The server's own word for the state. Read as a string, never a union. */
64
+ status: string;
65
+ account: string;
66
+ source: string;
67
+ creates: string[];
68
+ }
69
+
70
+ export interface ConnectorKeychainEntry {
71
+ id: string;
72
+ label: string;
73
+ /** The masked preview, or "" when this reader is not allowed one (R4). */
74
+ masked: string;
75
+ scope: string;
76
+ testable: boolean;
77
+ }
78
+
79
+ /**
80
+ * What the Connect form must ask for, and what the server will accept.
81
+ *
82
+ * ⭐ AN ADDITION TO C4's `keychain` HALF, and the alternative is worse: the contract pins
83
+ * `entries`, `canConnect` and `canDisconnect` but says nothing about where a form gets its
84
+ * fields, and the only other answer is a client-side `type -> fields` map — a second copy of a
85
+ * credential shape that already lives in the connector layer.
86
+ */
87
+ export interface ConnectorConnectField {
88
+ key: string;
89
+ label: string;
90
+ /** Renders as a password box, and is never echoed back. */
91
+ secret: boolean;
92
+ }
93
+
94
+ export interface ConnectorConnectSpec {
95
+ /** The keychain entry type this connector stores, in the server's own word. */
96
+ type: string;
97
+ fields: ConnectorConnectField[];
98
+ /** The scopes THIS reader may choose, already narrowed by R4 and by `TENANT_WIDE_TYPES`. */
99
+ scopes: string[];
100
+ tenantWide: boolean;
101
+ }
102
+
103
+ export interface ConnectorKeychainHalf {
104
+ entries: ConnectorKeychainEntry[];
105
+ canConnect: boolean;
106
+ canDisconnect: boolean;
107
+ /** `null` when this connector has no credential door at all (Webhooks, the Scraper, OAuth). */
108
+ connect: ConnectorConnectSpec | null;
109
+ }
110
+
111
+ export interface ConnectorDatabaseField {
112
+ key: string;
113
+ label: string;
114
+ type: string;
115
+ /** C4 spells this `source_field` on the wire; the client speaks camelCase. */
116
+ sourceField: string;
117
+ enabled: boolean;
118
+ }
119
+
120
+ export interface ConnectorDatabaseExclusion {
121
+ sourceField: string;
122
+ reason: string;
123
+ }
124
+
125
+ export interface ConnectorDatabase {
126
+ key: string;
127
+ label: string;
128
+ enabled: boolean;
129
+ fields: ConnectorDatabaseField[];
130
+ excluded: ConnectorDatabaseExclusion[];
131
+ /**
132
+ * ⭐⭐ W49-T14 — THE OTHER DATABASES READING THE SAME SOURCE MODEL, by key.
133
+ *
134
+ * ⛔ MEASURED, AND THE DATABASES TAB WOULD LIE WITHOUT IT: `ut_odoo_invoices` and
135
+ * `ut_odoo_bills` are both `account.move`; `ut_odoo_agents` and `ut_odoo_vendors` are both
136
+ * `res.partner`. The enablement flag is keyed `"<model>.<rawName>"`, so one field switch flips
137
+ * the field under both names, and a screen that printed the same rows twice in silence would be
138
+ * offering a per-database control that is not per-database.
139
+ */
140
+ sharesFieldsWith: string[];
141
+ }
142
+
143
+ /**
144
+ * ⭐ W49-T14 · R24 — MAY THE DATABASES TAB DISCLOSE ANYTHING, AND TO THIS READER?
145
+ *
146
+ * ⛔ AN ADDITION TO C4, DECLARED, exactly as `keychain.connect` is. Without it an empty
147
+ * `databases` list means "this connector has no schema" and "this connector's schema could not be
148
+ * read" at the same time, and the tab has to pick one. The server knows which; it says so.
149
+ */
150
+ export interface ConnectorIntrospection {
151
+ introspectable: boolean;
152
+ /** Why not, in a sentence the tab prints. Empty when it is. */
153
+ reason: string;
154
+ fieldsVisible: boolean;
155
+ canToggleFields: boolean;
156
+ canToggleTables: boolean;
157
+ catalogueComplete: boolean;
158
+ capturedAt: string;
159
+ /** What an EMPTY `excluded` list actually means, composed where the diff is computed. */
160
+ excludedBasis: string;
161
+ }
162
+
163
+ export interface ConnectorDetail {
164
+ overview: ConnectorOverview;
165
+ keychain: ConnectorKeychainHalf;
166
+ databases: ConnectorDatabase[];
167
+ introspection: ConnectorIntrospection;
168
+ relationships: ConnectorRelationshipGraph;
169
+ }
170
+
171
+ const str = (v: unknown): string => (typeof v === "string" ? v : "");
172
+ const obj = (v: unknown): Record<string, unknown> =>
173
+ v && typeof v === "object" ? (v as Record<string, unknown>) : {};
174
+
175
+ function parseStrings(raw: unknown): string[] {
176
+ if (!Array.isArray(raw)) return [];
177
+ return raw.map((item) => str(item).trim()).filter((item) => item.length > 0);
178
+ }
179
+
180
+ function parseKeychainHalf(raw: unknown): ConnectorKeychainHalf {
181
+ const source = obj(raw);
182
+ const entries: ConnectorKeychainEntry[] = [];
183
+ for (const item of Array.isArray(source.entries) ? source.entries : []) {
184
+ const entry = obj(item);
185
+ const id = str(entry.id).trim();
186
+ // A credential row with no id has nothing a later tab could act on, so it is dropped
187
+ // rather than rendered as a row that refuses every control.
188
+ if (!id) continue;
189
+ entries.push({
190
+ id,
191
+ label: str(entry.label).trim() || id,
192
+ masked: str(entry.masked),
193
+ scope: str(entry.scope).trim(),
194
+ testable: entry.testable === true,
195
+ });
196
+ }
197
+ return {
198
+ entries,
199
+ canConnect: source.canConnect === true,
200
+ canDisconnect: source.canDisconnect === true,
201
+ connect: parseConnectSpec(source.connect),
202
+ };
203
+ }
204
+
205
+ /**
206
+ * The Connect descriptor, or `null`.
207
+ *
208
+ * ⛔ A SPEC WITH NO FIELDS IS `null`, NOT AN EMPTY FORM. A form that asks for nothing and then
209
+ * POSTs an empty `fields` object is refused by `keychain.add_entry` ("fields must be a non-empty
210
+ * object"), so it would be a Connect button that always fails — R7's banned shape, arrived at by
211
+ * degrading gracefully instead of honestly.
212
+ */
213
+ export function parseConnectSpec(raw: unknown): ConnectorConnectSpec | null {
214
+ const source = obj(raw);
215
+ const type = str(source.type).trim();
216
+ if (!type) return null;
217
+ const fields: ConnectorConnectField[] = [];
218
+ for (const item of Array.isArray(source.fields) ? source.fields : []) {
219
+ const field = obj(item);
220
+ const key = str(field.key).trim();
221
+ if (!key) continue;
222
+ fields.push({ key, label: str(field.label).trim() || key, secret: field.secret === true });
223
+ }
224
+ if (!fields.length) return null;
225
+ const scopes = parseStrings(source.scopes);
226
+ return {
227
+ type,
228
+ fields,
229
+ // An empty list would render a picker with no options; `business` is what every connection
230
+ // stored before this wave actually is, which is the same read default the scope bucket uses.
231
+ scopes: scopes.length ? scopes : ["business"],
232
+ tenantWide: source.tenantWide === true,
233
+ };
234
+ }
235
+
236
+ function parseDatabases(raw: unknown): ConnectorDatabase[] {
237
+ if (!Array.isArray(raw)) return [];
238
+ const out: ConnectorDatabase[] = [];
239
+ for (const item of raw) {
240
+ const row = obj(item);
241
+ const key = str(row.key).trim();
242
+ const label = str(row.label).trim();
243
+ // Same rule as `parseDirectory`: a database with no name is never rendered from its key,
244
+ // which would put an internal identifier on screen.
245
+ if (!key || !label) continue;
246
+ const fields: ConnectorDatabaseField[] = [];
247
+ for (const rawField of Array.isArray(row.fields) ? row.fields : []) {
248
+ const field = obj(rawField);
249
+ const fieldKey = str(field.key).trim();
250
+ if (!fieldKey) continue;
251
+ fields.push({
252
+ key: fieldKey,
253
+ label: str(field.label).trim() || fieldKey,
254
+ type: str(field.type).trim(),
255
+ sourceField: str(field.source_field).trim(),
256
+ enabled: field.enabled === true,
257
+ });
258
+ }
259
+ const excluded: ConnectorDatabaseExclusion[] = [];
260
+ for (const rawItem of Array.isArray(row.excluded) ? row.excluded : []) {
261
+ const item2 = obj(rawItem);
262
+ const reason = str(item2.reason).trim();
263
+ if (!reason) continue;
264
+ excluded.push({ sourceField: str(item2.source_field).trim(), reason });
265
+ }
266
+ out.push({
267
+ key,
268
+ label,
269
+ enabled: row.enabled === true,
270
+ fields,
271
+ excluded,
272
+ sharesFieldsWith: parseStrings(row.sharesFieldsWith),
273
+ });
274
+ }
275
+ return out;
276
+ }
277
+
278
+ /**
279
+ * R24's answer, read defensively.
280
+ *
281
+ * ⛔ THE DEFAULT IS "NOT INTROSPECTABLE", NOT "INTROSPECTABLE WITH NOTHING IN IT". A payload
282
+ * missing this half is a server that predates it, and the fail-closed direction shows the card's
283
+ * own content rather than a disclosure screen with empty lists and live toggles on it.
284
+ */
285
+ function parseIntrospection(raw: unknown): ConnectorIntrospection {
286
+ const source = obj(raw);
287
+ return {
288
+ introspectable: source.introspectable === true,
289
+ reason: str(source.reason).trim(),
290
+ fieldsVisible: source.fieldsVisible === true,
291
+ canToggleFields: source.canToggleFields === true,
292
+ canToggleTables: source.canToggleTables === true,
293
+ catalogueComplete: source.catalogueComplete === true,
294
+ capturedAt: str(source.capturedAt).trim(),
295
+ excludedBasis: str(source.excludedBasis).trim(),
296
+ };
297
+ }
298
+
299
+ /**
300
+ * Read the detail payload for the card that was actually clicked.
301
+ *
302
+ * ⛔ THE SELECTED KEY IS A SECOND GUARD, exactly as it is for the relationship graph: a stale
303
+ * response that arrives after the reader opened a different connector is REFUSED rather than
304
+ * painted under the new title. `parseRelationshipGraph` already applies that rule to its own
305
+ * half; this applies it to the envelope.
306
+ */
307
+ export function parseConnectorDetail(body: unknown, selectedKey: string): ConnectorDetail | null {
308
+ const source = obj(body);
309
+ const overview = obj(source.overview);
310
+ const key = str(overview.key).trim();
311
+ if (!key || key !== selectedKey) return null;
312
+ return {
313
+ overview: {
314
+ key,
315
+ label: str(overview.label).trim(),
316
+ status: str(overview.status).trim(),
317
+ account: str(overview.account).trim(),
318
+ source: str(overview.source).trim(),
319
+ creates: parseStrings(overview.creates),
320
+ },
321
+ keychain: parseKeychainHalf(source.keychain),
322
+ databases: parseDatabases(source.databases),
323
+ introspection: parseIntrospection(source.introspection),
324
+ relationships: parseRelationshipGraph(source.relationships, selectedKey),
325
+ };
326
+ }
327
+
328
+ /**
329
+ * The Access row's sentence, derived from C4's `keychain` half.
330
+ *
331
+ * ⛔ IT COMES FROM THE DETAIL PAYLOAD, NOT FROM THE CARD. The done-when says the Account, Access
332
+ * and Source rows are read from `GET /api/v1/connectors/{key}/detail`, and C4's `overview` has no
333
+ * `access` key to add one to. Reaching back into the directory row for `scope` would make one of
334
+ * three rows come from a different read, which is how two views of one connection drift apart.
335
+ *
336
+ * ⚠ BUSINESS WINS over personal for the same reason `_entry_types` says so on the server: a reader
337
+ * holding both is connected business-wide, and the stronger fact is the true one.
338
+ *
339
+ * ⛔⛔ IT TAKES THE STATUS TOO, AND THAT ARGUMENT IS THE WHOLE CORRECTNESS OF THIS ROW. Read from
340
+ * the entries alone, a connection with no KEYCHAIN entry reads as *"nobody has connected this
341
+ * yet"* — and most connected cards have no keychain entry at all: Odoo is connected through
342
+ * `env_odoo_available` on tenant #0, an OAuth provider is connected through a per-user slot,
343
+ * Webhooks and the Scraper hold no credential a keychain lists. So the modal would have said
344
+ * "nobody has connected this" beside a status pill reading `connected`, over a card whose own
345
+ * `scopeNote` says "Business-wide". That is the confidently-wrong shape this directory's server
346
+ * header was written about, and no source scan or type check can see it.
347
+ */
348
+ export function accessSentence(keychain: ConnectorKeychainHalf, status: string): string {
349
+ const scopes = keychain.entries.map((entry) => entry.scope);
350
+ if (scopes.includes("business")) return "Business-wide, for everyone in this workspace";
351
+ if (scopes.includes("personal")) return "Your own personal connection";
352
+ if (keychain.entries.length) return "Connected, and this workspace did not record the scope";
353
+ if (status === "connected") {
354
+ // True of every case that reaches here, and it names the cause rather than guessing at one:
355
+ // the connection is real, and its credential is not a keychain entry this reader can see.
356
+ return "Connected. The credential behind it is not one the keychain holds for this account.";
357
+ }
358
+ return keychain.canConnect
359
+ ? "Nobody has connected this yet. You can add a key from the Keychain tab."
360
+ : "Nobody has connected this yet, and this account cannot add a key for it.";
361
+ }
362
+
363
+ /** The brand mark, or the two-letter fallback tile the directory already uses (wave 30, R4). */
364
+ export function ConnectorMark({ connectorKey, label }: { connectorKey: string; label: string }) {
365
+ const mark = brandForConnector(connectorKey, 20);
366
+ return (
367
+ <span className="conn-modal-mark" aria-hidden="true">
368
+ {mark ?? <span className="shell-db-chip conn-tile">{tileText(label)}</span>}
369
+ </span>
370
+ );
371
+ }
372
+
373
+ /**
374
+ * ⭐ THE OVERVIEW TAB, PURE AND EXPORTED — for the same reason `ConnectorCard` and
375
+ * `DirectoryGaps` are. The modal fetches on mount and `renderToStaticMarkup` does not run
376
+ * effects, so a static render of the modal is a spinner forever. This ticket's done-when is
377
+ * VISUAL, so the thing that has to be looked at has to be paintable from a payload.
378
+ */
379
+ /**
380
+ * ⭐⭐ W49-T19 · R31 — IS THIS THE AMAZON CARD? Read off the KEY, never the label.
381
+ *
382
+ * `core/connector_directory.monid_rows` mints `md_` + `slug(name)`, so Amazon is `md_amazon` and
383
+ * the key is stable in a way a display string is not: a label is a sentence somebody may rewrite,
384
+ * and matching on one would silently stop offering the pull the day it changed.
385
+ *
386
+ * ⚠ THE NATIVE HALF IS INCLUDED ON PURPOSE. R27 keeps a catalogue card beside a native one for
387
+ * the four overlapping platforms, and if a native Amazon connector is ever added it reaches the
388
+ * same reviews through the same paid slice — so both keys open the same door rather than the
389
+ * feature quietly belonging to whichever row happened to exist first.
390
+ */
391
+ export function isAmazonConnector(key: string): boolean {
392
+ const k = String(key || "").toLowerCase();
393
+ return k === "md_amazon" || k === "amazon";
394
+ }
395
+
396
+ export function ConnectorOverviewPanel({
397
+ detail,
398
+ onPullReviews,
399
+ }: {
400
+ detail: ConnectorDetail;
401
+ /**
402
+ * ⭐ OPTIONAL, AND THE FILE'S OWN HEADER SAYS WHY. The static proof sheets render this panel
403
+ * with `renderToStaticMarkup` and pass no handlers; a required prop would red `tsc` on files
404
+ * this ticket does not own — the same lesson `onOpen` paid for one ticket earlier.
405
+ *
406
+ * ⛔ ABSENT MEANS NO CONTROL, NOT A DISABLED ONE. This directory's rule is that a reader who
407
+ * may not do a thing sees no door for it rather than one that would 403.
408
+ */
409
+ onPullReviews?: () => void;
410
+ }) {
411
+ const { overview, keychain } = detail;
412
+ return (
413
+ <div>
414
+ <dl className="conn-modal-rows">
415
+ <dt>Account</dt>
416
+ <dd>{overview.account || "No account name was recorded for this connection."}</dd>
417
+ <dt>Access</dt>
418
+ <dd>{accessSentence(keychain, overview.status)}</dd>
419
+ <dt>Source</dt>
420
+ <dd>{overview.source || "This connector did not name its source system."}</dd>
421
+ </dl>
422
+ <p className="conn-modal-creates">
423
+ {overview.creates.length
424
+ ? `Creates: ${overview.creates.join(", ")}`
425
+ : "Creates: this connector has not declared any databases in this workspace yet."}
426
+ </p>
427
+ {/* ⭐⭐ W49-T19 · R31 / C5 — THE PAID DOOR, AND IT NAMES WHAT IT DOES.
428
+ The button opens the dialog; the dialog states the price before anything is spent. The
429
+ sentence beside it is here rather than in the dialog because the decision to open it is
430
+ already a decision about money, and DESIGN.md §4 puts the explanation where the choice
431
+ is made instead of in a tour. */}
432
+ {onPullReviews ? (
433
+ <div className="conn-modal-act">
434
+ <button type="button" className="conn-modal-go" onClick={onPullReviews}>
435
+ Pull reviews
436
+ </button>
437
+ <span className="conn-modal-act-note">
438
+ Amazon reviews for the ASINs you name, landing in a database. Each ASIN is charged to
439
+ this workspace&apos;s Monid balance.
440
+ </span>
441
+ </div>
442
+ ) : null}
443
+ </div>
444
+ );
445
+ }
446
+
447
+ // ── The three tabs that are not built yet. ⛔ EACH IS ITS OWN COMPONENT SLOT so W49-T13, T14 and
448
+ // T15 replace a named component rather than editing a sentence out of a branch, and the switch
449
+ // below never has to change shape. Plain sentences, no dashes, no emojis.
450
+
451
+ /* ⛔⛔ `KeychainTabPlaceholder` STOOD HERE AND IS REPLACED BY W49-T13. The real tab is
452
+ `connectors/KeychainTab.tsx`, mounted below from the loaded detail payload rather than from a
453
+ branch that answers before the fetch — which is the one structural change this ticket makes to
454
+ `renderTab`: the keychain half is DATA, so its tab cannot render before the read lands. */
455
+
456
+ /* ⛔⛔ `DatabasesTabPlaceholder` STOOD HERE AND IS REPLACED BY W49-T14. The real tab is
457
+ `connectors/DatabasesTab.tsx`, mounted below from the loaded detail payload rather than from a
458
+ branch that answers before the fetch. That is the same structural move the keychain and
459
+ relationship tabs each made, for the third time and for the same reason: the database list, its
460
+ field catalogue and R24's introspectable flag are all DATA on this read, so a tab rendering
461
+ above the load guard could only ever paint an empty disclosure and, worse, would read
462
+ `introspectable: false` on every connector for as long as the fetch was in flight. */
463
+
464
+ /* ⛔⛔ `RelationshipsTabPlaceholder` STOOD HERE AND IS REPLACED BY W49-T15. The real tab is
465
+ `connectors/RelationshipDiagram.tsx`, mounted below from the loaded detail payload rather than
466
+ from a branch that answers before the fetch. That move is the one structural change this ticket
467
+ makes to `renderTab`, and it is the same lesson the keychain tab paid for one ticket earlier:
468
+ the relationship graph is DATA on this read, so a tab rendering above the load guard can only
469
+ ever draw an empty diagram and call it the connection's shape. */
470
+
471
+ type Load =
472
+ | { phase: "loading" }
473
+ | { phase: "ready"; detail: ConnectorDetail }
474
+ | { phase: "error"; message: string };
475
+
476
+ /**
477
+ * THE MODAL. Centered, portalled to <body>, focus-trapped, dismissed by Escape or a click
478
+ * outside, and it hands focus back to the control that opened it.
479
+ */
480
+ export default function ConnectorModal({
481
+ row,
482
+ onClose,
483
+ initialTab = "overview",
484
+ }: {
485
+ row: ConnectorRow;
486
+ onClose: () => void;
487
+ /** W49-T13 opens this modal on the Keychain tab from Settings; every other door opens Overview. */
488
+ initialTab?: ConnectorTab;
489
+ }) {
490
+ const panelRef = useRef<HTMLDivElement>(null);
491
+ const [tab, setTab] = useState<ConnectorTab>(initialTab);
492
+ const [load, setLoad] = useState<Load>({ phase: "loading" });
493
+ /**
494
+ * ⭐ W49-T13 — THE RE-READ, AND IT IS NOT OPTIONAL POLISH. The Keychain tab WRITES: it stores,
495
+ * tests, deletes and disconnects. Keying the fetch on `connectorKey` alone leaves a deleted key
496
+ * on screen until the modal is closed and reopened, which reads as a delete that did not land —
497
+ * so the effect below keys on this counter as well and every write bumps it.
498
+ */
499
+ const [reads, setReads] = useState(0);
500
+ const reread = useCallback(() => setReads((n) => n + 1), []);
501
+ /**
502
+ * ⭐⭐ W49-T19 · R31 — THE AMAZON REVIEWS PULL, OPENED FROM THE OVERVIEW TAB.
503
+ * A second overlay above this one, which is why it takes the PORTAL step and this modal keeps
504
+ * the DIALOG step ([[z-layering-is-a-three-way-order]]).
505
+ */
506
+ const [pulling, setPulling] = useState(false);
507
+ /**
508
+ * ⛔⛔ THE PULL DIALOG'S OWN SURFACE, HELD IN STATE RATHER THAN A REF, because
509
+ * `useOverlayLayer` reads `outsideElements` on every RENDER and a ref that fills in after mount
510
+ * would never reach it. See the dismissal note on the layer below.
511
+ */
512
+ const [pullSurface, setPullSurface] = useState<HTMLElement | null>(null);
513
+ const canPull = isAmazonConnector(row.key);
514
+
515
+ useOverlayLayer({
516
+ panelRef,
517
+ /**
518
+ * ⛔⛔ DISMISS THE TOP LAYER, NOT BOTH OF THEM, AND THE HOOK CANNOT DO THIS FOR US HERE.
519
+ *
520
+ * `useOverlayLayer` guards its handlers with `stack.isTop(id)` and that guard is INERT in this
521
+ * app: `OverlaySurface.tsx` exports `OverlayProvider` and nothing mounts it, so the context is
522
+ * null and every layer believes it is the top one. Both layers also listen on `document` in
523
+ * the CAPTURE phase, where `stopPropagation` does not stop a sibling listener on the same
524
+ * node. So Escape inside the pull dialog would close the dialog AND this modal underneath it.
525
+ * Answering here keeps the fix in this ticket's own files: while the pull dialog is open,
526
+ * this layer's dismissal closes THAT and stops.
527
+ */
528
+ onDismiss: () => {
529
+ if (pulling) {
530
+ setPulling(false);
531
+ return;
532
+ }
533
+ onClose();
534
+ },
535
+ dismissOnOutside: true,
536
+ /**
537
+ * ⛔ AND THE POINTER HALF OF THE SAME PROBLEM. The dialog portals as a SIBLING of this
538
+ * panel, so a press inside it is literally outside `panelRef` and would dismiss this modal
539
+ * out from under it in the middle of a paid pull. `outsideElements` is the hook's own answer.
540
+ */
541
+ outsideElements: pullSurface ? [pullSurface] : [],
542
+ initialFocus: "[data-overlay-autofocus]",
543
+ trapFocus: true,
544
+ // The layer captures whatever was focused when it mounted and focuses it again on unmount,
545
+ // which is the card's own open button. That is the done-when's "focus returns to the card".
546
+ restoreFocus: true,
547
+ });
548
+
549
+ const connectorKey = row.key;
550
+ useEffect(() => {
551
+ let dead = false;
552
+ setLoad({ phase: "loading" });
553
+ void (async () => {
554
+ try {
555
+ const res = await fetch(
556
+ `${API_V1}/connectors/${encodeURIComponent(connectorKey)}/detail`,
557
+ { credentials: CREDENTIALS }
558
+ );
559
+ const body = (await res.json().catch(() => null)) as
560
+ | { error?: { message?: string } }
561
+ | null;
562
+ if (dead) return;
563
+ if (!res.ok) {
564
+ setLoad({
565
+ phase: "error",
566
+ message: body?.error?.message || `The server answered ${res.status}.`,
567
+ });
568
+ return;
569
+ }
570
+ const detail = parseConnectorDetail(body, connectorKey);
571
+ if (!detail) {
572
+ setLoad({
573
+ phase: "error",
574
+ message:
575
+ "This connector's details were refused because the answer described a different connection.",
576
+ });
577
+ return;
578
+ }
579
+ setLoad({ phase: "ready", detail });
580
+ } catch {
581
+ if (!dead) setLoad({ phase: "error", message: "Cannot reach the server." });
582
+ }
583
+ })();
584
+ return () => {
585
+ dead = true;
586
+ };
587
+ }, [connectorKey, reads]);
588
+
589
+ const renderTab = useCallback(() => {
590
+ // ⛔ THE KEYCHAIN TAB IS BELOW THE LOAD GUARD, and the placeholder it replaces was above it.
591
+ // C4 serves the credential rows on the SAME payload as the overview, so a keychain tab that
592
+ // rendered before the read landed could only render an empty list — i.e. "nobody has
593
+ // connected this" about a connection nobody had asked the server about yet.
594
+ if (load.phase === "loading") {
595
+ return (
596
+ <p className="conn-modal-note" role="status" aria-live="polite">
597
+ Reading this connector.
598
+ </p>
599
+ );
600
+ }
601
+ if (load.phase === "error") {
602
+ return (
603
+ <p className="conn-modal-note" role="alert">
604
+ {load.message}
605
+ </p>
606
+ );
607
+ }
608
+ if (tab === "keychain") {
609
+ return <KeychainTab row={row} keychain={load.detail.keychain} onChanged={reread} />;
610
+ }
611
+ if (tab === "databases") {
612
+ return <DatabasesTab row={row} detail={load.detail} onChanged={reread} />;
613
+ }
614
+ if (tab === "relationships") {
615
+ return <RelationshipDiagram connector={row.label} graph={load.detail.relationships} />;
616
+ }
617
+ return (
618
+ <ConnectorOverviewPanel
619
+ detail={load.detail}
620
+ onPullReviews={canPull ? () => setPulling(true) : undefined}
621
+ />
622
+ );
623
+ }, [canPull, load, reread, row, tab]);
624
+
625
+ const status = load.phase === "ready" ? load.detail.overview.status : row.state;
626
+ const title = load.phase === "ready" ? load.detail.overview.label || row.label : row.label;
627
+
628
+ return (
629
+ <BodyPortal>
630
+ <div className="conn-modal-backdrop">
631
+ <section
632
+ className="conn-modal"
633
+ ref={panelRef}
634
+ role="dialog"
635
+ aria-modal="true"
636
+ aria-label={`${row.label} connector`}
637
+ data-overlay-kind="connector-detail"
638
+ tabIndex={-1}
639
+ >
640
+ <header className="conn-modal-head">
641
+ <ConnectorMark connectorKey={row.key} label={row.label} />
642
+ <span className="conn-modal-name">{title}</span>
643
+ {/* The server's own word, sentence-cased by CSS and never by `toUpperCase`. */}
644
+ {/* ⚠ ONLY WHEN THERE IS A WORD. A modal opened from Settings > Keychains carries no
645
+ card to read a state off, so until `/detail` lands there is nothing to say and an
646
+ empty pill would be a coloured hole in the header. */}
647
+ {status ? (
648
+ <span className={"conn-modal-pill" + stateTone(status)}>{status}</span>
649
+ ) : null}
650
+ <button
651
+ type="button"
652
+ className="conn-modal-close"
653
+ aria-label={`Close the ${row.label} connector`}
654
+ data-overlay-autofocus
655
+ onClick={onClose}
656
+ >
657
+ ×
658
+ </button>
659
+ </header>
660
+ <div className="conn-modal-tabs" role="tablist" aria-label="Connector sections">
661
+ {CONNECTOR_TABS.map((entry) => (
662
+ <button
663
+ key={entry.key}
664
+ type="button"
665
+ role="tab"
666
+ id={`conn-tab-${entry.key}`}
667
+ className="conn-modal-tab"
668
+ aria-selected={tab === entry.key}
669
+ aria-controls="conn-tab-panel"
670
+ onClick={() => setTab(entry.key)}
671
+ >
672
+ {entry.label}
673
+ </button>
674
+ ))}
675
+ </div>
676
+ <div
677
+ className="conn-modal-body"
678
+ id="conn-tab-panel"
679
+ role="tabpanel"
680
+ aria-labelledby={`conn-tab-${tab}`}
681
+ >
682
+ {renderTab()}
683
+ </div>
684
+ </section>
685
+ </div>
686
+ {/* ⛔ RENDERED AS A SIBLING OF THE MODAL, INSIDE THE SAME PORTAL. Nesting it in
687
+ `.conn-modal-body` would put it inside a scrolling, overflow-hidden box and the overlay
688
+ would be clipped by the panel it is supposed to sit above. */}
689
+ {pulling ? (
690
+ <MonidRunDialog
691
+ label={row.label}
692
+ onClose={() => setPulling(false)}
693
+ surfaceRef={setPullSurface}
694
+ />
695
+ ) : null}
696
+ </BodyPortal>
697
+ );
698
+ }
web/src/connectors/ConnectorsPage.tsx CHANGED
@@ -28,18 +28,39 @@
28
  // ---------------------------------------------------------------------------
29
 
30
  import { useEffect, useState } from "react";
 
31
  import { API_V1, CREDENTIALS } from "../apiContract";
32
  import { brandForConnector } from "./brandMarks";
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
33
  import OdooConfigPanel, { type OdooConfig } from "./OdooConfig";
34
  import {
35
  AutomationError,
36
  getOdooSchema,
37
  getOdooStatus,
38
- setOdooFieldEnabled,
39
  type OdooSchema,
40
  type OdooStatus,
41
  } from "../automation/automationApi";
42
  import "../styles/wave45/agent-operator.css";
 
 
 
 
43
 
44
  /** One row of the directory. Everything optional but `key` + `label` is genuinely optional on
45
  * the wire — a builtin has no provider, a planned connector has no `connectedAs`. */
@@ -47,11 +68,47 @@ export interface ConnectorRow {
47
  key: string;
48
  label: string;
49
  desc: string;
50
- /** `connected` | `available` | `planned` — read as a STRING, never a union. */
 
51
  state: string;
52
- /** `builtin` | `oauth` | `token`. */
53
  kind: string;
54
- provider?: string;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
55
  /** What is missing before it can connect — shown on the card, never invented here. */
56
  needs?: string;
57
  /** The server's reader-scoped graph for this exact connection, never a provider example. */
@@ -143,7 +200,13 @@ export interface ConnectorGap {
143
 
144
  type Load =
145
  | { phase: "loading" }
146
- | { phase: "ready"; rows: ConnectorRow[]; gaps: ConnectorGap[] }
 
 
 
 
 
 
147
  | { phase: "error"; message: string };
148
 
149
  const str = (v: unknown): string => (typeof v === "string" ? v : "");
@@ -193,6 +256,18 @@ export function parseGaps(body: unknown): ConnectorGap[] {
193
  return out;
194
  }
195
 
 
 
 
 
 
 
 
 
 
 
 
 
196
  export function parseDirectory(body: unknown): ConnectorRow[] {
197
  const raw = (body as { connectors?: unknown } | null)?.connectors;
198
  if (!Array.isArray(raw)) return [];
@@ -211,7 +286,17 @@ export function parseDirectory(body: unknown): ConnectorRow[] {
211
  desc: str(c.desc),
212
  state: str(c.state) || "available",
213
  kind: str(c.kind),
214
- ...(str(c.provider) ? { provider: str(c.provider) } : {}),
 
 
 
 
 
 
 
 
 
 
215
  ...(str(c.needs) ? { needs: str(c.needs) } : {}),
216
  ...(str(c.connectedAs) ? { connectedAs: str(c.connectedAs) } : {}),
217
  ...(str(c.manage) ? { manage: str(c.manage) } : {}),
@@ -309,17 +394,14 @@ export function parseRelationshipGraph(raw: unknown, selectedKey: string): Conne
309
  return { connectionKey, status, reason, tables, relationships };
310
  }
311
 
312
- /** The selected key is a second guard after parsing: stale/filtering state never renders another card's graph. */
313
- export function selectConnectorGraph(
314
- row: ConnectorRow | undefined,
315
- selectedKey: string,
316
- ): ConnectorRelationshipGraph | null {
317
- if (!selectedKey) return null;
318
- if (!row || row.key !== selectedKey || row.relationshipGraph.connectionKey !== selectedKey) {
319
- return graphRefusal(selectedKey, "This relationship graph was refused because it does not match the selected connection.");
320
- }
321
- return row.relationshipGraph;
322
- }
323
 
324
  /** The card's FALLBACK mark: two letters from the connector's own name, in the database chip
325
  * family. Unicode-aware for the same reason the account monogram is (`Shell.tsx:299`).
@@ -347,11 +429,14 @@ export function matches(row: ConnectorRow, query: string): boolean {
347
  /**
348
  * The chip's tone for a state.
349
  *
350
- * ⚠ FIVE STATES ARRIVE, NOT THREE. C11's prose names `connected | available | planned`; the real
351
- * payload also sends `reconnect` (the token expired) and `unconfigured` (nobody registered the
352
- * client on this deployment) — a distinction the route's own comment calls the point of the
353
- * change. Read as strings and mapped here, so a SIXTH state renders in the neutral tone rather
354
- * than dropping the card (the wave-9 law: no client union over a server vocabulary).
 
 
 
355
  */
356
  /**
357
  * ⭐⭐ WAVE 32 · R4 — the SENTENCE a scope earns on a card, or "" for none.
@@ -365,14 +450,37 @@ export function matches(row: ConnectorRow, query: string): boolean {
365
  export function scopeNote(state: string, scope: string | undefined): string {
366
  if (state !== "connected") return "";
367
  if (scope === "personal") return "Your personal connection";
368
- if (scope === "business") return "Business-wide — everyone in this workspace";
 
 
369
  return "";
370
  }
371
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
372
  export function stateTone(state: string): string {
373
  if (state === "connected") return " is-on";
374
  if (state === "available" || state === "reconnect") return " is-open";
375
- return ""; // planned, unconfigured, and anything new
376
  }
377
 
378
  export default function ConnectorsPage({
@@ -390,7 +498,56 @@ export default function ConnectorsPage({
390
  }) {
391
  const [load, setLoad] = useState<Load>({ phase: "loading" });
392
  const [query, setQuery] = useState("");
393
- const [selectedConnectionKey, setSelectedConnectionKey] = useState("");
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
394
 
395
  useEffect(() => {
396
  let dead = false;
@@ -410,7 +567,12 @@ export default function ConnectorsPage({
410
  });
411
  return;
412
  }
413
- setLoad({ phase: "ready", rows: parseDirectory(body), gaps: parseGaps(body) });
 
 
 
 
 
414
  } catch {
415
  if (!dead) setLoad({ phase: "error", message: "Cannot reach the server." });
416
  }
@@ -420,10 +582,66 @@ export default function ConnectorsPage({
420
  };
421
  }, []);
422
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
423
  const allRows = load.phase === "ready" ? load.rows : [];
424
- const rows = allRows.filter((r) => matches(r, query));
425
- const selectedRow = allRows.find((row) => row.key === selectedConnectionKey);
426
- const selectedGraph = selectConnectorGraph(selectedRow, selectedConnectionKey);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
427
 
428
  return (
429
  <div className="shell-conn">
@@ -437,6 +655,15 @@ export default function ConnectorsPage({
437
  onChange={(e) => setQuery(e.target.value)}
438
  />
439
 
 
 
 
 
 
 
 
 
 
440
  {load.phase === "loading" ? (
441
  <div className="shell-loading">
442
  <span className="lp-spin lp-spin--lg" role="status" aria-label="Loading" />
@@ -461,8 +688,15 @@ export default function ConnectorsPage({
461
  */}
462
  <DirectoryGaps gaps={load.phase === "ready" ? load.gaps : []} />
463
  {load.phase === "ready" && rows.length === 0 ? (
 
 
 
464
  <p className="conn-note">
465
- {query ? "No connector matches that." : "No connectors are available yet."}
 
 
 
 
466
  </p>
467
  ) : null}
468
 
@@ -472,12 +706,41 @@ export default function ConnectorsPage({
472
  key={row.key}
473
  row={row}
474
  onKeychain={onKeychain}
475
- onSelectGraph={() => setSelectedConnectionKey(row.key)}
476
- graphSelected={row.key === selectedConnectionKey}
 
 
 
 
477
  />
478
  ))}
479
  </div>
480
- <ConnectorRelationshipPanel row={selectedRow} graph={selectedGraph} />
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
481
  </div>
482
  );
483
  }
@@ -499,9 +762,13 @@ export default function ConnectorsPage({
499
  function OdooManage({
500
  connected,
501
  onKeychain,
 
502
  }: {
503
  connected: boolean;
504
  onKeychain: () => void;
 
 
 
505
  }) {
506
  const [open, setOpen] = useState(false);
507
  const [cfg, setCfg] = useState<OdooConfig | null>(null);
@@ -567,7 +834,7 @@ function OdooManage({
567
  {open ? (
568
  <>
569
  {err ? <p className="conn-card-meta">{err}</p> : null}
570
- <OdooSyncStatus />
571
  {cfg ? (
572
  <OdooConfigPanel
573
  cfg={cfg}
@@ -600,7 +867,29 @@ function OdooManage({
600
  );
601
  }
602
 
603
- export function OdooSyncStatus() {
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
604
  const [status, setStatus] = useState<OdooStatus | null>(null);
605
  const [schema, setSchema] = useState<OdooSchema | null>(null);
606
  const [problem, setProblem] = useState("");
@@ -628,26 +917,18 @@ export function OdooSyncStatus() {
628
  <div><dt>Errors</dt><dd>{status.errors.length ? status.errors.map(String).join(", ") : "None reported"}</dd></div>
629
  </dl>
630
  <h4>Field catalog</h4>
631
- <p>Fields are default off unless an administrator enables them. Field permissions still apply.</p>
632
- <div className="w45-chip-row">
633
- {schema.fields.map((field) => (
634
- <label className={`w45-chip ${field.enabled ? "is-on" : "is-off"}`} key={field.key}>
635
- <input
636
- type="checkbox"
637
- checked={field.enabled}
638
- onChange={async (event) => {
639
- const enabled = event.currentTarget.checked;
640
- try {
641
- await setOdooFieldEnabled(field.key, enabled);
642
- setSchema((current) => current ? { ...current, fields: current.fields.map((candidate) =>
643
- candidate.key === field.key ? { ...candidate, enabled } : candidate) } : current);
644
- } catch (error) { setProblem(error instanceof Error ? error.message : "Field setting unavailable."); }
645
- }}
646
- />
647
- {field.label}{field.defaultEnabled === false ? " (default off)" : ""}
648
- </label>
649
- ))}
650
- </div>
651
  </section>
652
  );
653
  }
@@ -676,7 +957,9 @@ export function DirectoryGaps({ gaps }: { gaps: ConnectorGap[] }) {
676
  {gaps.map((g) => (
677
  <li key={g.source + g.cause}>
678
  {g.cause}
679
- {g.recommendation ? ` — ${g.recommendation}` : ""}
 
 
680
  </li>
681
  ))}
682
  </ul>
@@ -694,62 +977,194 @@ export function DirectoryGaps({ gaps }: { gaps: ConnectorGap[] }) {
694
  * provable by a picture of the shipping component rather than by a picture of a copy of it.
695
  * ⚠ Behaviour is byte-identical: this is the same JSX, lifted whole out of the map.
696
  */
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
697
  export function ConnectorCard({
698
  row,
699
  onKeychain,
700
- onSelectGraph,
701
- graphSelected = false,
 
702
  }: {
703
  row: ConnectorRow;
704
  onKeychain: () => void;
705
- /** Omitted only by the static proof sheet; the shipping page always supplies the selection door. */
706
- onSelectGraph?: () => void;
707
- graphSelected?: boolean;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
708
  }) {
709
- const planned = row.state === "planned";
 
 
 
 
 
 
 
 
 
 
 
710
  const connected = row.state === "connected";
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
711
  return (
712
  <div
713
- className={"conn-card" + (planned ? " is-planned" : "")}
714
- // ⛔ `aria-disabled`, NOT `inert`/`pointer-events` alone. A planned card is
 
715
  // non-interactive by R8, and a card that merely LOOKS faded while still taking a
716
  // click is the painted-but-unclickable failure in reverse
717
  // ([[ui-invisible-to-assertions]]). It carries no controls at all, so there is
718
  // nothing to disable — the attribute is what says so to a screen reader.
719
- {...(planned ? { "aria-disabled": true } : {})}
720
  >
721
- <div className="conn-card-head">
722
- {/* ⭐ WAVE 30 · R4 — THE LOGO, OR THE LETTERS. Two mutually exclusive marks, and
723
- they take DIFFERENT chips deliberately: letters ride the base chip because
724
- 12px text needs 4.5:1 and only `--lp-primary` clears it, while a logo brings
725
- its own colour and wants neutral ground under it. Writing one span that
726
- switched only its contents would have put a brand mark on a blue chip. */}
727
- {brandForConnector(row.key, 22) ? (
728
- <span className="conn-tile is-brand" aria-hidden="true">
729
- {brandForConnector(row.key, 22)}
730
- </span>
731
- ) : (
732
- <span className="shell-db-chip conn-tile" aria-hidden="true">
733
- {tileText(row.label)}
734
- </span>
735
- )}
736
- <span className="conn-card-name">{row.label}</span>
737
- <span className={"conn-state" + stateTone(row.state)}>
738
- {/* The server's own word, sentence-cased by CSS never by `toUpperCase` — R6
739
- bans caps in app chrome, and a chip is chrome. */}
740
- {row.state}
741
- </span>
742
- </div>
743
  <p className="conn-card-desc">{row.desc}</p>
744
- {!planned && onSelectGraph ? (
745
- <button
746
- type="button"
747
- className="conn-card-go"
748
- aria-pressed={graphSelected}
749
- onClick={onSelectGraph}
750
- >
751
- {graphSelected ? "Relationship graph selected" : "View relationship graph"}
752
- </button>
 
 
 
 
 
 
 
 
 
 
753
  ) : null}
754
  {/* ⭐⭐ WAVE 30 · R4 — THE DRILL, AND IT IS COLLAPSED FOR THE SAME REASON THE
755
  TRIGGER MENU'S IS. The owner's words are a sequence, not a layout: *"Only when
@@ -789,21 +1204,46 @@ export function ConnectorCard({
789
  ) : null}
790
  {/* ⚠ `needs` IS SHOWN WHATEVER THE STATE, and that is a correction: gating it on
791
  "not connected" hid the one line that explains an `unconfigured` row, which is
792
- the state it exists for ("the owner registers the client"). Only `planned`
793
- suppresses it, because "not built yet" beside a card already marked planned is
794
- the same sentence twice. */}
795
- {!planned && row.needs ? (
796
  <p className="conn-card-meta">{row.needs}</p>
797
  ) : null}
798
  {/* R13's honesty line for a token connector: the key is stored, the data arrives
799
  later. Shown ON the card where the decision is, never in a paragraph. */}
800
- {!planned && row.note ? <p className="conn-card-meta">{row.note}</p> : null}
801
  {/* ── the ACTION. `manage` names WHERE it lives; this decides how to open it.
802
  Every door here already existed — an OAuth start URL, the keychain dialog,
803
  the automation surface — which is exactly why this page can be chrome: it
804
  mints no new credential path (C11). An empty `manage` (a non-admin) renders
805
  NO control rather than one that would 403. */}
806
- {!planned && row.manage === "oauth" && row.startUrl ? (
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
807
  <a className="conn-card-go" href={row.startUrl}>
808
  {row.state === "reconnect" ? "Reconnect" : "Connect"}
809
  </a>
@@ -816,9 +1256,13 @@ export function ConnectorCard({
816
  ⚠ `onKeychain` stays reachable underneath: adding or replacing the KEY still
817
  happens in the room that owns keys, and this panel does not mint a second
818
  credential path (C11's rule, which is what lets this page be chrome). */}
819
- {!planned && row.manage === "keychain" && row.key === "odoo" ? (
820
- <OdooManage connected={connected} onKeychain={onKeychain} />
821
- ) : !planned && row.manage === "keychain" ? (
 
 
 
 
822
  <button type="button" className="conn-card-go" onClick={onKeychain}>
823
  {connected ? "Manage keys" : "Add keys"}
824
  </button>
@@ -832,12 +1276,12 @@ export function ConnectorCard({
832
  entries), so a member whose colleague connected Stripe business-wide still reads
833
  the card as connected and is offered nothing to fix — which is correct: there is
834
  nothing for them to do. */}
835
- {!planned && row.manage === "keychain_personal" ? (
836
  <button type="button" className="conn-card-go" onClick={onKeychain}>
837
  {connected ? "Your connection" : "Connect your own"}
838
  </button>
839
  ) : null}
840
- {!planned && row.manage === "automation" ? (
841
  <a className="conn-card-go" href="#/automation">
842
  Open automations
843
  </a>
@@ -846,92 +1290,37 @@ export function ConnectorCard({
846
  );
847
  }
848
 
849
- const CONNECTOR_GRAPH_CSS = `
850
- .conn-graph { margin: 16px 0 0; }.conn-graph-title { margin: 0 0 6px; color: var(--lp-ink); font-size: var(--lp-fs-3xs); font-weight: 600; }.conn-graph-canvas { display: block; width: 100%; min-width: 0; border: 1px solid var(--lp-line); border-radius: var(--lp-r-sm); background: var(--lp-surface-2); }.conn-graph-line { stroke: var(--lp-blue-deep); stroke-width: 1.5; fill: none; }.conn-graph-card { fill: var(--lp-surface); stroke: var(--lp-line); stroke-width: 1; }.conn-graph-card-title { fill: var(--lp-ink); font: 600 var(--lp-fs-4xs) Inter, sans-serif; }.conn-graph-field { fill: var(--lp-muted); font: var(--lp-fs-5xs) Inter, sans-serif; }.conn-graph-relation { fill: var(--lp-blue-deep); font: var(--lp-fs-5xs) Inter, sans-serif; }.conn-graph-empty { margin: 0; color: var(--lp-muted); font-size: var(--lp-fs-3xs); }`;
851
-
852
- type GraphPosition = { x: number; y: number; width: number; height: number };
853
-
854
- /** Layout follows the selected DTO's table count and permitted field counts, never provider coordinates. */
855
- function graphLayout(tables: ConnectorGraphTable[]): { positions: Map<string, GraphPosition>; width: number; height: number } {
856
- const columns = Math.min(3, Math.max(1, Math.ceil(Math.sqrt(tables.length))));
857
- const cardWidth = 196;
858
- const cardGap = 32;
859
- const padding = 20;
860
- const titleHeight = 30;
861
- const lineHeight = 16;
862
- const bottomPadding = 16;
863
- const rowHeights: number[] = [];
864
- for (let index = 0; index < tables.length; index += 1) {
865
- const row = Math.floor(index / columns);
866
- const tableHeight = titleHeight + Math.max(1, tables[index].fields.length) * lineHeight + bottomPadding;
867
- rowHeights[row] = Math.max(rowHeights[row] ?? 0, tableHeight);
868
- }
869
- const rowOffsets: number[] = [];
870
- let y = padding;
871
- for (const rowHeight of rowHeights) {
872
- rowOffsets.push(y);
873
- y += rowHeight + cardGap;
874
- }
875
- const positions = new Map<string, GraphPosition>();
876
- tables.forEach((table, index) => {
877
- const row = Math.floor(index / columns);
878
- const column = index % columns;
879
- positions.set(table.key, {
880
- x: padding + column * (cardWidth + cardGap),
881
- y: rowOffsets[row],
882
- width: cardWidth,
883
- height: rowHeights[row],
884
- });
885
- });
886
- return {
887
- positions,
888
- width: padding * 2 + columns * cardWidth + (columns - 1) * cardGap,
889
- height: Math.max(110, y - cardGap + padding),
890
- };
891
- }
892
-
893
- export function ConnectorRelationshipPanel({
894
- row,
895
- graph,
896
- }: {
897
- row: ConnectorRow | undefined;
898
- graph: ConnectorRelationshipGraph | null;
899
- }) {
900
- if (!graph) return null;
901
- const connector = row?.label || "Selected connection";
902
- if (graph.status !== "ready") {
903
- return <section className="conn-graph" aria-label={`${connector} relationship graph`}><style>{CONNECTOR_GRAPH_CSS}</style><p className="conn-graph-title">{connector} relationship graph</p><p className="conn-graph-empty" role="status">{graph.reason}</p></section>;
904
- }
905
- return <section className="conn-graph" aria-label={`${connector} relationship graph`}><style>{CONNECTOR_GRAPH_CSS}</style><p className="conn-graph-title">{connector} relationship graph</p><ConnectorRelationshipCanvas connector={connector} graph={graph} /></section>;
906
- }
907
 
908
- export function ConnectorRelationshipCanvas({
909
- connector,
910
- graph,
911
- }: {
912
- connector: string;
913
- graph: ConnectorRelationshipGraph;
914
- }) {
915
- const layout = graphLayout(graph.tables);
916
- const centerFor = (tableKey: string) => {
917
- const position = layout.positions.get(tableKey);
918
- return position ? { x: position.x + position.width / 2, y: position.y + position.height / 2 } : null;
919
- };
920
- return <>
921
- <svg className="conn-graph-canvas" viewBox={`0 0 ${layout.width} ${layout.height}`} role="img" aria-label={`${connector} actual table relationships`}>
922
- {graph.relationships.map((relationship) => {
923
- const from = centerFor(relationship.from.table);
924
- const to = centerFor(relationship.to.table);
925
- if (!from || !to) return null;
926
- const relationKey = `${relationship.from.table}.${relationship.from.field}-${relationship.to.table}.${relationship.to.field}`;
927
- return <g key={relationKey} aria-label={`${relationship.from.table}.${relationship.from.field} relates to ${relationship.to.table}.${relationship.to.field} by ${relationship.label}`}><line className="conn-graph-line" x1={from.x} y1={from.y} x2={to.x} y2={to.y} /><text className="conn-graph-relation" x={(from.x + to.x) / 2} y={(from.y + to.y) / 2 - 4} textAnchor="middle">{relationship.label}</text></g>;
928
- })}
929
- {graph.tables.map((table) => {
930
- const position = layout.positions.get(table.key);
931
- if (!position) return null;
932
- return <g key={table.key} aria-label={`${table.label}: ${table.fields.map((field) => field.label).join(", ") || "no permitted fields"}`}><rect className="conn-graph-card" x={position.x} y={position.y} width={position.width} height={position.height} rx="7" /><text className="conn-graph-card-title" x={position.x + 12} y={position.y + 20}>{table.label}</text>{table.fields.length ? table.fields.map((field, index) => <text className="conn-graph-field" key={field.key} x={position.x + 12} y={position.y + 40 + index * 16}>{field.label}</text>) : <text className="conn-graph-field" x={position.x + 12} y={position.y + 40}>No permitted fields</text>}</g>;
933
- })}
934
- </svg>
935
- {graph.relationships.length === 0 ? <p className="conn-graph-empty">No declared relationships connect the permitted tables.</p> : null}
936
- </>;
937
- }
 
28
  // ---------------------------------------------------------------------------
29
 
30
  import { useEffect, useState } from "react";
31
+ import type { MouseEvent } from "react";
32
  import { API_V1, CREDENTIALS } from "../apiContract";
33
  import { brandForConnector } from "./brandMarks";
34
+ import ConnectorModal from "./ConnectorModal";
35
+ // ⚠ A SEPARATE LINE ON PURPOSE. `verify_ui`'s `connector_modal_faults` pins the default import by
36
+ // its literal shape (`import ConnectorModal from "./ConnectorModal"`), so folding the type into
37
+ // that statement's braces reds the T12 door leg with nothing wrong with the door.
38
+ import type { ConnectorTab } from "./ConnectorModal";
39
+ // ⭐⭐ W49-T18 · R27 — the category rail and the ONE predicate that decides what a chip shows.
40
+ import DirectoryChips, {
41
+ ALL_CATEGORIES,
42
+ inCategory,
43
+ parseCategories,
44
+ type DirectoryCategory,
45
+ } from "./DirectoryChips";
46
+ // ⭐⭐ W49-T19 — the run dialog opens FROM THE CARD, with no modal in between. The catalogue has
47
+ // no `/detail` composer behind an `md_*` key, so routing Amazon through `ConnectorModal` would
48
+ // have made the one openable catalogue card a 404. See `ConnectorCard` below for the suppression
49
+ // that keeps it out of the modal path.
50
+ import MonidRunDialog from "./MonidRunDialog";
51
  import OdooConfigPanel, { type OdooConfig } from "./OdooConfig";
52
  import {
53
  AutomationError,
54
  getOdooSchema,
55
  getOdooStatus,
 
56
  type OdooSchema,
57
  type OdooStatus,
58
  } from "../automation/automationApi";
59
  import "../styles/wave45/agent-operator.css";
60
+ // ⭐ W49-T12 — the card's own open control and the relationship canvas rules live here now. The
61
+ // `CONNECTOR_GRAPH_CSS` string this file used to inject through `<style>` is DELETED: a rules
62
+ // string in a component is invisible to the R5 font scan, which walks `src/**/*.css` only.
63
+ import "../styles/wave49/connectors.css";
64
 
65
  /** One row of the directory. Everything optional but `key` + `label` is genuinely optional on
66
  * the wire — a builtin has no provider, a planned connector has no `connectedAs`. */
 
68
  key: string;
69
  label: string;
70
  desc: string;
71
+ /** `connected` | `available` | `reconnect` | `unconfigured` | `planned` | `catalogue` —
72
+ * read as a STRING, never a union. */
73
  state: string;
74
+ /** `builtin` | `oauth` | `token` | `catalogue`. */
75
  kind: string;
76
+ /**
77
+ * ⭐⭐ W49-T18 · R27 / C4 — THE ONE CATEGORY THIS CARD IS FILED UNDER, from Monid's fourteen.
78
+ * Empty for a connector nobody has filed yet, which renders under `All` only and is what
79
+ * `verify_catalog.py` names when it goes red.
80
+ */
81
+ category?: string;
82
+ /**
83
+ * ⭐ THE TAG LIST, and it is a different field from `category` on purpose. Monid's categories
84
+ * OVERLAP, so a provider carries several; the rail counts and filters on this, and `category`
85
+ * is only the primary one. `DirectoryChips.inCategory` is the single reader.
86
+ */
87
+ categories?: string[];
88
+ /** How many endpoints the catalogue lists for this provider. Measured, never estimated. */
89
+ endpoints?: number;
90
+ /**
91
+ * ⭐⭐ W49-T19 — THE DIRECT ACTION THIS CARD OFFERS, or absent for the 117 catalogue rows that
92
+ * offer none. Today the one value is `amazon_reviews`, authored in
93
+ * `core/connector_directory.MONID_ACTIONS`.
94
+ *
95
+ * ⛔ IT IS A CAPABILITY, NOT A PERMISSION. The row says the action EXISTS; whether this session
96
+ * may use it is the server's answer at `GET /monid/amazon-reviews/meta` (`canRun`), read by the
97
+ * page below. Both halves are required before a control renders, because the run route is
98
+ * admin-only and a button that 403s is the affordance R8 forbids.
99
+ *
100
+ * ⚠ READ AS A STRING, never a union (the wave-9 law): a second action added server-side must
101
+ * render as "no button here yet", not as a dropped card.
102
+ */
103
+ action?: string;
104
+ /**
105
+ * ⛔⛔ `provider` STOOD HERE AND IS DELETED BY W49-T18 / C4. The server row now carries
106
+ * `provider: "native" | "monid"` and `routes_connectors.connectors_directory` STRIPS it through
107
+ * `core.connector_directory.to_client_row` before answering, because R27's design rule is that
108
+ * which side a row came from never renders: no badge, no tooltip, nothing. Declaring the field
109
+ * here again would be an invitation to paint it. The key this field used to carry was the OAuth
110
+ * transport's own slug, read by nothing on this side.
111
+ */
112
  /** What is missing before it can connect — shown on the card, never invented here. */
113
  needs?: string;
114
  /** The server's reader-scoped graph for this exact connection, never a provider example. */
 
200
 
201
  type Load =
202
  | { phase: "loading" }
203
+ | {
204
+ phase: "ready";
205
+ rows: ConnectorRow[];
206
+ gaps: ConnectorGap[];
207
+ /** W49-T18: the category rail, exactly as the server counted it. */
208
+ chips: DirectoryCategory[];
209
+ }
210
  | { phase: "error"; message: string };
211
 
212
  const str = (v: unknown): string => (typeof v === "string" ? v : "");
 
256
  return out;
257
  }
258
 
259
+ /** A row's category TAGS, read the way every other list on this page is: strings only, blanks
260
+ * dropped, a non-array yields `[]` so an older server simply files nothing. */
261
+ export function parseCategoryTags(raw: unknown): string[] {
262
+ if (!Array.isArray(raw)) return [];
263
+ const out: string[] = [];
264
+ for (const item of raw) {
265
+ const name = str(item).trim();
266
+ if (name && !out.includes(name)) out.push(name);
267
+ }
268
+ return out;
269
+ }
270
+
271
  export function parseDirectory(body: unknown): ConnectorRow[] {
272
  const raw = (body as { connectors?: unknown } | null)?.connectors;
273
  if (!Array.isArray(raw)) return [];
 
286
  desc: str(c.desc),
287
  state: str(c.state) || "available",
288
  kind: str(c.kind),
289
+ ...(str(c.category) ? { category: str(c.category) } : {}),
290
+ ...(parseCategoryTags(c.categories).length
291
+ ? { categories: parseCategoryTags(c.categories) }
292
+ : {}),
293
+ ...(typeof c.endpoints === "number" && c.endpoints > 0
294
+ ? { endpoints: c.endpoints }
295
+ : {}),
296
+ // ⭐⭐ W49-T19 — the direct action, COPIED rather than assumed. This parser builds every
297
+ // row key by key, so a field the server adds and this line does not name is a field the
298
+ // page never sees: the button would be wired, `tsc` green, and nothing would render.
299
+ ...(str(c.action) ? { action: str(c.action) } : {}),
300
  ...(str(c.needs) ? { needs: str(c.needs) } : {}),
301
  ...(str(c.connectedAs) ? { connectedAs: str(c.connectedAs) } : {}),
302
  ...(str(c.manage) ? { manage: str(c.manage) } : {}),
 
394
  return { connectionKey, status, reason, tables, relationships };
395
  }
396
 
397
+ /*
398
+ * ⛔ `selectConnectorGraph` STOOD HERE AND IS DELETED BY W49-T12 / R26, together with the downward
399
+ * expand it served. It was the page's second guard over a graph selected by `selectedConnectionKey`
400
+ * — and that state, that panel and that button are all gone: the modal reads
401
+ * `GET /api/v1/connectors/{key}/detail`, whose `relationships` half is bound to the key that was
402
+ * asked for, and `parseRelationshipGraph` still refuses a graph belonging to another connection.
403
+ * So the guard survives; only this second copy of it does not.
404
+ */
 
 
 
405
 
406
  /** The card's FALLBACK mark: two letters from the connector's own name, in the database chip
407
  * family. Unicode-aware for the same reason the account monogram is (`Shell.tsx:299`).
 
429
  /**
430
  * The chip's tone for a state.
431
  *
432
+ * ⚠ SIX STATES ARRIVE, NOT THREE. C11's prose names `connected | available | planned`; the real
433
+ * payload also sends `reconnect` (the token expired), `unconfigured` (nobody registered the
434
+ * client on this deployment) and `catalogue` (a provider a vendor lists, which we have not
435
+ * built) — distinctions the route's own comments call the point of each change. Read as strings
436
+ * and mapped here, so a SEVENTH state renders in the neutral tone rather than dropping the card
437
+ * (the wave-9 law: no client union over a server vocabulary). The neutral tone is the answer for
438
+ * `planned`, `unconfigured` and `catalogue` alike, which is why the catalogue word could be told
439
+ * apart from the roadmap word without a card changing colour.
440
  */
441
  /**
442
  * ⭐⭐ WAVE 32 · R4 — the SENTENCE a scope earns on a card, or "" for none.
 
450
  export function scopeNote(state: string, scope: string | undefined): string {
451
  if (state !== "connected") return "";
452
  if (scope === "personal") return "Your personal connection";
453
+ // ⚠ NO EM DASH. Standing rule 2 bans U+2014 and U+2013 in any string that reaches a screen, and
454
+ // the rule says REWRITE rather than merely delete the character, so the clause became a comma.
455
+ if (scope === "business") return "Business-wide, for everyone in this workspace";
456
  return "";
457
  }
458
 
459
+ /**
460
+ * ⭐⭐ W49-T19 — THE ONE DIRECT ACTION A CATALOGUE CARD CAN CARRY, and the client half of the
461
+ * contract `core/connector_directory.MONID_ACTIONS` authors. Exported so `verify_catalog.py` can
462
+ * read the same literal on both sides rather than trusting that two spellings agree.
463
+ */
464
+ export const AMAZON_REVIEWS_ACTION = "amazon_reviews";
465
+
466
+ /**
467
+ * ⭐⭐ THE STATE A CATALOGUE LISTING WEARS, and the client half of the word
468
+ * `core/connector_directory.CATALOGUE_STATE` authors. Exported for the same reason
469
+ * `AMAZON_REVIEWS_ACTION` is: `verify_catalog.py` reads the literal on BOTH sides rather than
470
+ * trusting that two spellings agree.
471
+ *
472
+ * ⛔ IT IS NOT A SECOND WORD FOR `planned`. A planned row is a connector we intend to build, it
473
+ * is enumerated in the server's `PLANNED` list, and it carries a `needs` saying what it waits on.
474
+ * A catalogue listing is a provider we can SEE in a vendor's directory: not on our roadmap, not
475
+ * waiting on us, nothing to say. Both render faded and neither is openable, which is exactly why
476
+ * one was borrowed for the other and why that had to stop.
477
+ */
478
+ export const CATALOGUE_STATE = "catalogue";
479
+
480
  export function stateTone(state: string): string {
481
  if (state === "connected") return " is-on";
482
  if (state === "available" || state === "reconnect") return " is-open";
483
+ return ""; // planned, unconfigured, catalogue, and anything new
484
  }
485
 
486
  export default function ConnectorsPage({
 
498
  }) {
499
  const [load, setLoad] = useState<Load>({ phase: "loading" });
500
  const [query, setQuery] = useState("");
501
+ /**
502
+ * ⭐⭐ W49-T12 · R26 — THE CARD OPENS A CENTERED MODAL, and this is the whole of the page's
503
+ * share of it: which connector is open, by key.
504
+ *
505
+ * ⛔ IT REPLACES `selectedConnectionKey`, WHICH DROVE A DOWNWARD EXPAND. The relationship graph
506
+ * used to render in a panel BELOW the card grid, so clicking a card pushed the rest of the page
507
+ * down and put the answer nowhere near the question. R26 replaces that with the modal; the panel
508
+ * and its inline CSS string are deleted rather than hidden.
509
+ */
510
+ const [openKey, setOpenKey] = useState("");
511
+ /**
512
+ * ⭐⭐ W49-T14 · O9 · R26 — WHICH TAB THE MODAL OPENS ON, and it exists because the modal is now
513
+ * the ONE door to field enablement. The Odoo card used to carry its own "Field catalog" chip
514
+ * row calling `setOdooFieldEnabled`, so the same setting had two doors that could disagree; the
515
+ * chip row is deleted and its place carries a link into this tab instead.
516
+ *
517
+ * ⛔ AND IT IS RESET WHEN THE MODAL CLOSES, not by each opener. `ConnectorModal` reads
518
+ * `initialTab` as a `useState` INITIALIZER with no resync, so the value simply rides the next
519
+ * remount: leave it on "databases" and the next ordinary card click opens on Databases instead
520
+ * of Overview. Close is the chokepoint every future door already crosses, because the modal
521
+ * cannot be mounted again without being closed first; asking each opener to remember would put
522
+ * the same bug one new door away. See the `onClose` below.
523
+ */
524
+ const [openTab, setOpenTab] = useState<ConnectorTab>("overview");
525
+ /** ⭐ W49-T18 — the selected chip, by name. `All` is a real chip in Monid's sidebar rather than
526
+ * a control we invented, so the default is that name and not an empty string. */
527
+ const [category, setCategory] = useState(ALL_CATEGORIES);
528
+ /**
529
+ * ⭐⭐ W49-T19 — WHICH CARD'S PULL DIALOG IS OPEN, by key, and it is a SECOND piece of state
530
+ * beside `openKey` rather than a mode of it. The two doors lead to different surfaces: `openKey`
531
+ * mounts `ConnectorModal` over a `/detail` payload, and a catalogue row has no such payload.
532
+ */
533
+ const [pullKey, setPullKey] = useState("");
534
+ /**
535
+ * ⛔⛔ MAY THIS SESSION RUN THE PULL. The run route is admin-only, so a non-admin who is shown a
536
+ * "Pull reviews" button is being offered a 403 (R8: a card never offers an affordance that
537
+ * cannot work). The answer is the SERVER'S, read from the free
538
+ * `GET /monid/amazon-reviews/meta`, whose `canRun` is `bool(session.admin)`; the route carries
539
+ * that field for exactly this purpose.
540
+ *
541
+ * ⚠ THE ROW-LEVEL PATH WAS NOT AVAILABLE. `routes_connectors.directory` already knows
542
+ * `is_admin`, but it calls `monid_rows()` with no arguments and that file is outside this
543
+ * ticket's fence, so the admin answer arrives at a different layer. It is the same guarantee,
544
+ * from the same session, decided by the same server attribute.
545
+ *
546
+ * ⚠ IT DEFAULTS TO FALSE AND STAYS FALSE ON ANY FAILURE. A meta read that 401s, times out or
547
+ * answers nonsense must hide the control, never reveal it: the safe direction for a button that
548
+ * spends money is closed.
549
+ */
550
+ const [canPull, setCanPull] = useState(false);
551
 
552
  useEffect(() => {
553
  let dead = false;
 
567
  });
568
  return;
569
  }
570
+ setLoad({
571
+ phase: "ready",
572
+ rows: parseDirectory(body),
573
+ gaps: parseGaps(body),
574
+ chips: parseCategories(body),
575
+ });
576
  } catch {
577
  if (!dead) setLoad({ phase: "error", message: "Cannot reach the server." });
578
  }
 
582
  };
583
  }, []);
584
 
585
+ /**
586
+ * ⭐ W49-T19 — IS THERE ANYTHING FOR THE ADMIN ANSWER TO BE ABOUT. The directory is 130-odd
587
+ * cards and one of them has an action; asking the server whether this reader may pull reviews
588
+ * when no such card is on the page would be a request that can change nothing.
589
+ */
590
+ const hasPullRow =
591
+ load.phase === "ready" &&
592
+ load.rows.some((row) => row.action === AMAZON_REVIEWS_ACTION);
593
+
594
+ /**
595
+ * ⛔⛔ THE ADMIN ANSWER, AND IT IS KEPT OUT OF `load` ON PURPOSE. Folding a failed meta read
596
+ * into the page's load state would turn a missing Monid key, or a 401 on one free endpoint,
597
+ * into the whole directory rendering as an error banner. This request decides ONE button.
598
+ */
599
+ useEffect(() => {
600
+ if (!hasPullRow) return;
601
+ let dead = false;
602
+ void (async () => {
603
+ try {
604
+ const res = await fetch(`${API_V1}/monid/amazon-reviews/meta`, {
605
+ credentials: CREDENTIALS,
606
+ });
607
+ const body = (await res.json().catch(() => null)) as
608
+ | { canRun?: unknown }
609
+ | null;
610
+ if (dead) return;
611
+ // Both halves must be affirmative. A non-ok answer carries no `canRun` worth reading, and
612
+ // anything other than a literal `true` is not permission.
613
+ setCanPull(res.ok && body?.canRun === true);
614
+ } catch {
615
+ if (!dead) setCanPull(false);
616
+ }
617
+ })();
618
+ return () => {
619
+ dead = true;
620
+ };
621
+ }, [hasPullRow]);
622
+
623
  const allRows = load.phase === "ready" ? load.rows : [];
624
+ // ⭐ W49-T18 — TWO FILTERS, ONE GRID, AND THEY COMPOSE. The chip narrows the taxonomy and the
625
+ // search box narrows the text; a reader who picks "Finance" and then types keeps both, which is
626
+ // what every directory of this shape does and what the rail would be annoying without.
627
+ const rows = allRows.filter((r) => inCategory(r, category) && matches(r, query));
628
+ // ⚠ Resolved against `allRows`, not the filtered list: typing in the search box while a modal is
629
+ // open must not close the modal out from under the reader.
630
+ const openRow = allRows.find((row) => row.key === openKey);
631
+ // ⚠ Same rule, and here it protects a PAID run: filtering the grid while a pull is in flight
632
+ // must not unmount the dialog that is spending the wallet.
633
+ const pullRow = allRows.find((row) => row.key === pullKey);
634
+ /**
635
+ * ⭐⭐ W49-T19 — THE CARD'S DOOR, AND BOTH CONDITIONS ARE LOAD-BEARING. The row must carry the
636
+ * action (there IS something behind this card) and the server must have said this reader may
637
+ * run it (they can actually use it). Either one alone paints a button that 403s or a button on
638
+ * 118 cards with nothing behind them. `undefined` means the card renders no control at all,
639
+ * which is what the other unavailable doors on this page already do.
640
+ */
641
+ const pullHandler = (row: ConnectorRow) =>
642
+ canPull && row.action === AMAZON_REVIEWS_ACTION
643
+ ? () => setPullKey(row.key)
644
+ : undefined;
645
 
646
  return (
647
  <div className="shell-conn">
 
655
  onChange={(e) => setQuery(e.target.value)}
656
  />
657
 
658
+ {/* ⭐⭐ W49-T18 · R27 — THE CATEGORY RAIL, above the grid and below the search box, so the
659
+ two narrowing controls sit together. It renders nothing at all when the server sent no
660
+ taxonomy, which is the honest degradation rather than an empty rail. */}
661
+ <DirectoryChips
662
+ chips={load.phase === "ready" ? load.chips : []}
663
+ active={category}
664
+ onPick={setCategory}
665
+ />
666
+
667
  {load.phase === "loading" ? (
668
  <div className="shell-loading">
669
  <span className="lp-spin lp-spin--lg" role="status" aria-label="Loading" />
 
688
  */}
689
  <DirectoryGaps gaps={load.phase === "ready" ? load.gaps : []} />
690
  {load.phase === "ready" && rows.length === 0 ? (
691
+ // ONE line and the way out, never a paragraph (DESIGN.md §4). A chip that hides
692
+ // everything is a filter, not an empty product, so the sentence says which control to
693
+ // undo rather than explaining the taxonomy.
694
  <p className="conn-note">
695
+ {query
696
+ ? "No connector matches that."
697
+ : category !== ALL_CATEGORIES
698
+ ? `No connector is filed under ${category}.`
699
+ : "No connectors are available yet."}
700
  </p>
701
  ) : null}
702
 
 
706
  key={row.key}
707
  row={row}
708
  onKeychain={onKeychain}
709
+ onOpen={() => setOpenKey(row.key)}
710
+ onOpenDatabases={() => {
711
+ setOpenTab("databases");
712
+ setOpenKey(row.key);
713
+ }}
714
+ onPullReviews={pullHandler(row)}
715
  />
716
  ))}
717
  </div>
718
+ {openRow ? (
719
+ <ConnectorModal
720
+ row={openRow}
721
+ initialTab={openTab}
722
+ onClose={() => {
723
+ setOpenKey("");
724
+ // ⛔⛔ THE RESET LIVES ON CLOSE, WHICH IS THE ONLY PLACE THAT CATCHES EVERY DOOR.
725
+ // `ConnectorModal` reads `initialTab` as a `useState` INITIALIZER with no resync, so
726
+ // the value simply rides the next remount: open Databases from the card's link, close
727
+ // it, then click any card, and without this line that card opens on Databases. `tsc`
728
+ // is green either way and a source scan is green either way -- only a SECOND click
729
+ // finds it. Resetting in each opener instead would mean every future door had to
730
+ // remember; the modal cannot be mounted without first being closed, so this is the
731
+ // one chokepoint.
732
+ setOpenTab("overview");
733
+ }}
734
+ />
735
+ ) : null}
736
+ {/* ⭐⭐ W49-T19 — MOUNTED BY THE PAGE, NOT BY THE CARD, and not behind the modal. The card
737
+ is a pure component the static proof sheets paint, so the overlay lives where the rest
738
+ of this page's overlays live. No `surfaceRef` is handed down: that handle exists to
739
+ name this dialog's surface to a `ConnectorModal` UNDERNEATH it, and on this path there
740
+ is no modal underneath. */}
741
+ {pullRow ? (
742
+ <MonidRunDialog label={pullRow.label} onClose={() => setPullKey("")} />
743
+ ) : null}
744
  </div>
745
  );
746
  }
 
762
  function OdooManage({
763
  connected,
764
  onKeychain,
765
+ onOpenDatabases,
766
  }: {
767
  connected: boolean;
768
  onKeychain: () => void;
769
+ /** ⭐ W49-T14 · O9 — the page's door into the modal's Databases tab, passed straight through to
770
+ * `OdooSyncStatus`. Optional so the static proof sheets keep compiling. */
771
+ onOpenDatabases?: () => void;
772
  }) {
773
  const [open, setOpen] = useState(false);
774
  const [cfg, setCfg] = useState<OdooConfig | null>(null);
 
834
  {open ? (
835
  <>
836
  {err ? <p className="conn-card-meta">{err}</p> : null}
837
+ <OdooSyncStatus onOpenDatabases={onOpenDatabases} />
838
  {cfg ? (
839
  <OdooConfigPanel
840
  cfg={cfg}
 
867
  );
868
  }
869
 
870
+ /**
871
+ * ⭐⭐ W49-T14 · O9 · R26 — THE SYNC PANEL REPORTS; IT NO LONGER SETS.
872
+ *
873
+ * ⛔⛔ THIS COMPONENT USED TO BE THE SECOND DOOR TO FIELD ENABLEMENT. It painted a "Field catalog"
874
+ * chip row whose every checkbox called `setOdooFieldEnabled`, i.e. `PATCH /connectors/odoo/schema/
875
+ * {key}` — the exact route the modal's Databases tab writes through `DatabasesTab::flipField`.
876
+ * Two doors onto one setting is what R26 forbids, and the cost is not tidiness: each door held its
877
+ * OWN copy of the schema, so a field switched off in the modal still read as on here until the
878
+ * card was remounted, and an administrator would have been looking at a stale answer while
879
+ * believing they had just set it.
880
+ *
881
+ * ⭐ WHAT REPLACES IT IS A LINK, NOT A SMALLER CONTROL. The panel keeps reading `getOdooSchema`
882
+ * as its readiness check (a Sync panel that cannot reach the schema has not got an answer to
883
+ * report), and the setting itself is one click away in the tab that owns it.
884
+ *
885
+ * ⛔ AND IT DELIBERATELY PRINTS NO COUNT. "N of M fields are on" was drafted here and cut:
886
+ * `OdooSchema` carries `complete: boolean` because that field list can be PARTIAL, so on an
887
+ * incomplete read the sentence would have stated a total nobody had.
888
+ *
889
+ * ⚠ NO CALLBACK MEANS NO LINK. `_conn_shot.tsx` and any other static painter pass nothing, and a
890
+ * link with no modal behind it is an affordance that cannot work (R8).
891
+ */
892
+ export function OdooSyncStatus({ onOpenDatabases }: { onOpenDatabases?: () => void } = {}) {
893
  const [status, setStatus] = useState<OdooStatus | null>(null);
894
  const [schema, setSchema] = useState<OdooSchema | null>(null);
895
  const [problem, setProblem] = useState("");
 
917
  <div><dt>Errors</dt><dd>{status.errors.length ? status.errors.map(String).join(", ") : "None reported"}</dd></div>
918
  </dl>
919
  <h4>Field catalog</h4>
920
+ {/* ⛔ ONE SHORT LINE AND NO COUNT. A first draft said "N of M fields are on", and
921
+ `OdooSchema` carries `complete: boolean` precisely because that list can be PARTIAL:
922
+ on an incomplete read the sentence would have claimed a total it does not have, which
923
+ is the confident-wrong-number failure this repo keeps paying for. The Databases tab
924
+ shows the fields themselves, so the count belongs beside them, not here.
925
+ DESIGN.md §4 - never explain the default-off policy here either; that sentence lives
926
+ next to the switches it governs. */}
927
+ {onOpenDatabases ? (
928
+ <button type="button" className="conn-db-link" onClick={onOpenDatabases}>
929
+ Manage fields in the Databases tab
930
+ </button>
931
+ ) : null}
 
 
 
 
 
 
 
 
932
  </section>
933
  );
934
  }
 
957
  {gaps.map((g) => (
958
  <li key={g.source + g.cause}>
959
  {g.cause}
960
+ {/* ⚠ The joiner was an em dash and standing rule 2 bans it on screen. A full stop
961
+ carries the same pause and needs no glyph. */}
962
+ {g.recommendation ? `. ${g.recommendation}` : ""}
963
  </li>
964
  ))}
965
  </ul>
 
977
  * provable by a picture of the shipping component rather than by a picture of a copy of it.
978
  * ⚠ Behaviour is byte-identical: this is the same JSX, lifted whole out of the map.
979
  */
980
+ /**
981
+ * The card's identity row: mark, name, state chip. Extracted in W49-T12 so it can be the same
982
+ * markup whether or not it is wrapped in the modal's open button, rather than two copies that
983
+ * drift.
984
+ */
985
+ /**
986
+ * ⭐ W49-T18 — THE MARK FOR A CARD, catalogue rows included.
987
+ *
988
+ * ⛔ NO NEW ARTWORK, AND THAT IS A RULE RATHER THAN LAZINESS. The catalogue adds 118 cards, and
989
+ * drawing 118 third-party logos would be 118 licensing decisions plus a wall of SVG nobody can
990
+ * review. So a catalogue row asks the EXISTING mark registry under its own name (its key without
991
+ * the internal prefix, which is the only thing that prefix is in the way of), and everything the
992
+ * registry has no answer for keeps the two-letter tile `tileText` has always drawn. That is the
993
+ * honest fallback and it is not an emoji, which DESIGN.md §4 bans outright.
994
+ */
995
+ export function markKey(key: string): string {
996
+ return key.startsWith("md_") ? key.slice(3) : key;
997
+ }
998
+
999
+ function ConnectorCardIdentity({ row }: { row: ConnectorRow }) {
1000
+ const mark = brandForConnector(markKey(row.key), 22);
1001
+ return (
1002
+ <>
1003
+ {/* ⭐ WAVE 30 · R4 — THE LOGO, OR THE LETTERS. Two mutually exclusive marks, and they take
1004
+ DIFFERENT chips deliberately: letters ride the base chip because 12px text needs 4.5:1
1005
+ and only `--lp-primary` clears it, while a logo brings its own colour and wants neutral
1006
+ ground under it. Writing one span that switched only its contents would have put a brand
1007
+ mark on a blue chip. */}
1008
+ {mark ? (
1009
+ <span className="conn-tile is-brand" aria-hidden="true">
1010
+ {mark}
1011
+ </span>
1012
+ ) : (
1013
+ <span className="shell-db-chip conn-tile" aria-hidden="true">
1014
+ {tileText(row.label)}
1015
+ </span>
1016
+ )}
1017
+ <span className="conn-card-name">{row.label}</span>
1018
+ <span className={"conn-state" + stateTone(row.state)}>
1019
+ {/* The server's own word, sentence-cased by CSS never by `toUpperCase`. R6 bans caps in
1020
+ app chrome, and a chip is chrome. */}
1021
+ {row.state}
1022
+ </span>
1023
+ </>
1024
+ );
1025
+ }
1026
+
1027
+ function ConnectorCardHead({ row, onOpen }: { row: ConnectorRow; onOpen?: () => void }) {
1028
+ if (!onOpen) {
1029
+ return (
1030
+ <div className="conn-card-head">
1031
+ <ConnectorCardIdentity row={row} />
1032
+ </div>
1033
+ );
1034
+ }
1035
+ return (
1036
+ <div className="conn-card-head">
1037
+ <button
1038
+ type="button"
1039
+ className="conn-card-open"
1040
+ aria-haspopup="dialog"
1041
+ aria-label={`Open the ${row.label} connector`}
1042
+ >
1043
+ <ConnectorCardIdentity row={row} />
1044
+ </button>
1045
+ </div>
1046
+ );
1047
+ }
1048
+
1049
  export function ConnectorCard({
1050
  row,
1051
  onKeychain,
1052
+ onOpen,
1053
+ onOpenDatabases,
1054
+ onPullReviews,
1055
  }: {
1056
  row: ConnectorRow;
1057
  onKeychain: () => void;
1058
+ /**
1059
+ * ⭐⭐ W49-T12 · R26 — OPEN THE CONNECTOR MODAL. Optional for the same reason `onSelectGraph`
1060
+ * was: the static proof sheets (`_conn_shot.tsx` and friends) paint this card without a door,
1061
+ * and making the prop required would red `tsc` on files this ticket does not own.
1062
+ *
1063
+ * ⛔ AND THAT IS EXACTLY WHY `verify_ui`'s `connector_modal_faults` EXISTS. An optional prop the
1064
+ * shipping page forgets to pass is a modal with no way in, compiling green
1065
+ * ([[ui-invisible-to-assertions]], and W38-T19's Metrics toggle one wave over). The type system
1066
+ * cannot enforce it, so the gate does.
1067
+ */
1068
+ onOpen?: () => void;
1069
+ /**
1070
+ * ⭐⭐ W49-T19 — OPEN THIS ROW'S OWN RUN DIALOG. Supplied by the page ONLY when the row carries
1071
+ * the action AND the server said this reader may run it, so the card's whole test is "did
1072
+ * somebody hand me this". A card never decides on its own that it may spend money.
1073
+ *
1074
+ * ⛔ AND IT IS WHY THIS CARD IS NOT MODAL-OPENABLE. A catalogue key has no `/detail` composer,
1075
+ * so `ConnectorModal` would open on a 404; `openable` below withholds the modal door from any
1076
+ * row carrying an action, which is what keeps this one interactive card honest while the other
1077
+ * 117 stay faded.
1078
+ */
1079
+ onPullReviews?: () => void;
1080
+ /**
1081
+ * ⭐⭐ W49-T14 · O9 · R26 — OPEN THE CONNECTOR MODAL ON ITS DATABASES TAB. The Odoo card's sync
1082
+ * panel used to enable fields ITSELF, through a chip row wired to `setOdooFieldEnabled`; that
1083
+ * made field enablement a setting with two doors, and R26 says the modal is the one door. The
1084
+ * chip row is deleted and this prop is what its replacement link calls.
1085
+ *
1086
+ * ⚠ Optional for the same reason `onOpen` is: `_conn_shot.tsx` paints this card with neither,
1087
+ * and a required prop would red `tsc` on a file this ticket does not own. A card handed no
1088
+ * callback shows no link rather than a control that cannot work.
1089
+ */
1090
+ onOpenDatabases?: () => void;
1091
  }) {
1092
+ /**
1093
+ * ⭐⭐ THE CARD HAS NO DOOR, AND THAT IS THE CONDITION EVERY GUARD BELOW WANTS — not the
1094
+ * literal word `planned`, which is what they all used to read.
1095
+ *
1096
+ * ⛔⛔ TWO DIFFERENT ROWS RENDER THIS WAY AND THEY ARE NOT THE SAME CLAIM. A `planned` row is
1097
+ * on the server's `PLANNED` roadmap and says in `needs` what it waits on; a `catalogue` row is
1098
+ * a provider we can see in a vendor's directory and is waiting on nothing. W49-T18 gave the
1099
+ * catalogue rows `planned` BECAUSE this fade keyed on that word, which put 117 listings into
1100
+ * our own to-do list to buy a visual. Reading "has no door" instead is what let the state word
1101
+ * go back to being true, and it is why the cards did not move a pixel when it did.
1102
+ */
1103
+ const doorless = row.state === "planned" || row.state === CATALOGUE_STATE;
1104
  const connected = row.state === "connected";
1105
+ /**
1106
+ * ⛔⛔ A ROW WITH A DIRECT ACTION IS NOT MODAL-OPENABLE, AND THIS IS THE LINE THAT SAYS SO.
1107
+ * Making `md_amazon` neither planned nor catalogue is what puts a real control on its card; it
1108
+ * must not also hand the card to `ConnectorModal`, whose Overview reads
1109
+ * `/api/v1/connectors/{key}/detail` and would 404 on a catalogue key. So the action REPLACES
1110
+ * the modal door rather than adding to it.
1111
+ */
1112
+ const hasAction = !!row.action;
1113
+ const openable = !!onOpen && !doorless && !hasAction;
1114
+ /**
1115
+ * Clicking the CARD opens the modal, and clicking one of the card's own controls does what that
1116
+ * control says. The head is a real `<button>` so the keyboard can reach the modal at all and so
1117
+ * `useOverlayLayer`'s focus restore has somewhere to put focus back; this handler is what makes
1118
+ * the rest of the card's surface open it too.
1119
+ */
1120
+ const openFromCard = (event: MouseEvent<HTMLDivElement>) => {
1121
+ if (!openable || !onOpen) return;
1122
+ const target = event.target as HTMLElement | null;
1123
+ const control = target?.closest("a, button, summary, input, label, select, textarea");
1124
+ if (control && !control.classList.contains("conn-card-open")) return;
1125
+ // Focus the card's own open button BEFORE the modal mounts: the overlay layer captures
1126
+ // whatever is focused at mount and restores it on unmount, which is the done-when's "focus
1127
+ // returns to the card that opened it".
1128
+ event.currentTarget.querySelector<HTMLElement>(".conn-card-open")?.focus();
1129
+ onOpen();
1130
+ };
1131
  return (
1132
  <div
1133
+ className={"conn-card" + (doorless ? " is-planned" : "")}
1134
+ onClick={openable ? openFromCard : undefined}
1135
+ // ⛔ `aria-disabled`, NOT `inert`/`pointer-events` alone. A doorless card is
1136
  // non-interactive by R8, and a card that merely LOOKS faded while still taking a
1137
  // click is the painted-but-unclickable failure in reverse
1138
  // ([[ui-invisible-to-assertions]]). It carries no controls at all, so there is
1139
  // nothing to disable — the attribute is what says so to a screen reader.
1140
+ {...(doorless ? { "aria-disabled": true } : {})}
1141
  >
1142
+ {/* ⭐⭐ W49-T12 · R26 — THE HEAD IS THE DOOR. When the page supplies `onOpen` the
1143
+ mark, the name and the state chip sit inside one real `<button>`: that is what a
1144
+ keyboard can reach, and it is what focus comes back TO when the modal closes. The
1145
+ static proof sheets pass no `onOpen` and get the plain head they always had, so
1146
+ nothing outside this ticket's fence has to change. */}
1147
+ <ConnectorCardHead row={row} onOpen={openable ? onOpen : undefined} />
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1148
  <p className="conn-card-desc">{row.desc}</p>
1149
+ {/* ⭐⭐ W49-T18 · R27 / C4 — WHERE THIS CARD IS FILED, AND HOW MUCH IS BEHIND IT.
1150
+ Two measured facts and no sentence: the category is the one it is filed under,
1151
+ and the endpoint count is the catalogue's own number for that provider. With
1152
+ more than a hundred cards on this page, an explanatory line per card would be
1153
+ the paragraph DESIGN.md §4 forbids.
1154
+ ⛔ NOTHING HERE SAYS WHICH SIDE THE ROW CAME FROM. `provider` is stripped from
1155
+ the payload before it leaves the server (C4), and R27's design rule is that the
1156
+ distinction never renders: no badge, no tooltip, no different tone. */}
1157
+ {row.category || row.endpoints ? (
1158
+ <p className="conn-card-file">
1159
+ {row.category ? (
1160
+ <span className="conn-file-cat">{row.category}</span>
1161
+ ) : null}
1162
+ {row.endpoints ? (
1163
+ <span className="conn-file-n">
1164
+ {row.endpoints} endpoint{row.endpoints === 1 ? "" : "s"}
1165
+ </span>
1166
+ ) : null}
1167
+ </p>
1168
  ) : null}
1169
  {/* ⭐⭐ WAVE 30 · R4 — THE DRILL, AND IT IS COLLAPSED FOR THE SAME REASON THE
1170
  TRIGGER MENU'S IS. The owner's words are a sequence, not a layout: *"Only when
 
1204
  ) : null}
1205
  {/* ⚠ `needs` IS SHOWN WHATEVER THE STATE, and that is a correction: gating it on
1206
  "not connected" hid the one line that explains an `unconfigured` row, which is
1207
+ the state it exists for ("the owner registers the client"). Only a DOORLESS
1208
+ card suppresses it, because "not built yet" beside a card already marked planned
1209
+ is the same sentence twice, and a catalogue listing has no `needs` to show. */}
1210
+ {!doorless && row.needs ? (
1211
  <p className="conn-card-meta">{row.needs}</p>
1212
  ) : null}
1213
  {/* R13's honesty line for a token connector: the key is stored, the data arrives
1214
  later. Shown ON the card where the decision is, never in a paragraph. */}
1215
+ {!doorless && row.note ? <p className="conn-card-meta">{row.note}</p> : null}
1216
  {/* ── the ACTION. `manage` names WHERE it lives; this decides how to open it.
1217
  Every door here already existed — an OAuth start URL, the keychain dialog,
1218
  the automation surface — which is exactly why this page can be chrome: it
1219
  mints no new credential path (C11). An empty `manage` (a non-admin) renders
1220
  NO control rather than one that would 403. */}
1221
+ {/* ⭐⭐ W49-T19 — THE CATALOGUE'S ONE DIRECT ACTION, AND IT IS THE DOOR THIS
1222
+ TICKET EXISTS FOR. `manage` names a CREDENTIAL destination and this is not one:
1223
+ the Monid key is already stored, and what the operator is choosing here is to
1224
+ RUN something that spends it. So it reads off `action`, and it opens the run
1225
+ dialog in place rather than a modal, because a catalogue key has no detail
1226
+ route behind it (`openable` above).
1227
+ ⛔ IT RENDERS ONLY WHEN THE PAGE HANDED DOWN A HANDLER, which happens only for
1228
+ an admin whose session the server said may run it. A non-admin sees this card
1229
+ exactly as they see every other catalogue card: readable, and with no control
1230
+ on it. That is the same choice `manage: ""` already makes for a non-admin on
1231
+ every keychain card, applied to a paid action.
1232
+ ⚠ It wears `.conn-card-go`, the quiet text action every other card on this page
1233
+ uses, and not a filled button: this is not the page's primary call to action,
1234
+ and a second button family for one card would be a second visual vocabulary. */}
1235
+ {onPullReviews ? (
1236
+ <button
1237
+ type="button"
1238
+ className="conn-card-go"
1239
+ aria-haspopup="dialog"
1240
+ aria-label={`Pull reviews for ${row.label}`}
1241
+ onClick={onPullReviews}
1242
+ >
1243
+ Pull reviews
1244
+ </button>
1245
+ ) : null}
1246
+ {!doorless && row.manage === "oauth" && row.startUrl ? (
1247
  <a className="conn-card-go" href={row.startUrl}>
1248
  {row.state === "reconnect" ? "Reconnect" : "Connect"}
1249
  </a>
 
1256
  ⚠ `onKeychain` stays reachable underneath: adding or replacing the KEY still
1257
  happens in the room that owns keys, and this panel does not mint a second
1258
  credential path (C11's rule, which is what lets this page be chrome). */}
1259
+ {!doorless && row.manage === "keychain" && row.key === "odoo" ? (
1260
+ <OdooManage
1261
+ connected={connected}
1262
+ onKeychain={onKeychain}
1263
+ onOpenDatabases={doorless ? undefined : onOpenDatabases}
1264
+ />
1265
+ ) : !doorless && row.manage === "keychain" ? (
1266
  <button type="button" className="conn-card-go" onClick={onKeychain}>
1267
  {connected ? "Manage keys" : "Add keys"}
1268
  </button>
 
1276
  entries), so a member whose colleague connected Stripe business-wide still reads
1277
  the card as connected and is offered nothing to fix — which is correct: there is
1278
  nothing for them to do. */}
1279
+ {!doorless && row.manage === "keychain_personal" ? (
1280
  <button type="button" className="conn-card-go" onClick={onKeychain}>
1281
  {connected ? "Your connection" : "Connect your own"}
1282
  </button>
1283
  ) : null}
1284
+ {!doorless && row.manage === "automation" ? (
1285
  <a className="conn-card-go" href="#/automation">
1286
  Open automations
1287
  </a>
 
1290
  );
1291
  }
1292
 
1293
+ /*
1294
+ * ⛔⛔ `CONNECTOR_GRAPH_CSS` STOOD HERE AND IS DELETED BY W49-T12. Every rule it carried now lives
1295
+ * in `styles/wave49/connectors.css`, byte for byte, and this file imports that stylesheet at the
1296
+ * top. Two reasons, and the second is the one that matters:
1297
+ * · a rules string injected through `<style>` re-injects itself on every mount of the component
1298
+ * that owns it;
1299
+ * · and it is INVISIBLE to `verify_ui`'s R5 font scan, which walks `src/**` for `*.css` files.
1300
+ * A literal font size written here would have ridden into the tree with the gate green, which
1301
+ * is this repo's own [[gate-can-report-green-on-nothing]] shape wearing a template literal.
1302
+ */
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1303
 
1304
+ /*
1305
+ * ⛔⛔ `graphLayout`, `GraphPosition` AND `ConnectorRelationshipCanvas` STOOD HERE AND ARE DELETED
1306
+ * BY W49-T15 / RULING R33. The drawing now lives in `connectors/RelationshipDiagram.tsx`, and the
1307
+ * three symbols went together because the defect was in the GEOMETRY, not in the styling:
1308
+ *
1309
+ * · `graphLayout` sized every card to ALL of its permitted fields (16 for vendors, 15 for three
1310
+ * others), so a card was taller than the viewport. R33: keys and links only, expand on demand.
1311
+ * · `ConnectorRelationshipCanvas` drew each edge centre-to-centre and put its label at the
1312
+ * midpoint of the two card centres with a fixed offset. `ut_odoo_bills` and `ut_odoo_vendors`
1313
+ * are joined by TWO relationships in opposite directions, and for two edges over one pair that
1314
+ * midpoint is the SAME POINT: both labels painted on top of each other, which is the smear in
1315
+ * `reference/ERROR 19 connector.png`. Port-to-port routing is the fix, because two edges then
1316
+ * attach to different field rows and take different lanes.
1317
+ *
1318
+ * ⛔⛔ AND `ConnectorRelationshipPanel` STOOD HERE TOO, deleted one ticket earlier by W49-T12 /
1319
+ * RULING R26. It was the DOWNWARD EXPAND: a section rendered BELOW the whole card grid, so
1320
+ * clicking a card pushed the page down and put the answer a scroll away from the question. R26
1321
+ * replaces it with the centered modal opened from the card, and that is not re-litigated. A hidden
1322
+ * panel would be a second surface for one fact, which is why it was deleted rather than disabled.
1323
+ *
1324
+ * ⭐ WHAT SURVIVES IS THE READER. `parseRelationshipGraph` above is untouched and still refuses a
1325
+ * graph bound to another connection; `relationship_graphs` is FROZEN by C4. Only the drawing moved.
1326
+ */
 
 
 
 
 
 
 
web/src/connectors/DatabasesTab.tsx ADDED
@@ -0,0 +1,438 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // ---------------------------------------------------------------------------
2
+ // connectors/DatabasesTab.tsx — W49-T14, rulings R21/R22/R23/R24/R26, contracts C3 + C4.
3
+ //
4
+ // ⭐⭐ R21, verbatim: *"Build the onboarding DISCLOSURE, generalized: show the
5
+ // source schema and the N databases a connection will create, with what is
6
+ // excluded. The table list stays authored in code; the screen DISCLOSES it, it
7
+ // does not DERIVE it."*
8
+ //
9
+ // This file is the DISCLOSURE and nothing else. Every list it paints arrives on
10
+ // `GET /connectors/{key}/detail`, composed from `odoo_relational.TABLES` (the
11
+ // authored list) joined to the Odoo field catalogue. There is no table name,
12
+ // no field name and no count written into this file — a client-side table list
13
+ // would be a second answer to "what does this connection create", and the two
14
+ // would drift the first time a ninth table was added server-side.
15
+ //
16
+ // ⛔⛔ R24 — ONLY AN INTROSPECTABLE CONNECTOR GETS THIS SCREEN, AND THE ANSWER
17
+ // IS THE SERVER'S. `detail.introspection.introspectable` is authored in
18
+ // `core/connector_directory.INTROSPECTABLE_CONNECTORS`; it is NOT "the
19
+ // databases list came back empty". Those two are the same empty list and they
20
+ // mean opposite things: Meta Ads has no schema, while an Odoo connection whose
21
+ // store read failed has one nobody could reach. Inferring the ruling from the
22
+ // payload would tell an administrator that Odoo has no schema on the one day
23
+ // the schema mattered.
24
+ //
25
+ // ⛔⛔ R23 — THE SWITCH-OFF ASKS FIRST, AND THE REFUSAL IS QUOTED, NEVER
26
+ // COMPOSED. `GET /dependents?kind=table&key=...` answers with a sentence
27
+ // ("Odoo customers is used by 25 views, 7 Routes, 2 shares and 1 chart") whose
28
+ // ZERO-COUNT KINDS ARE ABSENT BY CONSTRUCTION. Building that sentence here from
29
+ // the counts would be a second copy of C3's grammar, and the copy would have to
30
+ // decide what to say about `sheet_cell` — a kind whose provider is not
31
+ // registered until W49-T11 lands, so the truth is UNKNOWN and not zero. Quoting
32
+ // the server's string is the only way this screen cannot claim zero.
33
+ //
34
+ // ⛔ AND A CHECK THAT DID NOT ANSWER IS NOT A CHECK THAT SAID "NOTHING". If
35
+ // `/dependents` fails for any reason the table is LEFT ON and the cause is
36
+ // printed. Writing the flag anyway would make R23 a suggestion.
37
+ //
38
+ // ⚠ PURE OVER PROPS, AND IT FETCHES ONLY ON A CLICK. The modal reads `/detail`
39
+ // on mount and `renderToStaticMarkup` runs no effects, so a static proof of
40
+ // this tab has to be paintable from a payload — the same reason
41
+ // `ConnectorOverviewPanel` and `KeychainTab` are exported panels.
42
+ // ---------------------------------------------------------------------------
43
+
44
+ import { useCallback, useMemo, useState } from "react";
45
+ import { API_V1, CREDENTIALS } from "../apiContract";
46
+ import type { ConnectorDatabase, ConnectorDetail } from "./ConnectorModal";
47
+ import type { ConnectorRow } from "./ConnectorsPage";
48
+
49
+ /** What `GET /dependents` said, or why it could not say anything. */
50
+ type DependentsAnswer =
51
+ | { ok: true; refusal: string }
52
+ | { ok: false; message: string };
53
+
54
+ /**
55
+ * C3's door, read verbatim.
56
+ *
57
+ * ⛔ `refusal` IS TAKEN AS A STRING AND SHOWN AS ONE. The payload also carries a `dependents`
58
+ * array with per-kind counts, and re-deriving the sentence from it is the tempting shape: it is
59
+ * also how a client starts printing "and 0 Sheet cells" about a provider that is not registered.
60
+ */
61
+ async function readDependents(tableKey: string): Promise<DependentsAnswer> {
62
+ try {
63
+ const res = await fetch(
64
+ `${API_V1}/dependents?kind=table&key=${encodeURIComponent(tableKey)}`,
65
+ { credentials: CREDENTIALS }
66
+ );
67
+ const body = (await res.json().catch(() => null)) as
68
+ | { refusal?: unknown; error?: { message?: string } }
69
+ | null;
70
+ if (!res.ok) {
71
+ return { ok: false, message: body?.error?.message || `The server answered ${res.status}.` };
72
+ }
73
+ return { ok: true, refusal: typeof body?.refusal === "string" ? body.refusal : "" };
74
+ } catch {
75
+ return { ok: false, message: "Cannot reach the server." };
76
+ }
77
+ }
78
+
79
+ async function write(path: string, method: "PUT" | "PATCH", body: unknown): Promise<string> {
80
+ try {
81
+ const res = await fetch(`${API_V1}${path}`, {
82
+ method,
83
+ credentials: CREDENTIALS,
84
+ headers: { "Content-Type": "application/json" },
85
+ body: JSON.stringify(body ?? {}),
86
+ });
87
+ const payload = (await res.json().catch(() => null)) as
88
+ | { error?: { message?: string } }
89
+ | null;
90
+ if (!res.ok) return payload?.error?.message || `The server answered ${res.status}.`;
91
+ return "";
92
+ } catch {
93
+ return "Cannot reach the server.";
94
+ }
95
+ }
96
+
97
+ /** The on/off control, one shape for both rails (DESIGN.md section 4: one control shape). */
98
+ function Switch({
99
+ on,
100
+ label,
101
+ busy,
102
+ onFlip,
103
+ }: {
104
+ on: boolean;
105
+ /** The accessible name. No dash, ever, including here (standing rule 2). */
106
+ label: string;
107
+ busy: boolean;
108
+ onFlip: (next: boolean) => void;
109
+ }) {
110
+ return (
111
+ <button
112
+ type="button"
113
+ role="switch"
114
+ aria-checked={on}
115
+ aria-label={label}
116
+ className={"conn-db-switch" + (on ? " is-on" : "")}
117
+ disabled={busy}
118
+ onClick={() => onFlip(!on)}
119
+ >
120
+ <span className="conn-db-knob" aria-hidden="true" />
121
+ </button>
122
+ );
123
+ }
124
+
125
+ /**
126
+ * ⭐ R24's OTHER SIDE, and it is a real branch rather than an empty list.
127
+ *
128
+ * A scraper, Meta Ads or a catalogue listing keeps what its CARD says: the connector's own
129
+ * description, plus the server's sentence for why there is no schema behind it. No toggles are
130
+ * rendered at all — not disabled ones — because this directory's rule is that a reader who may
131
+ * not do a thing sees no door for it rather than one that refuses.
132
+ */
133
+ export function DatabasesUnavailable({ row, reason }: { row: ConnectorRow; reason: string }) {
134
+ return (
135
+ <div className="conn-db">
136
+ {row.desc ? <p className="conn-db-desc">{row.desc}</p> : null}
137
+ <p className="conn-db-note">
138
+ {reason || "This connector does not publish a field catalogue."}
139
+ </p>
140
+ </div>
141
+ );
142
+ }
143
+
144
+ /** One database's disclosure: its fields, and what the catalogue left out. */
145
+ function DatabasePanel({
146
+ database,
147
+ siblingLabels,
148
+ fieldsVisible,
149
+ canToggleFields,
150
+ catalogueComplete,
151
+ excludedBasis,
152
+ busyField,
153
+ onField,
154
+ }: {
155
+ database: ConnectorDatabase;
156
+ /** The OTHER databases reading the same Odoo model, by label. See the shared note below. */
157
+ siblingLabels: string[];
158
+ fieldsVisible: boolean;
159
+ canToggleFields: boolean;
160
+ catalogueComplete: boolean;
161
+ excludedBasis: string;
162
+ busyField: string;
163
+ onField: (fieldKey: string, next: boolean) => void;
164
+ }) {
165
+ /**
166
+ * ⛔⛔ THREE DIFFERENT EMPTIES, AND COLLAPSING THEM IS THE DEFECT. An empty `fields` list means
167
+ * "you may not see the catalogue" for a member, "no schema sync has completed" for an
168
+ * administrator with no snapshot, and "Odoo reported nothing for this model" otherwise. One
169
+ * sentence for all three would be confidently wrong twice.
170
+ */
171
+ if (!fieldsVisible) {
172
+ return (
173
+ <p className="conn-db-note">The field list for this database is administrator only.</p>
174
+ );
175
+ }
176
+ if (!catalogueComplete) {
177
+ return (
178
+ <p className="conn-db-note">
179
+ No schema sync has finished, so this workspace holds no field list from Odoo yet.
180
+ </p>
181
+ );
182
+ }
183
+ return (
184
+ <>
185
+ {/* ⛔⛔ MEASURED, AND THE SCREEN WOULD LIE WITHOUT IT: `ut_odoo_invoices` and
186
+ `ut_odoo_bills` are both `account.move`, and `ut_odoo_agents` and `ut_odoo_vendors` are
187
+ both `res.partner`. The enablement flag is keyed by MODEL, so one switch here flips the
188
+ field under both names. The reader would otherwise discover that by watching the other
189
+ database change. */}
190
+ {siblingLabels.length ? (
191
+ <p className="conn-db-shared">
192
+ These fields come from the same Odoo source as {siblingLabels.join(", ")}, so switching
193
+ one on or off changes it there too.
194
+ </p>
195
+ ) : null}
196
+ {database.fields.length ? (
197
+ <table className="conn-db-fields">
198
+ <thead>
199
+ <tr>
200
+ <th scope="col">Source field</th>
201
+ <th scope="col">Type</th>
202
+ <th scope="col">Mapped column</th>
203
+ <th scope="col">Enabled</th>
204
+ </tr>
205
+ </thead>
206
+ <tbody>
207
+ {database.fields.map((field) => (
208
+ <tr key={field.key}>
209
+ <td className="conn-db-src">{field.sourceField || field.key}</td>
210
+ <td className="conn-db-type">{field.type}</td>
211
+ <td>{field.label}</td>
212
+ <td className="conn-db-cell-switch">
213
+ {canToggleFields ? (
214
+ <Switch
215
+ on={field.enabled}
216
+ busy={busyField === field.key}
217
+ label={
218
+ field.enabled
219
+ ? `Switch the field ${field.label} off`
220
+ : `Switch the field ${field.label} on`
221
+ }
222
+ onFlip={(next) => onField(field.key, next)}
223
+ />
224
+ ) : (
225
+ <span className="conn-db-state">{field.enabled ? "On" : "Off"}</span>
226
+ )}
227
+ </td>
228
+ </tr>
229
+ ))}
230
+ </tbody>
231
+ </table>
232
+ ) : (
233
+ <p className="conn-db-note">Odoo reported no fields for this database.</p>
234
+ )}
235
+ <div className="conn-db-excluded">
236
+ <h4 className="conn-db-sub">Excluded</h4>
237
+ {/* ⛔⛔ THE BASIS IS PRINTED WHETHER OR NOT THE LIST IS EMPTY, and it is the server's own
238
+ sentence. `excluded` is a DIFF of the captured raw fields against the catalogue, and
239
+ the catalogue offers everything it captured, so the list is EMPTY BY CONSTRUCTION
240
+ today. "Excluded: none" over that would be a claim about POLICY the number cannot
241
+ support. */}
242
+ {database.excluded.length ? (
243
+ <ul className="conn-db-exlist">
244
+ {database.excluded.map((item) => (
245
+ <li key={item.sourceField}>
246
+ <span className="conn-db-src">{item.sourceField}</span>
247
+ <span className="conn-db-reason">{item.reason}</span>
248
+ </li>
249
+ ))}
250
+ </ul>
251
+ ) : (
252
+ <p className="conn-db-note">The field catalogue held nothing back from this database.</p>
253
+ )}
254
+ {excludedBasis ? <p className="conn-db-basis">{excludedBasis}</p> : null}
255
+ </div>
256
+ </>
257
+ );
258
+ }
259
+
260
+ /**
261
+ * ⭐ THE TAB, PURE AND EXPORTED. Everything it lists is `detail`; the only network it does is a
262
+ * write the reader asked for, plus R23's pre-flight on the way to one.
263
+ */
264
+ export default function DatabasesTab({
265
+ row,
266
+ detail,
267
+ onChanged,
268
+ }: {
269
+ row: ConnectorRow;
270
+ detail: ConnectorDetail;
271
+ /** Re-read `/detail` after a write, so a flag that landed is a flag on screen. */
272
+ onChanged: () => void;
273
+ }) {
274
+ const { databases, introspection } = detail;
275
+ const [open, setOpen] = useState<Record<string, boolean>>(() =>
276
+ databases.length ? { [databases[0].key]: true } : {}
277
+ );
278
+ const [busy, setBusy] = useState("");
279
+ const [refusals, setRefusals] = useState<Record<string, string>>({});
280
+ const [error, setError] = useState("");
281
+
282
+ const labels = useMemo(() => {
283
+ const out: Record<string, string> = {};
284
+ for (const database of databases) out[database.key] = database.label;
285
+ return out;
286
+ }, [databases]);
287
+
288
+ /**
289
+ * ⛔⛔ R23's ENFORCEMENT, AND TODAY IT LIVES HERE. The write door is
290
+ * `PUT /admin/connectors/odoo/config`, which sets the flag for any key it recognises and knows
291
+ * nothing about dependents, so the ASK has to happen before the write. That makes this the only
292
+ * enforcer of the ruling, which is stated in the handoff rather than left to be discovered.
293
+ *
294
+ * ⛔ AND A FAILED CHECK IS NOT A PASSED ONE. Any non-answer leaves the table on and prints the
295
+ * cause; proceeding would turn "REFUSED" into "usually refused".
296
+ */
297
+ const flipTable = useCallback(
298
+ async (database: ConnectorDatabase, next: boolean) => {
299
+ setBusy(database.key);
300
+ setError("");
301
+ setRefusals((current) => ({ ...current, [database.key]: "" }));
302
+ if (!next) {
303
+ const answer = await readDependents(database.key);
304
+ if (!answer.ok) {
305
+ setBusy("");
306
+ setError(
307
+ `${database.label} was left switched on: the check for what depends on it did not ` +
308
+ `answer. ${answer.message}`
309
+ );
310
+ return;
311
+ }
312
+ if (answer.refusal) {
313
+ setBusy("");
314
+ // The server's sentence, verbatim. C3 omits every zero-count kind, so this cannot
315
+ // claim a count it does not have.
316
+ setRefusals((current) => ({ ...current, [database.key]: answer.refusal }));
317
+ return;
318
+ }
319
+ }
320
+ const message = await write("/admin/connectors/odoo/config", "PUT", {
321
+ grids: { [database.key]: next },
322
+ });
323
+ setBusy("");
324
+ if (message) setError(message);
325
+ else onChanged();
326
+ },
327
+ [onChanged]
328
+ );
329
+
330
+ const flipField = useCallback(
331
+ async (fieldKey: string, next: boolean) => {
332
+ setBusy(fieldKey);
333
+ setError("");
334
+ const message = await write(
335
+ `/connectors/odoo/schema/${encodeURIComponent(fieldKey)}`,
336
+ "PATCH",
337
+ { enabled: next }
338
+ );
339
+ setBusy("");
340
+ if (message) setError(message);
341
+ else onChanged();
342
+ },
343
+ [onChanged]
344
+ );
345
+
346
+ if (!introspection.introspectable) {
347
+ return <DatabasesUnavailable row={row} reason={introspection.reason} />;
348
+ }
349
+
350
+ if (!databases.length) {
351
+ // One line plus the action that fills it (DESIGN.md section 4), and it names the cause
352
+ // rather than implying the connector creates nothing.
353
+ return (
354
+ <p className="conn-db-note">
355
+ This connection has not declared any databases in this workspace. Connect it from the
356
+ Keychain tab to read its schema.
357
+ </p>
358
+ );
359
+ }
360
+
361
+ return (
362
+ <div className="conn-db">
363
+ {error ? (
364
+ <p className="conn-db-error" role="alert">
365
+ {error}
366
+ </p>
367
+ ) : null}
368
+ <p className="conn-db-lede">
369
+ <span className="conn-db-n">{databases.length}</span> databases are created from this
370
+ connection.
371
+ </p>
372
+ <ul className="conn-db-list">
373
+ {databases.map((database) => {
374
+ const isOpen = open[database.key] === true;
375
+ const refusal = refusals[database.key] || "";
376
+ return (
377
+ <li className="conn-db-item" key={database.key}>
378
+ <div className="conn-db-head">
379
+ <button
380
+ type="button"
381
+ className="conn-db-more"
382
+ aria-expanded={isOpen}
383
+ onClick={() =>
384
+ setOpen((current) => ({ ...current, [database.key]: !isOpen }))
385
+ }
386
+ >
387
+ <span className="conn-db-name">{database.label}</span>
388
+ <span className="conn-db-count">
389
+ {database.fields.length ? `${database.fields.length} fields` : "Fields"}
390
+ </span>
391
+ </button>
392
+ {/* ⭐ R22 — ANY table can be switched off, not only the ones we mark optional.
393
+ Every row gets the same control, and nothing here decides that one of them is
394
+ too important to turn off: R23's ask is what protects a table in use. */}
395
+ {introspection.canToggleTables ? (
396
+ <Switch
397
+ on={database.enabled}
398
+ busy={busy === database.key}
399
+ label={
400
+ database.enabled
401
+ ? `Switch off the database ${database.label}`
402
+ : `Switch on the database ${database.label}`
403
+ }
404
+ onFlip={(next) => void flipTable(database, next)}
405
+ />
406
+ ) : (
407
+ <span className="conn-db-state">{database.enabled ? "On" : "Off"}</span>
408
+ )}
409
+ </div>
410
+ {refusal ? (
411
+ // ⚠ A REFUSAL IS NOT AN ERROR THE READER CAUSED (DESIGN.md section 4). It states
412
+ // the cause and the subject, in the server's own sentence, and offers nothing to
413
+ // dismiss because the table simply stayed on.
414
+ <p className="conn-db-refusal" role="alert">
415
+ {refusal}
416
+ </p>
417
+ ) : null}
418
+ {isOpen ? (
419
+ <DatabasePanel
420
+ database={database}
421
+ siblingLabels={database.sharesFieldsWith
422
+ .map((key) => labels[key] || "")
423
+ .filter((label) => label.length > 0)}
424
+ fieldsVisible={introspection.fieldsVisible}
425
+ canToggleFields={introspection.canToggleFields}
426
+ catalogueComplete={introspection.catalogueComplete}
427
+ excludedBasis={introspection.excludedBasis}
428
+ busyField={busy}
429
+ onField={(fieldKey, next) => void flipField(fieldKey, next)}
430
+ />
431
+ ) : null}
432
+ </li>
433
+ );
434
+ })}
435
+ </ul>
436
+ </div>
437
+ );
438
+ }
web/src/connectors/DirectoryChips.tsx ADDED
@@ -0,0 +1,117 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // ---------------------------------------------------------------------------
2
+ // connectors/DirectoryChips.tsx — W49-T18, ruling R27, contract C4.
3
+ //
4
+ // THE CATEGORY RAIL over the connector directory: Monid's fourteen sidebar
5
+ // categories as filter chips, each with the number of cards behind it.
6
+ //
7
+ // ⭐⭐ THE NUMBER IS A COUNT OF CARDS, NOT A SUM OF ENDPOINTS, and this file does
8
+ // not decide that — the server does, in `core/connector_directory.chip_counts`,
9
+ // which carries the argument. It matters here because a chip that says 20 and
10
+ // then shows 14 cards is a lie the reader can see: this component RENDERS the
11
+ // server's number and `inCategory` below is the predicate the page filters with,
12
+ // so the two are the same rule written once each and pinned together by
13
+ // `verify_catalog.py`.
14
+ //
15
+ // ⛔ THE CATEGORY NAMES ARE PROPER NOUNS AND ARE NOT RE-CASED. "Search & SEO",
16
+ // "Crypto & DeFi", "E-commerce", "AI" and "Phone & Messaging" are how Monid
17
+ // writes them; DESIGN.md's no-ALL-CAPS rule is about app chrome, and a name is
18
+ // not chrome. Nothing here calls `toUpperCase`.
19
+ //
20
+ // ⚠ NO CLIENT UNION OVER THE CATEGORY NAMES. They are the server's vocabulary
21
+ // and arrive as strings (the wave-9 law): a `type Category = "AI" | …` here
22
+ // turns "the taxonomy gained a row" into "the chip disappears".
23
+ //
24
+ // ⚠ THE HIDDEN PROVIDER LABEL IS NOT IN THIS FILE AND MUST NOT BE. C4 keeps
25
+ // `provider` (`native` | `monid`) server-side; R27's design rule is that it
26
+ // never renders, so there is no badge, no tooltip and no title attribute for it
27
+ // anywhere in this component.
28
+ // ---------------------------------------------------------------------------
29
+
30
+ import type { ConnectorRow } from "./ConnectorsPage";
31
+
32
+ /** One chip: a category name and the number of cards carrying it. Both the server's. */
33
+ export interface DirectoryCategory {
34
+ name: string;
35
+ count: number;
36
+ }
37
+
38
+ /** The everything chip. Declared once so the page and this file cannot disagree about it. */
39
+ export const ALL_CATEGORIES = "All";
40
+
41
+ /**
42
+ * The chips, read the way `parseDirectory` reads a row: anything without a name is dropped, and
43
+ * a payload with no `categories` at all yields `[]`.
44
+ *
45
+ * ⚠ AN OLDER SERVER THEREFORE SHOWS NO RAIL, which is the honest degradation: a server that does
46
+ * not send the taxonomy has no counts to render, and inventing them on the client would be a
47
+ * second answer to a question the server already answers (this repo's `one-question-two-
48
+ * normalizers` shape). The grid still renders every card.
49
+ */
50
+ export function parseCategories(body: unknown): DirectoryCategory[] {
51
+ const raw = (body as { categories?: unknown } | null)?.categories;
52
+ if (!Array.isArray(raw)) return [];
53
+ const out: DirectoryCategory[] = [];
54
+ for (const item of raw) {
55
+ if (!item || typeof item !== "object") continue;
56
+ const c = item as Record<string, unknown>;
57
+ const name = typeof c.name === "string" ? c.name.trim() : "";
58
+ if (!name) continue;
59
+ out.push({ name, count: typeof c.count === "number" ? c.count : 0 });
60
+ }
61
+ return out;
62
+ }
63
+
64
+ /**
65
+ * Does this card belong under this chip?
66
+ *
67
+ * ⛔ THE PREDICATE IS MEMBERSHIP IN `categories`, THE PLURAL FIELD, and that is the whole reason
68
+ * the row carries both. `category` is the ONE name the card is filed under and reads well beside
69
+ * the label; `categories` is the tag list a provider can carry several of, and the rail is built
70
+ * from tags because Monid's categories overlap. Filtering on the singular would empty a chip of
71
+ * every card whose primary category is a different one.
72
+ */
73
+ export function inCategory(row: ConnectorRow, name: string): boolean {
74
+ if (!name || name === ALL_CATEGORIES) return true;
75
+ return (row.categories || []).includes(name);
76
+ }
77
+
78
+ /**
79
+ * The rail itself.
80
+ *
81
+ * ⛔ ONE CONTROL SHAPE (DESIGN.md §4: *"a filter rail keeps one control shape"*). Every chip is
82
+ * the same `<button>` with the same class; the selected one differs by state, never by being a
83
+ * different kind of control. The base rule in `styles/wave49/connectors.css` resets the native
84
+ * chrome the way §4 demands, because a `<button>` styled by class that forgets to do so wears the
85
+ * platform's own grey pill under our paint.
86
+ */
87
+ export default function DirectoryChips({
88
+ chips,
89
+ active,
90
+ onPick,
91
+ }: {
92
+ chips: DirectoryCategory[];
93
+ active: string;
94
+ onPick: (name: string) => void;
95
+ }) {
96
+ if (!chips.length) return null;
97
+ return (
98
+ <div className="conn-chips" role="group" aria-label="Filter connectors by category">
99
+ {chips.map((chip) => {
100
+ const on = (active || ALL_CATEGORIES) === chip.name;
101
+ return (
102
+ <button
103
+ key={chip.name}
104
+ type="button"
105
+ className={"conn-chip" + (on ? " is-on" : "")}
106
+ aria-pressed={on}
107
+ aria-label={`${chip.name}, ${chip.count} connectors`}
108
+ onClick={() => onPick(chip.name)}
109
+ >
110
+ <span className="conn-chip-name">{chip.name}</span>
111
+ <span className="conn-chip-n">{chip.count}</span>
112
+ </button>
113
+ );
114
+ })}
115
+ </div>
116
+ );
117
+ }
web/src/connectors/KeychainTab.tsx ADDED
@@ -0,0 +1,416 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // ---------------------------------------------------------------------------
2
+ // connectors/KeychainTab.tsx — W49-T13, ruling R26, contract C4.
3
+ //
4
+ // ⭐⭐ R26, verbatim: *"The Keychain moves INTO it and Settings > Keychains
5
+ // becomes a link to the modal (one door)."* This file is the "moves INTO it"
6
+ // half: it replaces `ConnectorModal.tsx::KeychainTabPlaceholder` and is the ONE
7
+ // place a connector's credential is added, tested or removed.
8
+ //
9
+ // ⛔⛔ ONE DOOR MEANS THE OTHER ONE CLOSES. `SettingsModal.tsx::KeychainPane`
10
+ // keeps its list for entries that stand behind no connector (a generic secret
11
+ // has no card to be edited from) and links here for the rest. Leaving both
12
+ // editable would be two answers to "where do I change this key?", which is the
13
+ // shape R26 exists to end.
14
+ //
15
+ // ⛔ THE CLIENT OWNS NO CREDENTIAL VOCABULARY. Which fields a connector asks
16
+ // for, which scopes it may take, and whether it is tenant-wide all arrive on
17
+ // C4's `keychain.connect` half. The tempting shape here is
18
+ // `type === "odoo" ? [url, db, user, api_key] : [api_key]` and that is a second
19
+ // copy of a credential SHAPE that already lives in `harness/connectors/odoo.py`
20
+ // — a connector whose credential grows a field would then need a client edit
21
+ // before it could be stored at all.
22
+ //
23
+ // ⛔⛔ A STORED SECRET LEAVES THE SERVER MASKED OR NOT AT ALL. Nothing here ever
24
+ // reads a credential back: the add form is write-only and clears on success,
25
+ // `masked` is rendered exactly as served, and there is no reveal affordance
26
+ // because the server has no route for one.
27
+ //
28
+ // ⛔⛔ TWO REMOVALS THAT ARE NOT A DELETE, and routing one of them to
29
+ // `DELETE /admin/keychain/{id}` would silently re-open a fixed defect:
30
+ // · Odoo goes through `POST /admin/connectors/odoo/disconnect`, which writes
31
+ // the pause flag BEFORE dropping the credential (W33-T65, D-259) and
32
+ // freezes the grids as static data (R10). A raw delete skips both.
33
+ // · An OAuth connection is not a keychain entry at all — it lives in the
34
+ // per-user secret slots — so it goes through `POST /oauth/{slug}/disconnect`.
35
+ // ---------------------------------------------------------------------------
36
+
37
+ import { useCallback, useState } from "react";
38
+ import { API_V1, CREDENTIALS } from "../apiContract";
39
+ import type {
40
+ ConnectorConnectSpec,
41
+ ConnectorKeychainEntry,
42
+ ConnectorKeychainHalf,
43
+ } from "./ConnectorModal";
44
+ import type { ConnectorRow } from "./ConnectorsPage";
45
+
46
+ /**
47
+ * ⭐ WAVE 32 · R4 / contract C1 — WHO A CONNECTION IS FOR, in the two words the server declares.
48
+ *
49
+ * ⛔ THE VOCABULARY IS THE SERVER'S AND THIS IS A PRESENTATION OF IT, never a union: a scope the
50
+ * server adds later renders as its own word rather than dropping the row (the wave-9 law).
51
+ * ⚠ EXPORTED, AND `SettingsModal` IMPORTS IT FROM HERE rather than keeping the copy it used to
52
+ * hold. Two label maps for one server vocabulary is [[one-question-two-normalizers]], and the
53
+ * direction is this one because the pane is becoming a link INTO this tab.
54
+ */
55
+ const SCOPE_LABEL: Record<string, string> = {
56
+ business: "Business-wide",
57
+ personal: "Personal",
58
+ };
59
+
60
+ export function scopeLabel(scope: string | undefined): string {
61
+ const word = String(scope || "business");
62
+ return SCOPE_LABEL[word] || word;
63
+ }
64
+
65
+ /** `true` when this connector removes its connection through a route of its own, not a delete. */
66
+ export function hasOwnDisconnect(row: ConnectorRow): boolean {
67
+ return row.key === "odoo" || row.kind === "oauth";
68
+ }
69
+
70
+ async function post(path: string, body?: unknown): Promise<string> {
71
+ try {
72
+ const res = await fetch(`${API_V1}${path}`, {
73
+ method: "POST",
74
+ credentials: CREDENTIALS,
75
+ headers: { "Content-Type": "application/json" },
76
+ body: JSON.stringify(body ?? {}),
77
+ });
78
+ const payload = (await res.json().catch(() => null)) as
79
+ | { error?: { message?: string } }
80
+ | null;
81
+ if (!res.ok) return payload?.error?.message || `The server answered ${res.status}.`;
82
+ return "";
83
+ } catch {
84
+ return "Cannot reach the server.";
85
+ }
86
+ }
87
+
88
+ async function del(path: string): Promise<string> {
89
+ try {
90
+ const res = await fetch(`${API_V1}${path}`, { method: "DELETE", credentials: CREDENTIALS });
91
+ const payload = (await res.json().catch(() => null)) as
92
+ | { error?: { message?: string } }
93
+ | null;
94
+ if (!res.ok) return payload?.error?.message || `The server answered ${res.status}.`;
95
+ return "";
96
+ } catch {
97
+ return "Cannot reach the server.";
98
+ }
99
+ }
100
+
101
+ /**
102
+ * The Connect form: exactly the fields C4 said this connector asks for.
103
+ *
104
+ * ⚠ THE SCOPE IS A SENTENCE WHENEVER THERE IS NO CHOICE. `connect.scopes` carries what the server
105
+ * will honour, so a single option is stated rather than offered as a picker whose save would 400 —
106
+ * the button-that-leads-nowhere shape R7 removed one module over.
107
+ */
108
+ function ConnectForm({
109
+ spec,
110
+ label,
111
+ onDone,
112
+ onCancel,
113
+ }: {
114
+ spec: ConnectorConnectSpec;
115
+ label: string;
116
+ onDone: () => void;
117
+ onCancel: () => void;
118
+ }) {
119
+ const [entryLabel, setEntryLabel] = useState(label);
120
+ const [values, setValues] = useState<Record<string, string>>({});
121
+ const [scope, setScope] = useState(spec.scopes[0] || "business");
122
+ const [busy, setBusy] = useState(false);
123
+ const [error, setError] = useState("");
124
+
125
+ const save = async () => {
126
+ if (busy) return;
127
+ setBusy(true);
128
+ setError("");
129
+ const fields: Record<string, string> = {};
130
+ for (const field of spec.fields) {
131
+ const value = (values[field.key] || "").trim();
132
+ if (value) fields[field.key] = value;
133
+ }
134
+ const message = await post("/admin/keychain", {
135
+ label: entryLabel.trim(),
136
+ type: spec.type,
137
+ scope,
138
+ fields,
139
+ });
140
+ if (message) {
141
+ setError(message);
142
+ setBusy(false);
143
+ return;
144
+ }
145
+ // The form is dropped rather than cleared: a secret that has been stored must not sit in a
146
+ // React state object waiting for the next render.
147
+ onDone();
148
+ };
149
+
150
+ return (
151
+ <div className="conn-kc-form">
152
+ <div className="conn-kc-field">
153
+ <label htmlFor="conn-kc-label">Name this connection</label>
154
+ <input
155
+ id="conn-kc-label"
156
+ value={entryLabel}
157
+ maxLength={80}
158
+ onChange={(event) => setEntryLabel(event.target.value)}
159
+ />
160
+ </div>
161
+ <div className="conn-kc-field">
162
+ <label htmlFor="conn-kc-scope">Who can use it</label>
163
+ {spec.scopes.length > 1 ? (
164
+ <select
165
+ id="conn-kc-scope"
166
+ value={scope}
167
+ onChange={(event) => setScope(event.target.value)}
168
+ >
169
+ {spec.scopes.map((option) => (
170
+ <option key={option} value={option}>
171
+ {option === "personal"
172
+ ? "Personal: only me"
173
+ : "Business-wide: everyone in this workspace"}
174
+ </option>
175
+ ))}
176
+ </select>
177
+ ) : (
178
+ <p className="conn-kc-note">
179
+ {spec.tenantWide
180
+ ? "Business-wide. This workspace's databases are read through this connection, so it applies to everyone here."
181
+ : scope === "personal"
182
+ ? "Personal, so only you. An administrator can add one for the whole workspace."
183
+ : "Business-wide, for everyone in this workspace."}
184
+ </p>
185
+ )}
186
+ </div>
187
+ {spec.fields.map((field) => (
188
+ <div className="conn-kc-field" key={field.key}>
189
+ <label htmlFor={`conn-kc-${field.key}`}>{field.label}</label>
190
+ <input
191
+ id={`conn-kc-${field.key}`}
192
+ type={field.secret ? "password" : "text"}
193
+ autoComplete={field.secret ? "new-password" : "off"}
194
+ value={values[field.key] ?? ""}
195
+ onChange={(event) =>
196
+ setValues((current) => ({ ...current, [field.key]: event.target.value }))
197
+ }
198
+ />
199
+ </div>
200
+ ))}
201
+ {error ? (
202
+ <p className="conn-kc-error" role="alert">
203
+ {error}
204
+ </p>
205
+ ) : null}
206
+ <div className="conn-kc-actions">
207
+ <button type="button" className="conn-kc-btn" onClick={onCancel}>
208
+ Cancel
209
+ </button>
210
+ <button
211
+ type="button"
212
+ className="conn-kc-btn is-primary"
213
+ disabled={busy || !entryLabel.trim()}
214
+ onClick={() => void save()}
215
+ >
216
+ {busy ? "Storing" : "Store the key"}
217
+ </button>
218
+ </div>
219
+ </div>
220
+ );
221
+ }
222
+
223
+ /**
224
+ * ⭐ THE PANEL, PURE AND EXPORTED, for the reason `ConnectorOverviewPanel` is: the modal fetches
225
+ * on mount and `renderToStaticMarkup` runs no effects, so a static proof of this tab has to be
226
+ * paintable from a payload rather than from a request.
227
+ */
228
+ export default function KeychainTab({
229
+ row,
230
+ keychain,
231
+ onChanged,
232
+ }: {
233
+ row: ConnectorRow;
234
+ keychain: ConnectorKeychainHalf;
235
+ /** Re-read `/detail` after a write. Without it a deleted key stays on screen until the modal
236
+ * is closed and reopened, which reads as a delete that did not land. */
237
+ onChanged: () => void;
238
+ }) {
239
+ const [busyId, setBusyId] = useState("");
240
+ const [tested, setTested] = useState<Record<string, string>>({});
241
+ const [error, setError] = useState("");
242
+ const [adding, setAdding] = useState(false);
243
+
244
+ const runTest = useCallback(async (entry: ConnectorKeychainEntry) => {
245
+ setTested((current) => ({ ...current, [entry.id]: "Testing" }));
246
+ try {
247
+ const res = await fetch(
248
+ `${API_V1}/admin/keychain/${encodeURIComponent(entry.id)}/test`,
249
+ { method: "POST", credentials: CREDENTIALS }
250
+ );
251
+ const body = (await res.json().catch(() => null)) as
252
+ | { ok?: boolean; message?: string; error?: { message?: string } }
253
+ | null;
254
+ const said = res.ok
255
+ ? `${body?.ok ? "Working" : "Refused"}: ${body?.message || "the connector said nothing"}`
256
+ : body?.error?.message || `The server answered ${res.status}.`;
257
+ setTested((current) => ({ ...current, [entry.id]: said }));
258
+ } catch {
259
+ setTested((current) => ({ ...current, [entry.id]: "Cannot reach the server." }));
260
+ }
261
+ }, []);
262
+
263
+ const remove = useCallback(
264
+ async (entry: ConnectorKeychainEntry) => {
265
+ const sure = window.confirm(
266
+ `Remove the connection "${entry.label}"? A stored secret cannot be recovered.`
267
+ );
268
+ if (!sure) return;
269
+ setBusyId(entry.id);
270
+ setError("");
271
+ const message = await del(`/admin/keychain/${encodeURIComponent(entry.id)}`);
272
+ setBusyId("");
273
+ if (message) setError(message);
274
+ else onChanged();
275
+ },
276
+ [onChanged]
277
+ );
278
+
279
+ /**
280
+ * ⛔⛔ THE ROUTED DISCONNECT. Odoo and OAuth each remove a connection through a door that does
281
+ * more than drop a row, and choosing the raw delete here is how a fixed defect comes back in a
282
+ * new caller: `odoo_disconnect` writes the pause flag before the credential goes (D-259) and
283
+ * freezes the grids as static data (R10), and an OAuth token is not in the keychain bucket at
284
+ * all. Everything else genuinely IS its stored entries, so removing them is the disconnection.
285
+ */
286
+ const disconnect = useCallback(async () => {
287
+ const sure = window.confirm(
288
+ `Disconnect ${row.label}? Data already read stays; nothing new will be read.`
289
+ );
290
+ if (!sure) return;
291
+ setBusyId("disconnect");
292
+ setError("");
293
+ let message = "";
294
+ if (row.key === "odoo") {
295
+ message = await post("/admin/connectors/odoo/disconnect");
296
+ } else if (row.kind === "oauth") {
297
+ message = await post(`/oauth/${encodeURIComponent(row.key)}/disconnect`);
298
+ } else {
299
+ for (const entry of keychain.entries) {
300
+ message = await del(`/admin/keychain/${encodeURIComponent(entry.id)}`);
301
+ if (message) break;
302
+ }
303
+ }
304
+ setBusyId("");
305
+ if (message) setError(message);
306
+ else onChanged();
307
+ }, [keychain.entries, onChanged, row.key, row.kind, row.label]);
308
+
309
+ const ownDisconnect = hasOwnDisconnect(row);
310
+
311
+ if (adding && keychain.connect) {
312
+ return (
313
+ <ConnectForm
314
+ spec={keychain.connect}
315
+ label={row.label}
316
+ onCancel={() => setAdding(false)}
317
+ onDone={() => {
318
+ setAdding(false);
319
+ onChanged();
320
+ }}
321
+ />
322
+ );
323
+ }
324
+
325
+ return (
326
+ <div className="conn-kc">
327
+ {error ? (
328
+ <p className="conn-kc-error" role="alert">
329
+ {error}
330
+ </p>
331
+ ) : null}
332
+ {keychain.entries.length ? (
333
+ <ul className="conn-kc-list">
334
+ {keychain.entries.map((entry) => (
335
+ <li className="conn-kc-row" key={entry.id}>
336
+ <div className="conn-kc-main">
337
+ <span className="conn-kc-label">{entry.label}</span>
338
+ <span className="conn-kc-meta">
339
+ {/* An empty preview is a RULE, not a gap: R4 withholds the last four characters
340
+ of a business key from a member who did not store it, and saying so is
341
+ better than an empty cell that reads as a bug. */}
342
+ {entry.masked || "The preview is hidden for connections you did not add"}
343
+ {" · "}
344
+ {scopeLabel(entry.scope)}
345
+ </span>
346
+ {tested[entry.id] ? (
347
+ <span className="conn-kc-test" role="status">
348
+ {tested[entry.id]}
349
+ </span>
350
+ ) : null}
351
+ </div>
352
+ <div className="conn-kc-controls">
353
+ {entry.testable ? (
354
+ <button
355
+ type="button"
356
+ className="conn-kc-btn"
357
+ onClick={() => void runTest(entry)}
358
+ >
359
+ Test
360
+ </button>
361
+ ) : null}
362
+ {/* ⛔ NO RAW DELETE where the connector owns a disconnect route: see the comment
363
+ on `disconnect` above. The act is offered once, below, and it is the safe one. */}
364
+ {ownDisconnect ? null : (
365
+ <button
366
+ type="button"
367
+ className="conn-kc-btn is-danger"
368
+ disabled={busyId === entry.id}
369
+ onClick={() => void remove(entry)}
370
+ >
371
+ {busyId === entry.id ? "Removing" : "Delete"}
372
+ </button>
373
+ )}
374
+ </div>
375
+ </li>
376
+ ))}
377
+ </ul>
378
+ ) : (
379
+ // One line, plus the action that fills it. Never a paragraph (DESIGN.md).
380
+ <p className="conn-kc-empty">
381
+ {keychain.canConnect
382
+ ? "No key is stored for this connector yet."
383
+ : "No key is stored for this connector, and this account cannot add one."}
384
+ </p>
385
+ )}
386
+ <div className="conn-kc-actions">
387
+ {keychain.canConnect && keychain.connect ? (
388
+ <button
389
+ type="button"
390
+ className="conn-kc-btn is-primary"
391
+ onClick={() => setAdding(true)}
392
+ >
393
+ {keychain.entries.length ? "Add another key" : "Connect"}
394
+ </button>
395
+ ) : null}
396
+ {/* An OAuth connection starts at the provider, so its Connect is a real link and not a
397
+ form. `startUrl` is the server's, never composed here. */}
398
+ {keychain.canConnect && !keychain.connect && row.startUrl ? (
399
+ <a className="conn-kc-btn is-primary" href={row.startUrl}>
400
+ {keychain.entries.length ? "Reconnect" : "Connect"}
401
+ </a>
402
+ ) : null}
403
+ {keychain.canDisconnect ? (
404
+ <button
405
+ type="button"
406
+ className="conn-kc-btn is-danger"
407
+ disabled={busyId === "disconnect"}
408
+ onClick={() => void disconnect()}
409
+ >
410
+ {busyId === "disconnect" ? "Disconnecting" : "Disconnect"}
411
+ </button>
412
+ ) : null}
413
+ </div>
414
+ </div>
415
+ );
416
+ }
web/src/connectors/MonidRunDialog.tsx ADDED
@@ -0,0 +1,414 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // ---------------------------------------------------------------------------
2
+ // connectors/MonidRunDialog.tsx — W49-T19, ruling R31, contract C5.
3
+ //
4
+ // ⭐⭐ R31, verbatim: *"Monid's one working slice is Amazon reviews for our ASINs,
5
+ // landing as a database linkable to Odoo products."*
6
+ //
7
+ // ⛔⛔ THIS DIALOG SPENDS REAL MONEY, SO IT SAYS WHAT IT COSTS AND REFUSES TO
8
+ // GUESS A TOTAL. Monid prices this endpoint PER_RESULT at $0.00135, and the unit
9
+ // price is the only part of the charge that is knowable in advance.
10
+ //
11
+ // ⛔⛔ IT USED TO PRINT A TOTAL, AND THE FIRST LIVE RUN PROVED THAT NUMBER
12
+ // WRONG BY 10x. The vendor's own pricing note says "one result per input query",
13
+ // so this dialog multiplied the ASIN count by the unit price and promised the
14
+ // answer. Measured: two ASINs returned twenty results, billed twenty units, and
15
+ // the wallet moved 1.000 to 0.973. A result is one REVIEW RETURNED, and how many
16
+ // reviews an ASIN carries is not knowable until the run finishes.
17
+ //
18
+ // ⛔ SO THE COPY STATES THE PER-REVIEW PRICE AND SAYS PLAINLY THAT THE CHARGE
19
+ // SCALES WITH WHAT COMES BACK. No total, no invented range, and no cap the
20
+ // endpoint does not offer: there is no result-limit parameter, so a cap printed
21
+ // here would be a promise nothing could keep. A confident wrong number is worse
22
+ // than an honest unknown, because it is the one the owner budgets against.
23
+ //
24
+ // ⭐ IT FETCHES ITS OWN `meta`, NOT THE CONNECTOR DETAIL. `/monid/amazon-reviews/meta`
25
+ // is free, and it carries the three facts this dialog cannot invent: whether the
26
+ // caller may run (`canRun`, the server's admin answer), whether a key exists at
27
+ // all, and the price. Reading them off `ConnectorDetail` instead would tie this
28
+ // surface to a payload that answers a different question.
29
+ //
30
+ // ⛔ THE ASINs ARE PASTED, AND THAT IS A MEASUREMENT. `fields_get` on Odoo's
31
+ // `product.template` and `product.product` was read on 2026-09-02: the only
32
+ // Amazon-shaped field either model carries is `x_studio_amazon_sku` ("Amazon
33
+ // SKU"), whose 162 populated values are merchant SKUs such as `RI-SHR-09_BLK`.
34
+ // Those are not ASINs, no mapping exists, and inventing one would spend the
35
+ // wallet on ten-character strings Amazon has never heard of. So the operator
36
+ // pastes, and the dialog says why.
37
+ //
38
+ // ⛔ EVERY REFUSAL IS A PLAIN SENTENCE NAMING CAUSE AND SUBJECT. The 402 sentence
39
+ // is exactly "Monid wallet is empty", authored in `core/monid.py`, printed here
40
+ // unchanged, and nothing on this side retries it.
41
+ //
42
+ // ⚠ `trapFocus` DEFAULTS TO `false` on `useOverlayLayer` and is passed
43
+ // explicitly below, the way `ConnectorModal.tsx` passes it. A dialog whose focus
44
+ // is not trapped tabs out onto the page behind it while looking correct.
45
+ //
46
+ // ⚠ THIS SITS ON THE PORTAL STEP, ABOVE THE DIALOG STEP. `ConnectorModal` owns
47
+ // `--cg-z-record`; this overlay opens on top of it, so it takes
48
+ // `--cg-z-overlay` ([[z-layering-is-a-three-way-order]]). Tokens, never a
49
+ // number, and the surface paints its own background because a portalled overlay
50
+ // that does not is transparent over whatever it covers
51
+ // ([[a-portal-overlay-carries-its-own-surface]]).
52
+ // ---------------------------------------------------------------------------
53
+
54
+ import { useEffect, useMemo, useRef, useState } from "react";
55
+ import { API_V1, CREDENTIALS } from "../apiContract";
56
+ import { BodyPortal, useOverlayLayer } from "../customer-grid/OverlaySurface";
57
+ import "../styles/wave49/connectors.css";
58
+
59
+ /** What the free `meta` read answers. Strings stay strings (the wave-9 law). */
60
+ export interface MonidRunMeta {
61
+ canRun: boolean;
62
+ configured: boolean;
63
+ provider: string;
64
+ endpoint: string;
65
+ unitPrice: number;
66
+ currency: string;
67
+ maxAsins: number;
68
+ tableLabel: string;
69
+ balance: { value: number | null; currency: string | null } | null;
70
+ asinNote: string;
71
+ }
72
+
73
+ /** What a finished pull reports back. `pending` is a real outcome, not a failure. */
74
+ export interface MonidRunResult {
75
+ pending: boolean;
76
+ runId: string;
77
+ cost: number;
78
+ /**
79
+ * ⛔ WHETHER THAT NUMBER WAS MEASURED OR GUESSED. A completed run reports its own `cost` and
80
+ * that figure reconciles to the wallet; when a run reports none, the server writes a FLOOR that
81
+ * is known to under-read (the first live run under-read by 10x). The two must never be printed
82
+ * in the same words.
83
+ */
84
+ costEstimated?: boolean;
85
+ records: number;
86
+ imported?: number;
87
+ tableKey: string;
88
+ message: string;
89
+ unmappedColumns?: string[];
90
+ }
91
+
92
+ /**
93
+ * ⭐ THE MONEY SENTENCE, EXPORTED AND PURE, for the same reason `accessSentence` is. It is the
94
+ * one thing in this file that must be right before anything is spent, and a pure function can be
95
+ * read and asserted without mounting a dialog.
96
+ *
97
+ * ⛔ IT TAKES `count` AND DOES NOT MULTIPLY BY IT. The count is in the sentence so the operator
98
+ * knows which pull is being described; using it as a multiplier is exactly the bug the first live
99
+ * run exposed. `verify_catalog.py` reddens if a total reappears here.
100
+ */
101
+ export function costSentence(count: number, unitPrice: number, currency: string): string {
102
+ if (count <= 0) return "Nothing is charged until you enter an ASIN.";
103
+ return (
104
+ `Monid charges ${currency} ${unitPrice.toFixed(5)} for every review it returns, and how many ` +
105
+ `reviews ${count === 1 ? "this 1 ASIN carries" : `these ${count} ASINs carry`} is not known ` +
106
+ `until the run finishes, so the total is not known in advance.`
107
+ );
108
+ }
109
+
110
+ /**
111
+ * ⭐ THE ASIN READ, EXPORTED AND PURE, AND IT MIRRORS `core/monid.clean_asins`.
112
+ * The server is the authority and re-validates everything; this exists so the operator sees the
113
+ * count that is about to be paid for BEFORE they press the button, rather than after a refusal.
114
+ * ⚠ Kept deliberately identical in rule: ten characters, letters and digits, upper cased,
115
+ * de-duplicated, order preserved. If the two ever disagree the price shown is a price for a
116
+ * different pull, which is the one lie this surface must not tell.
117
+ */
118
+ export function readAsins(raw: string): { good: string[]; bad: string[] } {
119
+ const good: string[] = [];
120
+ const bad: string[] = [];
121
+ const seen = new Set<string>();
122
+ for (const part of String(raw || "").split(/[\s,;]+/)) {
123
+ const token = part.trim().toUpperCase();
124
+ if (!token) continue;
125
+ if (!/^[A-Z0-9]{10}$/.test(token)) {
126
+ bad.push(part.trim());
127
+ continue;
128
+ }
129
+ if (seen.has(token)) continue;
130
+ seen.add(token);
131
+ good.push(token);
132
+ }
133
+ return { good, bad };
134
+ }
135
+
136
+ type Phase =
137
+ | { kind: "meta" }
138
+ | { kind: "ready" }
139
+ | { kind: "running" }
140
+ | { kind: "done"; result: MonidRunResult }
141
+ | { kind: "refused"; message: string };
142
+
143
+ /**
144
+ * THE DIALOG. Portalled, focus-trapped, dismissed by Escape or a click outside, and it hands
145
+ * focus back to the control that opened it.
146
+ */
147
+ export default function MonidRunDialog({
148
+ label,
149
+ onClose,
150
+ surfaceRef,
151
+ }: {
152
+ /** The provider's own name, for the heading and the aria label. */
153
+ label: string;
154
+ onClose: () => void;
155
+ /**
156
+ * ⛔⛔ THE NODE THE MODAL BELOW MUST NOT TREAT AS "OUTSIDE", AND IT IS NOT OPTIONAL POLISH.
157
+ *
158
+ * `useOverlayLayer` has a topmost-layer guard, `stack.isTop(id)`, and it is INERT in this app:
159
+ * `OverlaySurface.tsx` exports `OverlayProvider` and NOTHING MOUNTS IT, so `useContext` returns
160
+ * null and every layer believes it is the top one. This dialog portals as a SIBLING of the
161
+ * connector modal's panel, so without this handle a pointer press inside this dialog is
162
+ * "outside" that modal, the modal dismisses, and this dialog unmounts in the middle of a paid
163
+ * pull. `outsideElements` on the layer below is the mechanism the hook provides for exactly
164
+ * this, and handing up the surface node is how the layer below can name it.
165
+ */
166
+ surfaceRef?: (element: HTMLElement | null) => void;
167
+ }) {
168
+ const panelRef = useRef<HTMLDivElement>(null);
169
+ const [meta, setMeta] = useState<MonidRunMeta | null>(null);
170
+ const [phase, setPhase] = useState<Phase>({ kind: "meta" });
171
+ const [text, setText] = useState("");
172
+
173
+ useOverlayLayer({
174
+ panelRef,
175
+ onDismiss: onClose,
176
+ dismissOnOutside: true,
177
+ initialFocus: "[data-overlay-autofocus]",
178
+ // ⚠ EXPLICIT. The hook's own default is `false`.
179
+ trapFocus: true,
180
+ restoreFocus: true,
181
+ });
182
+
183
+ useEffect(() => {
184
+ let dead = false;
185
+ void (async () => {
186
+ try {
187
+ const res = await fetch(`${API_V1}/monid/amazon-reviews/meta`, {
188
+ credentials: CREDENTIALS,
189
+ });
190
+ const body = (await res.json().catch(() => null)) as
191
+ | (MonidRunMeta & { error?: { message?: string } })
192
+ | null;
193
+ if (dead) return;
194
+ if (!res.ok || !body) {
195
+ setPhase({
196
+ kind: "refused",
197
+ message:
198
+ body?.error?.message || "This workspace could not read the Monid connection.",
199
+ });
200
+ return;
201
+ }
202
+ setMeta(body);
203
+ setPhase({ kind: "ready" });
204
+ } catch {
205
+ if (!dead) setPhase({ kind: "refused", message: "Cannot reach the server." });
206
+ }
207
+ })();
208
+ return () => {
209
+ dead = true;
210
+ };
211
+ }, []);
212
+
213
+ const parsed = useMemo(() => readAsins(text), [text]);
214
+ const unit = meta?.unitPrice ?? 0;
215
+ const currency = meta?.currency || "USD";
216
+ const overCap = meta ? parsed.good.length > meta.maxAsins : false;
217
+ const canSubmit =
218
+ phase.kind === "ready" &&
219
+ !!meta?.canRun &&
220
+ !!meta?.configured &&
221
+ parsed.good.length > 0 &&
222
+ parsed.bad.length === 0 &&
223
+ !overCap;
224
+
225
+ const submit = async () => {
226
+ if (!canSubmit) return;
227
+ setPhase({ kind: "running" });
228
+ try {
229
+ const res = await fetch(`${API_V1}/monid/amazon-reviews/run`, {
230
+ method: "POST",
231
+ credentials: CREDENTIALS,
232
+ headers: { "Content-Type": "application/json" },
233
+ body: JSON.stringify({ asins: parsed.good }),
234
+ });
235
+ const body = (await res.json().catch(() => null)) as
236
+ | (MonidRunResult & { error?: { message?: string } })
237
+ | null;
238
+ if (!res.ok || !body) {
239
+ setPhase({
240
+ kind: "refused",
241
+ // ⛔ THE SERVER'S OWN SENTENCE, PRINTED UNCHANGED. A 402 arrives here reading
242
+ // "Monid wallet is empty" and this side neither rewords it nor tries again.
243
+ message: body?.error?.message || `The server answered ${res.status}.`,
244
+ });
245
+ return;
246
+ }
247
+ setPhase({ kind: "done", result: body });
248
+ } catch {
249
+ setPhase({ kind: "refused", message: "Cannot reach the server." });
250
+ }
251
+ };
252
+
253
+ return (
254
+ <BodyPortal>
255
+ <div className="monid-run-backdrop" ref={surfaceRef}>
256
+ <section
257
+ className="monid-run"
258
+ ref={panelRef}
259
+ role="dialog"
260
+ aria-modal="true"
261
+ aria-label={`Pull reviews from ${label}`}
262
+ data-overlay-kind="monid-run"
263
+ tabIndex={-1}
264
+ >
265
+ <header className="monid-run-head">
266
+ <span className="monid-run-name">Pull reviews</span>
267
+ <button
268
+ type="button"
269
+ className="monid-run-close"
270
+ aria-label="Close the pull reviews dialog"
271
+ data-overlay-autofocus
272
+ onClick={onClose}
273
+ >
274
+ <svg viewBox="0 0 16 16" width="14" height="14" aria-hidden="true" focusable="false">
275
+ <path
276
+ d="M4 4l8 8M12 4l-8 8"
277
+ fill="none"
278
+ stroke="currentColor"
279
+ strokeWidth="1.5"
280
+ strokeLinecap="round"
281
+ />
282
+ </svg>
283
+ </button>
284
+ </header>
285
+
286
+ <div className="monid-run-body">
287
+ {phase.kind === "meta" ? (
288
+ <p className="monid-run-note" role="status" aria-live="polite">
289
+ Reading the Monid connection.
290
+ </p>
291
+ ) : null}
292
+
293
+ {phase.kind === "refused" ? (
294
+ <p className="monid-run-refusal" role="alert">
295
+ {phase.message}
296
+ </p>
297
+ ) : null}
298
+
299
+ {meta && !meta.configured ? (
300
+ <p className="monid-run-refusal" role="alert">
301
+ Monid is not connected in this workspace. An administrator adds the key before a
302
+ pull can run.
303
+ </p>
304
+ ) : null}
305
+
306
+ {meta && meta.configured && !meta.canRun ? (
307
+ <p className="monid-run-refusal" role="alert">
308
+ Only an administrator can pull Amazon reviews, because the pull spends this
309
+ workspace&apos;s Monid balance.
310
+ </p>
311
+ ) : null}
312
+
313
+ {meta && phase.kind === "done" ? (
314
+ <div className="monid-run-done" role="status" aria-live="polite">
315
+ <p className="monid-run-line">{phase.result.message}</p>
316
+ {/* ⛔ A PENDING RUN HAS NO COUNTS, AND PRINTING THEM WOULD BE A LIE THE SERVER
317
+ DID NOT TELL. A 202 that outlives the poll ceiling comes back with
318
+ `pending: true` and zeroes, and reading those zeroes as a result would say
319
+ "0 records came back" about a run that is still going. The spend is real
320
+ either way, so that sentence is the one both branches share. */}
321
+ {phase.result.pending ? (
322
+ <p className="monid-run-line">
323
+ This run has cost {phase.result.costEstimated ? "at least " : ""}
324
+ {currency} {phase.result.cost.toFixed(5)} and is already in the spend ledger.
325
+ Check {meta.tableLabel} shortly.
326
+ </p>
327
+ ) : (
328
+ <p className="monid-run-line">
329
+ {phase.result.records} record
330
+ {phase.result.records === 1 ? "" : "s"} came back and{" "}
331
+ {phase.result.imported ?? 0} landed in {meta.tableLabel}. This run cost{" "}
332
+ {phase.result.costEstimated ? "at least " : ""}
333
+ {currency} {phase.result.cost.toFixed(5)} and is in the spend ledger.
334
+ </p>
335
+ )}
336
+ {phase.result.unmappedColumns && phase.result.unmappedColumns.length ? (
337
+ <p className="monid-run-line">
338
+ These fields came back and the existing database has no column for them:{" "}
339
+ {phase.result.unmappedColumns.join(", ")}.
340
+ </p>
341
+ ) : null}
342
+ </div>
343
+ ) : null}
344
+
345
+ {meta && meta.canRun && meta.configured && phase.kind !== "done" ? (
346
+ <>
347
+ <label className="monid-run-label" htmlFor="monid-asins">
348
+ ASINs
349
+ </label>
350
+ <textarea
351
+ id="monid-asins"
352
+ className="monid-run-input"
353
+ rows={4}
354
+ spellCheck={false}
355
+ value={text}
356
+ placeholder="B08N5WRWNW B07XJ8C8F5"
357
+ disabled={phase.kind === "running"}
358
+ onChange={(e) => setText(e.target.value)}
359
+ />
360
+ {/* ⭐ WHERE THE ASINs COME FROM, SAID ONCE, WHERE THE DECISION IS MADE. */}
361
+ <p className="monid-run-hint">{meta.asinNote}</p>
362
+ {parsed.bad.length ? (
363
+ <p className="monid-run-refusal" role="alert">
364
+ These are not ASINs: {parsed.bad.slice(0, 5).join(", ")}. An ASIN is ten
365
+ characters, letters and digits.
366
+ </p>
367
+ ) : null}
368
+ {overCap ? (
369
+ <p className="monid-run-refusal" role="alert">
370
+ One pull takes at most {meta.maxAsins} ASINs, because every review each one
371
+ returns is charged. Remove {parsed.good.length - meta.maxAsins} and run the
372
+ rest after.
373
+ </p>
374
+ ) : null}
375
+ {/* ⛔⛔ THE PRICE, BEFORE THE BUTTON AND NOT BEHIND IT. */}
376
+ <p className="monid-run-cost">{costSentence(parsed.good.length, unit, currency)}</p>
377
+ <p className="monid-run-hint">
378
+ {meta.balance && typeof meta.balance.value === "number"
379
+ ? `The Monid wallet holds ${meta.balance.currency || currency} ${meta.balance.value.toFixed(2)}.`
380
+ : "The Monid wallet balance could not be read just now."}
381
+ </p>
382
+ </>
383
+ ) : null}
384
+ </div>
385
+
386
+ <footer className="monid-run-foot">
387
+ <button type="button" className="monid-run-btn" onClick={onClose}>
388
+ {phase.kind === "done" ? "Close" : "Cancel"}
389
+ </button>
390
+ {phase.kind !== "done" ? (
391
+ <button
392
+ type="button"
393
+ className="monid-run-btn is-primary"
394
+ /* ⚠ `!canSubmit` IS THE WHOLE CONDITION, and adding `|| phase.kind === "running"`
395
+ beside it does not compile: `canSubmit` already requires `phase.kind ===
396
+ "ready"`, and TypeScript reads that as a narrowing predicate, so the second
397
+ clause is provably unreachable. The running case is disabled because it is not
398
+ ready, which is the same fact said once. */
399
+ disabled={!canSubmit}
400
+ onClick={() => void submit()}
401
+ >
402
+ {/* ⛔ NO TOTAL ON THE BUTTON EITHER. This read
403
+ `Pull reviews for USD 0.00270` and that figure was wrong by 10x on the first
404
+ real call. The price is stated in full above it; the control just names the
405
+ action. */}
406
+ {phase.kind === "running" ? "Pulling reviews" : "Pull reviews"}
407
+ </button>
408
+ ) : null}
409
+ </footer>
410
+ </section>
411
+ </div>
412
+ </BodyPortal>
413
+ );
414
+ }
web/src/connectors/RelationshipDiagram.tsx ADDED
@@ -0,0 +1,770 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // ---------------------------------------------------------------------------
2
+ // connectors/RelationshipDiagram.tsx - W49-T15, ruling R33, contract C4.
3
+ //
4
+ // R33, verbatim: *"Relationship diagram cards show keys and links only, expand
5
+ // on demand; edges run port-to-port with orthogonal routing; labels sit on the
6
+ // edge, never inside a card; nodes are the real databases the connection
7
+ // created."*
8
+ //
9
+ // WHY THE RETIRED CANVAS WAS WRONG AND NOT MERELY UGLY. It placed every edge
10
+ // label at the midpoint of the two CARD CENTRES. `ut_odoo_bills` and
11
+ // `ut_odoo_vendors` are joined by TWO relationships in OPPOSITE directions
12
+ // ("Vendor record" and "Bills"), and so are `ut_odoo_invoices` and
13
+ // `ut_odoo_orders` ("Order record" and "Invoices"). For two edges joining ONE
14
+ // pair of cards that midpoint is the SAME POINT, so both labels painted on top
15
+ // of each other: that overprint is the illegible smear in
16
+ // `reference/ERROR 19 connector.png`, which reads as "ndBilkec".
17
+ //
18
+ // ⭐ PORT-TO-PORT ROUTING IS THEREFORE THE FIX, NOT A RESTYLE. Two edges between
19
+ // one pair attach to DIFFERENT field rows at each end and take DIFFERENT lanes
20
+ // in the corridor between the columns, so their labels separate by
21
+ // construction. A renderer that keeps centre-to-centre geometry and only
22
+ // restyles the label reproduces the defect on this exact pair, which is what
23
+ // `verify_ui.py`'s geometry check exists to catch (its negative control forces
24
+ // the old formula back and the leg must go red).
25
+ //
26
+ // ⛔ THE SECOND HALF OF THE DEFECT WAS CARD SIZE. The old card listed every
27
+ // permitted field: 16 for vendors, 15 for three others, so cards were taller
28
+ // than the viewport. A card here shows its unique key and its link fields, and
29
+ // everything else is behind a real "+N more fields" button that expands IN
30
+ // PLACE (R33). A tooltip or a route to another surface is not that.
31
+ //
32
+ // ⛔ NODES ARE THE ACTUAL TABLES THE RESPONSE RETURNS. There is no provider
33
+ // template anywhere in this file: no table name, no field name and no
34
+ // coordinate is written here. `relationship_graphs` is FROZEN by C4 and this
35
+ // ticket changes only the drawing.
36
+ //
37
+ // ⚠ HTML CARDS OVER AN SVG EDGE LAYER, and the button is why. R33 wants a real
38
+ // affordance and DESIGN.md wants a control that resets native chrome; an SVG
39
+ // <text role="button"> has no native chrome to reset and no keyboard behaviour
40
+ // to inherit. So the cards are absolutely positioned <article>s carrying a real
41
+ // <button>, the edges are an <svg role="img"> underneath them, and BOTH are
42
+ // positioned from the one `relationshipLayout` return the gate measures. Card
43
+ // text is inside its own card by construction; the only text that could ever
44
+ // land in another card's rect is an edge label, which is exactly where the
45
+ // defect was.
46
+ //
47
+ // ⚠ THE TYPE SIZES BELOW ARE THE RESOLVED VALUES OF THE TOKENS THE STYLESHEET
48
+ // NAMES, against the 17px root DESIGN.md section 2 pins. A layout that measures
49
+ // text at 10px while the CSS paints it at 11.6875px is a geometry proof over
50
+ // numbers nothing renders, so `verify_ui.py` carries a parity leg tying each
51
+ // constant here to the `--lp-fs-*` token used by the matching rule.
52
+ // ---------------------------------------------------------------------------
53
+
54
+ import { useCallback, useMemo, useState } from "react";
55
+ import type { ConnectorRelationshipGraph } from "./ConnectorsPage";
56
+ import "../styles/wave49/connectors.css";
57
+
58
+ /* --------------------------------------------------------------------------
59
+ The input, read STRUCTURALLY.
60
+
61
+ ⛔ This is C4's `relationship_graphs` shape and not a second vocabulary for
62
+ it: `ConnectorRelationshipGraph` satisfies it, so `parseRelationshipGraph`
63
+ stays the only reader and this file never learns a provider's field names.
64
+ Declaring it structurally also keeps the compiled module free of any runtime
65
+ import but React, which is what lets the gate run the layout under bare node.
66
+ -------------------------------------------------------------------------- */
67
+
68
+ export interface DiagramField { key: string; label: string }
69
+ export interface DiagramTable { key: string; label: string; fields: DiagramField[] }
70
+ export interface DiagramEndpoint { table: string; field: string }
71
+ export interface DiagramRelationship {
72
+ from: DiagramEndpoint;
73
+ to: DiagramEndpoint;
74
+ label: string;
75
+ }
76
+ export interface DiagramInput {
77
+ tables: DiagramTable[];
78
+ relationships: DiagramRelationship[];
79
+ }
80
+
81
+ /* ---------------------------------------------------------- type geometry */
82
+
83
+ /** The root the rem tokens resolve against (DESIGN.md section 2). */
84
+ export const ROOT_FONT_PX = 17;
85
+ /** `--lp-fs-2xs` 0.75rem, the card title. */
86
+ export const TITLE_FONT_PX = 12.75;
87
+ /** `--lp-fs-3xs` 0.6875rem, every field row and the expand control. */
88
+ export const ROW_FONT_PX = 11.6875;
89
+ /** `--lp-fs-3xs` 0.6875rem, the edge label. */
90
+ export const EDGE_FONT_PX = 11.6875;
91
+ /**
92
+ * A deliberate OVER-estimate of Inter's average advance width. Over-estimating
93
+ * makes both truncation and the collision proof stricter, which is the safe
94
+ * direction: a label the layout thinks is wider than it paints can only ever be
95
+ * placed further from a card, never closer.
96
+ */
97
+ export const CHAR_WIDTH_RATIO = 0.58;
98
+ export const LINE_HEIGHT_RATIO = 1.3;
99
+
100
+ export function textWidth(text: string, fontPx: number): number {
101
+ return text.length * fontPx * CHAR_WIDTH_RATIO;
102
+ }
103
+ export function textHeight(fontPx: number): number {
104
+ return fontPx * LINE_HEIGHT_RATIO;
105
+ }
106
+
107
+ /** Trim to a measured width, ending in an ellipsis. Never a dash (standing rule 2). */
108
+ export function fitText(text: string, fontPx: number, maxWidth: number): string {
109
+ if (textWidth(text, fontPx) <= maxWidth) return text;
110
+ const per = fontPx * CHAR_WIDTH_RATIO;
111
+ const room = Math.max(1, Math.floor(maxWidth / per) - 1);
112
+ return text.slice(0, room) + "…";
113
+ }
114
+
115
+ /* ------------------------------------------------------------- the metrics */
116
+
117
+ export const PAD = 20;
118
+ export const CARD_W = 210;
119
+ export const CARD_PAD_X = 12;
120
+ export const HEADER_H = 32;
121
+ export const ROW_H = 22;
122
+ export const MORE_H = 28;
123
+ export const CARD_BOTTOM = 8;
124
+ export const CARD_GAP_Y = 16;
125
+ export const SINGLE_GAP = 18;
126
+ /** The corridor every edge between two columns is routed through. */
127
+ export const GUTTER = 168;
128
+ /** Bands clear each other by more than a label can ever hang below a card. */
129
+ export const BAND_GAP = 40;
130
+ /** Two edges over one pair take different lanes: this is the x separation. */
131
+ export const LANE_GAP_X = 30;
132
+ /** ...and this is the y separation, which is what stops two labels overprinting. */
133
+ export const LANE_GAP_Y = 20;
134
+ /** The horizontal stub between a port and its corridor. */
135
+ export const STUB = 14;
136
+ export const KEY_BADGE_W = 28;
137
+ export const LABEL_MARGIN = 8;
138
+
139
+ /* --------------------------------------------------------------- the model */
140
+
141
+ export type TextRole = "title" | "row" | "badge" | "more" | "edge" | "note";
142
+
143
+ export interface DiagramText {
144
+ id: string;
145
+ /** The card this text belongs to, or `null` for an edge label. */
146
+ owner: string | null;
147
+ role: TextRole;
148
+ text: string;
149
+ /** The rect the glyphs occupy: x and y are the LEFT and TOP edges. */
150
+ x: number;
151
+ y: number;
152
+ width: number;
153
+ height: number;
154
+ }
155
+
156
+ export interface DiagramRow {
157
+ key: string;
158
+ label: string;
159
+ text: string;
160
+ isKey: boolean;
161
+ isLink: boolean;
162
+ /** The row's vertical centre, which is the y every port on it uses. */
163
+ portY: number;
164
+ portLeft: boolean;
165
+ portRight: boolean;
166
+ }
167
+
168
+ export interface DiagramCard {
169
+ key: string;
170
+ label: string;
171
+ titleText: string;
172
+ x: number;
173
+ y: number;
174
+ width: number;
175
+ height: number;
176
+ column: number;
177
+ rows: DiagramRow[];
178
+ hiddenCount: number;
179
+ expanded: boolean;
180
+ moreText: string;
181
+ /** The empty sentence when a permitted table has no permitted fields at all. */
182
+ note: string;
183
+ }
184
+
185
+ export interface DiagramPoint { x: number; y: number }
186
+
187
+ export interface DiagramEdge {
188
+ id: string;
189
+ label: string;
190
+ labelText: string;
191
+ from: DiagramEndpoint;
192
+ to: DiagramEndpoint;
193
+ /** The orthogonal route: out of the source port, along one corridor, into the target port. */
194
+ points: DiagramPoint[];
195
+ fromPoint: DiagramPoint;
196
+ toPoint: DiagramPoint;
197
+ corridorX: number;
198
+ labelX: number;
199
+ labelY: number;
200
+ lane: number;
201
+ }
202
+
203
+ export interface DiagramLayout {
204
+ width: number;
205
+ height: number;
206
+ cards: DiagramCard[];
207
+ edges: DiagramEdge[];
208
+ texts: DiagramText[];
209
+ }
210
+
211
+ /* ------------------------------------------------------------ the layout */
212
+
213
+ function rowsFor(table: DiagramTable, linked: Set<string>, expanded: boolean): DiagramField[] {
214
+ if (expanded) return table.fields.slice();
215
+ const keyField = table.fields.length ? table.fields[0].key : "";
216
+ // ⚠ ONE ROW PER FIELD. `ut_odoo_orders.order_no` is both the derived key and the
217
+ // target of "Order record", and a naive key-plus-links list would give that card
218
+ // two rows for one field, i.e. two ports at two different y values for one port.
219
+ // Key-ness is a FLAG on a row, never a row of its own.
220
+ return table.fields.filter((field) => field.key === keyField || linked.has(field.key));
221
+ }
222
+
223
+ /**
224
+ * THE UNIQUE KEY IS THE TABLE'S FIRST COLUMN, and that is a reading of the DTO
225
+ * rather than a guess about a provider. `relationship_graphs` emits the fields in
226
+ * the table definition's own order and an AIOS user table carries its identifying
227
+ * column first; on the eight tables this connection actually created that is
228
+ * `agent`, `account_code`, `entry`, `invoice_no`, `order_no`, `order_no`,
229
+ * `bill_no`, `vendor`. C4 carries no primary-key marker to read instead, and
230
+ * inventing one client-side would be a second answer to a server question.
231
+ */
232
+ function keyKeyFor(table: DiagramTable): string {
233
+ return table.fields.length ? table.fields[0].key : "";
234
+ }
235
+
236
+ function moreLabel(hidden: number, expanded: boolean): string {
237
+ if (expanded) return "Show fewer fields";
238
+ if (hidden === 1) return "+1 more field";
239
+ return "+" + String(hidden) + " more fields";
240
+ }
241
+
242
+ /**
243
+ * Lay the whole diagram out from the response alone.
244
+ *
245
+ * Pure: no DOM, no measurement, no state. `verify_ui.py` runs this exact
246
+ * function under node and proves the geometry over its return value, so every
247
+ * number a reader sees on the screen is a number the gate has checked.
248
+ */
249
+ export function relationshipLayout(graph: DiagramInput, expandedKeys: string[] = []): DiagramLayout {
250
+ const expanded = new Set(expandedKeys);
251
+ const tables = graph.tables.slice();
252
+ const relationships = graph.relationships.slice();
253
+ const byKey = new Map<string, DiagramTable>();
254
+ for (const table of tables) byKey.set(table.key, table);
255
+
256
+ // Which fields of which table an edge actually touches. This is what makes a
257
+ // collapsed card show its LINKS and not an arbitrary prefix of its columns.
258
+ const touched = new Map<string, Set<string>>();
259
+ const linkedTables = new Set<string>();
260
+ for (const relation of relationships) {
261
+ if (!byKey.has(relation.from.table) || !byKey.has(relation.to.table)) continue;
262
+ linkedTables.add(relation.from.table);
263
+ linkedTables.add(relation.to.table);
264
+ for (const end of [relation.from, relation.to]) {
265
+ const set = touched.get(end.table) ?? new Set<string>();
266
+ set.add(end.field);
267
+ touched.set(end.table, set);
268
+ }
269
+ }
270
+
271
+ // ---- components over the linked tables, so a related pair sits side by side.
272
+ const parent = new Map<string, string>();
273
+ const find = (key: string): string => {
274
+ let root = key;
275
+ while ((parent.get(root) ?? root) !== root) root = parent.get(root) ?? root;
276
+ return root;
277
+ };
278
+ for (const key of linkedTables) parent.set(key, key);
279
+ const adjacency = new Map<string, Set<string>>();
280
+ for (const key of linkedTables) adjacency.set(key, new Set<string>());
281
+ for (const relation of relationships) {
282
+ const a = relation.from.table;
283
+ const b = relation.to.table;
284
+ if (!linkedTables.has(a) || !linkedTables.has(b)) continue;
285
+ adjacency.get(a)?.add(b);
286
+ adjacency.get(b)?.add(a);
287
+ const ra = find(a);
288
+ const rb = find(b);
289
+ if (ra !== rb) parent.set(ra, rb);
290
+ }
291
+ const components = new Map<string, string[]>();
292
+ for (const key of Array.from(linkedTables).sort()) {
293
+ const root = find(key);
294
+ const list = components.get(root) ?? [];
295
+ list.push(key);
296
+ components.set(root, list);
297
+ }
298
+ const bands = Array.from(components.values()).sort((a, b) => {
299
+ if (b.length !== a.length) return b.length - a.length;
300
+ return a[0] < b[0] ? -1 : 1;
301
+ });
302
+
303
+ // ---- column per table: BFS depth parity inside a band, so an edge crosses ONE gutter.
304
+ const columnOf = new Map<string, number>();
305
+ const bandOf = new Map<string, number>();
306
+ const bandMembers: string[][] = [];
307
+ bands.forEach((band, bandIndex) => {
308
+ const seen = new Set<string>();
309
+ const queue: string[] = [];
310
+ const start = band.slice().sort()[0];
311
+ queue.push(start);
312
+ seen.add(start);
313
+ columnOf.set(start, 0);
314
+ while (queue.length) {
315
+ const current = queue.shift() as string;
316
+ const depth = columnOf.get(current) ?? 0;
317
+ for (const next of Array.from(adjacency.get(current) ?? []).sort()) {
318
+ if (seen.has(next)) continue;
319
+ seen.add(next);
320
+ columnOf.set(next, (depth + 1) % 2);
321
+ queue.push(next);
322
+ }
323
+ }
324
+ for (const key of band) {
325
+ if (!columnOf.has(key)) columnOf.set(key, 0);
326
+ bandOf.set(key, bandIndex);
327
+ }
328
+ bandMembers[bandIndex] = band;
329
+ });
330
+
331
+ const columnX = (column: number): number => PAD + column * (CARD_W + GUTTER);
332
+
333
+ const cards: DiagramCard[] = [];
334
+ const cardByKey = new Map<string, DiagramCard>();
335
+ const makeCard = (table: DiagramTable, x: number, y: number, column: number): DiagramCard => {
336
+ const isExpanded = expanded.has(table.key);
337
+ const links = touched.get(table.key) ?? new Set<string>();
338
+ const shown = rowsFor(table, links, isExpanded);
339
+ const keyKey = keyKeyFor(table);
340
+ const rows: DiagramRow[] = shown.map((field, index) => {
341
+ const isKey = field.key === keyKey;
342
+ const room = CARD_W - CARD_PAD_X * 2 - (isKey ? KEY_BADGE_W : 0);
343
+ return {
344
+ key: field.key,
345
+ label: field.label,
346
+ text: fitText(field.label, ROW_FONT_PX, room),
347
+ isKey,
348
+ isLink: links.has(field.key),
349
+ portY: y + HEADER_H + index * ROW_H + ROW_H / 2,
350
+ portLeft: false,
351
+ portRight: false,
352
+ };
353
+ });
354
+ const hiddenCount = table.fields.length - shown.length;
355
+ const hasMore = hiddenCount > 0 || isExpanded;
356
+ const note = rows.length === 0 ? "No permitted fields" : "";
357
+ const bodyRows = Math.max(rows.length, note ? 1 : 0);
358
+ const card: DiagramCard = {
359
+ key: table.key,
360
+ label: table.label,
361
+ titleText: fitText(table.label, TITLE_FONT_PX, CARD_W - CARD_PAD_X * 2),
362
+ x,
363
+ y,
364
+ width: CARD_W,
365
+ height: HEADER_H + bodyRows * ROW_H + (hasMore ? MORE_H : 0) + CARD_BOTTOM,
366
+ column,
367
+ rows,
368
+ hiddenCount,
369
+ expanded: isExpanded,
370
+ moreText: hasMore ? moreLabel(hiddenCount, isExpanded) : "",
371
+ note,
372
+ };
373
+ cards.push(card);
374
+ cardByKey.set(card.key, card);
375
+ return card;
376
+ };
377
+
378
+ // ---- the bands: two columns each, stacked.
379
+ let cursorY = PAD;
380
+ bandMembers.forEach((band) => {
381
+ const columnCursor = [cursorY, cursorY];
382
+ const ordered = band.slice().sort((a, b) => {
383
+ const ca = columnOf.get(a) ?? 0;
384
+ const cb = columnOf.get(b) ?? 0;
385
+ if (ca !== cb) return ca - cb;
386
+ return a < b ? -1 : 1;
387
+ });
388
+ for (const key of ordered) {
389
+ const table = byKey.get(key);
390
+ if (!table) continue;
391
+ const column = columnOf.get(key) ?? 0;
392
+ const card = makeCard(table, columnX(column), columnCursor[column], column);
393
+ columnCursor[column] = card.y + card.height + CARD_GAP_Y;
394
+ }
395
+ cursorY = Math.max(columnCursor[0], columnCursor[1]) - CARD_GAP_Y + BAND_GAP;
396
+ });
397
+
398
+ // ---- the tables no relationship touches, in a wrapped grid under the bands.
399
+ const singles = tables.filter((table) => !linkedTables.has(table.key));
400
+ const linkedWidth = bandMembers.length ? CARD_W * 2 + GUTTER : CARD_W * 3 + SINGLE_GAP * 2;
401
+ const perRow = Math.max(1, Math.floor((linkedWidth + SINGLE_GAP) / (CARD_W + SINGLE_GAP)));
402
+ let singleRowTop = cursorY;
403
+ let rowHeight = 0;
404
+ singles.forEach((table, index) => {
405
+ const column = index % perRow;
406
+ if (column === 0 && index > 0) {
407
+ singleRowTop += rowHeight + CARD_GAP_Y;
408
+ rowHeight = 0;
409
+ }
410
+ const card = makeCard(table, PAD + column * (CARD_W + SINGLE_GAP), singleRowTop, column);
411
+ rowHeight = Math.max(rowHeight, card.height);
412
+ });
413
+ if (singles.length) cursorY = singleRowTop + rowHeight + PAD;
414
+ else cursorY = cursorY - BAND_GAP + PAD;
415
+
416
+ /* ---- the edges, port to port.
417
+ *
418
+ * Every edge leaves the exact field row it names and arrives at the exact field
419
+ * row it names. Edges sharing a corridor are given LANES, and a lane separates
420
+ * its label in x AND in y: two edges over one pair of cards are symmetric, so
421
+ * their vertical midpoints are identical and an x offset alone would still let
422
+ * the two label rects overlap. That symmetry is the defect from ERROR 19.
423
+ */
424
+ const laneKeyOf = (relation: DiagramRelationship): string => {
425
+ const fromCard = cardByKey.get(relation.from.table);
426
+ const toCard = cardByKey.get(relation.to.table);
427
+ if (!fromCard || !toCard) return "none";
428
+ const low = Math.min(fromCard.column, toCard.column);
429
+ const high = Math.max(fromCard.column, toCard.column);
430
+ const band = bandOf.get(relation.from.table) ?? -1;
431
+ return String(band) + ":" + String(low) + ":" + String(high);
432
+ };
433
+ const laneTotals = new Map<string, number>();
434
+ for (const relation of relationships) {
435
+ const laneKey = laneKeyOf(relation);
436
+ laneTotals.set(laneKey, (laneTotals.get(laneKey) ?? 0) + 1);
437
+ }
438
+ const laneTaken = new Map<string, number>();
439
+
440
+ const edges: DiagramEdge[] = [];
441
+ for (const relation of relationships) {
442
+ const fromCard = cardByKey.get(relation.from.table);
443
+ const toCard = cardByKey.get(relation.to.table);
444
+ if (!fromCard || !toCard) continue;
445
+ const fromRow = fromCard.rows.find((row) => row.key === relation.from.field);
446
+ const toRow = toCard.rows.find((row) => row.key === relation.to.field);
447
+ if (!fromRow || !toRow) continue;
448
+
449
+ const laneKey = laneKeyOf(relation);
450
+ const lane = laneTaken.get(laneKey) ?? 0;
451
+ laneTaken.set(laneKey, lane + 1);
452
+ const lanes = laneTotals.get(laneKey) ?? 1;
453
+ const laneOffset = (lane - (lanes - 1) / 2) * LANE_GAP_X;
454
+ const laneDy = (lane - (lanes - 1) / 2) * LANE_GAP_Y;
455
+
456
+ // The corridor: the gutter BETWEEN the two columns when they differ, and the
457
+ // free space to the right of the column when they do not (a chain that folds
458
+ // back on itself, or a table linked to itself, both of which C4 permits).
459
+ let corridorCentre: number;
460
+ let leftBound: number;
461
+ let rightBound: number;
462
+ let exitX: number;
463
+ let enterX: number;
464
+ if (toCard.column > fromCard.column) {
465
+ leftBound = columnX(fromCard.column) + CARD_W;
466
+ rightBound = columnX(toCard.column);
467
+ exitX = fromCard.x + fromCard.width;
468
+ enterX = toCard.x;
469
+ } else if (toCard.column < fromCard.column) {
470
+ leftBound = columnX(toCard.column) + CARD_W;
471
+ rightBound = columnX(fromCard.column);
472
+ exitX = fromCard.x;
473
+ enterX = toCard.x + toCard.width;
474
+ } else {
475
+ leftBound = columnX(fromCard.column) + CARD_W;
476
+ rightBound = leftBound + GUTTER;
477
+ exitX = fromCard.x + fromCard.width;
478
+ enterX = toCard.x + toCard.width;
479
+ }
480
+ corridorCentre = (leftBound + rightBound) / 2;
481
+ const corridorX = corridorCentre + laneOffset;
482
+
483
+ const y1 = fromRow.portY;
484
+ const y2 = toRow.portY;
485
+ const fromPoint = { x: exitX, y: y1 };
486
+ const toPoint = { x: enterX, y: y2 };
487
+ const stubOut = exitX === fromCard.x ? exitX - STUB : exitX + STUB;
488
+ const stubIn = enterX === toCard.x ? enterX - STUB : enterX + STUB;
489
+ const points: DiagramPoint[] = [
490
+ fromPoint,
491
+ { x: stubOut, y: y1 },
492
+ { x: corridorX, y: y1 },
493
+ { x: corridorX, y: y2 },
494
+ { x: stubIn, y: y2 },
495
+ toPoint,
496
+ ];
497
+
498
+ const midY = (y1 + y2) / 2;
499
+ const span = textHeight(EDGE_FONT_PX);
500
+ const low = Math.min(y1, y2) - span;
501
+ const high = Math.max(y1, y2) + span;
502
+ const labelX = corridorX;
503
+ const labelY = Math.min(high, Math.max(low, midY + laneDy));
504
+ const halfRoom = Math.min(corridorX - leftBound, rightBound - corridorX);
505
+ const labelRoom = Math.max(1, (halfRoom - LABEL_MARGIN) * 2);
506
+ const labelText = fitText(relation.label, EDGE_FONT_PX, labelRoom);
507
+
508
+ fromRow.portRight = fromRow.portRight || exitX > fromCard.x;
509
+ fromRow.portLeft = fromRow.portLeft || exitX === fromCard.x;
510
+ toRow.portRight = toRow.portRight || enterX > toCard.x;
511
+ toRow.portLeft = toRow.portLeft || enterX === toCard.x;
512
+
513
+ edges.push({
514
+ id: relation.from.table + "." + relation.from.field + ">"
515
+ + relation.to.table + "." + relation.to.field,
516
+ label: relation.label,
517
+ labelText,
518
+ from: relation.from,
519
+ to: relation.to,
520
+ points,
521
+ fromPoint,
522
+ toPoint,
523
+ corridorX,
524
+ labelX,
525
+ labelY,
526
+ lane,
527
+ });
528
+ }
529
+
530
+ /* ---- every glyph the surface paints, as a rect the gate can test.
531
+ * A card's own text is inside its own card by construction; an edge label is
532
+ * the only text that could land in another card, which is where the defect was.
533
+ */
534
+ const texts: DiagramText[] = [];
535
+ for (const card of cards) {
536
+ texts.push({
537
+ id: card.key + ":title",
538
+ owner: card.key,
539
+ role: "title",
540
+ text: card.titleText,
541
+ x: card.x + CARD_PAD_X,
542
+ y: card.y + (HEADER_H - textHeight(TITLE_FONT_PX)) / 2,
543
+ width: textWidth(card.titleText, TITLE_FONT_PX),
544
+ height: textHeight(TITLE_FONT_PX),
545
+ });
546
+ card.rows.forEach((row) => {
547
+ texts.push({
548
+ id: card.key + ":row:" + row.key,
549
+ owner: card.key,
550
+ role: "row",
551
+ text: row.text,
552
+ x: card.x + CARD_PAD_X,
553
+ y: row.portY - textHeight(ROW_FONT_PX) / 2,
554
+ width: textWidth(row.text, ROW_FONT_PX),
555
+ height: textHeight(ROW_FONT_PX),
556
+ });
557
+ if (row.isKey) {
558
+ texts.push({
559
+ id: card.key + ":badge:" + row.key,
560
+ owner: card.key,
561
+ role: "badge",
562
+ text: "Key",
563
+ x: card.x + CARD_W - CARD_PAD_X - KEY_BADGE_W,
564
+ y: row.portY - textHeight(ROW_FONT_PX) / 2,
565
+ width: KEY_BADGE_W,
566
+ height: textHeight(ROW_FONT_PX),
567
+ });
568
+ }
569
+ });
570
+ if (card.note) {
571
+ texts.push({
572
+ id: card.key + ":note",
573
+ owner: card.key,
574
+ role: "note",
575
+ text: card.note,
576
+ x: card.x + CARD_PAD_X,
577
+ y: card.y + HEADER_H + (ROW_H - textHeight(ROW_FONT_PX)) / 2,
578
+ width: textWidth(card.note, ROW_FONT_PX),
579
+ height: textHeight(ROW_FONT_PX),
580
+ });
581
+ }
582
+ if (card.moreText) {
583
+ texts.push({
584
+ id: card.key + ":more",
585
+ owner: card.key,
586
+ role: "more",
587
+ text: card.moreText,
588
+ x: card.x + CARD_PAD_X,
589
+ y: card.y + card.height - CARD_BOTTOM - MORE_H
590
+ + (MORE_H - textHeight(ROW_FONT_PX)) / 2,
591
+ width: textWidth(card.moreText, ROW_FONT_PX),
592
+ height: textHeight(ROW_FONT_PX),
593
+ });
594
+ }
595
+ }
596
+ for (const edge of edges) {
597
+ const width = textWidth(edge.labelText, EDGE_FONT_PX);
598
+ const height = textHeight(EDGE_FONT_PX);
599
+ texts.push({
600
+ id: edge.id + ":label",
601
+ owner: null,
602
+ role: "edge",
603
+ text: edge.labelText,
604
+ x: edge.labelX - width / 2,
605
+ y: edge.labelY - height / 2,
606
+ width,
607
+ height,
608
+ });
609
+ }
610
+
611
+ let width = PAD;
612
+ for (const card of cards) width = Math.max(width, card.x + card.width);
613
+ for (const edge of edges) width = Math.max(width, edge.corridorX);
614
+ for (const text of texts) width = Math.max(width, text.x + text.width);
615
+ let height = PAD;
616
+ for (const card of cards) height = Math.max(height, card.y + card.height);
617
+ for (const text of texts) height = Math.max(height, text.y + text.height);
618
+
619
+ return {
620
+ width: Math.round(width + PAD),
621
+ height: Math.round(Math.max(height + PAD, cursorY)),
622
+ cards,
623
+ edges,
624
+ texts,
625
+ };
626
+ }
627
+
628
+ /* --------------------------------------------------------------- the view */
629
+
630
+ /**
631
+ * The accessible name for the edge layer.
632
+ *
633
+ * ⛔ AN <svg role="img"> HIDES ITS CHILDREN FROM ASSISTIVE TECHNOLOGY, so the
634
+ * label text painted on the lines is not readable by itself. The name therefore
635
+ * carries the relationships in words. The cards are real HTML, so they need no
636
+ * such treatment and this sentence does not repeat them.
637
+ */
638
+ export function edgeSummary(connector: string, graph: DiagramInput): string {
639
+ const name = connector.trim() || "This connection";
640
+ if (!graph.relationships.length) {
641
+ return name + " relationship map. No declared links join these databases.";
642
+ }
643
+ // ⚠ THE DATABASE'S NAME, NOT ITS STORAGE KEY. A summary reading "ut_odoo_bills" says the
644
+ // table's internal key out loud to the one reader who cannot see the card that translates it.
645
+ const named = (key: string): string => {
646
+ for (const table of graph.tables) {
647
+ if (table.key === key) return table.label;
648
+ }
649
+ return key;
650
+ };
651
+ const parts = graph.relationships.map((relation) =>
652
+ named(relation.from.table) + " to " + named(relation.to.table) + ", by " + relation.label);
653
+ return name + " relationship map. " + String(graph.relationships.length)
654
+ + (graph.relationships.length === 1 ? " link: " : " links: ") + parts.join("; ") + ".";
655
+ }
656
+
657
+ export default function RelationshipDiagram({
658
+ connector,
659
+ graph,
660
+ }: {
661
+ connector: string;
662
+ graph: ConnectorRelationshipGraph;
663
+ }) {
664
+ const [expandedKeys, setExpandedKeys] = useState<string[]>([]);
665
+ // ⚠ HOOKS BEFORE ANY EARLY RETURN. A refused graph must not change the hook
666
+ // order between renders ([[react-hooks-order-gate]]).
667
+ const layout = useMemo(() => relationshipLayout(graph, expandedKeys), [graph, expandedKeys]);
668
+ const toggle = useCallback((key: string) => {
669
+ setExpandedKeys((keys) => (keys.includes(key) ? keys.filter((k) => k !== key) : keys.concat(key)));
670
+ }, []);
671
+
672
+ if (graph.status !== "ready") {
673
+ return (
674
+ <p className="conn-rd-note" role="status">
675
+ {graph.reason || "This connection did not make an actual relationship graph available."}
676
+ </p>
677
+ );
678
+ }
679
+ if (!graph.tables.length) {
680
+ return <p className="conn-rd-note">This connection has created no databases yet.</p>;
681
+ }
682
+
683
+ return (
684
+ <div className="conn-rd">
685
+ <div className="conn-rd-scroll">
686
+ <div className="conn-rd-stage" style={{ width: layout.width, height: layout.height }}>
687
+ <svg
688
+ className="conn-rd-edges"
689
+ width={layout.width}
690
+ height={layout.height}
691
+ viewBox={"0 0 " + String(layout.width) + " " + String(layout.height)}
692
+ role="img"
693
+ aria-label={edgeSummary(connector, graph)}
694
+ >
695
+ <defs>
696
+ <marker
697
+ id="conn-rd-arrow"
698
+ markerWidth="7"
699
+ markerHeight="7"
700
+ refX="6"
701
+ refY="3"
702
+ orient="auto"
703
+ >
704
+ <path className="conn-rd-arrow" d="M0 0 L6 3 L0 6 Z" />
705
+ </marker>
706
+ </defs>
707
+ {layout.edges.map((edge) => (
708
+ <g key={edge.id}>
709
+ <polyline
710
+ className="conn-rd-line"
711
+ points={edge.points.map((point) => String(point.x) + "," + String(point.y)).join(" ")}
712
+ markerEnd="url(#conn-rd-arrow)"
713
+ />
714
+ <text
715
+ className="conn-rd-label"
716
+ x={edge.labelX}
717
+ y={edge.labelY}
718
+ textAnchor="middle"
719
+ dominantBaseline="middle"
720
+ >
721
+ {edge.labelText}
722
+ </text>
723
+ </g>
724
+ ))}
725
+ </svg>
726
+ {layout.cards.map((card) => (
727
+ <article
728
+ key={card.key}
729
+ className="conn-rd-card"
730
+ style={{ left: card.x, top: card.y, width: card.width, height: card.height }}
731
+ >
732
+ <h4 className="conn-rd-card-title" title={card.label}>{card.titleText}</h4>
733
+ {card.note ? (
734
+ <p className="conn-rd-empty">{card.note}</p>
735
+ ) : (
736
+ <ul className="conn-rd-rows">
737
+ {card.rows.map((row) => (
738
+ <li
739
+ key={row.key}
740
+ className={row.isLink ? "conn-rd-row is-link" : "conn-rd-row"}
741
+ title={row.label}
742
+ >
743
+ {row.portLeft ? <span className="conn-rd-port is-left" aria-hidden="true" /> : null}
744
+ <span className="conn-rd-row-name">{row.text}</span>
745
+ {row.isKey ? <span className="conn-rd-key">Key</span> : null}
746
+ {row.portRight ? <span className="conn-rd-port is-right" aria-hidden="true" /> : null}
747
+ </li>
748
+ ))}
749
+ </ul>
750
+ )}
751
+ {card.moreText ? (
752
+ <button
753
+ type="button"
754
+ className="conn-rd-more"
755
+ onClick={() => toggle(card.key)}
756
+ aria-expanded={card.expanded}
757
+ >
758
+ {card.moreText}
759
+ </button>
760
+ ) : null}
761
+ </article>
762
+ ))}
763
+ </div>
764
+ </div>
765
+ {layout.edges.length === 0 ? (
766
+ <p className="conn-rd-note">No declared relationships connect the permitted tables.</p>
767
+ ) : null}
768
+ </div>
769
+ );
770
+ }
web/src/connectors/ViewDeleteDisclosure.tsx ADDED
@@ -0,0 +1,299 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // ---------------------------------------------------------------------------
2
+ // connectors/ViewDeleteDisclosure.tsx — W49-T16, ruling R32, contract C3.
3
+ //
4
+ // ⭐⭐ R32, second half, verbatim: *"deleting a view must first disclose who it
5
+ // is shared to and which Sheet cells depend on it."* So this is not a generic
6
+ // "Are you sure?" — the whole point is the two FACTS above the button:
7
+ //
8
+ // Shared with Anna and 2 others · used by 3 Sheet cells
9
+ //
10
+ // ⛔ THIS TICKET SHIPS THE COMPONENT, NOT ITS MOUNT. `CustomerGrid.tsx`'s
11
+ // `deleteView` is wired in W49-T17, a declared handover owned by the combine
12
+ // session, and that file lives in another lane's fence. Shipping unmounted is
13
+ // the plan, not an omission.
14
+ //
15
+ // ⭐ REUSED, NOT HAND-ROLLED. `customer-grid/OverlaySurface` already owns the
16
+ // dismissal/focus contract (Escape, outside-pointer dismiss, Tab focus trap,
17
+ // focus restored on unmount) and `ConnectorModal.tsx` next door is the in-repo
18
+ // precedent for using it from this directory. ⚠ `trapFocus` DEFAULTS TO FALSE,
19
+ // so a confirm dialog must pass it explicitly.
20
+ //
21
+ // ⛔⛔ TWO TRAPS, BOTH PAID FOR ALREADY:
22
+ // (a) a portalled overlay paints its OWN background or it renders transparent
23
+ // over whatever it covers ([[a-portal-overlay-carries-its-own-surface]]);
24
+ // (b) z-order is a THREE-WAY order, so this sits on the DIALOG step
25
+ // (`--cg-z-record`) and the portal step (`--cg-z-overlay`) stays above it
26
+ // ([[z-layering-is-a-three-way-order]]). A token, never a number.
27
+ //
28
+ // ⚠ STYLES ARE INLINE `var(--lp-*)` RATHER THAN A STYLESHEET, and that is a
29
+ // FENCE fact rather than a preference: W49-T16 owns five files and no CSS file
30
+ // is among them. The discipline DESIGN.md §5 asks for is unchanged — every
31
+ // colour, size, radius and z-index below is a token, there is not one literal
32
+ // hex and not one literal font-size. If this component later earns a stylesheet,
33
+ // the rules lift out of `S` unchanged.
34
+ //
35
+ // ⛔ DESTRUCTIVE MEANS RED (DESIGN.md §3). The confirming action wears
36
+ // `--lp-red-deep` on `--lp-red-tint`, never `--lp-primary`, and every button
37
+ // resets native chrome (appearance / border / background / font / color).
38
+ //
39
+ // ⛔ STANDING RULE 2 — NO EM DASH AND NO EN DASH IN ANY STRING THAT REACHES A
40
+ // SCREEN. The separator between the two facts is a MIDDOT (·), which the ruling
41
+ // quotes itself. Sentence case throughout, no ALL-CAPS chrome, no emojis: the
42
+ // one icon is inline SVG.
43
+ //
44
+ // ⚠ NO CLIENT UNION OVER A SERVER VOCABULARY (the wave-9 law). A dependent's
45
+ // `kind` and `label` arrive as STRINGS from `/api/v1/dependents`, so a kind the
46
+ // server adds later — `sheet_cell` the moment W49-T11 registers it — renders
47
+ // with no change here.
48
+ // ---------------------------------------------------------------------------
49
+
50
+ import { useCallback, useRef, useState } from "react";
51
+ import type { CSSProperties } from "react";
52
+ import { BodyPortal, useOverlayLayer } from "../customer-grid/OverlaySurface";
53
+
54
+ /** One row of C3's `Dependent`. `kind` and `label` are read as strings, never a union. */
55
+ export interface ViewDependent {
56
+ kind: string;
57
+ label: string;
58
+ count: number;
59
+ ids: string[];
60
+ }
61
+
62
+ /** The share half of `GET /api/v1/dependents?kind=view`. `names` are usernames. */
63
+ export interface ViewShareAudience {
64
+ owner?: string | null;
65
+ names: string[];
66
+ count: number;
67
+ /** The server's own sentence, when it sent one. Preferred over recomposing it here. */
68
+ sentence?: string;
69
+ }
70
+
71
+ export interface ViewDeleteDisclosureProps {
72
+ /** The saved view's name, as the user knows it. */
73
+ viewName: string;
74
+ /** Everything that depends on the view. Zero-count kinds are ABSENT, never zero. */
75
+ dependents: ViewDependent[];
76
+ /** Who the view is shared with, or undefined while it is still loading. */
77
+ share?: ViewShareAudience;
78
+ /** True while the disclosure is still being fetched. */
79
+ loading?: boolean;
80
+ /** A kind the server could not answer, so the dialog does not imply it is empty. */
81
+ unanswered?: string[];
82
+ busy?: boolean;
83
+ error?: string;
84
+ onConfirm: () => void;
85
+ onCancel: () => void;
86
+ }
87
+
88
+ /**
89
+ * "Shared with anna and 2 others", or "" when nobody holds a grant.
90
+ *
91
+ * ⛔ THE EMPTY STRING IS THE ANSWER FOR "shared with nobody", not "Shared with 0
92
+ * people". Same rule as the dependents list: a zero is a claim, and an absent
93
+ * clause is the honest rendering.
94
+ */
95
+ export function audienceSentence(share?: ViewShareAudience): string {
96
+ const names = (share?.names ?? []).map((name) => String(name || "").trim()).filter(Boolean);
97
+ if (!names.length) return "";
98
+ if (names.some((name) => name === "*")) return "Shared with everyone in this workspace";
99
+ if (names.length === 1) return `Shared with ${names[0]}`;
100
+ if (names.length === 2) return `Shared with ${names[0]} and 1 other`;
101
+ return `Shared with ${names[0]} and ${names.length - 1} others`;
102
+ }
103
+
104
+ /**
105
+ * "used by 3 Sheet cells", or "" when nothing depends.
106
+ *
107
+ * The counts and their nouns both come from the server, so a kind registered
108
+ * after this file shipped still reads correctly.
109
+ */
110
+ export function usageSentence(dependents: ViewDependent[]): string {
111
+ const parts = (dependents ?? [])
112
+ .filter((item) => Number(item?.count) > 0)
113
+ .map((item) => `${item.count} ${item.label}`);
114
+ if (!parts.length) return "";
115
+ const listed =
116
+ parts.length === 1 ? parts[0] : `${parts.slice(0, -1).join(", ")} and ${parts.at(-1)}`;
117
+ return `used by ${listed}`;
118
+ }
119
+
120
+ /** The two facts, joined by a MIDDOT. Never a dash (standing rule 2). */
121
+ export function disclosureLine(share: ViewShareAudience | undefined,
122
+ dependents: ViewDependent[]): string {
123
+ return [audienceSentence(share), usageSentence(dependents)].filter(Boolean).join(" · ");
124
+ }
125
+
126
+ /** Token-only rules. No literal hex, no literal font-size, no literal z-index. */
127
+ const S: Record<string, CSSProperties> = {
128
+ backdrop: {
129
+ position: "fixed",
130
+ inset: 0,
131
+ zIndex: "var(--cg-z-record)" as unknown as CSSProperties["zIndex"],
132
+ display: "grid",
133
+ placeItems: "center",
134
+ padding: "24px",
135
+ // (a) the portal paints its own scrim, or it renders transparent.
136
+ background: "color-mix(in srgb, var(--lp-ink) 34%, transparent)",
137
+ },
138
+ panel: {
139
+ width: "min(420px, calc(100vw - 48px))",
140
+ display: "flex",
141
+ flexDirection: "column",
142
+ gap: "12px",
143
+ padding: "20px",
144
+ borderRadius: "var(--lp-r-lg)",
145
+ border: "1px solid color-mix(in srgb, var(--lp-line) 82%, var(--lp-muted))",
146
+ background: "var(--lp-surface)",
147
+ color: "var(--lp-ink)",
148
+ fontFamily: 'Inter, ui-sans-serif, system-ui, -apple-system, "Segoe UI", sans-serif',
149
+ fontSize: "var(--lp-fs-sm)",
150
+ lineHeight: "var(--lp-lh)",
151
+ boxShadow: "0 30px 80px color-mix(in srgb, var(--lp-ink) 22%, transparent)",
152
+ outline: "none",
153
+ },
154
+ head: { display: "flex", alignItems: "center", gap: "10px" },
155
+ mark: { display: "inline-flex", color: "var(--lp-red-deep)" },
156
+ title: { margin: 0, fontSize: "var(--lp-fs-md)", lineHeight: "var(--lp-lh-tight)" },
157
+ facts: { margin: 0, color: "var(--lp-muted)" },
158
+ note: { margin: 0, color: "var(--lp-muted)", fontSize: "var(--lp-fs-2xs)" },
159
+ alert: { margin: 0, color: "var(--lp-red-deep)", fontSize: "var(--lp-fs-2xs)" },
160
+ actions: { display: "flex", justifyContent: "flex-end", gap: "8px", marginTop: "4px" },
161
+ button: {
162
+ // DESIGN.md §4: a button resets native chrome before it is styled.
163
+ appearance: "none",
164
+ border: "1px solid transparent",
165
+ background: "transparent",
166
+ font: "inherit",
167
+ color: "inherit",
168
+ padding: "7px 14px",
169
+ borderRadius: "var(--lp-r-md)",
170
+ cursor: "pointer",
171
+ },
172
+ };
173
+
174
+ const cancelStyle: CSSProperties = {
175
+ ...S.button,
176
+ borderColor: "var(--lp-line)",
177
+ background: "var(--lp-surface)",
178
+ color: "var(--lp-ink)",
179
+ };
180
+
181
+ const confirmStyle: CSSProperties = {
182
+ ...S.button,
183
+ // Red is the destructive hue. Never --lp-primary on a delete confirm.
184
+ borderColor: "color-mix(in srgb, var(--lp-red-deep) 40%, transparent)",
185
+ background: "var(--lp-red-tint)",
186
+ color: "var(--lp-red-deep)",
187
+ };
188
+
189
+ function TrashMark() {
190
+ // NO EMOJIS. Icons are inline SVG (DESIGN.md §4).
191
+ return (
192
+ <svg width="16" height="16" viewBox="0 0 16 16" aria-hidden="true" focusable="false">
193
+ <path
194
+ d="M3 4.5h10M6.5 4.5V3.2h3v1.3M4.6 4.5l.6 8.1h5.6l.6-8.1M6.7 7v3.4M9.3 7v3.4"
195
+ fill="none"
196
+ stroke="currentColor"
197
+ strokeWidth="1.2"
198
+ strokeLinecap="round"
199
+ strokeLinejoin="round"
200
+ />
201
+ </svg>
202
+ );
203
+ }
204
+
205
+ /**
206
+ * R32's pre-delete disclosure: the facts, then the action.
207
+ *
208
+ * ⭐ NEVER OVER-EXPLAIN (DESIGN.md §4). One line of facts, one line of scope when
209
+ * there is something to say, and two buttons. There is no paragraph explaining
210
+ * what deleting means.
211
+ */
212
+ export function ViewDeleteDisclosure({
213
+ viewName,
214
+ dependents,
215
+ share,
216
+ loading = false,
217
+ unanswered = [],
218
+ busy = false,
219
+ error = "",
220
+ onConfirm,
221
+ onCancel,
222
+ }: ViewDeleteDisclosureProps) {
223
+ const panelRef = useRef<HTMLDivElement | null>(null);
224
+ const [confirming, setConfirming] = useState(false);
225
+
226
+ useOverlayLayer({
227
+ panelRef,
228
+ onDismiss: onCancel,
229
+ // ⚠ EXPLICIT: the shared hook defaults `trapFocus` to false, which is right
230
+ // for an anchored menu and wrong for a confirm dialog.
231
+ trapFocus: true,
232
+ initialFocus: "first",
233
+ restoreFocus: true,
234
+ });
235
+
236
+ const confirm = useCallback(() => {
237
+ if (busy || confirming) return;
238
+ setConfirming(true);
239
+ onConfirm();
240
+ }, [busy, confirming, onConfirm]);
241
+
242
+ const facts = disclosureLine(share, dependents);
243
+ const pending = busy || confirming;
244
+
245
+ return (
246
+ <BodyPortal>
247
+ <div style={S.backdrop}>
248
+ <div
249
+ ref={panelRef}
250
+ style={S.panel}
251
+ role="dialog"
252
+ aria-modal="true"
253
+ aria-label={`Delete the view ${viewName}`}
254
+ tabIndex={-1}
255
+ >
256
+ <div style={S.head}>
257
+ <span style={S.mark}>
258
+ <TrashMark />
259
+ </span>
260
+ <h2 style={S.title}>Delete {viewName}?</h2>
261
+ </div>
262
+
263
+ {loading ? (
264
+ <p style={S.facts} role="status" aria-live="polite">
265
+ Checking what depends on this view
266
+ </p>
267
+ ) : facts ? (
268
+ <p style={S.facts}>{facts}</p>
269
+ ) : (
270
+ <p style={S.facts}>Nothing else depends on this view.</p>
271
+ )}
272
+
273
+ {unanswered.length > 0 ? (
274
+ <p style={S.note}>
275
+ {unanswered.join(", ")} could not be checked, so this list may be incomplete.
276
+ </p>
277
+ ) : null}
278
+
279
+ {error ? (
280
+ <p style={S.alert} role="alert">
281
+ {error}
282
+ </p>
283
+ ) : null}
284
+
285
+ <div style={S.actions}>
286
+ <button type="button" style={cancelStyle} onClick={onCancel} disabled={pending}>
287
+ Keep it
288
+ </button>
289
+ <button type="button" style={confirmStyle} onClick={confirm} disabled={pending}>
290
+ {pending ? "Deleting" : "Delete view"}
291
+ </button>
292
+ </div>
293
+ </div>
294
+ </div>
295
+ </BodyPortal>
296
+ );
297
+ }
298
+
299
+ export default ViewDeleteDisclosure;
web/src/customer-grid/CustomerGrid.tsx CHANGED
The diff for this file is too large to render. See raw diff
 
web/src/customer-grid/TimeSeriesPanel.tsx CHANGED
@@ -337,6 +337,46 @@ function readFormulaContract(body: unknown): FormulaContract | null {
337
  };
338
  }
339
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
340
  export default function TimeSeriesPanel({
341
  scope,
342
  pids,
@@ -352,30 +392,30 @@ export default function TimeSeriesPanel({
352
  const database = databaseForScope(scope);
353
  const classed = useMemo(() => classifyFields(fields), [fields]);
354
  type MetricCatalogItem = { key: string; label: string; description?: string; format?: string; source?: string; approved: true };
355
- type SemanticField = { field: string; state?: string; role?: string; sensitivity?: string; valueProfile?: { redacted?: boolean; distinctCount?: number | null; values?: string[]; sample?: string[] } };
356
- const [semanticFields, setSemanticFields] = useState<SemanticField[]>([]);
357
  const [metricCatalog, setMetricCatalog] = useState<MetricCatalogItem[]>([]);
 
 
358
  useEffect(() => {
359
  const controller = new AbortController();
360
- void fetch(`${API_V1}/query/semantics/${encodeURIComponent(database)}`, { credentials: CREDENTIALS, signal: controller.signal })
361
- .then(async (response) => response.ok ? response.json() : { fields: [] })
362
- .then((body) => { if (!controller.signal.aborted) setSemanticFields(Array.isArray(body?.fields) ? body.fields : []); })
363
- .catch(() => undefined);
364
- return () => controller.abort();
365
- }, [database]);
366
- useEffect(() => {
367
- const controller = new AbortController();
368
  void fetch(`${API_V1}/query/metrics?database=${encodeURIComponent(database)}`, { credentials: CREDENTIALS, signal: controller.signal })
369
- .then(async (response) => response.ok ? response.json() : { metrics: [] })
370
- .then((body) => {
371
  if (controller.signal.aborted) return;
372
  const offered = Array.isArray(body?.metrics) ? body.metrics : [];
373
- setMetricCatalog(offered.filter((item: unknown): item is MetricCatalogItem => {
374
  if (!item || typeof item !== "object") return false;
375
  const metric = item as Partial<MetricCatalogItem>;
376
  return metric.approved === true && typeof metric.key === "string" && typeof metric.label === "string";
377
- }));
378
- }).catch(() => { if (!controller.signal.aborted) setMetricCatalog([]); });
 
 
379
  return () => controller.abort();
380
  }, [database]);
381
  // The OFFERED list: everything with a way onto the sheet, server-served first so a real series
@@ -925,7 +965,6 @@ export default function TimeSeriesPanel({
925
  panel rather than to whatever positioned ancestor happens to be above it, and changes
926
  no layout: an absolutely positioned child leaves the flex column entirely. */
927
  <div className="cg-ts" onPointerDown={foldNavOnWorkSurface} style={{ position: "relative" }}>
928
- <details className="cg-semantic-profile"><summary>Metric definitions and value profiles</summary>{semanticFields.map((item) => <div className="cg-semantic-row" key={item.field}><strong>{fields.find((field) => field.key === item.field)?.label ?? item.field}</strong><span>{item.state ?? "draft"} · {item.role ?? "attribute"} · {item.sensitivity ?? "internal"}</span>{item.valueProfile?.redacted ? <span className="cg-redacted">Values redacted</span> : <span>{item.valueProfile?.values?.join(", ") || item.valueProfile?.sample?.join(", ") || `${item.valueProfile?.distinctCount ?? 0} distinct values`}</span>}</div>)}</details>
929
  {formulaContractError && <div className="cg-ts-note" role="alert">{formulaContractError}</div>}
930
  {Object.entries(formulaPreviewErrors).some(([, error]) => error) && <div className="cg-ts-note" role="alert">{Object.entries(formulaPreviewErrors).filter(([, error]) => error).map(([id, error]) => <span key={id}>{error}</span>)}</div>}
931
  {seriesValidationError && <div className="cg-ts-note" role="alert">{seriesValidationError}</div>}
@@ -959,6 +998,15 @@ export default function TimeSeriesPanel({
959
  ))}
960
  </select>
961
  </label>
 
 
 
 
 
 
 
 
 
962
  <label className="cg-ts-ctl">
963
  <span className="cg-ts-ctl-k">Native metric</span>
964
  <select className="cg-select" value="" disabled={!onDisplay} onChange={(event) => {
@@ -972,6 +1020,7 @@ export default function TimeSeriesPanel({
972
  {metricCatalog.filter((metric) => !(display?.tsMetrics ?? []).some((item) => item.key === metric.key)).map((metric) => <option key={metric.key} value={metric.key}>{metric.label}</option>)}
973
  </select>
974
  </label>
 
975
 
976
  {/* Item 18 — four named comparisons where there used to be one unnamed toggle.
977
  "Change vs prior" could not say WHICH prior, and there are four honest answers.
@@ -1416,7 +1465,7 @@ function TsRowBlock({
1416
  className="cg-ts-rowinput"
1417
  value={row.label}
1418
  maxLength={TS_ROW_LABEL_MAX}
1419
- placeholder="Note — type a heading for this section"
1420
  aria-label="Note row label"
1421
  onChange={(e) => onEditRow({ label: e.target.value })}
1422
  />
 
337
  };
338
  }
339
 
340
+ /* ⭐⭐ W49-T22 / CONTRACT C7 — THE EMPTY PICKER SAYS WHY, IN ONE PLAIN SENTENCE.
341
+ *
342
+ * R28: Joel Pal, on Royal Imports, opens an Odoo database, opens Time series, and finds a metric
343
+ * control with nothing in it. The control said "Add native metric" and then offered nothing, which
344
+ * reads as a broken screen rather than as an explanation. There are exactly three causes and the
345
+ * SERVER is the only party that can tell them apart, so `GET /query/metrics` now returns a
346
+ * `reason` beside the list and this map turns it into the sentence.
347
+ *
348
+ * ⛔ THE SENTENCES ARE THE CONTRACT, NOT DECORATION. Each names the CAUSE and the SUBJECT (the
349
+ * PRD's refusal rule), none of them is dressed as an error, none carries an icon, and none
350
+ * contains an em or en dash (CLAUDE.md rule 2 — this copy reaches a screen). Rewording one is a
351
+ * contract change, not a copy edit.
352
+ */
353
+ export type TsMetricEmptyReason = "no_metrics" | "refused" | "no_topic";
354
+
355
+ export const TS_METRIC_EMPTY_COPY: Record<TsMetricEmptyReason, string> = {
356
+ no_metrics: "No metrics are defined for this database yet",
357
+ refused: "Your permissions hide the metrics on this database",
358
+ no_topic: "This database has no time axis to chart",
359
+ };
360
+
361
+ /** The reason for an empty catalogue, or null when it is not yet known.
362
+ *
363
+ * ⛔ `null` IS A REAL ANSWER AND MUST STAY ONE. While the request is in flight, or when it failed
364
+ * for a reason the contract does not name (an abort, a dropped connection), we do NOT know which
365
+ * of the three sentences is true — and printing "No metrics are defined for this database yet"
366
+ * over a network blip would be a false statement about the tenant's model. The picker prints
367
+ * nothing until it knows, which is the only honest fourth state.
368
+ */
369
+ export function tsMetricEmptyReason(status: number, body: unknown): TsMetricEmptyReason | null {
370
+ // The two refusals that never carry a body: the record wall, and a database no topic declares.
371
+ if (status === 403) return "refused";
372
+ if (status === 404) return "no_topic";
373
+ if (status < 200 || status >= 300) return null;
374
+ const reason = (body as { reason?: unknown } | null | undefined)?.reason;
375
+ return typeof reason === "string" && reason in TS_METRIC_EMPTY_COPY
376
+ ? (reason as TsMetricEmptyReason)
377
+ : null;
378
+ }
379
+
380
  export default function TimeSeriesPanel({
381
  scope,
382
  pids,
 
392
  const database = databaseForScope(scope);
393
  const classed = useMemo(() => classifyFields(fields), [fields]);
394
  type MetricCatalogItem = { key: string; label: string; description?: string; format?: string; source?: string; approved: true };
 
 
395
  const [metricCatalog, setMetricCatalog] = useState<MetricCatalogItem[]>([]);
396
+ // C7. `null` until the door answers; see `tsMetricEmptyReason` for why that state has to exist.
397
+ const [metricsReason, setMetricsReason] = useState<TsMetricEmptyReason | null>(null);
398
  useEffect(() => {
399
  const controller = new AbortController();
400
+ setMetricsReason(null);
401
+ // ⛔ THE STATUS CODE IS THE SIGNAL AND IT USED TO BE THROWN AWAY. This read
402
+ // `response.ok ? response.json() : { metrics: [] }`, which collapsed a 403 (the permission
403
+ // wall) and a 404 (no semantic topic) into the same empty list the server sends when a
404
+ // database genuinely has no metric declared. Three different truths, one indistinguishable
405
+ // shape, and the picker could only ever say nothing.
 
 
406
  void fetch(`${API_V1}/query/metrics?database=${encodeURIComponent(database)}`, { credentials: CREDENTIALS, signal: controller.signal })
407
+ .then(async (response) => ({ status: response.status, body: response.ok ? await response.json() : { metrics: [] } }))
408
+ .then(({ status, body }) => {
409
  if (controller.signal.aborted) return;
410
  const offered = Array.isArray(body?.metrics) ? body.metrics : [];
411
+ const admitted = offered.filter((item: unknown): item is MetricCatalogItem => {
412
  if (!item || typeof item !== "object") return false;
413
  const metric = item as Partial<MetricCatalogItem>;
414
  return metric.approved === true && typeof metric.key === "string" && typeof metric.label === "string";
415
+ });
416
+ setMetricCatalog(admitted);
417
+ setMetricsReason(admitted.length ? null : tsMetricEmptyReason(status, body));
418
+ }).catch(() => { if (!controller.signal.aborted) { setMetricCatalog([]); setMetricsReason(null); } });
419
  return () => controller.abort();
420
  }, [database]);
421
  // The OFFERED list: everything with a way onto the sheet, server-served first so a real series
 
965
  panel rather than to whatever positioned ancestor happens to be above it, and changes
966
  no layout: an absolutely positioned child leaves the flex column entirely. */
967
  <div className="cg-ts" onPointerDown={foldNavOnWorkSurface} style={{ position: "relative" }}>
 
968
  {formulaContractError && <div className="cg-ts-note" role="alert">{formulaContractError}</div>}
969
  {Object.entries(formulaPreviewErrors).some(([, error]) => error) && <div className="cg-ts-note" role="alert">{Object.entries(formulaPreviewErrors).filter(([, error]) => error).map(([id, error]) => <span key={id}>{error}</span>)}</div>}
970
  {seriesValidationError && <div className="cg-ts-note" role="alert">{seriesValidationError}</div>}
 
998
  ))}
999
  </select>
1000
  </label>
1001
+ {/* C7 / R28. An empty catalogue is an EXPLANATION, not a failure: muted ink, no icon,
1002
+ no alert role, and the control it replaces rather than a banner over the panel. The
1003
+ select is not merely disabled, because a disabled dropdown still promises a list. */}
1004
+ {metricCatalog.length === 0 && metricsReason ? (
1005
+ <div className="cg-ts-ctl">
1006
+ <span className="cg-ts-ctl-k">Native metric</span>
1007
+ <span className="cg-ts-note">{TS_METRIC_EMPTY_COPY[metricsReason]}</span>
1008
+ </div>
1009
+ ) : (
1010
  <label className="cg-ts-ctl">
1011
  <span className="cg-ts-ctl-k">Native metric</span>
1012
  <select className="cg-select" value="" disabled={!onDisplay} onChange={(event) => {
 
1020
  {metricCatalog.filter((metric) => !(display?.tsMetrics ?? []).some((item) => item.key === metric.key)).map((metric) => <option key={metric.key} value={metric.key}>{metric.label}</option>)}
1021
  </select>
1022
  </label>
1023
+ )}
1024
 
1025
  {/* Item 18 — four named comparisons where there used to be one unnamed toggle.
1026
  "Change vs prior" could not say WHICH prior, and there are four honest answers.
 
1465
  className="cg-ts-rowinput"
1466
  value={row.label}
1467
  maxLength={TS_ROW_LABEL_MAX}
1468
+ placeholder="Note: type a heading for this section"
1469
  aria-label="Note row label"
1470
  onChange={(e) => onEditRow({ label: e.target.value })}
1471
  />
web/src/customer-grid/viewModes.tsx CHANGED
@@ -529,6 +529,18 @@ export function MapSettings({
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,24 +554,54 @@ export function MapSettings({
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
- )}
548
- {sizeChoices.length > 0 && (
549
- <FieldSelectButton
550
- className="cg-mode-field"
551
- ariaLabel="Size pins by"
552
- placeholder="Size: none"
553
- value={sizeField?.key ?? ""}
554
- onChange={onPickSizeField}
555
- fields={[
556
- { key: "", label: "No size", type: undefined },
557
- ...sizeChoices.map((f) => ({
558
- key: f.key, label: `Size: ${f.label}`, type: f.type,
559
- })),
560
- ]}
561
- />
562
- )}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
563
  </div>
564
  );
565
  }
 
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
+ /**
533
+ * ⭐ W49-T20 / CONTRACT C8 — THE ANSWER IS BAKED INTO THE TRIGGER, NOT STOOD BESIDE IT.
534
+ * `Filter` / `Sort` / `Group` all read "<name> · <current answer>", so the control says what it
535
+ * is doing without a second chip. W47-T05's sibling icon mark existed only because
536
+ * `FieldSelectButton` had no trigger-level icon slot. `Popover` has one, so that
537
+ * sibling mark span and its three rules in `styles/wave46/map-panels.css` are deleted rather
538
+ * than restyled. Its class name is deliberately not repeated here: W49-T20's done-when is that
539
+ * this component no longer contains it, and `verify_map.py` reads this block as text.
540
+ * ⚠ `sizeField.label` DIRECTLY, never a `sizeChoices.find(...)` lookup: a key that has left
541
+ * the choice list would then render a placeholder in place of the column the map is still using.
542
+ */
543
+ const sizeLabel = sizeField ? `Bubble size · ${sizeField.label}` : "Bubble size";
544
  return (
545
  <div className="cg-map-settings" aria-label="Map settings">
546
  <button
 
554
  <IconRouteZone />
555
  <span>Routes{selectedCount >= 2 ? ` / ${selectedCount} selected` : ""}</span>
556
  </button>
557
+ {/* ⛔ RENDERED UNCONDITIONALLY, like Filter / Sort / Group. The old pair hid itself when the
558
+ table had no numeric column, which left the row reading "Routes" and nothing else and gave
559
+ the person no way to learn WHY the map cannot size its bubbles. The empty panel says it.
560
+ ⚠ `tone="sort"` is the ticket's and C8's explicit instruction. It sits against
561
+ `Popover.tsx`'s own argument that a hue is for controls changing what the table SAYS, and
562
+ bubble size changes how the map LOOKS — recorded here so the next reader knows the
563
+ mismatch was chosen, not missed.
564
+ ⚠ `name="cg-bubble-size"`, not `cg-color`: radio grouping is document-global and the
565
+ toolbar's Color popover is mounted on this same screen. */}
566
+ <Popover label={sizeLabel} icon={<IconSizeBy />} active={!!sizeField} tone="sort">
567
+ {(close) => (
568
+ <div className="cg-pop-body">
569
+ <div className="cg-pop-title">Size bubbles by</div>
570
+ <label className="cg-radio-row">
571
+ <input
572
+ type="radio"
573
+ name="cg-bubble-size"
574
+ checked={!sizeField}
575
+ onChange={() => {
576
+ onPickSizeField("");
577
+ close();
578
+ }}
579
+ />
580
+ <span>None</span>
581
+ </label>
582
+ {sizeChoices.map((f) => (
583
+ <label key={f.key} className="cg-radio-row">
584
+ <input
585
+ type="radio"
586
+ name="cg-bubble-size"
587
+ checked={sizeField?.key === f.key}
588
+ onChange={() => {
589
+ onPickSizeField(f.key);
590
+ close();
591
+ }}
592
+ />
593
+ <FieldTypeIcon type={f.type} size={11} />
594
+ <span>{f.label}</span>
595
+ </label>
596
+ ))}
597
+ {sizeChoices.length === 0 && (
598
+ <div className="cg-pop-note">
599
+ This table has no number column to size bubbles by.
600
+ </div>
601
+ )}
602
+ </div>
603
+ )}
604
+ </Popover>
605
  </div>
606
  );
607
  }
web/src/settings/SettingsModal.tsx CHANGED
@@ -56,6 +56,17 @@ import {
56
  testKeychainEntry,
57
  } from "./settingsApi";
58
  import type { ConnectorRow, KeyEntry, UnsyncedInfo } from "./settingsApi";
 
 
 
 
 
 
 
 
 
 
 
59
  import { PermsEditor } from "./PermsEditor";
60
  // Wave 19 contract C2 — session D's self-contained plane; see the mount below.
61
  import { AdminPane } from "./AdminPane";
@@ -974,20 +985,24 @@ export function SettingsModal({
974
  // ── Wave 18 (C7): the Keychain pane ─────────────────────────────────────────────────────────
975
  // Secrets go IN and never come back out: rows carry a masked preview, the add form clears on
976
  // success, and there is no reveal affordance by design (the server has no route for one).
977
- /**
978
- * ⭐⭐ WAVE 32 · R4 / contract C1 — WHO A CONNECTION IS FOR, in the two words the ruling uses.
979
- *
980
- * ⛔ THE VOCABULARY IS THE SERVER'S. `routes_keychain.SCOPES` declares it and `verify_meta`
981
- * asserts these two literals appear on both sides, so the label map is a PRESENTATION of a
982
- * server word and never a client-side union — a `type Scope = …` here would turn "the server
983
- * added a scope" into "the client drops the row" (the wave-9 law).
984
  */
985
- const SCOPE_LABEL: Record<string, string> = {
986
- business: "Business-wide",
987
- personal: "Personal",
 
 
 
 
 
 
988
  };
989
- const scopeLabel = (s: string | undefined): string =>
990
- SCOPE_LABEL[String(s || "business")] || String(s);
991
 
992
  function KeychainPane() {
993
  const [entries, setEntries] = useState<KeyEntry[]>([]);
@@ -998,14 +1013,24 @@ function KeychainPane() {
998
  * the account record — the server is the wall and the client renders what it will honour. */
999
  const [canBusiness, setCanBusiness] = useState(false);
1000
  const [tenantWide, setTenantWide] = useState<string[]>([]);
 
 
 
 
 
 
 
1001
  const [form, setForm] = useState<{
1002
- type: "odoo" | "generic";
1003
  label: string;
1004
  scope: string;
1005
  fields: Record<string, string>;
1006
  busy: boolean;
1007
  } | null>(null);
1008
  const [testResult, setTestResult] = useState<Record<string, string>>({});
 
 
 
 
1009
 
1010
  const reload = useCallback(async () => {
1011
  const r = await listKeychain();
@@ -1024,18 +1049,53 @@ function KeychainPane() {
1024
  void reload();
1025
  }, [reload]);
1026
 
1027
- /** The scope a NEW key of this type may take. `odoo` and `meta_ads` are what the whole
1028
- * workspace's databases are read through, so the server refuses to make them personal — the
1029
- * picker says so here instead of letting the save fail. */
 
1030
  const forcedBusiness = (t: string) => tenantWide.includes(t);
1031
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1032
  const submit = async () => {
1033
  if (!form || form.busy) return;
1034
  setForm({ ...form, busy: true });
1035
  const fields = Object.fromEntries(
1036
  Object.entries(form.fields).filter(([, v]) => v.trim() !== "")
1037
  );
1038
- const r = await addKeychainEntry(form.label, form.type, fields, form.scope);
1039
  if (r.ok) {
1040
  setForm(null);
1041
  void reload();
@@ -1045,12 +1105,17 @@ function KeychainPane() {
1045
  }
1046
  };
1047
 
1048
- const odooFields: Array<[string, string]> = [
1049
- ["url", "Server URL (https://...)"],
1050
- ["db", "Database"],
1051
- ["user", "API user"],
1052
- ["api_key", "API key"],
1053
- ];
 
 
 
 
 
1054
 
1055
  return (
1056
  <div className="set-pane">
@@ -1066,13 +1131,48 @@ function KeychainPane() {
1066
  </p>
1067
  ) : null}
1068
  {err ? <p className="set-error">{err}</p> : null}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1069
  {!loaded ? (
1070
  <p className="set-help">Loading…</p>
1071
  ) : entries.length === 0 ? (
1072
  <p className="set-help">No keys stored yet.</p>
 
 
 
 
 
1073
  ) : (
1074
  <div className="set-card">
1075
- {entries.map((e) => (
1076
  <div key={e.id} className="set-kv-row kc-row">
1077
  <div className="kc-main">
1078
  <strong>{e.label}</strong>
@@ -1143,39 +1243,20 @@ function KeychainPane() {
1143
  )}
1144
  {form ? (
1145
  <div className="set-card kc-form">
1146
- <div className="set-field">
1147
- <label>Type</label>
1148
- <select
1149
- value={form.type}
1150
- onChange={(e) => {
1151
- const type = e.target.value as "odoo" | "generic";
1152
- setForm({
1153
- ...form,
1154
- type,
1155
- fields: {},
1156
- // A tenant-wide type has exactly one legal scope; snapping the picker is the
1157
- // honest move, because the alternative is a save that 400s on a choice the
1158
- // form offered.
1159
- scope: forcedBusiness(type) ? "business" : form.scope,
1160
- });
1161
- }}
1162
- >
1163
- <option value="odoo">Odoo</option>
1164
- <option value="generic">Generic secret</option>
1165
- </select>
1166
- </div>
1167
  {/* ⭐⭐ WAVE 32 · R4 — WHO IS THIS CONNECTION FOR. Two options, no more: the ruling says
1168
  there is a business-wide kind and a personal kind, and business-wide is an
1169
  administrator's to give. A member sees the sentence instead of a disabled radio,
1170
  because a control you cannot use is worse than a line telling you why. */}
1171
  <div className="set-field">
1172
  <label>Who can use it</label>
1173
- {forcedBusiness(form.type) ? (
1174
- <p className="set-help">
1175
- Business-wide. This workspace's databases are read through an {form.type}{" "}
1176
- connection, so it applies to everyone here and cannot be personal.
1177
- </p>
1178
- ) : canBusiness ? (
1179
  <select
1180
  value={form.scope}
1181
  onChange={(e) => setForm({ ...form, scope: e.target.value })}
@@ -1195,22 +1276,19 @@ function KeychainPane() {
1195
  <input
1196
  value={form.label}
1197
  maxLength={80}
1198
- placeholder={form.type === "odoo" ? "Production Odoo" : "e.g. Shipping API"}
1199
  onChange={(e) => setForm({ ...form, label: e.target.value })}
1200
  />
1201
  </div>
1202
- {(form.type === "odoo"
1203
- ? odooFields
1204
- : ([
1205
- ["name", "Name"],
1206
- ["value", "Secret value"],
1207
- ] as Array<[string, string]>)
1208
- ).map(([k, label]) => (
1209
  <div className="set-field" key={k}>
1210
  <label>{label}</label>
1211
  <input
1212
  value={form.fields[k] ?? ""}
1213
- type={k === "api_key" || k === "value" ? "password" : "text"}
1214
  onChange={(e) =>
1215
  setForm({ ...form, fields: { ...form.fields, [k]: e.target.value } })
1216
  }
@@ -1238,7 +1316,6 @@ function KeychainPane() {
1238
  disabled={locked}
1239
  onClick={() =>
1240
  setForm({
1241
- type: "odoo",
1242
  label: "",
1243
  // ⚠ The default is the SAFE one for the account opening the form: a member can only
1244
  // create a personal connection, so starting on `business` would put a value in the
@@ -1252,6 +1329,22 @@ function KeychainPane() {
1252
  Add a key
1253
  </button>
1254
  )}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1255
  </div>
1256
  );
1257
  }
 
56
  testKeychainEntry,
57
  } from "./settingsApi";
58
  import type { ConnectorRow, KeyEntry, UnsyncedInfo } from "./settingsApi";
59
+ // ⭐⭐ W49-T13 / R26 — ONE DOOR. The Keychains pane links INTO the connector modal instead of
60
+ // editing a connector's credential itself, so this room imports that one.
61
+ // ⚠ THE NAME COLLIDES ON PURPOSE-FREE GROUNDS: `settingsApi.ConnectorRow` is the
62
+ // `/admin/connectors` row (a credential with a status column) and the directory's row is a CARD.
63
+ // Two different payloads that happen to share a word, so the second is aliased rather than one of
64
+ // them renamed under another ticket's file.
65
+ import { API_V1, CREDENTIALS } from "../apiContract";
66
+ import ConnectorModal from "../connectors/ConnectorModal";
67
+ import { scopeLabel } from "../connectors/KeychainTab";
68
+ import { parseDirectory } from "../connectors/ConnectorsPage";
69
+ import type { ConnectorRow as DirectoryRow } from "../connectors/ConnectorsPage";
70
  import { PermsEditor } from "./PermsEditor";
71
  // Wave 19 contract C2 — session D's self-contained plane; see the mount below.
72
  import { AdminPane } from "./AdminPane";
 
985
  // ── Wave 18 (C7): the Keychain pane ─────────────────────────────────────────────────────────
986
  // Secrets go IN and never come back out: rows carry a masked preview, the add form clears on
987
  // success, and there is no reveal affordance by design (the server has no route for one).
988
+ /*
989
+ * ⛔⛔ `SCOPE_LABEL` AND ITS `scopeLabel` READER STOOD HERE AND ARE IMPORTED NOW, from
990
+ * `connectors/KeychainTab.tsx`. The vocabulary is still the server's (`routes_keychain.SCOPES`,
991
+ * asserted on both sides by `verify_meta`'s C1 parity leg) — what changes is that ONE file
992
+ * presents it, because R26 moves credential editing into the connector modal and a second label
993
+ * map beside a pane that no longer edits keys is [[one-question-two-normalizers]] waiting to
994
+ * drift. The direction is pane -> tab and not the reverse, or the import would be a cycle.
995
  */
996
+
997
+ /** A stored key, plus the connector card that owns its door (R26). The extra key is served by
998
+ * `routes_keychain.list_keychain` and read here rather than added to `KeyEntry`, whose file
999
+ * belongs to no ticket this wave. */
1000
+ type OwnedKeyEntry = KeyEntry & { connector?: { key: string; label: string } };
1001
+
1002
+ const keyConnector = (e: KeyEntry): { key: string; label: string } | null => {
1003
+ const owner = (e as OwnedKeyEntry).connector;
1004
+ return owner && owner.key ? owner : null;
1005
  };
 
 
1006
 
1007
  function KeychainPane() {
1008
  const [entries, setEntries] = useState<KeyEntry[]>([]);
 
1013
  * the account record — the server is the wall and the client renders what it will honour. */
1014
  const [canBusiness, setCanBusiness] = useState(false);
1015
  const [tenantWide, setTenantWide] = useState<string[]>([]);
1016
+ /**
1017
+ * ⛔⛔ THE TYPE PICKER IS GONE AND THE FORM IS `generic` ONLY (R26, one door). Every other
1018
+ * credential type stands behind a connector card, and the card's Keychain tab is now the place
1019
+ * it is stored — with the connector's own fields, its own scope rule and, for Odoo, the freeze
1020
+ * and reconnect semantics a bare key form has never carried. A `generic` secret has no card, so
1021
+ * this pane keeps it rather than stranding it.
1022
+ */
1023
  const [form, setForm] = useState<{
 
1024
  label: string;
1025
  scope: string;
1026
  fields: Record<string, string>;
1027
  busy: boolean;
1028
  } | null>(null);
1029
  const [testResult, setTestResult] = useState<Record<string, string>>({});
1030
+ /** Which connector card the reader asked to open, and the directory row it needs. */
1031
+ const [openKey, setOpenKey] = useState("");
1032
+ const [directory, setDirectory] = useState<DirectoryRow[]>([]);
1033
+ const [linkNote, setLinkNote] = useState("");
1034
 
1035
  const reload = useCallback(async () => {
1036
  const r = await listKeychain();
 
1049
  void reload();
1050
  }, [reload]);
1051
 
1052
+ /** The scope a key of this type may take. `odoo` and `meta_ads` are what the whole workspace's
1053
+ * databases are read through, so the server refuses to make them personal.
1054
+ * ⚠ STILL READ FOR THE LIST even though the form is `generic` only: a stored tenant-wide key
1055
+ * must not be offered a scope toggle this room cannot honour. */
1056
  const forcedBusiness = (t: string) => tenantWide.includes(t);
1057
 
1058
+ /**
1059
+ * ⭐⭐ R26's LINK. It reads the connector DIRECTORY, because the modal is opened over a CARD
1060
+ * and the card is what carries the label, the state and the graph it will paint.
1061
+ *
1062
+ * ⛔ `parseDirectory` IS IMPORTED, NOT RE-IMPLEMENTED. A second reader of that payload here
1063
+ * would drop a row on a different rule than the page does, which is how one connector comes to
1064
+ * exist in one room and not the other.
1065
+ * ⚠ A CONNECTOR THE DIRECTORY DOES NOT LIST IS REPORTED, never opened blank: the entry is real
1066
+ * and its card is not, and that is a fact worth one sentence rather than an empty modal.
1067
+ */
1068
+ const openConnector = useCallback(async (key: string) => {
1069
+ setLinkNote("");
1070
+ if (directory.some((r) => r.key === key)) {
1071
+ setOpenKey(key);
1072
+ return;
1073
+ }
1074
+ let body: unknown = null;
1075
+ try {
1076
+ const res = await fetch(`${API_V1}/connectors/directory`, { credentials: CREDENTIALS });
1077
+ if (!res.ok) {
1078
+ setLinkNote(`The connector list could not be read (the server answered ${res.status}).`);
1079
+ return;
1080
+ }
1081
+ body = await res.json();
1082
+ } catch {
1083
+ setLinkNote("Cannot reach the server.");
1084
+ return;
1085
+ }
1086
+ const rows = parseDirectory(body);
1087
+ setDirectory(rows);
1088
+ if (rows.some((row) => row.key === key)) setOpenKey(key);
1089
+ else setLinkNote("This workspace's connector list does not carry that connector right now.");
1090
+ }, [directory]);
1091
+
1092
  const submit = async () => {
1093
  if (!form || form.busy) return;
1094
  setForm({ ...form, busy: true });
1095
  const fields = Object.fromEntries(
1096
  Object.entries(form.fields).filter(([, v]) => v.trim() !== "")
1097
  );
1098
+ const r = await addKeychainEntry(form.label, "generic", fields, form.scope);
1099
  if (r.ok) {
1100
  setForm(null);
1101
  void reload();
 
1105
  }
1106
  };
1107
 
1108
+ /* ⛔ THE FOUR ODOO FIELDS STOOD HERE AND MOVED SERVER-SIDE (R26). They are declared once, in
1109
+ `routes_connectors._CONNECT_FIELDS`, and served on C4's `keychain.connect` half — so the
1110
+ connector that grows a credential field does not need a client edit before it can be stored. */
1111
+
1112
+ // ⚠ SPLIT BY WHAT THE SERVER SAID, not by a client-side type list. `list_keychain` stamps each
1113
+ // entry with the connector that owns its door, so a connector added later hands its keys over
1114
+ // with no edit here — and a type this build has never heard of stays editable rather than
1115
+ // vanishing into a room it cannot open.
1116
+ const linked = entries.filter((e) => keyConnector(e) !== null);
1117
+ const own = entries.filter((e) => keyConnector(e) === null);
1118
+ const openRow = directory.find((r) => r.key === openKey) || null;
1119
 
1120
  return (
1121
  <div className="set-pane">
 
1131
  </p>
1132
  ) : null}
1133
  {err ? <p className="set-error">{err}</p> : null}
1134
+ {linkNote ? <p className="set-error">{linkNote}</p> : null}
1135
+ {/* ⭐⭐ R26 · ONE DOOR — THE HAND-OFF, AND IT IS THE WHOLE OF THIS TICKET'S SETTINGS HALF.
1136
+ A key that stands behind a connector card is edited in that card's Keychain tab, where
1137
+ the credential's own fields, its scope rule and (for Odoo) its freeze and reconnect
1138
+ semantics live. This room keeps the LIST so nothing disappears, and offers the door
1139
+ rather than a second set of controls for the same secret. */}
1140
+ {linked.length ? (
1141
+ <div className="set-card">
1142
+ {linked.map((e) => (
1143
+ <div key={e.id} className="set-kv-row kc-row">
1144
+ <div className="kc-main">
1145
+ <strong>{e.label}</strong>
1146
+ <span className="kc-meta">
1147
+ {e.type}
1148
+ {e.preview ? " · " + e.preview : ""} · {scopeLabel(e.scope)}
1149
+ </span>
1150
+ </div>
1151
+ <div className="kc-actions">
1152
+ <button
1153
+ type="button"
1154
+ className="conn-kc-link"
1155
+ onClick={() => void openConnector(keyConnector(e)?.key || "")}
1156
+ >
1157
+ {"Open the " + (keyConnector(e)?.label || e.type) + " connector"}
1158
+ </button>
1159
+ </div>
1160
+ </div>
1161
+ ))}
1162
+ </div>
1163
+ ) : null}
1164
  {!loaded ? (
1165
  <p className="set-help">Loading…</p>
1166
  ) : entries.length === 0 ? (
1167
  <p className="set-help">No keys stored yet.</p>
1168
+ ) : own.length === 0 ? (
1169
+ // One line, and it names where the rest went rather than reading as an empty room.
1170
+ <p className="set-help">
1171
+ Every stored key belongs to a connector, and each one is managed from its own card.
1172
+ </p>
1173
  ) : (
1174
  <div className="set-card">
1175
+ {own.map((e) => (
1176
  <div key={e.id} className="set-kv-row kc-row">
1177
  <div className="kc-main">
1178
  <strong>{e.label}</strong>
 
1243
  )}
1244
  {form ? (
1245
  <div className="set-card kc-form">
1246
+ {/* ⛔ NO TYPE PICKER. R26 gives every connector-backed credential its own door, so the
1247
+ only kind this room still creates is the one with no connector behind it. A select
1248
+ with one option is a control that decides nothing. */}
1249
+ <p className="set-help">
1250
+ A secret with no connector behind it, for a step that needs one. A connector's own key
1251
+ is added from that connector's card.
1252
+ </p>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1253
  {/* ⭐⭐ WAVE 32 · R4 — WHO IS THIS CONNECTION FOR. Two options, no more: the ruling says
1254
  there is a business-wide kind and a personal kind, and business-wide is an
1255
  administrator's to give. A member sees the sentence instead of a disabled radio,
1256
  because a control you cannot use is worse than a line telling you why. */}
1257
  <div className="set-field">
1258
  <label>Who can use it</label>
1259
+ {canBusiness ? (
 
 
 
 
 
1260
  <select
1261
  value={form.scope}
1262
  onChange={(e) => setForm({ ...form, scope: e.target.value })}
 
1276
  <input
1277
  value={form.label}
1278
  maxLength={80}
1279
+ placeholder="e.g. Shipping API"
1280
  onChange={(e) => setForm({ ...form, label: e.target.value })}
1281
  />
1282
  </div>
1283
+ {([
1284
+ ["name", "Name"],
1285
+ ["value", "Secret value"],
1286
+ ] as Array<[string, string]>).map(([k, label]) => (
 
 
 
1287
  <div className="set-field" key={k}>
1288
  <label>{label}</label>
1289
  <input
1290
  value={form.fields[k] ?? ""}
1291
+ type={k === "value" ? "password" : "text"}
1292
  onChange={(e) =>
1293
  setForm({ ...form, fields: { ...form.fields, [k]: e.target.value } })
1294
  }
 
1316
  disabled={locked}
1317
  onClick={() =>
1318
  setForm({
 
1319
  label: "",
1320
  // ⚠ The default is the SAFE one for the account opening the form: a member can only
1321
  // create a personal connection, so starting on `business` would put a value in the
 
1329
  Add a key
1330
  </button>
1331
  )}
1332
+ {/* ⚠ IT SITS ABOVE THIS ROOM RATHER THAN INSIDE IT. `.conn-modal-backdrop` is on the
1333
+ `--cg-z-record` step (100) and `.set-backdrop` is on `--cg-z-drawer` (70), so the
1334
+ connector modal paints over the settings modal that opened it and no z-order changes —
1335
+ which is the whole reason this link could be a modal at all. */}
1336
+ {openRow ? (
1337
+ <ConnectorModal
1338
+ row={openRow}
1339
+ initialTab="keychain"
1340
+ onClose={() => {
1341
+ setOpenKey("");
1342
+ // The tab writes, so the list behind it is re-read rather than left as it was before
1343
+ // the key was added or removed.
1344
+ void reload();
1345
+ }}
1346
+ />
1347
+ ) : null}
1348
  </div>
1349
  );
1350
  }
web/src/sheet/BindingEditor.tsx ADDED
@@ -0,0 +1,208 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // sheet/BindingEditor.tsx — what a bound cell points at (wave 49, W49-T06, R4/R8/R14).
2
+ //
3
+ // ⭐⭐ R4 SAYS "THE FILTER USES THE EXACT SAME UI AS A VIEW'S FILTER", SO THIS MOUNTS
4
+ // `filter-kit/FilterBuilderPanel` ITSELF. That component turned out to need NO change to run here:
5
+ // its only required props are `fields`, `filters` and `onChange`, and its own docstrings already
6
+ // anticipate "a panel over a module whose rows it has never loaded" - which is exactly a Sheet
7
+ // cell. The ticket allowed adding an optional prop if one were needed; none was.
8
+ //
9
+ // ⛔ THE FILTER TREE SAVED HERE IS BYTE-COMPATIBLE WITH A VIEW'S. `FilterBuilderPanel` emits a
10
+ // `FilterTree` (`{conj, nodes}`) and that value is stored verbatim on the binding. Inventing a
11
+ // second shape here is the failure C2 names: the server compiles a view's filter and a cell's
12
+ // filter through the same `compile_filter_tree`, so two shapes would mean two dialects and one of
13
+ // them would eventually stop being tested.
14
+ //
15
+ // ⚠ DESIGN CONTRACT: sentence case, quiet buttons, token-only colour and type, motion 150 ms
16
+ // ease-out on opacity and transform, no emoji, and no em dash or en dash in any string on screen.
17
+
18
+ import { useEffect, useMemo, useState } from "react";
19
+ import { fetchWorkspace } from "../customer-grid/apiBridge";
20
+ import type { SurfaceScope } from "../customer-grid/apiBridge";
21
+ import type { Field, FilterTree } from "../customer-grid/types";
22
+ import { FilterBuilderPanel } from "../filter-kit";
23
+ import { isNumericType } from "../filter-kit/ops";
24
+ import { previewCell } from "./sheetApi";
25
+
26
+ const AGGREGATES = [
27
+ { fn: "sum", label: "Sum" },
28
+ { fn: "count", label: "Count" },
29
+ { fn: "avg", label: "Average" },
30
+ { fn: "min", label: "Minimum" },
31
+ { fn: "max", label: "Maximum" },
32
+ ] as const;
33
+
34
+ /** A Sheet names a DATABASE KEY; the workspace door speaks `SurfaceScope`. Same pair as DrillModal. */
35
+ const scopeOf = (database: string): SurfaceScope | null => {
36
+ if (database === "customer_data") return "customer";
37
+ if (database === "product_data") return "product";
38
+ return database.startsWith("ut_") ? (database as SurfaceScope) : null;
39
+ };
40
+
41
+ export interface BindingEditorProps {
42
+ workbookId: string;
43
+ addr: string;
44
+ /** Every database this reader may open (R8). The page supplies it; this panel invents nothing. */
45
+ databases: { key: string; label: string }[];
46
+ initial?: Record<string, unknown> | null;
47
+ onSave: (binding: Record<string, unknown>) => void;
48
+ onCancel: () => void;
49
+ }
50
+
51
+ export default function BindingEditor({
52
+ workbookId, addr, databases, initial, onSave, onCancel,
53
+ }: BindingEditorProps) {
54
+ const [database, setDatabase] = useState<string>(
55
+ String((initial?.database as string) ?? databases[0]?.key ?? ""),
56
+ );
57
+ const [fn, setFn] = useState<string>("sum");
58
+ const [field, setField] = useState<string>("");
59
+ const [scopeKind, setScopeKind] = useState<"view" | "filter">("view");
60
+ const [viewId, setViewId] = useState<string>("");
61
+ const [tree, setTree] = useState<FilterTree>({ conj: "and", nodes: [] });
62
+ const [periodRef, setPeriodRef] = useState<string>("");
63
+ const [fields, setFields] = useState<Field[]>([]);
64
+ const [views, setViews] = useState<{ id: string; name: string }[]>([]);
65
+ const [preview, setPreview] = useState<string>("");
66
+ const [notice, setNotice] = useState<string>("");
67
+
68
+ // The field and view lists come from the SAME door the grid uses, so a cell can never offer a
69
+ // column the grid does not have.
70
+ useEffect(() => {
71
+ let live = true;
72
+ const scope = scopeOf(database);
73
+ if (!scope) {
74
+ setFields([]);
75
+ setViews([]);
76
+ return () => { live = false; };
77
+ }
78
+ (async () => {
79
+ const ws = await fetchWorkspace(scope, { allowCached: true });
80
+ if (!live || !ws) return;
81
+ setFields((ws.fields ?? []) as Field[]);
82
+ setViews(((ws.views ?? []) as { id: string; name: string }[])
83
+ .map((v) => ({ id: v.id, name: v.name })));
84
+ })();
85
+ return () => { live = false; };
86
+ }, [database]);
87
+
88
+ // ⭐ THE PROJECT'S OWN PREDICATE, NOT A HAND-WRITTEN TYPE LIST. `isNumericType` is what the
89
+ // filter kit already uses to decide numeric behaviour, so the columns this editor offers to SUM
90
+ // are exactly the ones the filter engine treats as numbers. A local list would drift, and it was
91
+ // wrong on its first attempt: the numeric family is `int` / `currency` / `pct`, and there is no
92
+ // `"number"` in `FieldType` at all - tsc caught that before it could ship as an empty picker.
93
+ const numericFields = useMemo(
94
+ () => fields.filter((f) => isNumericType(f.type)),
95
+ [fields],
96
+ );
97
+
98
+ const binding = useMemo(() => {
99
+ const agg: Record<string, unknown> = fn === "count" ? { fn } : { fn, field };
100
+ const scope: Record<string, unknown> = scopeKind === "view"
101
+ ? { view_id: viewId, view_name: views.find((v) => v.id === viewId)?.name ?? "" }
102
+ : { filter: tree };
103
+ const out: Record<string, unknown> = { database, aggregate: agg, scope };
104
+ // R14: a period SOURCE is a `$`-anchored cell reference. The A1 resolver reads it BEFORE the
105
+ // query is built, so it is an INPUT to the filter and never a post-filter.
106
+ if (periodRef.trim()) out.period = { ref: periodRef.trim() };
107
+ return out;
108
+ }, [database, fn, field, scopeKind, viewId, views, tree, periodRef]);
109
+
110
+ // ⭐ THE NUMBER APPEARS BEFORE SAVING. `preview` evaluates the binding without persisting it,
111
+ // which is what lets someone see whether they picked the right thing while they can still change
112
+ // their mind - and it is the same door the cell will use, so the number cannot differ.
113
+ const runPreview = async () => {
114
+ setNotice("");
115
+ setPreview("");
116
+ const got = await previewCell(workbookId, addr, binding);
117
+ if (!got.ok) {
118
+ setNotice(got.message);
119
+ return;
120
+ }
121
+ setPreview(got.value.display || String(got.value.value ?? ""));
122
+ };
123
+
124
+ const ready = Boolean(database) && (fn === "count" || Boolean(field))
125
+ && (scopeKind === "filter" || Boolean(viewId));
126
+
127
+ return (
128
+ <section className="sheet-binding" aria-label={`What ${addr} points at`}>
129
+ <h2 className="sheet-binding-title">{`What ${addr} points at`}</h2>
130
+
131
+ <label className="sheet-field">
132
+ <span>Database</span>
133
+ <select value={database} onChange={(e) => setDatabase(e.target.value)}>
134
+ {databases.map((d) => <option key={d.key} value={d.key}>{d.label}</option>)}
135
+ </select>
136
+ </label>
137
+
138
+ <div className="sheet-field-row">
139
+ <label className="sheet-field">
140
+ <span>Aggregate</span>
141
+ <select value={fn} onChange={(e) => setFn(e.target.value)}>
142
+ {AGGREGATES.map((a) => <option key={a.fn} value={a.fn}>{a.label}</option>)}
143
+ </select>
144
+ </label>
145
+ {/* Count takes no column, and offering one would suggest count(column), which skips
146
+ blanks and answers a smaller number than the person meant. */}
147
+ {fn !== "count" && (
148
+ <label className="sheet-field">
149
+ <span>Column</span>
150
+ <select value={field} onChange={(e) => setField(e.target.value)}>
151
+ <option value="">Choose a column</option>
152
+ {numericFields.map((f) => <option key={f.key} value={f.key}>{f.label}</option>)}
153
+ </select>
154
+ </label>
155
+ )}
156
+ </div>
157
+
158
+ <fieldset className="sheet-scope">
159
+ <legend>Rows to include</legend>
160
+ <label className="sheet-radio">
161
+ <input type="radio" checked={scopeKind === "view"}
162
+ onChange={() => setScopeKind("view")} />
163
+ <span>A saved view</span>
164
+ </label>
165
+ {scopeKind === "view" && (
166
+ <select value={viewId} onChange={(e) => setViewId(e.target.value)}>
167
+ <option value="">Choose a view</option>
168
+ {views.map((v) => <option key={v.id} value={v.id}>{v.name}</option>)}
169
+ </select>
170
+ )}
171
+ <label className="sheet-radio">
172
+ <input type="radio" checked={scopeKind === "filter"}
173
+ onChange={() => setScopeKind("filter")} />
174
+ <span>A filter I build here</span>
175
+ </label>
176
+ {scopeKind === "filter" && (
177
+ <FilterBuilderPanel fields={fields} filters={tree} onChange={setTree} />
178
+ )}
179
+ </fieldset>
180
+
181
+ <label className="sheet-field">
182
+ <span>Period from a cell</span>
183
+ <input
184
+ type="text"
185
+ value={periodRef}
186
+ onChange={(e) => setPeriodRef(e.target.value)}
187
+ placeholder="$B$1"
188
+ />
189
+ </label>
190
+
191
+ {preview && <p className="sheet-preview">{`This cell would show ${preview}`}</p>}
192
+ {notice && <p className="sheet-notice" role="alert">{notice}</p>}
193
+
194
+ <div className="sheet-binding-actions">
195
+ <button type="button" className="sheet-action" onClick={runPreview} disabled={!ready}>
196
+ Preview
197
+ </button>
198
+ <button type="button" className="sheet-action" onClick={() => onSave(binding)}
199
+ disabled={!ready}>
200
+ Save
201
+ </button>
202
+ <button type="button" className="sheet-action" onClick={onCancel}>
203
+ Cancel
204
+ </button>
205
+ </div>
206
+ </section>
207
+ );
208
+ }
web/src/sheet/CellActionBar.tsx ADDED
@@ -0,0 +1,99 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // sheet/CellActionBar.tsx — the non-modal bar that appears beside a selected cell (W49-T05, R11).
2
+ //
3
+ // ⭐⭐ NON-MODAL IS THE RULING, AND IT DICTATES THREE THINGS THIS COMPONENT DOES NOT DO. R11 says a
4
+ // cell click SELECTS and the bar carries Edit / View rows / Refresh. So it does NOT trap focus, it
5
+ // does NOT render a backdrop, and it does NOT autofocus anything: the grid keeps the keyboard the
6
+ // whole time, which is what lets someone arrow to the next cell without dismissing anything. That
7
+ // is the opposite discipline from `LinkGridModal`, which is modal and traps focus deliberately.
8
+ //
9
+ // ⚠ `onMouseDown` PREVENTS DEFAULT ON THE BAR ITSELF. Without it, pressing a button blurs the grid
10
+ // canvas, glide-data-grid drops its selection, and the bar unmounts before the click lands. The
11
+ // button then does nothing and it looks like a dead control.
12
+ //
13
+ // ⚠ DESIGN CONTRACT. Sentence case; quiet buttons are muted ink with a hover wash; icons are inline
14
+ // SVG on `currentColor`; motion is 150 ms ease-out on opacity and transform only; no emoji; no em
15
+ // dash or en dash in any string; z-order rides a `--cg-z-*` token, never a literal.
16
+
17
+ import type { CSSProperties } from "react";
18
+
19
+ export interface CellActionBarProps {
20
+ /** Viewport rect of the selected cell. The bar sits just above it, clamped to the viewport. */
21
+ anchor: { x: number; y: number; width: number; height: number };
22
+ /** R17: a formula cell cannot drill, and the reason is named on hover. */
23
+ drill: { enabled: boolean; reason: string };
24
+ canEdit: boolean;
25
+ busy?: boolean;
26
+ onEdit: () => void;
27
+ onViewRows: () => void;
28
+ onRefresh: () => void;
29
+ }
30
+
31
+ function IconEdit() {
32
+ return (
33
+ <svg viewBox="0 0 16 16" aria-hidden="true" className="sheet-action-icon">
34
+ <path d="M2.8 13.2h3l7-7a1.6 1.6 0 0 0 0-2.2l-.8-.8a1.6 1.6 0 0 0-2.2 0l-7 7z" />
35
+ <path d="M9.4 4.6l2 2" />
36
+ </svg>
37
+ );
38
+ }
39
+
40
+ function IconRows() {
41
+ return (
42
+ <svg viewBox="0 0 16 16" aria-hidden="true" className="sheet-action-icon">
43
+ <rect x="2.4" y="3.2" width="11.2" height="9.6" rx="1.2" />
44
+ <path d="M2.4 6.4h11.2M2.4 9.6h11.2" />
45
+ </svg>
46
+ );
47
+ }
48
+
49
+ function IconRefresh() {
50
+ return (
51
+ <svg viewBox="0 0 16 16" aria-hidden="true" className="sheet-action-icon">
52
+ <path d="M13 8a5 5 0 1 1-1.6-3.7" />
53
+ <path d="M13.2 2.6v2.9h-2.9" />
54
+ </svg>
55
+ );
56
+ }
57
+
58
+ export default function CellActionBar({
59
+ anchor, drill, canEdit, busy = false, onEdit, onViewRows, onRefresh,
60
+ }: CellActionBarProps) {
61
+ // Clamped so a cell at the very top or the right edge still shows its bar on screen.
62
+ const style: CSSProperties = {
63
+ left: Math.max(8, Math.min(anchor.x, window.innerWidth - 232)),
64
+ top: Math.max(8, anchor.y - 40),
65
+ };
66
+
67
+ return (
68
+ <div
69
+ className="sheet-action-bar"
70
+ style={style}
71
+ role="toolbar"
72
+ aria-label="Cell actions"
73
+ onMouseDown={(e) => e.preventDefault()}
74
+ >
75
+ <button type="button" className="sheet-action" onClick={onEdit} disabled={!canEdit || busy}>
76
+ <IconEdit />
77
+ <span>Edit</span>
78
+ </button>
79
+ <button
80
+ type="button"
81
+ className="sheet-action"
82
+ onClick={onViewRows}
83
+ disabled={!drill.enabled || busy}
84
+ // ⭐ R17: the reason is NAMED rather than left to a disabled control with no explanation.
85
+ // `title` carries it on hover and `aria-description` carries it to a screen reader, so the
86
+ // two audiences get the same sentence.
87
+ title={drill.enabled ? "View the rows behind this cell" : drill.reason}
88
+ aria-description={drill.enabled ? undefined : drill.reason}
89
+ >
90
+ <IconRows />
91
+ <span>View rows</span>
92
+ </button>
93
+ <button type="button" className="sheet-action" onClick={onRefresh} disabled={busy}>
94
+ <IconRefresh />
95
+ <span>Refresh</span>
96
+ </button>
97
+ </div>
98
+ );
99
+ }