fsanyoto commited on
Commit
bea2cff
·
verified ·
1 Parent(s): e8cc149

Deploy AIOS web (React glide grid + FastAPI slice)

Browse files
RELEASES.json CHANGED
@@ -1,4 +1,4 @@
1
  {
2
- "current": "1bcb46977",
3
  "releases": []
4
  }
 
1
  {
2
+ "current": "89c4b5cb2",
3
  "releases": []
4
  }
VERSION CHANGED
@@ -1 +1 @@
1
- 1bcb46977
 
1
+ 89c4b5cb2
api/routes_customers.py CHANGED
@@ -34,7 +34,7 @@ from fastapi import APIRouter, Body, Depends, Response
34
  import scope_cache
35
  from deps import Session, err, module_gate, require_session
36
  from routes_grid import row_patch_receipt
37
- from routes_tables import _row_patch_identity, _note_delta, _patch_cell_notes, _project_cell_notes, _builtin_note_context
38
 
39
  router = APIRouter(prefix="/api/v1")
40
 
@@ -1094,6 +1094,7 @@ def _compute_grid_assembly(session: Session, scope: str = "customer", storage_ke
1094
  # grain with the most of them. Three calls, one predicate.
1095
  may_metrics = perm_scope.may_metrics(session.user, MODULE)
1096
  measures = measure_resolve.offer(team_id, on_error=_measure_err) if may_metrics else []
 
1097
  measure_sets = measure_resolve.condition_sets(
1098
  [v.get("config") or {} for v in (views or [])], None, team_id, pids, today, stamp,
1099
  rt.mset_memo, on_error=_measure_err) if may_metrics and with_rows and needed is None else {}
@@ -1169,6 +1170,7 @@ def _compute_grid_assembly(session: Session, scope: str = "customer", storage_ke
1169
  return {"rows_src": rows_src, "pids": pids, "ws": ws, "workspace": workspace,
1170
  "fields": fields, "views": views, "lists": lists, "derived": derived,
1171
  "_permission_scope": permission_scope,
 
1172
  "measures": measures, "measure_sets": measure_sets, "today": today,
1173
  "team_id": team_id, "routes": normalized_routes, "zones": normalized_zones}
1174
 
@@ -1188,8 +1190,9 @@ def _payload(session: Session, related=None):
1188
  import aios_grid
1189
 
1190
  g = grid_assembly(session, consume_corrections=not bool(related))
 
1191
  rows = aios_grid.rows_from_pool(
1192
- g["rows_src"], g["fields"], g["ws"].get("overlays"), derived=g["derived"])
1193
  from core import route_system
1194
  rows = route_system.apply_customer_projections(rows, g["routes"], g["zones"])
1195
  from routes_odoo_tables import narrow_related_rows
@@ -1198,6 +1201,7 @@ def _payload(session: Session, related=None):
1198
  rows, g['fields'], metric_refusals = scope_linked_metrics(
1199
  session, MODULE, rows, g['fields'], g['measures'], related)
1200
  rows = _project_cell_notes(MODULE, rows, g['fields'], session.runtime)
 
1201
  if related:
1202
  g["pids"] = frozenset(row["pid"] for row in rows)
1203
  # ⭐ C4 / D-138 (W30-T37) — THE DOCUMENTS PRODUCER FOR THE CUSTOMER SCOPE. The write door
@@ -1215,7 +1219,7 @@ def _payload(session: Session, related=None):
1215
  from core import grid_events as _ge
1216
  return {"fields": g["fields"], "rows": rows,
1217
  "refusals": metric_refusals,
1218
- "limits": linked_metric_limits(metric_refusals),
1219
  # `today` rides the payload because every relative date condition must resolve against
1220
  # the TENANT's day, never the browser's — a client that falls back to its own clock
1221
  # disagrees with the server for everyone west of it.
@@ -1326,12 +1330,19 @@ def assigned_view_rows(view_id: str, session: Session = Depends(module_gate(MODU
1326
  pids = set(filter_eval.visible_pids(
1327
  {"nodes": cfg.get("filters") or [], "conj": cfg.get("filterConj") or "and"},
1328
  g["rows_src"], g["fields"], member_pids=cfg.get("memberPids") or []))
 
1329
  rows = aios_grid.rows_from_pool(
1330
  [row for row in g["rows_src"] if row.get("pid") in pids],
1331
- g["fields"], g["ws"].get("overlays"), derived=g["derived"])
 
 
 
1332
  rows = _project_cell_notes(MODULE, rows, g['fields'], session.runtime)
 
1333
  return {"fields": g["fields"], "rows": rows, "viewId": view_id,
1334
- "locked": True, "today": g["today"]}
 
 
1335
 
1336
 
1337
  # ── Wave 44: normalized, Loopable-owned Route/Zone APIs ─────────────────────
 
34
  import scope_cache
35
  from deps import Session, err, module_gate, require_session
36
  from routes_grid import row_patch_receipt
37
+ from routes_tables import _row_patch_identity, _note_delta, _patch_cell_notes, _project_cell_notes, _builtin_note_context, _exclude_sourceless
38
 
39
  router = APIRouter(prefix="/api/v1")
40
 
 
1094
  # grain with the most of them. Three calls, one predicate.
1095
  may_metrics = perm_scope.may_metrics(session.user, MODULE)
1096
  measures = measure_resolve.offer(team_id, on_error=_measure_err) if may_metrics else []
1097
+ measures = [measure for measure in measures if f"measure_{measure['key']}" not in hidden]
1098
  measure_sets = measure_resolve.condition_sets(
1099
  [v.get("config") or {} for v in (views or [])], None, team_id, pids, today, stamp,
1100
  rt.mset_memo, on_error=_measure_err) if may_metrics and with_rows and needed is None else {}
 
1170
  return {"rows_src": rows_src, "pids": pids, "ws": ws, "workspace": workspace,
1171
  "fields": fields, "views": views, "lists": lists, "derived": derived,
1172
  "_permission_scope": permission_scope,
1173
+ "hidden": hidden | set(_ov_hidden or ()),
1174
  "measures": measures, "measure_sets": measure_sets, "today": today,
1175
  "team_id": team_id, "routes": normalized_routes, "zones": normalized_zones}
1176
 
 
1190
  import aios_grid
1191
 
1192
  g = grid_assembly(session, consume_corrections=not bool(related))
1193
+ field_limits = []
1194
  rows = aios_grid.rows_from_pool(
1195
+ g["rows_src"], g["fields"], g["ws"].get("overlays"), derived=g["derived"], limits=field_limits)
1196
  from core import route_system
1197
  rows = route_system.apply_customer_projections(rows, g["routes"], g["zones"])
1198
  from routes_odoo_tables import narrow_related_rows
 
1201
  rows, g['fields'], metric_refusals = scope_linked_metrics(
1202
  session, MODULE, rows, g['fields'], g['measures'], related)
1203
  rows = _project_cell_notes(MODULE, rows, g['fields'], session.runtime)
1204
+ rows = _exclude_sourceless(rows, g['fields'])
1205
  if related:
1206
  g["pids"] = frozenset(row["pid"] for row in rows)
1207
  # ⭐ C4 / D-138 (W30-T37) — THE DOCUMENTS PRODUCER FOR THE CUSTOMER SCOPE. The write door
 
1219
  from core import grid_events as _ge
1220
  return {"fields": g["fields"], "rows": rows,
1221
  "refusals": metric_refusals,
1222
+ "limits": field_limits + linked_metric_limits(metric_refusals),
1223
  # `today` rides the payload because every relative date condition must resolve against
1224
  # the TENANT's day, never the browser's — a client that falls back to its own clock
1225
  # disagrees with the server for everyone west of it.
 
1330
  pids = set(filter_eval.visible_pids(
1331
  {"nodes": cfg.get("filters") or [], "conj": cfg.get("filterConj") or "and"},
1332
  g["rows_src"], g["fields"], member_pids=cfg.get("memberPids") or []))
1333
+ field_limits = []
1334
  rows = aios_grid.rows_from_pool(
1335
  [row for row in g["rows_src"] if row.get("pid") in pids],
1336
+ g["fields"], g["ws"].get("overlays"), derived=g["derived"], limits=field_limits)
1337
+ from routes_tables import scope_linked_metrics, linked_metric_limits
1338
+ rows, g['fields'], metric_refusals = scope_linked_metrics(
1339
+ session, MODULE, rows, g['fields'], g['measures'], None)
1340
  rows = _project_cell_notes(MODULE, rows, g['fields'], session.runtime)
1341
+ rows = _exclude_sourceless(rows, g['fields'])
1342
  return {"fields": g["fields"], "rows": rows, "viewId": view_id,
1343
+ "locked": True, "today": g["today"],
1344
+ "refusals": metric_refusals,
1345
+ "limits": field_limits + linked_metric_limits(metric_refusals)}
1346
 
1347
 
1348
  # ── Wave 44: normalized, Loopable-owned Route/Zone APIs ─────────────────────
api/routes_grid.py CHANGED
@@ -405,6 +405,37 @@ def _workspace_values(values, session, module, fields):
405
  return {str(pid): cells(raw) for pid, raw in values.items()}
406
 
407
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
408
  @router.get("/workspace")
409
  def workspace(scope: str = "customer",
410
  session: Session = Depends(require_session), fields_only: bool = False):
@@ -503,7 +534,8 @@ def workspace(scope: str = "customer",
503
  workspace["limits"] = g.get("limits") or []
504
  if fields_only:
505
  workspace["fieldsOnly"] = True
506
- return {"workspace": workspace}
 
507
 
508
  # ── Wave 16 C-TOPIC: the PRODUCT surface has its own assembly (own pool, own field
509
  # contract, own workspace BUCKET) and the contract's own storage key. It branches before
@@ -562,7 +594,8 @@ def workspace(scope: str = "customer",
562
  workspace["mapSetup"] = map_setup
563
  if fields_only:
564
  workspace["fieldsOnly"] = True
565
- return {"workspace": workspace}
 
566
 
567
  # The storage key mirrors the host's own convention byte-for-byte (app.py's `_table_grid`
568
  # call sites) with the session's TENANT in the host's hardcoded slot, so localStorage state
@@ -665,7 +698,8 @@ def workspace(scope: str = "customer",
665
  workspace["cohortMode"] = True
666
  # The create pane offers "this cohort table only" (default) vs "all customer tables".
667
  workspace["scopeChoice"] = True
668
- return {"workspace": workspace}
 
669
 
670
 
671
  _RECURRENCE_CONDITION_OPS = frozenset({"eq", "neq", "isNotEmpty", "between"})
@@ -2398,7 +2432,7 @@ def _pivot_reply(source, target, rows, fields, source_count, target_count,
2398
  return out
2399
 
2400
 
2401
- def _pivot_side(session, key, stack):
2402
  """Return a walled SQL read or the existing refusal envelope."""
2403
  from core import perm_scope, user_tables
2404
  import routes_odoo_tables as tables
@@ -2434,7 +2468,14 @@ def _pivot_side(session, key, stack):
2434
  return None, {'reason': f'{exc.cause}. {exc.recommendation}', 'subject': key}
2435
  except perm_scope.UnknownTable as exc:
2436
  return None, {'reason': str(exc), 'subject': key}
2437
- return dict(read, fields=fields), None
 
 
 
 
 
 
 
2438
 
2439
 
2440
  def _pivot_binding(read, key):
@@ -2652,12 +2693,13 @@ def grid_pivot(body: dict = Body(default=None),
2652
  from contextlib import ExitStack
2653
 
2654
  with ExitStack() as stack:
2655
- src, refusal = _pivot_side(session, source, stack)
 
2656
  if refusal is not None:
2657
- return _pivot_reply(source, target, [], [], 0, 0, refusal=refusal)
2658
- tgt, refusal = _pivot_side(session, target, stack)
2659
  if refusal is not None:
2660
- return _pivot_reply(source, target, [], [], 0, 0, refusal=refusal)
2661
  required = {'fields', 'cur', 'spec', 'cols', 'where', 'params'}
2662
  if any(not isinstance(read, dict) or not required.issubset(read) or 'rows' in read
2663
  for read in (src, tgt)):
@@ -2673,12 +2715,13 @@ def grid_pivot(body: dict = Body(default=None),
2673
  "reason": f"this filter carries a {' and a '.join(unanswerable)} condition, "
2674
  f"which is resolved by the grid that owns it and cannot be "
2675
  f"answered here. Pivot from a view filtered on columns and "
2676
- f"cohorts, or narrow the source grid first and pivot from that"})
 
2677
  target_key = route['link']['on'] if 'link' in route else route['target_key']
2678
  if _pivot_binding(tgt, target_key) is None:
2679
  return _pivot_reply(source, target, [], [], 0, 0,
2680
  refusal={"reason": "A column required by this link is unavailable.",
2681
- "message": "A column required by this link is unavailable."})
2682
  try:
2683
  selection = _pivot_selection(session, source, src, route, filters,
2684
  filter_conj, window, today)
@@ -2698,21 +2741,22 @@ def grid_pivot(body: dict = Body(default=None),
2698
  raise err(503, "pivot_unavailable", sentence)
2699
  except ValueError as exc:
2700
  return _pivot_reply(source, target, [], tgt_fields, 0, 0,
2701
- refusal={"subject": source, "reason": str(exc)})
2702
  if selection is None:
2703
  return _pivot_reply(source, target, [], [], 0, 0,
2704
  refusal={"reason": "A column required by this link is unavailable.",
2705
- "message": "A column required by this link is unavailable."})
2706
  source_count, keys = selection
2707
  if not source_count:
2708
- return _pivot_reply(source, target, [], tgt_fields, 0, 0)
2709
  if 'link' in route and window != 'all':
2710
  return _pivot_reply(source, target, [], [], 0, 0,
2711
  refusal={"reason": "This link does not support a time window.",
2712
- "message": "This link does not support a time window."})
2713
  keys = keys or []
2714
  rows = _pivot_target(tgt, target_key, keys, target, session) if keys else []
2715
- limits = [*src.get('limits', []), *tgt.get('limits', [])]
 
2716
  return _pivot_reply(source, target, rows, tgt_fields, source_count, len(rows),
2717
  bridge_count=len(rows) if 'link' in route else len(keys), limits=limits)
2718
 
@@ -3060,16 +3104,11 @@ def related_entries(session: Session, table: str):
3060
  second, laxer resolution on the read side would be a permission wall with a hole in it.
3061
  """
3062
  import core.relations as relations
3063
- import core.user_tables as user_tables
3064
-
3065
  table = str(table or "")
3066
- defs = {}
3067
- try:
3068
- defs = dict(user_tables.all_defs(st=session.runtime) or {})
3069
- except Exception: # noqa: BLE001
3070
- defs = {}
3071
- entries = relations.related(table, fields=_source_fields(session, table), defs=defs)
3072
- return [e for e in entries if _may_open(session, e["target"])]
3073
 
3074
 
3075
  def _ensure_odoo_spec():
@@ -3195,6 +3234,38 @@ def _relation_context(session: Session, table: str, memo: dict = None):
3195
  # `product_data` is a second ~550 ms for an answer already in hand.
3196
  wall_memo = memo if memo is not None else {}
3197
  open_memo, field_memo, wide_memo = {}, {}, {}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3198
 
3199
  def may_open(key):
3200
  if key not in open_memo:
@@ -3221,7 +3292,7 @@ def _relation_context(session: Session, table: str, memo: dict = None):
3221
  return wide_memo[key]
3222
 
3223
  read_status.update(defs=defs, may_open=may_open, fields_for=fields_for,
3224
- open_fields_for=open_fields_for)
3225
  return read_status
3226
 
3227
 
@@ -3245,7 +3316,7 @@ def related_path_entries(session: Session, table: str, depth: int, ctx: dict = N
3245
  ctx["cacheable"] = False
3246
  return relations.related_paths(table, fields=ctx["fields_for"](table), defs=ctx["defs"],
3247
  depth=depth, may_open=ctx["may_open"],
3248
- fields_for=ctx["fields_for"])
3249
 
3250
 
3251
  def related_measure_pin(session, target, related, requested):
@@ -3387,7 +3458,8 @@ def related_refusals(session: Session, table: str, depth: int, entries: list, ct
3387
  return relations.wall_refusals(
3388
  table, fields=ctx["fields_for"](table), defs=ctx["defs"], depth=depth,
3389
  may_open=ctx["may_open"], fields_for=ctx["fields_for"], entries=entries,
3390
- open_fields=ctx["open_fields_for"](table), open_fields_for=ctx["open_fields_for"])
 
3391
 
3392
 
3393
  #: ⭐ THE HTTP STATUS EACH REFUSAL CODE EARNS ON A **PIN**. The two permission answers are 403, the
@@ -3542,14 +3614,19 @@ def grid_related(table: str,
3542
  cache = getattr(session.runtime, "related_cache", None)
3543
  cache_key = (_related_cache_key(session, table, depth, wanted)
3544
  if spec_ready and cache is not None else None)
 
3545
  if spec_ready and cache_key is not None:
3546
  from copy import deepcopy
3547
  with session.runtime._lock:
3548
- cached = cache.get(cache_key)
3549
- if cached is not None:
3550
- return deepcopy(cached)
3551
-
3552
- ctx = _relation_context(session, table, memo=wall_memo)
 
 
 
 
3553
  entries = related_path_entries(session, table, depth, ctx)
3554
  if wanted is not None:
3555
  wanted = list(wanted)
@@ -3568,7 +3645,7 @@ def grid_related(table: str,
3568
  table, wanted, fields=ctx["fields_for"](table), defs=ctx["defs"],
3569
  may_open=ctx["may_open"], fields_for=ctx["fields_for"], depth=depth,
3570
  entries=entries, open_fields=ctx["open_fields_for"](table),
3571
- open_fields_for=ctx["open_fields_for"]))
3572
  # ⚠ A RESOLVED PIN REPORTS NO REFUSALS. The caller named one path and got it; the other
3573
  # tabs the wall removed are the LISTING's answer, not this one, and repeating them here
3574
  # would attach an unasked-for permission report to every successful read.
 
405
  return {str(pid): cells(raw) for pid, raw in values.items()}
406
 
407
 
408
+ def _workspace_filter_removals(workspace, fields, measures, hidden=()):
409
+ """Clean saved display filters on a detached wire copy, retaining removal reasons."""
410
+ from copy import deepcopy
411
+ import aios_grid
412
+
413
+ workspace = dict(workspace)
414
+ valid_keys = {field['key'] for field in fields} | {measure['key'] for measure in measures}
415
+ cohort_ids = {str(entry['id']) for entry in workspace.get('lists') or () if entry.get('id')}
416
+ view_ids = {str(view['id']) for view in workspace.get('views') or () if view.get('id')}
417
+ hidden = set(hidden or ())
418
+ hidden |= {key[len('measure_'):] for key in hidden if key.startswith('measure_')}
419
+ views = []
420
+ for saved in workspace.get('views') or ():
421
+ view = deepcopy(saved)
422
+ cfg = view.get('config')
423
+ if isinstance(cfg, dict):
424
+ reports = []
425
+ cfg['filters'] = aios_grid.clean_filter_tree(
426
+ cfg.get('filters'), valid_keys, cohort_ids=cohort_ids,
427
+ visible_view_ids=view_ids, report=reports)
428
+ removals = []
429
+ for report in [*(view.get('filterRemovals') or ()), *reports]:
430
+ if (isinstance(report, dict) and report.get('colId') not in hidden
431
+ and report.get('rhsColId') not in hidden and report not in removals):
432
+ removals.append(report)
433
+ view['filterRemovals'] = removals
434
+ views.append(view)
435
+ workspace['views'] = views
436
+ return workspace
437
+
438
+
439
  @router.get("/workspace")
440
  def workspace(scope: str = "customer",
441
  session: Session = Depends(require_session), fields_only: bool = False):
 
534
  workspace["limits"] = g.get("limits") or []
535
  if fields_only:
536
  workspace["fieldsOnly"] = True
537
+ return {"workspace": _workspace_filter_removals(
538
+ workspace, g['fields'], g['measures'], g.get('hidden') or ())}
539
 
540
  # ── Wave 16 C-TOPIC: the PRODUCT surface has its own assembly (own pool, own field
541
  # contract, own workspace BUCKET) and the contract's own storage key. It branches before
 
594
  workspace["mapSetup"] = map_setup
595
  if fields_only:
596
  workspace["fieldsOnly"] = True
597
+ return {"workspace": _workspace_filter_removals(
598
+ workspace, g['fields'], g['measures'], g.get('_note_hidden') or ())}
599
 
600
  # The storage key mirrors the host's own convention byte-for-byte (app.py's `_table_grid`
601
  # call sites) with the session's TENANT in the host's hardcoded slot, so localStorage state
 
698
  workspace["cohortMode"] = True
699
  # The create pane offers "this cohort table only" (default) vs "all customer tables".
700
  workspace["scopeChoice"] = True
701
+ return {"workspace": _workspace_filter_removals(
702
+ workspace, g['fields'], g['measures'], g.get('hidden') or ())}
703
 
704
 
705
  _RECURRENCE_CONDITION_OPS = frozenset({"eq", "neq", "isNotEmpty", "between"})
 
2432
  return out
2433
 
2434
 
2435
+ def _pivot_side(session, key, stack, limits=None):
2436
  """Return a walled SQL read or the existing refusal envelope."""
2437
  from core import perm_scope, user_tables
2438
  import routes_odoo_tables as tables
 
2468
  return None, {'reason': f'{exc.cause}. {exc.recommendation}', 'subject': key}
2469
  except perm_scope.UnknownTable as exc:
2470
  return None, {'reason': str(exc), 'subject': key}
2471
+ import aios_grid
2472
+ side_limits = list(read.get('limits') or ())
2473
+ field_limits = []
2474
+ aios_grid.rows_from_pool([], fields, limits=field_limits)
2475
+ side_limits.extend(report for report in field_limits if report not in side_limits)
2476
+ if limits is not None:
2477
+ limits.extend(side_limits)
2478
+ return dict(read, fields=fields, limits=side_limits), None
2479
 
2480
 
2481
  def _pivot_binding(read, key):
 
2693
  from contextlib import ExitStack
2694
 
2695
  with ExitStack() as stack:
2696
+ limits = []
2697
+ src, refusal = _pivot_side(session, source, stack, limits=limits)
2698
  if refusal is not None:
2699
+ return _pivot_reply(source, target, [], [], 0, 0, refusal=refusal, limits=limits)
2700
+ tgt, refusal = _pivot_side(session, target, stack, limits=limits)
2701
  if refusal is not None:
2702
+ return _pivot_reply(source, target, [], [], 0, 0, refusal=refusal, limits=limits)
2703
  required = {'fields', 'cur', 'spec', 'cols', 'where', 'params'}
2704
  if any(not isinstance(read, dict) or not required.issubset(read) or 'rows' in read
2705
  for read in (src, tgt)):
 
2715
  "reason": f"this filter carries a {' and a '.join(unanswerable)} condition, "
2716
  f"which is resolved by the grid that owns it and cannot be "
2717
  f"answered here. Pivot from a view filtered on columns and "
2718
+ f"cohorts, or narrow the source grid first and pivot from that"},
2719
+ limits=limits)
2720
  target_key = route['link']['on'] if 'link' in route else route['target_key']
2721
  if _pivot_binding(tgt, target_key) is None:
2722
  return _pivot_reply(source, target, [], [], 0, 0,
2723
  refusal={"reason": "A column required by this link is unavailable.",
2724
+ "message": "A column required by this link is unavailable."}, limits=limits)
2725
  try:
2726
  selection = _pivot_selection(session, source, src, route, filters,
2727
  filter_conj, window, today)
 
2741
  raise err(503, "pivot_unavailable", sentence)
2742
  except ValueError as exc:
2743
  return _pivot_reply(source, target, [], tgt_fields, 0, 0,
2744
+ refusal={"subject": source, "reason": str(exc)}, limits=limits)
2745
  if selection is None:
2746
  return _pivot_reply(source, target, [], [], 0, 0,
2747
  refusal={"reason": "A column required by this link is unavailable.",
2748
+ "message": "A column required by this link is unavailable."}, limits=limits)
2749
  source_count, keys = selection
2750
  if not source_count:
2751
+ return _pivot_reply(source, target, [], tgt_fields, 0, 0, limits=limits)
2752
  if 'link' in route and window != 'all':
2753
  return _pivot_reply(source, target, [], [], 0, 0,
2754
  refusal={"reason": "This link does not support a time window.",
2755
+ "message": "This link does not support a time window."}, limits=limits)
2756
  keys = keys or []
2757
  rows = _pivot_target(tgt, target_key, keys, target, session) if keys else []
2758
+ from routes_tables import _exclude_sourceless
2759
+ rows = _exclude_sourceless(rows, tgt_fields)
2760
  return _pivot_reply(source, target, rows, tgt_fields, source_count, len(rows),
2761
  bridge_count=len(rows) if 'link' in route else len(keys), limits=limits)
2762
 
 
3104
  second, laxer resolution on the read side would be a permission wall with a hole in it.
3105
  """
3106
  import core.relations as relations
 
 
3107
  table = str(table or "")
3108
+ ctx = _relation_context(session, table)
3109
+ entries = relations.related(table, fields=ctx['fields_for'](table), defs=ctx['defs'])
3110
+ return relations.filter_available_paths(
3111
+ entries, table_present=ctx['table_present'], may_open=ctx['may_open'])
 
 
 
3112
 
3113
 
3114
  def _ensure_odoo_spec():
 
3234
  # `product_data` is a second ~550 ms for an answer already in hand.
3235
  wall_memo = memo if memo is not None else {}
3236
  open_memo, field_memo, wide_memo = {}, {}, {}
3237
+ presence_memo, count_memo = {}, {}
3238
+
3239
+ def table_present(key):
3240
+ if key not in presence_memo:
3241
+ present = False
3242
+ try:
3243
+ from deps import module_cache_source
3244
+ from routes_odoo_tables import population, _table_cursor
3245
+ definition = defs.get(key)
3246
+ if isinstance(definition, dict):
3247
+ if (user_tables.is_connected(key, st=lent)
3248
+ or not user_tables.materialises(key, st=lent, defn=definition)):
3249
+ count = population(key, rt=session.runtime)
3250
+ else:
3251
+ if 'stored' not in count_memo:
3252
+ count_memo['stored'] = user_tables.definition_counts(st=session.runtime)
3253
+ count = count_memo['stored'].get(key)
3254
+ present = count is not None and int(count) > 0
3255
+ elif module_cache_source(key) is not None:
3256
+ from core import registry
3257
+ from harness import datastore
3258
+ source, _, entity = str(registry.subject_of(key) or '').partition(':')
3259
+ if source == 'odoo' and entity:
3260
+ count = datastore.count_rows(
3261
+ table=entity.replace('.', '_'), cur=_table_cursor(session.runtime, key))
3262
+ present = count is not None and int(count) > 0
3263
+ except Exception: # noqa: BLE001
3264
+ read_status['cacheable'] = False
3265
+ presence_memo[key] = present
3266
+ if not present:
3267
+ read_status['cacheable'] = False
3268
+ return presence_memo[key]
3269
 
3270
  def may_open(key):
3271
  if key not in open_memo:
 
3292
  return wide_memo[key]
3293
 
3294
  read_status.update(defs=defs, may_open=may_open, fields_for=fields_for,
3295
+ open_fields_for=open_fields_for, table_present=table_present)
3296
  return read_status
3297
 
3298
 
 
3316
  ctx["cacheable"] = False
3317
  return relations.related_paths(table, fields=ctx["fields_for"](table), defs=ctx["defs"],
3318
  depth=depth, may_open=ctx["may_open"],
3319
+ fields_for=ctx["fields_for"], table_present=ctx["table_present"])
3320
 
3321
 
3322
  def related_measure_pin(session, target, related, requested):
 
3458
  return relations.wall_refusals(
3459
  table, fields=ctx["fields_for"](table), defs=ctx["defs"], depth=depth,
3460
  may_open=ctx["may_open"], fields_for=ctx["fields_for"], entries=entries,
3461
+ open_fields=ctx["open_fields_for"](table), open_fields_for=ctx["open_fields_for"],
3462
+ table_present=ctx["table_present"])
3463
 
3464
 
3465
  #: ⭐ THE HTTP STATUS EACH REFUSAL CODE EARNS ON A **PIN**. The two permission answers are 403, the
 
3614
  cache = getattr(session.runtime, "related_cache", None)
3615
  cache_key = (_related_cache_key(session, table, depth, wanted)
3616
  if spec_ready and cache is not None else None)
3617
+ ctx = None
3618
  if spec_ready and cache_key is not None:
3619
  from copy import deepcopy
3620
  with session.runtime._lock:
3621
+ cached = deepcopy(cache.get(cache_key))
3622
+ if cached is not None:
3623
+ ctx = _relation_context(session, table, memo=wall_memo)
3624
+ available = relations.filter_available_paths(
3625
+ cached['related'], table_present=ctx['table_present'], may_open=ctx['may_open'])
3626
+ if available == cached['related'] and ctx.get('cacheable', False):
3627
+ return cached
3628
+
3629
+ ctx = ctx or _relation_context(session, table, memo=wall_memo)
3630
  entries = related_path_entries(session, table, depth, ctx)
3631
  if wanted is not None:
3632
  wanted = list(wanted)
 
3645
  table, wanted, fields=ctx["fields_for"](table), defs=ctx["defs"],
3646
  may_open=ctx["may_open"], fields_for=ctx["fields_for"], depth=depth,
3647
  entries=entries, open_fields=ctx["open_fields_for"](table),
3648
+ open_fields_for=ctx["open_fields_for"], table_present=ctx["table_present"]))
3649
  # ⚠ A RESOLVED PIN REPORTS NO REFUSALS. The caller named one path and got it; the other
3650
  # tabs the wall removed are the LISTING's answer, not this one, and repeating them here
3651
  # would attach an unasked-for permission report to every successful read.
api/routes_products.py CHANGED
@@ -32,7 +32,7 @@ import scope_cache
32
  from core import grid_events, user_tables
33
  from deps import Session, err, module_gate, require_session
34
  from routes_grid import row_patch_receipt
35
- from routes_tables import _row_patch_identity, _note_delta, _patch_cell_notes, _project_cell_notes, _builtin_note_context
36
 
37
  router = APIRouter(prefix="/api/v1")
38
 
@@ -672,7 +672,8 @@ def products(session: Session = Depends(module_gate(MODULE)), related: str = Non
672
  import modules.product_data as pd
673
 
674
  g = product_assembly(session, consume_corrections=not bool(related))
675
- rows = product_rows(g)
 
676
  from core import user_tables as _zones
677
  rows = _zones.zone_cells("product_data", rows, allowed_row_ids=g["pids"],
678
  st=session.runtime)
@@ -681,6 +682,7 @@ def products(session: Session = Depends(module_gate(MODULE)), related: str = Non
681
  from routes_tables import scope_linked_metrics, linked_metric_limits
682
  rows, g['fields'], metric_refusals = scope_linked_metrics(
683
  session, MODULE, rows, g['fields'], g['measures'], related)
 
684
  if related:
685
  pinned = {row["pid"] for row in rows}
686
  g["rows_src"] = [row for row in g["rows_src"] if row["pid"] in pinned]
@@ -704,7 +706,7 @@ def products(session: Session = Depends(module_gate(MODULE)), related: str = Non
704
  # the shape this route already established with `identity` and `scope`.
705
  return {"fields": g["fields"], "rows": rows,
706
  "refusals": metric_refusals,
707
- "limits": _duplicate_code_limits(g['rows_src'], g['fields']) + linked_metric_limits(metric_refusals),
708
  "today": g["today"], "pulled_at": time.strftime("%Y-%m-%d %H:%M"),
709
  "identity": {"pid": "pid", "businessKey": "code"},
710
  "identity_report": pd.identity_report(g["rows_src"]),
@@ -787,16 +789,17 @@ def patch_product(pid: int, body: dict = Body(default=None),
787
  PRODUCT_IMAGE_KEY = "image"
788
 
789
 
790
- def product_rows(assembly):
791
  """The grid and Assistant share the same permissioned overlay/default projection."""
792
  import aios_grid
793
  rows = aios_grid.rows_from_pool(assembly["rows_src"], assembly["fields"],
794
- assembly["ws"].get("overlays"), derived=assembly["derived"])
 
795
  rows = _seed_image(_seed_shared(rows, assembly["rows_src"], assembly["fields"]), assembly["fields"])
796
  if assembly.get('_note_runtime') is not None:
797
  rows = _project_cell_notes(MODULE, rows, assembly['fields'], assembly['_note_runtime'],
798
  hidden=assembly.get('_note_hidden') or ())
799
- return rows
800
 
801
 
802
  def _seed_shared(rows, rows_src, fields):
 
32
  from core import grid_events, user_tables
33
  from deps import Session, err, module_gate, require_session
34
  from routes_grid import row_patch_receipt
35
+ from routes_tables import _row_patch_identity, _note_delta, _patch_cell_notes, _project_cell_notes, _builtin_note_context, _exclude_sourceless
36
 
37
  router = APIRouter(prefix="/api/v1")
38
 
 
672
  import modules.product_data as pd
673
 
674
  g = product_assembly(session, consume_corrections=not bool(related))
675
+ field_limits = []
676
+ rows = product_rows(g, limits=field_limits)
677
  from core import user_tables as _zones
678
  rows = _zones.zone_cells("product_data", rows, allowed_row_ids=g["pids"],
679
  st=session.runtime)
 
682
  from routes_tables import scope_linked_metrics, linked_metric_limits
683
  rows, g['fields'], metric_refusals = scope_linked_metrics(
684
  session, MODULE, rows, g['fields'], g['measures'], related)
685
+ rows = _exclude_sourceless(rows, g['fields'])
686
  if related:
687
  pinned = {row["pid"] for row in rows}
688
  g["rows_src"] = [row for row in g["rows_src"] if row["pid"] in pinned]
 
706
  # the shape this route already established with `identity` and `scope`.
707
  return {"fields": g["fields"], "rows": rows,
708
  "refusals": metric_refusals,
709
+ "limits": field_limits + _duplicate_code_limits(g['rows_src'], g['fields']) + linked_metric_limits(metric_refusals),
710
  "today": g["today"], "pulled_at": time.strftime("%Y-%m-%d %H:%M"),
711
  "identity": {"pid": "pid", "businessKey": "code"},
712
  "identity_report": pd.identity_report(g["rows_src"]),
 
789
  PRODUCT_IMAGE_KEY = "image"
790
 
791
 
792
+ def product_rows(assembly, limits=None):
793
  """The grid and Assistant share the same permissioned overlay/default projection."""
794
  import aios_grid
795
  rows = aios_grid.rows_from_pool(assembly["rows_src"], assembly["fields"],
796
+ assembly["ws"].get("overlays"), derived=assembly["derived"],
797
+ limits=limits)
798
  rows = _seed_image(_seed_shared(rows, assembly["rows_src"], assembly["fields"]), assembly["fields"])
799
  if assembly.get('_note_runtime') is not None:
800
  rows = _project_cell_notes(MODULE, rows, assembly['fields'], assembly['_note_runtime'],
801
  hidden=assembly.get('_note_hidden') or ())
802
+ return _exclude_sourceless(rows, assembly['fields'])
803
 
804
 
805
  def _seed_shared(rows, rows_src, fields):
api/routes_tables.py CHANGED
@@ -158,6 +158,25 @@ def _project_cell_notes(table_key, rows, fields, st, *, hidden=()):
158
  return rows
159
 
160
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
161
  def _app_write_via(session, application_id):
162
  """Resolve write attribution through the viewer's stored App permissions."""
163
  # Direct Python callers omit the header and receive FastAPI's parameter descriptor.
@@ -2357,7 +2376,9 @@ def ut_measures(table_key, session, *, include_offer=True):
2357
  try:
2358
  from harness import semantic as sem
2359
  topic = sem.topic_for_grid(table_key)
2360
- return sem.entity_measures(topic) if topic else []
 
 
2361
  except Exception as e: # noqa: BLE001
2362
  _ut_measure_err("ut-measure-offer", e)
2363
  return []
@@ -3141,8 +3162,10 @@ def table_rows(table_key: str, session: Session = Depends(require_session),
3141
  # so a tenant using `json` for a short config sees no change at all.
3142
  projection_fields = (g['fields'] if source_needed is None
3143
  else [field for field in g['fields'] if field['key'] in source_needed])
 
3144
  rows = (aios_grid.rows_from_pool(
3145
- g["rows_src"], projection_fields, _thin_json(projection_fields, merged, table_key), derived=g["derived"])
 
3146
  if source_needed is None or projection_fields else [{'pid': row['pid']} for row in g['rows_src']])
3147
  rows = _ut().zone_cells(table_key, rows, allowed_row_ids=g["pids"], st=_lent)
3148
  # ⭐⭐ WAVE-34 (R13) — the per-cell enrichment STATE rides the row, beside `_created`/`lat`/
@@ -3186,6 +3209,7 @@ def table_rows(table_key: str, session: Session = Depends(require_session),
3186
  rows = connector_spec.decode_scoped_rows(table_key, rows, user=session.user, st=session.runtime)
3187
  rows = _project_cell_notes(table_key, rows, projection_fields, session.runtime,
3188
  hidden=g.get('hidden') or ())
 
3189
  return {"fields": _field_axes(g["fields"]), "rows": rows, "today": g["today"],
3190
  "refusals": metric_refusals,
3191
  "zones": _zones,
@@ -3194,7 +3218,7 @@ def table_rows(table_key: str, session: Session = Depends(require_session),
3194
  "pulled_at": time.strftime("%Y-%m-%d %H:%M"),
3195
  "identity": {"pid": "pid"},
3196
  "scope": {"table": table_key, "rowCount": len(rows)},
3197
- "limits": (([_report] if _report else []) + linked_metric_limits(metric_refusals)
3198
  + _walled + (g.get('limits') or [])),
3199
  "recordsMutable": _ut().records_mutable(table_key, st=_lent)}
3200
 
 
158
  return rows
159
 
160
 
161
+ def _exclude_sourceless(rows, fields):
162
+ """Remove unreadable cells and notes reattached by later projections."""
163
+ missing = {field['key'] for field in fields if not field.get('source')} - {'pid'}
164
+ if not missing:
165
+ return rows
166
+ out = []
167
+ for row in rows:
168
+ row = {key: value for key, value in row.items() if key not in missing}
169
+ notes = row.get('__cell_notes__')
170
+ if isinstance(notes, dict):
171
+ notes = {key: value for key, value in notes.items() if key not in missing}
172
+ if notes:
173
+ row['__cell_notes__'] = notes
174
+ else:
175
+ row.pop('__cell_notes__', None)
176
+ out.append(row)
177
+ return out
178
+
179
+
180
  def _app_write_via(session, application_id):
181
  """Resolve write attribution through the viewer's stored App permissions."""
182
  # Direct Python callers omit the header and receive FastAPI's parameter descriptor.
 
2376
  try:
2377
  from harness import semantic as sem
2378
  topic = sem.topic_for_grid(table_key)
2379
+ hidden = perm_scope.hidden_keys(session.user, table_key, (), st=session.runtime)
2380
+ return [measure for measure in sem.entity_measures(topic)
2381
+ if f"measure_{measure['key']}" not in hidden] if topic else []
2382
  except Exception as e: # noqa: BLE001
2383
  _ut_measure_err("ut-measure-offer", e)
2384
  return []
 
3162
  # so a tenant using `json` for a short config sees no change at all.
3163
  projection_fields = (g['fields'] if source_needed is None
3164
  else [field for field in g['fields'] if field['key'] in source_needed])
3165
+ field_limits = []
3166
  rows = (aios_grid.rows_from_pool(
3167
+ g["rows_src"], projection_fields, _thin_json(projection_fields, merged, table_key),
3168
+ derived=g["derived"], limits=field_limits)
3169
  if source_needed is None or projection_fields else [{'pid': row['pid']} for row in g['rows_src']])
3170
  rows = _ut().zone_cells(table_key, rows, allowed_row_ids=g["pids"], st=_lent)
3171
  # ⭐⭐ WAVE-34 (R13) — the per-cell enrichment STATE rides the row, beside `_created`/`lat`/
 
3209
  rows = connector_spec.decode_scoped_rows(table_key, rows, user=session.user, st=session.runtime)
3210
  rows = _project_cell_notes(table_key, rows, projection_fields, session.runtime,
3211
  hidden=g.get('hidden') or ())
3212
+ rows = _exclude_sourceless(rows, projection_fields)
3213
  return {"fields": _field_axes(g["fields"]), "rows": rows, "today": g["today"],
3214
  "refusals": metric_refusals,
3215
  "zones": _zones,
 
3218
  "pulled_at": time.strftime("%Y-%m-%d %H:%M"),
3219
  "identity": {"pid": "pid"},
3220
  "scope": {"table": table_key, "rowCount": len(rows)},
3221
+ "limits": (field_limits + ([_report] if _report else []) + linked_metric_limits(metric_refusals)
3222
  + _walled + (g.get('limits') or [])),
3223
  "recordsMutable": _ut().records_mutable(table_key, st=_lent)}
3224
 
platform/core/external_tools.py CHANGED
@@ -251,7 +251,8 @@ _APPLICATION = {
251
  # Mirrors aios-web/api/app_templates.TEMPLATES kinds; api_app_templates holds the parity.
252
  "templateKind": {"enum": ["route", "catalog", "competitor_watch", "ranking_diagnostic",
253
  "amazon_operator", "restock_planner", "reimbursements", "aged_stock",
254
- "opportunity_finder", "returns_repeat", "payouts", "account_health"]},
 
255
  "fieldMap": {"type": "object", "additionalProperties": _STRING},
256
  "navPlacement": _object({"section": {"const": "app"},
257
  "order": {"type": "integer", "minimum": 0, "maximum": 999}},
 
251
  # Mirrors aios-web/api/app_templates.TEMPLATES kinds; api_app_templates holds the parity.
252
  "templateKind": {"enum": ["route", "catalog", "competitor_watch", "ranking_diagnostic",
253
  "amazon_operator", "restock_planner", "reimbursements", "aged_stock",
254
+ "opportunity_finder", "returns_refunds", "repeat_buyers", "payouts", "account_health",
255
+ "amazon_dashboard"]},
256
  "fieldMap": {"type": "object", "additionalProperties": _STRING},
257
  "navPlacement": _object({"section": {"const": "app"},
258
  "order": {"type": "integer", "minimum": 0, "maximum": 999}},
platform/core/grid_events.py CHANGED
@@ -1667,10 +1667,11 @@ def handle_one(event, ctx):
1667
  '. A view cannot filter on a view that filters on it, because neither can '
1668
  'be worked out without the other.', view_id)
1669
  return False
 
1670
  filters = _ag.clean_filter_tree(cfg.get('filters'),
1671
  valid_keys | set(measure_keys),
1672
  cohort_ids=set(cohort_ids),
1673
- visible_view_ids=_view_ids)
1674
  sorts = []
1675
  for rule in list(cfg.get('sorts') or [])[:20]:
1676
  if (isinstance(rule, dict) and rule.get('colId') in valid_keys
@@ -1923,7 +1924,8 @@ def handle_one(event, ctx):
1923
  'locked': locked,
1924
  'createdBy': creator,
1925
  'note': str(raw.get('note') or '')[:2000],
1926
- 'config': config}
 
1927
  # System/list projections are not all persisted in this table store, but custom views
1928
  # may not impersonate their visible names. Persisted view names are allocated
1929
  # tenant-globally by TableStore inside the write transaction.
 
1667
  '. A view cannot filter on a view that filters on it, because neither can '
1668
  'be worked out without the other.', view_id)
1669
  return False
1670
+ filter_removals = []
1671
  filters = _ag.clean_filter_tree(cfg.get('filters'),
1672
  valid_keys | set(measure_keys),
1673
  cohort_ids=set(cohort_ids),
1674
+ visible_view_ids=_view_ids, report=filter_removals)
1675
  sorts = []
1676
  for rule in list(cfg.get('sorts') or [])[:20]:
1677
  if (isinstance(rule, dict) and rule.get('colId') in valid_keys
 
1924
  'locked': locked,
1925
  'createdBy': creator,
1926
  'note': str(raw.get('note') or '')[:2000],
1927
+ 'config': config,
1928
+ 'filterRemovals': filter_removals}
1929
  # System/list projections are not all persisted in this table store, but custom views
1930
  # may not impersonate their visible names. Persisted view names are allocated
1931
  # tenant-globally by TableStore inside the write transaction.
platform/harness/amazon_store.py CHANGED
@@ -93,7 +93,8 @@ SHARED_REPORT_SIBLINGS = {"orders": "order_items"}
93
  AFTER_SYNC = ("modules.amazon_profit:on_amazon_sync", "modules.competitor_watch:on_amazon_sync",
94
  "modules.ranking_diagnostic:on_amazon_sync", "modules.restock_planner:on_amazon_sync",
95
  "modules.account_health:on_amazon_sync", "modules.aged_stock:on_amazon_sync",
96
- "modules.returns_repeat:on_amazon_sync", "modules.opportunity_finder:on_amazon_sync")
 
97
 
98
  #: R18: `fn(tenant) -> iterable of str`. Older brand analytics weeks keep these search terms only.
99
  #: A missing module is an empty set; a reader that raises prunes nothing that pass.
 
93
  AFTER_SYNC = ("modules.amazon_profit:on_amazon_sync", "modules.competitor_watch:on_amazon_sync",
94
  "modules.ranking_diagnostic:on_amazon_sync", "modules.restock_planner:on_amazon_sync",
95
  "modules.account_health:on_amazon_sync", "modules.aged_stock:on_amazon_sync",
96
+ "modules.returns_refunds:on_amazon_sync", "modules.repeat_buyers:on_amazon_sync",
97
+ "modules.opportunity_finder:on_amazon_sync")
98
 
99
  #: R18: `fn(tenant) -> iterable of str`. Older brand analytics weeks keep these search terms only.
100
  #: A missing module is an empty set; a reader that raises prunes nothing that pass.
platform/modules/amazon_operator.py CHANGED
@@ -65,11 +65,11 @@ KEYS = (KEY_SETTINGS, KEY_DAYS, KEY_BASELINE, KEY_DECISIONS, KEY_OUTCOMES, KEY_I
65
 
66
  #: C7: the App modules whose C4 proposals() feed the inbox, imported lazily by name, in this order.
67
  PROPOSAL_SOURCES = ("modules.restock_planner", "modules.reimbursements", "modules.payouts",
68
- "modules.account_health", "modules.returns_repeat", "modules.aged_stock",
69
  "modules.opportunity_finder")
70
  #: The App's label when its module carries no APP_LABEL.
71
  APP_LABELS = {"restock_planner": "Restock planner", "reimbursements": "Reimbursements", "payouts": "Payouts and cash",
72
- "account_health": "Account health", "returns_repeat": "Returns and repeat",
73
  "aged_stock": "Aged stock", "opportunity_finder": "Opportunity finder"}
74
  #: Inbox statuses. `stale` is an item its App no longer lists; it cannot be approved.
75
  INBOX_OPEN = ("proposed",)
 
65
 
66
  #: C7: the App modules whose C4 proposals() feed the inbox, imported lazily by name, in this order.
67
  PROPOSAL_SOURCES = ("modules.restock_planner", "modules.reimbursements", "modules.payouts",
68
+ "modules.account_health", "modules.returns_refunds", "modules.aged_stock",
69
  "modules.opportunity_finder")
70
  #: The App's label when its module carries no APP_LABEL.
71
  APP_LABELS = {"restock_planner": "Restock planner", "reimbursements": "Reimbursements", "payouts": "Payouts and cash",
72
+ "account_health": "Account health", "returns_refunds": "Returns and refunds",
73
  "aged_stock": "Aged stock", "opportunity_finder": "Opportunity finder"}
74
  #: Inbox statuses. `stale` is an item its App no longer lists; it cannot be approved.
75
  INBOX_OPEN = ("proposed",)
web/public/AIOS_DEPLOY_RECEIPT CHANGED
@@ -1 +1 @@
1
- 67104a094a989c41b970588b13fdcbdfaf993f720fcc6c2edc6e0ce1d968fe55
 
1
+ 6209c9ccefc224a1548b887090eef31e4030528cd3246eb6fc6417e418f107f3
web/src/apps/amazon-profit/AccountView.tsx CHANGED
@@ -1,5 +1,8 @@
1
  import { useEffect, useId, useState } from "react";
2
  import type { ComponentType, ReactNode } from "react";
 
 
 
3
  import { API_V1, CREDENTIALS, UNAUTHORIZED_EVENT, checkTenant, signal } from "../../apiContract";
4
  import { refusalMessage } from "../../customer-grid/apiBridge";
5
  import WhatIf from "./WhatIf";
@@ -49,6 +52,7 @@ export type AccountSkuSelection = { sku: string; period: string; record: Account
49
  export type AccountFigurePoint = {
50
  label: string; value: number | null; validated: boolean; reason: string | null;
51
  noPrior: boolean; display: string; source_table: string; sourceTables: string[];
 
52
  series?: string; date?: string; comparisonDate?: string; sku?: string; isOther?: boolean; total?: boolean;
53
  };
54
  export type AccountFigure = Omit<AccountFigurePoint, "series"> & {
@@ -61,38 +65,27 @@ export type AccountTabsProps = {
61
  tabs: Array<{ id: AccountTab; label: string }>;
62
  activeTab: AccountTab; onTabChange: (tab: AccountTab) => void;
63
  };
64
- export type AccountDashboardFrameProps = {
65
- tableContent: { tableKey: "ut_amazon_sku_profit"; children: ReactNode };
66
- };
67
  export type AccountChartProps = {
68
  figure: AccountFigure; currency: string;
69
  onSelect?: (point: AccountFigurePoint) => void;
70
  };
71
  export type AccountDashboardComponents = {
72
- AppTabs: ComponentType<AccountTabsProps>;
73
- AppDashboard: ComponentType<AccountDashboardFrameProps>;
74
- KpiStrip: ComponentType<{ figures: AccountFigure[]; currency: string }>;
75
- FigureChart: ComponentType<AccountChartProps>;
 
76
  };
77
 
78
- const sharedFiles = import.meta.glob(["../AppTabs.tsx", "../AppDashboard.tsx", "../../viz/kit/index.ts"]);
79
-
80
- /** The merged rebuild discovers the shared components without importing absent peer files. */
81
  export async function loadAccountDashboardComponents(): Promise<AccountDashboardComponents> {
82
- const paths = ["../AppTabs.tsx", "../AppDashboard.tsx", "../../viz/kit/index.ts"];
83
- if (paths.some((path) => !sharedFiles[path])) throw new Error("Dashboard unavailable");
84
- const [tabs, frame, kit] = await Promise.all(paths.map(async (path) =>
85
- await sharedFiles[path]() as Record<string, unknown>));
86
- const components = {
87
- AppTabs: tabs.AppTabs ?? tabs.default,
88
- AppDashboard: frame.AppDashboard ?? frame.default,
89
- KpiStrip: kit.KpiStrip,
90
- FigureChart: kit.FigureChart,
91
  };
92
- if (Object.values(components).some((part) => !part || !["function", "object"].includes(typeof part))) {
93
- throw new Error("Dashboard unavailable");
94
- }
95
- return components as AccountDashboardComponents;
96
  }
97
 
98
  export function useAccountDashboardComponents(override?: AccountDashboardComponents, revision = 0) {
@@ -114,7 +107,11 @@ export function AccountTabs(props: AccountTabsProps & { components?: AccountDash
114
  const id = useId();
115
  if (props.components) {
116
  const Tabs = props.components.AppTabs;
117
- return <Tabs tabs={props.tabs} activeTab={props.activeTab} onTabChange={props.onTabChange} />;
 
 
 
 
118
  }
119
  return <div className="ap-tabs" role="tablist" aria-label="Amazon SKU profit">
120
  {props.tabs.map((tab, index) => <button type="button" role="tab" key={tab.id}
@@ -172,7 +169,8 @@ function metricProof(window: AccountWindow, key: MetricKey): Proof {
172
  }
173
 
174
  function metricPoint(window: AccountWindow, key: MetricKey, currency: string, label = metricLabels[key]) {
175
- return point(label, { ...window.metrics[key], noPrior: window.noPrior || window.metrics[key].noPrior }, currency, metricProof(window, key));
 
176
  }
177
 
178
  function figure(id: string, kind: AccountFigure["kind"], value: AccountFigurePoint,
@@ -197,16 +195,17 @@ export function accountFigures(data: AccountPayload, comparison: AccountComparis
197
  const waterfall = figure("waterfall", "waterfall", point("Profit breakdown", data.waterfall.netProfit,
198
  currency, { ...data.validate, ok: data.waterfall.validate.ok && data.validate.ok }), currency,
199
  [...data.waterfall.components.filter((part) => part.included).map((part) =>
200
- point(part.key === "cogs" ? "Cost of goods" : part.label, part, currency, data.waterfall.validate)),
201
  { ...metricPoint(data, "netProfit", currency), total: true }]);
202
  // A failed bridge cannot leave numeric chart rows behind a failed total.
203
  if (!waterfall.validated) waterfall.series = waterfall.series.map((row) => ({ ...row, value: null, validated: false,
204
  display: row.noPrior ? "No prior data" : "Unavailable", reason: row.reason ?? waterfall.reason }));
205
  const monthRows = [
206
  metricPoint(data.monthToDate, monthlyMetric, currency, `Month to date: ${periodLabel(data.monthToDate.period)}`),
207
- point("Forecast", data.paceForecast.metrics[monthlyMetric], currency, { ...data.paceForecast.validate,
208
  ok: data.paceForecast.validate.ok
209
  && data.paceForecast.validate.checks?.some((check) => check.ok && check.check.startsWith(`${monthlyMetric} pace `)) === true }),
 
210
  ...data.previousMonths.map((month) => metricPoint(month, monthlyMetric, currency, periodLabel(month.period))),
211
  ];
212
  const monthly = figure("monthly", "bar", metricPoint(data.monthToDate, monthlyMetric, currency, "Monthly comparison"), currency, monthRows);
@@ -226,14 +225,15 @@ export function accountFigures(data: AccountPayload, comparison: AccountComparis
226
  const date = new Date(Date.parse(data.period.start) + offset * 86400000).toISOString().slice(0, 10);
227
  daily.push({ ...point(summary.label, row[key], currency,
228
  { ...window.attribution.validate, ok: window.attribution.validate.ok && summary.validated, reason: summary.reason }),
229
- series: summary.label, date, comparisonDate: row.day });
230
  }
231
  }
232
  }
233
  const attribution = figure("attribution", "line", point("Organic and ad sales", data.metrics.netSales, currency,
234
  data.attribution.validate), currency, daily);
235
  const mix = figure("salesMix", "bar", point("Sales mix", data.metrics.netSales, currency, data.salesMixValidate), currency,
236
- data.salesMix.map((row) => ({ ...point(row.sku, row.sales, currency, data.salesMixValidate), sku: row.sku, isOther: row.isOther })));
 
237
  mix.orientation = "horizontal";
238
  const excluded = data.waterfall.components.filter((part) => !part.included).map((part) => point(part.label, part, currency));
239
  return { kpis, waterfall, monthly, attribution, mix, unavailable, excluded };
@@ -254,13 +254,26 @@ function ChartSection({ title, value, components, currency, children, onSelect,
254
  title: string; value: AccountFigure; components: AccountDashboardComponents;
255
  currency: string; children?: ReactNode; onSelect?: AccountChartProps["onSelect"]; unavailable?: AccountFigurePoint[];
256
  }) {
257
- const Chart = components.FigureChart;
 
 
 
 
 
 
 
 
 
 
258
  return <section className="ap-chart-section" aria-label={title} data-figure={value.id}>
259
  <div className="ap-chart-heading"><h3>{title}</h3>{children}</div>
260
- {value.validated ? <Chart figure={value} currency={currency} onSelect={onSelect} />
261
  : <div className="ap-state" role="status"><span>{value.display}</span>
262
  {value.reason && value.reason !== value.display && <span className="ap-reason">{value.reason}</span>}</div>}
263
- <MissingFigures points={unavailable ?? value.series} />
 
 
 
264
  </section>;
265
  }
266
 
@@ -343,7 +356,7 @@ export default function AccountView({ initialPeriod, periods = [], components: s
343
  const data = load.data;
344
  if (!data.sourceRows) return <p className="ap-state" role="status">No prior data</p>;
345
  const values = accountFigures(data, comparison, monthlyMetric);
346
- const { AppDashboard, KpiStrip } = shared.components;
347
  const openSku = (record: AccountSku) => setSelectedSku({ selection: { sku: record.sku, period, record }, currency: data.currency, key });
348
  const select = (row: AccountFigurePoint) => {
349
  if (row.isOther || !row.sku) return;
@@ -353,8 +366,18 @@ export default function AccountView({ initialPeriod, periods = [], components: s
353
  onSelectSku?.({ sku: record.sku, period, record });
354
  }
355
  };
356
- return <AppDashboard tableContent={{ tableKey: "ut_amazon_sku_profit", children: <>
357
- <KpiStrip figures={values.kpis} currency={data.currency} />
 
 
 
 
 
 
 
 
 
 
358
  <ChartSection title="Profit breakdown" value={values.waterfall} components={shared.components} currency={data.currency} />
359
  <MissingFigures points={values.excluded} />
360
  <ChartSection title="Monthly comparison" value={values.monthly} components={shared.components} currency={data.currency}>
@@ -376,7 +399,7 @@ export default function AccountView({ initialPeriod, periods = [], components: s
376
  .map((record) => <li key={record.sku}><button type="button" className="ap-button"
377
  onClick={() => { openSku(record); onSelectSku?.({ sku: record.sku, period, record }); }}>{record.sku}</button></li>)}</ul>}
378
  </section>
379
- </> }} />;
380
  };
381
 
382
  return <div className="ap-account" data-testid="amazon-profit-account" data-period={period} data-comparison={comparison}
 
1
  import { useEffect, useId, useState } from "react";
2
  import type { ComponentType, ReactNode } from "react";
3
+ import type { AppTabsProps } from "../AppTabs";
4
+ import type { AppDashboardProps } from "../AppDashboard";
5
+ import type { ChartSeries, KpiProps, KpiStripProps, TrendChartProps } from "../../viz/kit";
6
  import { API_V1, CREDENTIALS, UNAUTHORIZED_EVENT, checkTenant, signal } from "../../apiContract";
7
  import { refusalMessage } from "../../customer-grid/apiBridge";
8
  import WhatIf from "./WhatIf";
 
52
  export type AccountFigurePoint = {
53
  label: string; value: number | null; validated: boolean; reason: string | null;
54
  noPrior: boolean; display: string; source_table: string; sourceTables: string[];
55
+ sourcePeriod?: AccountPeriod;
56
  series?: string; date?: string; comparisonDate?: string; sku?: string; isOther?: boolean; total?: boolean;
57
  };
58
  export type AccountFigure = Omit<AccountFigurePoint, "series"> & {
 
65
  tabs: Array<{ id: AccountTab; label: string }>;
66
  activeTab: AccountTab; onTabChange: (tab: AccountTab) => void;
67
  };
 
 
 
68
  export type AccountChartProps = {
69
  figure: AccountFigure; currency: string;
70
  onSelect?: (point: AccountFigurePoint) => void;
71
  };
72
  export type AccountDashboardComponents = {
73
+ AppTabs: ComponentType<AppTabsProps>;
74
+ AppDashboard: ComponentType<AppDashboardProps>;
75
+ Kpi: ComponentType<KpiProps>;
76
+ KpiStrip: ComponentType<KpiStripProps>;
77
+ TrendChart: ComponentType<TrendChartProps>;
78
  };
79
 
80
+ /** Load the canonical frame and kit with their published prop types. */
 
 
81
  export async function loadAccountDashboardComponents(): Promise<AccountDashboardComponents> {
82
+ const [tabs, frame, kit] = await Promise.all([
83
+ import("../AppTabs"), import("../AppDashboard"), import("../../viz/kit"),
84
+ ]);
85
+ return {
86
+ AppTabs: tabs.AppTabs, AppDashboard: frame.AppDashboard,
87
+ Kpi: kit.Kpi, KpiStrip: kit.KpiStrip, TrendChart: kit.TrendChart,
 
 
 
88
  };
 
 
 
 
89
  }
90
 
91
  export function useAccountDashboardComponents(override?: AccountDashboardComponents, revision = 0) {
 
107
  const id = useId();
108
  if (props.components) {
109
  const Tabs = props.components.AppTabs;
110
+ return <Tabs tabs={props.tabs} value={props.activeTab} ariaLabel="Amazon SKU profit"
111
+ onChange={(value) => {
112
+ const tab = props.tabs.find((item) => item.id === value);
113
+ if (tab) props.onTabChange(tab.id);
114
+ }} />;
115
  }
116
  return <div className="ap-tabs" role="tablist" aria-label="Amazon SKU profit">
117
  {props.tabs.map((tab, index) => <button type="button" role="tab" key={tab.id}
 
169
  }
170
 
171
  function metricPoint(window: AccountWindow, key: MetricKey, currency: string, label = metricLabels[key]) {
172
+ return { ...point(label, { ...window.metrics[key], noPrior: window.noPrior || window.metrics[key].noPrior }, currency, metricProof(window, key)),
173
+ sourcePeriod: window.period };
174
  }
175
 
176
  function figure(id: string, kind: AccountFigure["kind"], value: AccountFigurePoint,
 
195
  const waterfall = figure("waterfall", "waterfall", point("Profit breakdown", data.waterfall.netProfit,
196
  currency, { ...data.validate, ok: data.waterfall.validate.ok && data.validate.ok }), currency,
197
  [...data.waterfall.components.filter((part) => part.included).map((part) =>
198
+ ({ ...point(part.key === "cogs" ? "Cost of goods" : part.label, part, currency, data.waterfall.validate), sourcePeriod: data.period })),
199
  { ...metricPoint(data, "netProfit", currency), total: true }]);
200
  // A failed bridge cannot leave numeric chart rows behind a failed total.
201
  if (!waterfall.validated) waterfall.series = waterfall.series.map((row) => ({ ...row, value: null, validated: false,
202
  display: row.noPrior ? "No prior data" : "Unavailable", reason: row.reason ?? waterfall.reason }));
203
  const monthRows = [
204
  metricPoint(data.monthToDate, monthlyMetric, currency, `Month to date: ${periodLabel(data.monthToDate.period)}`),
205
+ { ...point("Forecast", data.paceForecast.metrics[monthlyMetric], currency, { ...data.paceForecast.validate,
206
  ok: data.paceForecast.validate.ok
207
  && data.paceForecast.validate.checks?.some((check) => check.ok && check.check.startsWith(`${monthlyMetric} pace `)) === true }),
208
+ sourcePeriod: data.monthToDate.period },
209
  ...data.previousMonths.map((month) => metricPoint(month, monthlyMetric, currency, periodLabel(month.period))),
210
  ];
211
  const monthly = figure("monthly", "bar", metricPoint(data.monthToDate, monthlyMetric, currency, "Monthly comparison"), currency, monthRows);
 
225
  const date = new Date(Date.parse(data.period.start) + offset * 86400000).toISOString().slice(0, 10);
226
  daily.push({ ...point(summary.label, row[key], currency,
227
  { ...window.attribution.validate, ok: window.attribution.validate.ok && summary.validated, reason: summary.reason }),
228
+ series: summary.label, date, comparisonDate: row.day, sourcePeriod: window.period });
229
  }
230
  }
231
  }
232
  const attribution = figure("attribution", "line", point("Organic and ad sales", data.metrics.netSales, currency,
233
  data.attribution.validate), currency, daily);
234
  const mix = figure("salesMix", "bar", point("Sales mix", data.metrics.netSales, currency, data.salesMixValidate), currency,
235
+ data.salesMix.map((row) => ({ ...point(row.sku, row.sales, currency, data.salesMixValidate),
236
+ sku: row.sku, isOther: row.isOther, sourcePeriod: data.period })));
237
  mix.orientation = "horizontal";
238
  const excluded = data.waterfall.components.filter((part) => !part.included).map((part) => point(part.label, part, currency));
239
  return { kpis, waterfall, monthly, attribution, mix, unavailable, excluded };
 
254
  title: string; value: AccountFigure; components: AccountDashboardComponents;
255
  currency: string; children?: ReactNode; onSelect?: AccountChartProps["onSelect"]; unavailable?: AccountFigurePoint[];
256
  }) {
257
+ const Chart = components.TrendChart;
258
+ const groups = new Map<string, ChartSeries>();
259
+ for (const row of value.series) {
260
+ const label = row.series && row.sourcePeriod ? `${row.series}: ${periodLabel(row.sourcePeriod)}` : row.series ?? value.label;
261
+ const group = groups.get(label) ?? { label, points: [] };
262
+ group.points.push({ ...row, x: row.date ?? row.label,
263
+ date: row.comparisonDate ?? row.sourcePeriod?.start,
264
+ period_end: row.date ? undefined : row.sourcePeriod?.end,
265
+ value: row.validated && row.value !== null && Number.isFinite(row.value) ? row.value : null });
266
+ groups.set(label, group);
267
+ }
268
  return <section className="ap-chart-section" aria-label={title} data-figure={value.id}>
269
  <div className="ap-chart-heading"><h3>{title}</h3>{children}</div>
270
+ {value.validated ? <Chart label={value.label} series={[...groups.values()]} unit={currency} kind={value.kind === "kpi" ? "bar" : value.kind} />
271
  : <div className="ap-state" role="status"><span>{value.display}</span>
272
  {value.reason && value.reason !== value.display && <span className="ap-reason">{value.reason}</span>}</div>}
273
+ <MissingFigures points={[...value.series, ...(unavailable ?? [])]} />
274
+ {value.validated && onSelect && <div role="group" aria-label="Select SKU">{value.series
275
+ .filter((row) => row.validated && row.value !== null && Number.isFinite(row.value) && row.sku && !row.isOther)
276
+ .map((row) => <button key={row.sku} type="button" className="ap-button" onClick={() => onSelect(row)}>{row.label}</button>)}</div>}
277
  </section>;
278
  }
279
 
 
356
  const data = load.data;
357
  if (!data.sourceRows) return <p className="ap-state" role="status">No prior data</p>;
358
  const values = accountFigures(data, comparison, monthlyMetric);
359
+ const { AppDashboard, Kpi, KpiStrip } = shared.components;
360
  const openSku = (record: AccountSku) => setSelectedSku({ selection: { sku: record.sku, period, record }, currency: data.currency, key });
361
  const select = (row: AccountFigurePoint) => {
362
  if (row.isOther || !row.sku) return;
 
366
  onSelectSku?.({ sku: record.sku, period, record });
367
  }
368
  };
369
+ const previous = data.comparisons[comparison];
370
+ const comparisonLabel = `${comparison === "prior" ? "Prior window" : "Year ago"}: ${periodLabel(previous.period)}`;
371
+ const kpis = values.kpis.map((item) => ({ ...item, change: { previous: item.comparison.value,
372
+ reason: item.comparison.validated ? comparisonLabel : item.comparison.reason ?? item.comparison.display } }));
373
+ return <AppDashboard figures={kpis} charts={[]} period={data.period}>
374
+ <section aria-label={comparisonLabel}>
375
+ <h3>{comparison === "prior" ? "Prior window" : "Year ago"}</h3>
376
+ <KpiStrip label={comparisonLabel}>{values.kpis.map((item) => <Kpi key={item.id} label={item.label}
377
+ value={item.comparison.value} unit={data.currency} validated={item.comparison.validated}
378
+ reason={item.comparison.reason} noPrior={item.comparison.noPrior} period={periodLabel(previous.period)}
379
+ change={{ reason: "Comparison period" }} />)}</KpiStrip>
380
+ </section>
381
  <ChartSection title="Profit breakdown" value={values.waterfall} components={shared.components} currency={data.currency} />
382
  <MissingFigures points={values.excluded} />
383
  <ChartSection title="Monthly comparison" value={values.monthly} components={shared.components} currency={data.currency}>
 
399
  .map((record) => <li key={record.sku}><button type="button" className="ap-button"
400
  onClick={() => { openSku(record); onSelectSku?.({ sku: record.sku, period, record }); }}>{record.sku}</button></li>)}</ul>}
401
  </section>
402
+ </AppDashboard>;
403
  };
404
 
405
  return <div className="ap-account" data-testid="amazon-profit-account" data-period={period} data-comparison={comparison}
web/src/customer-grid/CustomerGrid.tsx CHANGED
@@ -3542,7 +3542,8 @@ function CustomerGridSurface({
3542
  );
3543
  const key = echoReemit(merged, view, local?.reemitted?.[view.id]);
3544
  if (key !== null) reemit.set(view.id, key);
3545
- byId.set(view.id, merged);
 
3546
  }
3547
  const initialViews = [...byId.values()].map((view) => ({
3548
  ...view,
@@ -3816,8 +3817,15 @@ function CustomerGridSurface({
3816
  normalizeConfig(config, nextFields);
3817
  const heldViews = reconcileHeldViews(views, hostWorkspaceViews, viewWritesRef.current,
3818
  now, normalize);
3819
- const nextViews = adoptNewViews(heldViews, hostWorkspaceViews, viewTombstonesRef.current,
3820
  now, normalize);
 
 
 
 
 
 
 
3821
  if (nextViews !== views) setViews(nextViews);
3822
  /**
3823
  * ⛔⛔ AND THE OPEN VIEW HAS TO FOLLOW ITS OWN DEFINITION, or the correction above is
@@ -10794,6 +10802,11 @@ function CustomerGridSurface({
10794
  const workspaceLoading = rowsLoading || workspacePending;
10795
 
10796
  const activeView = views.find((view) => view.id === activeViewId);
 
 
 
 
 
10797
  const routeSourceView: RouteSourceView | null = activeView
10798
  ? {
10799
  id: activeView.id,
@@ -11814,6 +11827,7 @@ function CustomerGridSurface({
11814
  not be wired yet: absent beats present-and-inert. A control row over a database whose
11815
  columns never arrived would offer Hide fields, Filter, Sort and Group on nothing. */}
11816
  {secondaryToolbar}
 
11817
  {duplicateLimitNote && <div className="cg-state-note" role="status">{duplicateLimitNote.full}</div>}
11818
  {[...cellSaveFailures.values()].some((cell) => cell.failure) && (
11819
  <div className="cg-cell-failures" aria-label="Unsaved cells">
 
3542
  );
3543
  const key = echoReemit(merged, view, local?.reemitted?.[view.id]);
3544
  if (key !== null) reemit.set(view.id, key);
3545
+ byId.set(view.id, view.filterRemovals === undefined ? merged
3546
+ : { ...merged, filterRemovals: view.filterRemovals });
3547
  }
3548
  const initialViews = [...byId.values()].map((view) => ({
3549
  ...view,
 
3817
  normalizeConfig(config, nextFields);
3818
  const heldViews = reconcileHeldViews(views, hostWorkspaceViews, viewWritesRef.current,
3819
  now, normalize);
3820
+ let nextViews = adoptNewViews(heldViews, hostWorkspaceViews, viewTombstonesRef.current,
3821
  now, normalize);
3822
+ const removalReports = new Map((hostWorkspaceViews ?? []).map((view) => [view.id, view.filterRemovals]));
3823
+ const reportedViews = nextViews.map((view) => {
3824
+ const reports = removalReports.get(view.id);
3825
+ return reports === undefined || JSON.stringify(reports) === JSON.stringify(view.filterRemovals)
3826
+ ? view : { ...view, filterRemovals: reports };
3827
+ });
3828
+ if (reportedViews.some((view, index) => view !== nextViews[index])) nextViews = reportedViews;
3829
  if (nextViews !== views) setViews(nextViews);
3830
  /**
3831
  * ⛔⛔ AND THE OPEN VIEW HAS TO FOLLOW ITS OWN DEFINITION, or the correction above is
 
10802
  const workspaceLoading = rowsLoading || workspacePending;
10803
 
10804
  const activeView = views.find((view) => view.id === activeViewId);
10805
+ const removedFilterNames = [...new Set((activeView?.filterRemovals ?? []).map((entry) =>
10806
+ entry.rhsColId || entry.colId).filter(Boolean))];
10807
+ const filterRemovalNote = removedFilterNames.length
10808
+ ? `Rule removed: ${removedFilterNames.map((key) => fieldByKey.get(key)?.label ?? key).join(", ")}.`
10809
+ : null;
10810
  const routeSourceView: RouteSourceView | null = activeView
10811
  ? {
10812
  id: activeView.id,
 
11827
  not be wired yet: absent beats present-and-inert. A control row over a database whose
11828
  columns never arrived would offer Hide fields, Filter, Sort and Group on nothing. */}
11829
  {secondaryToolbar}
11830
+ {filterRemovalNote && <div className="cg-state-note" role="status">{filterRemovalNote}</div>}
11831
  {duplicateLimitNote && <div className="cg-state-note" role="status">{duplicateLimitNote.full}</div>}
11832
  {[...cellSaveFailures.values()].some((cell) => cell.failure) && (
11833
  <div className="cg-cell-failures" aria-label="Unsaved cells">
web/src/customer-grid/types.ts CHANGED
@@ -4558,6 +4558,7 @@ export function pivotRefusalFromBody(body: unknown): PivotRefusal | null {
4558
  export type ViewKind = "system" | "list" | "custom" | "locked" | "assigned";
4559
 
4560
  export interface SavedView {
 
4561
  /** W48-T20 / C4: a recipient projection with an immutable server-owned filter. */
4562
  assigned?: boolean;
4563
  assignedBy?: string;
 
4558
  export type ViewKind = "system" | "list" | "custom" | "locked" | "assigned";
4559
 
4560
  export interface SavedView {
4561
+ filterRemovals?: { id: string; colId: string; reason: string; rhsColId?: string | null }[];
4562
  /** W48-T20 / C4: a recipient projection with an immutable server-owned filter. */
4563
  assigned?: boolean;
4564
  assignedBy?: string;