fsanyoto commited on
Commit
5fb4eca
Β·
verified Β·
1 Parent(s): fd099b3

Deploy Loopable

Browse files
.streamlit/config.toml CHANGED
@@ -9,8 +9,20 @@ borderColor = "#E6E9EF"
9
  dataframeBorderColor = "#E6E9EF"
10
  dataframeHeaderBackgroundColor = "#F6F8FB"
11
  font = "Inter, -apple-system, 'Segoe UI', Roboto, sans-serif"
12
- baseRadius = "4px"
13
- buttonRadius = "4px"
 
 
 
 
 
 
 
 
 
 
 
 
14
  # st.metric sites match the custom KPI cards (28px / 600, Mercury-calibrated)
15
  metricValueFontSize = "1.7rem"
16
  metricValueFontWeight = 600
@@ -26,8 +38,8 @@ textColor = "#202433"
26
  primaryColor = "#5B8FD9"
27
  borderColor = "#E6E9EF"
28
  linkColor = "#3D6FB8"
29
- baseRadius = "4px"
30
- buttonRadius = "4px"
31
 
32
  [client]
33
  toolbarMode = "minimal"
 
9
  dataframeBorderColor = "#E6E9EF"
10
  dataframeHeaderBackgroundColor = "#F6F8FB"
11
  font = "Inter, -apple-system, 'Segoe UI', Roboto, sans-serif"
12
+ # ---- wave-9 I9 (contract C1): "fonts slightly larger and not too sharp" -----------------------
13
+ # baseFontSize is the ROOT size every `rem` in app.py's _CSS resolves against, so raising it here
14
+ # scales all 32 historical rem values up UNIFORMLY (~6%) β€” the dominant body sizes move ~12.8px ->
15
+ # ~13.6px and ~13.6 -> ~14.5 β€” without 32 hand edits, each of which would be a chance to typo a
16
+ # size back out of the scale. It also reaches Streamlit's OWN widget text, which CSS overrides
17
+ # were never going to touch.
18
+ # ⚠ THE TRAP, recorded so nobody "fixes" it backwards: LOWERING this makes every rem-based rule
19
+ # SMALLER. Setting baseFontSize to 14 to get "14px body" would have shrunk .8rem to 11.2px β€” the
20
+ # exact opposite of the ask. rem is relative; the tokens ride this number.
21
+ baseFontSize = 17
22
+ # 4px read as sharp/rigid. 6px is the Airtable/Omni register the owner pointed at, and this is the
23
+ # ONE place that reaches BaseWeb widgets and their popovers β€” CSS cannot restyle those corners.
24
+ baseRadius = "6px"
25
+ buttonRadius = "6px"
26
  # st.metric sites match the custom KPI cards (28px / 600, Mercury-calibrated)
27
  metricValueFontSize = "1.7rem"
28
  metricValueFontWeight = 600
 
38
  primaryColor = "#5B8FD9"
39
  borderColor = "#E6E9EF"
40
  linkColor = "#3D6FB8"
41
+ baseRadius = "6px" # wave-9 C1: matches the main theme; the sidebar must not stay sharper
42
+ buttonRadius = "6px"
43
 
44
  [client]
45
  toolbarMode = "minimal"
aios_grid.py CHANGED
@@ -638,9 +638,20 @@ def _clean_rhs(raw, valid_keys):
638
  #: View DISPLAY MODES beside the grid (wave-6 item 10; 'map' wave-7 W11; 'dashboard' wave-8
639
  #: I19). Mirrors customer-grid/types.ts DISPLAY_MODES; 'grid' is what an absent/unknown
640
  #: display means, so it is never stored.
641
- DISPLAY_MODES = {'grid', 'list', 'calendar', 'kanban', 'map', 'dashboard'}
642
-
643
- #: Chart kinds a dashboard-mode view may hold (wave-8 I19, contract C2). Mirrors the client's
 
 
 
 
 
 
 
 
 
 
 
644
  #: union. Deliberately small: the owner asked to "start with simple charts" and expand, and a
645
  #: kind the client cannot draw is worse than one that does not exist yet.
646
  CHART_KINDS = {'bar', 'line', 'area', 'donut', 'kpi'}
@@ -648,6 +659,20 @@ CHART_AGGS = {'sum', 'avg', 'count', 'min', 'max'}
648
  MAX_CHARTS = 12 #: per view β€” a dashboard, not an unbounded render loop
649
  MAX_CHART_TITLE = 60
650
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
651
 
652
  def _clean_chart(raw, valid_keys):
653
  """One dashboard chart, fail-closed. Returns None if the chart cannot be drawn.
@@ -678,6 +703,53 @@ def _clean_chart(raw, valid_keys):
678
  title = raw.get('title')
679
  if isinstance(title, str) and title.strip():
680
  out['title'] = title.strip()[:MAX_CHART_TITLE]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
681
  return out
682
 
683
 
@@ -703,6 +775,10 @@ def _clean_display(raw, valid_keys):
703
  mode = raw.get('mode')
704
  if mode not in DISPLAY_MODES or mode == 'grid':
705
  return None
 
 
 
 
706
  out = {'mode': mode}
707
  for ref in ('dateField', 'stackField', 'titleField', 'colorField', 'sizeField'):
708
  if raw.get(ref) in valid_keys:
@@ -736,6 +812,85 @@ FOLDER_SURFACES = {"views", "cohorts"}
736
  MAX_FOLDERS = 60
737
  MAX_FOLDER_NAME = 80
738
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
739
 
740
  def clean_folders(raw):
741
  """Validate the per-surface folder lists, fail-closed. {surface: [{id, name, order}]}."""
@@ -754,7 +909,11 @@ def clean_folders(raw):
754
  order = int(f.get("order", len(items)))
755
  except (TypeError, ValueError):
756
  order = len(items)
757
- items.append({"id": fid, "name": name, "order": order})
 
 
 
 
758
  items.sort(key=lambda x: x["order"])
759
  for i, f in enumerate(items):
760
  f["order"] = i # re-index so `order` is always dense and total
 
638
  #: View DISPLAY MODES beside the grid (wave-6 item 10; 'map' wave-7 W11; 'dashboard' wave-8
639
  #: I19). Mirrors customer-grid/types.ts DISPLAY_MODES; 'grid' is what an absent/unknown
640
  #: display means, so it is never stored.
641
+ #: ⚠ 'dashboard' is RETAINED FOREVER (wave-9 I10, contract C2). The owner renamed the mode to
642
+ #: "Chart" (a Dashboard MODULE is coming and the two would collide), but this set is the
643
+ #: gatekeeper for a STORED value: `_clean_display` DROPS an unknown mode, so removing
644
+ #: 'dashboard' here would silently downgrade every already-saved chart view to grid β€” and live
645
+ #: views are sitting in mode:'dashboard' right now (wave 8's own close-out records one). The
646
+ #: rename is therefore a stored-value MIGRATION, not a constant rename: accept 'dashboard' on
647
+ #: READ forever, only ever WRITE 'chart'.
648
+ DISPLAY_MODES = {'grid', 'list', 'calendar', 'kanban', 'map', 'dashboard', 'chart'}
649
+
650
+ #: Old wire value -> the value we store today. Applied AFTER the membership test so an unknown
651
+ #: mode is still rejected rather than accidentally aliased.
652
+ _LEGACY_MODES = {'dashboard': 'chart'}
653
+
654
+ #: Chart kinds a chart-mode view may hold (wave-8 I19, contract C2). Mirrors the client's
655
  #: union. Deliberately small: the owner asked to "start with simple charts" and expand, and a
656
  #: kind the client cannot draw is worse than one that does not exist yet.
657
  CHART_KINDS = {'bar', 'line', 'area', 'donut', 'kpi'}
 
659
  MAX_CHARTS = 12 #: per view β€” a dashboard, not an unbounded render loop
660
  MAX_CHART_TITLE = 60
661
 
662
+ #: Wave-9 I11 (contract C2) β€” chart customisation, host-validated.
663
+ #:
664
+ #: `palette` names a colour JOB, never a colour. A browser must not be able to post a raw hex:
665
+ #: the four names below map to the four jobs a palette can do (identity / magnitude / polarity)
666
+ #: and resolve to brand ramps client-side, so a tenant restyle cannot be defeated by a stored
667
+ #: literal. STATUS colours (good/warning/serious/critical) are deliberately NOT selectable β€”
668
+ #: they are reserved signal, and reusing them as "series 4" is how a chart starts lying.
669
+ CHART_PALETTES = {'brand', 'categorical', 'sequential', 'diverging'}
670
+ CHART_FORMATS = {'auto', 'number', 'currency', 'percent', 'compact'}
671
+ MAX_AXIS_LABEL = 40
672
+ #: `size` is the I10 drag. Width is in GRID COLUMNS (a 12-column board), height in px.
673
+ CHART_W_RANGE = (1, 12)
674
+ CHART_H_RANGE = (120, 800)
675
+
676
 
677
  def _clean_chart(raw, valid_keys):
678
  """One dashboard chart, fail-closed. Returns None if the chart cannot be drawn.
 
703
  title = raw.get('title')
704
  if isinstance(title, str) and title.strip():
705
  out['title'] = title.strip()[:MAX_CHART_TITLE]
706
+
707
+ # ── wave-9 I11 (contract C2): customisation ────────────────────────────────────────────
708
+ # `splitBy` is the field whose values become the SERIES. It is deliberately not called
709
+ # `colorBy`: that name already means two other things here (`config.colorBy` = row
710
+ # colouring, `display.colorField` = map pin colour) and a third sense would be unreadable.
711
+ if raw.get('splitBy') in valid_keys and raw['splitBy'] != x:
712
+ out['splitBy'] = raw['splitBy']
713
+ # Stacking is only a question once there are series to stack, and only for the two kinds
714
+ # that can express it. Anywhere else it is dropped rather than stored as a lie the client
715
+ # would have to re-decide.
716
+ if out.get('splitBy') and kind in ('bar', 'area') and raw.get('stacked') is True:
717
+ out['stacked'] = True
718
+ if raw.get('palette') in CHART_PALETTES:
719
+ out['palette'] = raw['palette']
720
+
721
+ axis = raw.get('axis')
722
+ if isinstance(axis, dict):
723
+ # β›” ONE y-scale, always. There is no second-axis key here and there must never be:
724
+ # two y-scales on one frame can manufacture any correlation you like by rescaling, and
725
+ # the honest alternatives are two charts, small multiples, or indexing to a common base.
726
+ # Ruled explicitly in contract C2 against the "Tableau versatility" brief.
727
+ clean_axis = {}
728
+ for side in ('x', 'y'):
729
+ spec = axis.get(side)
730
+ if not isinstance(spec, dict):
731
+ continue
732
+ one = {}
733
+ lab = spec.get('label')
734
+ if isinstance(lab, str) and lab.strip():
735
+ one['label'] = lab.strip()[:MAX_AXIS_LABEL]
736
+ if spec.get('format') in CHART_FORMATS:
737
+ one['format'] = spec['format']
738
+ if one:
739
+ clean_axis[side] = one
740
+ if clean_axis:
741
+ out['axis'] = clean_axis
742
+
743
+ size = raw.get('size')
744
+ if isinstance(size, dict):
745
+ one = {}
746
+ for key, (lo, hi) in (('w', CHART_W_RANGE), ('h', CHART_H_RANGE)):
747
+ try:
748
+ one[key] = max(lo, min(hi, int(size[key])))
749
+ except (KeyError, TypeError, ValueError):
750
+ pass # a partial size is fine: the client defaults the missing axis
751
+ if one:
752
+ out['size'] = one
753
  return out
754
 
755
 
 
775
  mode = raw.get('mode')
776
  if mode not in DISPLAY_MODES or mode == 'grid':
777
  return None
778
+ # Wave-9 I10 (C2): normalise the legacy wire value AFTER the membership test, so an unknown
779
+ # mode is still rejected rather than accidentally aliased into a real one. Every already
780
+ # saved 'dashboard' view reads back as 'chart' from here on; nothing writes 'dashboard'.
781
+ mode = _LEGACY_MODES.get(mode, mode)
782
  out = {'mode': mode}
783
  for ref in ('dateField', 'stackField', 'titleField', 'colorField', 'sizeField'):
784
  if raw.get(ref) in valid_keys:
 
812
  MAX_FOLDERS = 60
813
  MAX_FOLDER_NAME = 80
814
 
815
+ #: Wave-9 I15 (contract C5) β€” a user-chosen folder icon, as {shape, tone}.
816
+ #:
817
+ #: Both halves are WHITELISTS, never free values: `shape` names geometry the client already
818
+ #: draws (one source, `iconShapes.ts`, read by both painters) and `tone` names a palette token,
819
+ #: not a colour β€” so a browser cannot post a hex and defeat a tenant restyle, and a shape the
820
+ #: client cannot render can never reach the store.
821
+ #: ⚠ MIRRORS CLIENT'S `iconShapes.ts` ENUMERATION EXACTLY (C5: CLIENT enumerates, HOST mirrors β€”
822
+ #: posted in the split doc 2026-07-29, HOST adopted it the same day, replacing a provisional
823
+ #: 12-shape guess of mine that contained shapes the client cannot draw). Do not extend this set
824
+ #: without the matching client geometry: an unknown shape falls back to the default folder mark,
825
+ #: which is also I14's "existing folders get the folder icon" for every pre-wave-9 folder.
826
+ FOLDER_ICON_SHAPES = {"folder", "star", "flag", "tag", "bookmark", "box", "circle", "square"}
827
+ #: Tones are the C1 pastels β€” FILLS ONLY, never text (the standing palette rule). 'grey' is the
828
+ #: default, and is CLIENT's key name: not 'neutral', which is what HOST first guessed.
829
+ FOLDER_ICON_TONES = {"blue", "green", "yellow", "red", "grey"}
830
+ FOLDER_ICON_DEFAULT_TONE = "grey"
831
+
832
+
833
+ #: Wave-9 I17 (contract C4) β€” who may EDIT a saved view.
834
+ #:
835
+ #: ⚠ READ THIS BEFORE BUILDING ON IT. Views are stored PER USER today
836
+ #: (`core/table_store.TableStore.workspace` reads `store.get(table_key)[username]`), so one
837
+ #: user's views are invisible to every other user and "collaborative" has nothing to act on
838
+ #: yet. This validator is therefore CORRECT-BUT-INERT plumbing: it makes the setting durable
839
+ #: and fail-closed now, so that when shared views land the permission does not need a data
840
+ #: migration and no saved view is retro-restricted. It does NOT make anything shared, and
841
+ #: nothing in the app currently reads it to grant or deny cross-user access.
842
+ #: Recorded as the C4 amendment in .claude/wiki/research/grid-wave9-split.md.
843
+ VIEW_EDIT_MODES = {'personal', 'collaborative', 'users'}
844
+ MAX_VIEW_USERS = 50
845
+
846
+
847
+ def clean_view_permissions(raw, default, known_users=None):
848
+ """{edit, users?} β€” fail-closed on both halves.
849
+
850
+ `default` is supplied by the CALLER because it splits by path, and that split is a
851
+ permission rule rather than a formatting one: absent on a view that already exists means a
852
+ pre-wave-9 view and must stay 'collaborative' (retro-restricting somebody's saved view is a
853
+ silent takeaway), while absent on CREATE must be 'personal' (a new view must never be
854
+ anyone-can-edit purely by omission).
855
+
856
+ `known_users` (when given) is the real account list: an unknown name is DROPPED, and an
857
+ 'users' grant left with nobody in it collapses to 'personal' rather than to everyone.
858
+ """
859
+ mode = (raw or {}).get('edit') if isinstance(raw, dict) else None
860
+ if mode not in VIEW_EDIT_MODES:
861
+ mode = default if default in VIEW_EDIT_MODES else 'personal'
862
+ if mode != 'users':
863
+ return {'edit': mode}
864
+ names, seen = [], set()
865
+ for u in list((raw or {}).get('users') or [])[:MAX_VIEW_USERS]:
866
+ u = str(u or '').strip()
867
+ if not u or u.lower() in seen:
868
+ continue
869
+ if known_users is not None and u not in known_users:
870
+ continue # fail-closed: a name we cannot resolve grants nothing
871
+ seen.add(u.lower())
872
+ names.append(u)
873
+ if not names:
874
+ return {'edit': 'personal'} # an empty grant is NOT "everyone"
875
+ return {'edit': 'users', 'users': names}
876
+
877
+
878
+ def clean_folder_icon(raw):
879
+ """{shape, tone} or None. Fail-closed on both halves, independently.
880
+
881
+ A folder with a valid shape but a junk tone keeps the shape and defaults the tone rather
882
+ than losing the icon entirely β€” losing a user's pick because one half was wrong is the kind
883
+ of silent data loss the folder events already avoid elsewhere.
884
+ """
885
+ if not isinstance(raw, dict):
886
+ return None
887
+ shape = raw.get("shape")
888
+ if shape not in FOLDER_ICON_SHAPES:
889
+ return None
890
+ tone = raw.get("tone")
891
+ return {"shape": shape,
892
+ "tone": tone if tone in FOLDER_ICON_TONES else FOLDER_ICON_DEFAULT_TONE}
893
+
894
 
895
  def clean_folders(raw):
896
  """Validate the per-surface folder lists, fail-closed. {surface: [{id, name, order}]}."""
 
909
  order = int(f.get("order", len(items)))
910
  except (TypeError, ValueError):
911
  order = len(items)
912
+ row = {"id": fid, "name": name, "order": order}
913
+ icon = clean_folder_icon(f.get("icon")) # wave-9 I15 (C5); absent = default mark
914
+ if icon:
915
+ row["icon"] = icon
916
+ items.append(row)
917
  items.sort(key=lambda x: x["order"])
918
  for i, f in enumerate(items):
919
  f["order"] = i # re-index so `order` is always dense and total
aios_grid_component/index.html CHANGED
The diff for this file is too large to render. See raw diff
 
aios_grid_embed.html CHANGED
The diff for this file is too large to render. See raw diff
 
app.py CHANGED
@@ -27,8 +27,10 @@ import core.odoo as _O
27
  import core.periods as P
28
  import core.context as ctxlib
29
  import core.registry as registry
 
30
  import core.users as users
31
  import core.store as store
 
32
  import modules.sales as sales_mod
33
  import modules.inventory as inv_mod
34
  import modules.ar as ar_mod
@@ -131,11 +133,30 @@ _LP_BLUE_D, _LP_GREEN_D, _LP_YELLOW_D = '#5B8FD9', '#3E9B66', '#D9A93A'
131
 
132
 
133
  def _loopable_svg(px):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
134
  return (f"<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 32 32' width='{px}' "
135
  f"height='{px}' fill='none' role='img' aria-label='Loopable'>"
136
- f"<circle cx='12.5' cy='12.5' r='7.5' stroke='{_LP_BLUE_D}' stroke-width='2'/>"
137
- f"<circle cx='19.5' cy='19.5' r='7.5' stroke='{_LP_GREEN_D}' stroke-width='2'/>"
138
- f"<circle cx='16' cy='16' r='2' fill='{_LP_YELLOW_D}'/>"
139
  "</svg>")
140
 
141
 
@@ -170,6 +191,38 @@ _CSS = """
170
  SEMANTICS: blue = interactive / selected / active nav. green = positive. red = negative +
171
  destructive. yellow = attention / brand accent rules. */
172
  --lp-ink:#202433; --lp-muted:#6B7280; --lp-line:#E6E9EF;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
173
  --lp-blue:#9DBFF2; --lp-blue-t:#EDF3FD; --lp-blue-d:#5B8FD9;
174
  --lp-yellow:#F5D989; --lp-yellow-t:#FBF4E0; --lp-yellow-d:#D9A93A;
175
  --lp-red:#F0A8A0; --lp-red-t:#FCEEEC; --lp-red-d:#C4564A;
@@ -206,12 +259,21 @@ html, body, .stApp, [class*="css"]{ font-family:__FONT__; color:var(--ink);
206
  section[data-testid="stMain"]:has(.aios-grid-host-marker) .block-container{
207
  width:100%; max-width:none; padding-left:1rem; padding-right:1rem;
208
  /* owner item 10 (2026-07-27): no page title on the table pages β€” reclaim the dashboard
209
- paddings so the grid starts at the top and runs the viewport. */
210
- padding-top:.65rem; padding-bottom:.4rem;
 
 
 
211
  }
212
  section[data-testid="stMain"]:has(.aios-grid-host-marker) [data-testid="stVerticalBlock"]{
213
- gap:.5rem;
214
  }
 
 
 
 
 
 
215
  /* Full-height grid (owner item 10). The element-style height comes from the component's
216
  setFrameHeight handshake; this !important wins, and the React shell (100%-height + a
217
  ResizeObserver) follows the box it is given. Offset measured against the page chrome that
@@ -382,6 +444,19 @@ section[data-testid="stSidebar"] [data-testid="stBaseButton-headerNoPadding"]{
382
  [data-testid="stSidebar"] [data-testid="stBaseButton-headerNoPadding"]::after{
383
  content:''; width:26px; height:26px; display:block;
384
  background:url('__LOGO_URI__') center/contain no-repeat; }
 
 
 
 
 
 
 
 
 
 
 
 
 
385
  /* group micro-labels (benchmark: 10-11px upper, letterspaced, AIR BEFORE each group). The label's
386
  element container collapses to ~3px in Streamlit's flex column (text overflowed onto the widget
387
  below) β€” pin a real min-height on the container so the rhythm is honest. */
@@ -535,13 +610,18 @@ section[data-testid="stSidebar"][aria-expanded="false"] .st-key-navrail{ padding
535
  the container, not per-row, so it cannot break between rows β€” and the per-row hairlines are
536
  REMOVED inside a family, because the guide already groups them and two kinds of rule in the
537
  same 3 rows is exactly the busy-ness the owner asked to get rid of. */
538
- [data-testid="stSidebar"] [class*="st-key-navkids_"]:has(button){
539
- margin:0 0 2px 13px; padding-left:11px; border-left:1px solid var(--lp-line); }
540
- [data-testid="stSidebar"] [class*="st-key-navkids_"] [data-testid="stVerticalBlock"]{ gap:0; }
541
- [data-testid="stSidebar"] [class*="st-key-navkids_"] button[kind="secondary"]{
542
- min-height:30px; font-size:12.5px; color:var(--ink-2); border-bottom:none; }
543
- [data-testid="stSidebar"] [class*="st-key-navkids_"] button[kind="secondary"] p{
544
- font-size:12.5px; }
 
 
 
 
 
545
  /* ACTIVE page */
546
  [data-testid="stSidebar"] .st-key-navtree [class*="st-key-navon_"] button[kind="secondary"]{
547
  background:var(--lp-blue-t); color:var(--lp-ink); font-weight:600; }
@@ -586,15 +666,38 @@ section[data-testid="stSidebar"][aria-expanded="false"] .st-key-navrail{ padding
586
  border-top:1px solid #E3E8EE; padding-top:12px; padding-bottom:12px; margin-top:4px; }
587
  [data-testid="stSidebar"] .st-key-side_user_card [data-testid="stHorizontalBlock"]{
588
  flex-wrap:nowrap; align-items:center; gap:8px; }
589
- .avatar-mono{ width:30px; height:30px; border-radius:50%; background:var(--lp-yellow-t);
590
- color:#8A6D2A; font-weight:700; font-size:12.5px; display:flex; align-items:center;
591
- justify-content:center; letter-spacing:.02em; }
592
- .side-user-sub{ font-size:.72rem; color:#64748D; white-space:nowrap; }
593
  [data-testid="stSidebar"] .st-key-side_user_card .side-user{
594
  white-space:nowrap; overflow:hidden; text-overflow:ellipsis; }
 
 
 
 
 
595
  [data-testid="stSidebar"] .st-key-side_user_card button{
596
- border-bottom:none !important; min-height:30px; height:30px; padding:2px 4px;
597
- justify-content:center; }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
598
  [data-testid="stSidebar"] .st-key-side_user_card [data-testid="stElementContainer"]:has(button){
599
  margin-top:0; } /* the flat-list -0.45rem lift must not tilt the card row */
600
  [data-testid="stSidebar"] .st-key-side_user_card [data-testid="stElementContainer"]:has(.side-user){
@@ -700,10 +803,12 @@ ul[data-testid="stSelectboxVirtualDropdown"] li[aria-selected="true"]{
700
  font-size:.72rem; color:#64748D; }
701
  /* sidebar captions must not inherit the main-area muted gray (mud on navy) */
702
  [data-testid="stSidebar"] [data-testid="stCaptionContainer"] p{ color:#64748D!important; }
703
- .side-user{ font-weight:600; color:#1A2332; font-size:.92rem; line-height:1.3; }
704
- .side-role{ display:inline-block; margin-left:.4rem; padding:1px 7px; border-radius:999px;
705
- background:var(--lp-yellow-t); color:#8A6D2A; font-size:.62rem; font-weight:700;
706
- letter-spacing:.08em; text-transform:uppercase; vertical-align:.08em; }
 
 
707
 
708
  /* ---- AI assistant chat surface (ChatGPT/Claude-style centred reading column) ---- */
709
  section[data-testid="stMain"] [data-testid="stChatMessage"]{
@@ -827,13 +932,18 @@ div[data-testid="stDialog"] .kpi-val{ font-size:1.38rem; white-space:nowrap; }
827
  border:1px solid var(--line); border-top:3px solid var(--gold);
828
  border-radius:8px; padding:26px 28px 18px; box-shadow:var(--shadow-overlay); }
829
  .login-mark svg{ display:block; }
830
- /* The wordmark is THIN (owner item 7: "make the font for this logo thin"). 250 is a real
831
- weight here, not a rounded-down 300: the self-hosted Inter is the VARIABLE face (wght
832
- 100-900), so the browser interpolates it exactly rather than snapping to the nearest
833
- static cut. Thin type needs air β€” negative tracking, which suits tight headings, makes a
834
- 250 wordmark look broken, so this one goes POSITIVE. */
835
- .login-logo{ font-size:1.5rem; font-weight:250; color:var(--lp-ink); letter-spacing:.05em;
836
- line-height:1.15; margin-top:10px; }
 
 
 
 
 
837
  /* Sign-in-with-Google (W10 template): Google's button spec β€” white, bordered, the G mark.
838
  Rendered only when configured (core/auth_google.configured()). */
839
  .login-or{ text-align:center; color:var(--faint); font-size:.74rem; margin:.55rem 0 .3rem; }
@@ -889,10 +999,36 @@ section[data-testid="stMain"] [data-testid="stElementContainer"]:has(> div > .se
889
  """.replace("__FONT__", _FONT).replace("__LOGO_URI__", _loopable_data_uri())
890
 
891
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
892
  def inject_css():
893
  # One stylesheet: the design system (sidebar compaction, totals row and all component
894
  # styles live in _CSS itself β€” keeping a single source of truth for the tokens).
895
- st.markdown(_CSS, unsafe_allow_html=True)
 
 
 
 
 
 
896
 
897
 
898
  # ----------------------------------------------------------------- auth (per-user accounts)
@@ -926,8 +1062,8 @@ def gate():
926
  st.markdown("<div style='height:12vh'></div>", unsafe_allow_html=True)
927
  with st.container(border=True, key='logincard'):
928
  st.markdown(
929
- f"<div class='login-mark'>{_loopable_svg(44)}</div>"
930
- "<div class='login-logo'>Loopable</div>", unsafe_allow_html=True)
931
  st.markdown("<div style='height:12px'></div>", unsafe_allow_html=True)
932
  fails = st.session_state.get('login_fails', 0)
933
  # Wave-5 item 4 (owner: "it blips twice when I enter my user name"). A bare
@@ -2641,6 +2777,77 @@ def page_sales():
2641
 
2642
 
2643
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2644
  def page_agent():
2645
  tid = brand_team()
2646
  b = agent_rollup_c(tid, cur_doc_mode())
@@ -2663,6 +2870,18 @@ def page_agent():
2663
  if sel and sel != 'All agents (overview)':
2664
  _agent_body(sel, tid, in_drawer=False)
2665
  else:
 
 
 
 
 
 
 
 
 
 
 
 
2666
  # ---- overview scorecard + the "what changed" read (standard entity-module template) ----
2667
  rows = b['rollup']
2668
  real = [r for r in rows if r['agent'] != '(none)']
@@ -4914,15 +5133,80 @@ def _cl_delete(uname, name):
4914
  st.session_state.get('cl_session_lists', {}).pop(name, None)
4915
 
4916
 
4917
- def _cl_table_workspace(uname):
4918
- """Durable Airtable-style view/schema/overlay state, with an honest session fallback."""
 
 
 
 
 
 
 
 
 
 
 
 
 
4919
  if store.available():
4920
- return cl_mod.table_workspace(uname)
 
 
 
 
 
 
 
 
 
 
 
 
4921
  return st.session_state.setdefault(
4922
  'cl_table_workspace', {}).setdefault(
4923
  uname, {'views': {}, 'fields': {}, 'overlays': {}})
4924
 
4925
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4926
  def _measure_leaves(nodes):
4927
  """Every leaf of a filter tree that carries a date WINDOW β€” i.e. every measure condition.
4928
 
@@ -5153,6 +5437,28 @@ def _cl_pending_view(component_value):
5153
  return view.get('config') if isinstance(view, dict) else None
5154
 
5155
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5156
  def _cl_handle_one(event, uname, allowed_pids, fields, measure_keys=(),
5157
  resolved_ids=(), cohort_ids=(), measure_offer=(), admin=False,
5158
  scope_key='customer'):
@@ -5208,7 +5514,7 @@ def _cl_handle_one(event, uname, allowed_pids, fields, measure_keys=(),
5208
  field_by_key = {f['key']: f for f in fields}
5209
  valid_keys = set(field_by_key)
5210
  overlay_keys = {f['key'] for f in fields if f.get('source') == 'overlay'}
5211
- ws = _cl_table_workspace(uname)
5212
 
5213
  def _session_ready():
5214
  ws.setdefault('views', {})
@@ -5287,10 +5593,76 @@ def _cl_handle_one(event, uname, allowed_pids, fields, measure_keys=(),
5287
  config['frozenCount'] = max(1, min(8, int(cfg['frozenCount'])))
5288
  except (TypeError, ValueError):
5289
  pass
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5290
  view = {'id': view_id, 'name': name,
5291
  'kind': raw.get('kind') if raw.get('kind') in ('system', 'list', 'custom')
5292
  else 'custom',
5293
- 'locked': bool(raw.get('locked')) if view_id == 'all-customers' else False,
 
 
5294
  'note': str(raw.get('note') or '')[:2000],
5295
  'config': config}
5296
  if store.available():
@@ -5326,7 +5698,14 @@ def _cl_handle_one(event, uname, allowed_pids, fields, measure_keys=(),
5326
  view_id = str(event.get('viewId') or '')[:120]
5327
  if not view_id or view_id == 'all-customers':
5328
  return False
 
 
 
5329
  if store.available():
 
 
 
 
5330
  cl_mod.delete_table_view(uname, view_id)
5331
  else:
5332
  _session_ready()
@@ -5614,13 +5993,26 @@ def _cl_handle_one(event, uname, allowed_pids, fields, measure_keys=(),
5614
  return None
5615
  if any(f['id'] == fid for f in lst):
5616
  return None
5617
- lst.append({'id': fid, 'name': name, 'order': len(lst)})
 
 
 
 
5618
  elif kind == 'folder_rename':
5619
  name = str(event.get('name') or '').strip()[:_agf.MAX_FOLDER_NAME]
5620
  hit = next((f for f in lst if f['id'] == fid), None)
5621
  if not hit or not name:
5622
  return None
5623
  hit['name'] = name
 
 
 
 
 
 
 
 
 
5624
  elif kind == 'folder_delete':
5625
  if not any(f['id'] == fid for f in lst):
5626
  return None
@@ -5972,9 +6364,12 @@ def _table_grid(*, uname, team_id, pool_rows, grid_rows, stamp, defs=None,
5972
  "re-render from server state", NOT "handled" β€” see _cl_handle_one).
5973
  """
5974
  import aios_grid
5975
- ws = _cl_table_workspace(uname)
5976
  pool_pids = {r['pid'] for r in pool_rows}
5977
  grid_pids = {r['pid'] for r in grid_rows}
 
 
 
 
5978
  # The "Add to list" targets, the `Where [Cohort] ...` vocabulary AND the derived Cohorts
5979
  # column's values β€” ONE array, so what the picker offers, what the engine tests and what
5980
  # the cell says cannot disagree. visible() scopes membership to what this caller may see;
@@ -7806,6 +8201,54 @@ def page_analyst():
7806
 
7807
 
7808
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7809
  PAGE_FUNCS = {
7810
  'customer_data': page_customer_data,
7811
  'cohort': page_cohort,
@@ -8335,16 +8778,33 @@ def main():
8335
  # ARCHIVED modules (owner 2026-07-27) are invisible to EVERYONE β€” excluded from the
8336
  # nav unconditionally. A stored Settings>Modules selection can only NARROW the active
8337
  # set, never restore an archived module (supersedes the 2026-07-23 restore semantics).
 
 
 
 
 
8338
  nav = [m for m in registry.REGISTRY
8339
  if (_allowed_mods is None or m['key'] in _allowed_mods) and m.get('nav', True)
8340
- and not m.get('parent') and not m.get('archived')
8341
  and (_lib_enabled is None or m['key'] in _lib_enabled)]
8342
  if not nav:
8343
  # a stored selection that deselects everything β€” fall back to the user's full
8344
  # PERMITTED active set (fail-closed: never wider than allowed_modules).
8345
  nav = [m for m in registry.REGISTRY
8346
  if (_allowed_mods is None or m['key'] in _allowed_mods)
8347
- and m.get('nav', True) and not m.get('parent') and not m.get('archived')]
 
 
 
 
 
 
 
 
 
 
 
 
8348
  w_labels = [m['label'] for m in nav]
8349
  # Analyst-spawned dashboards (views.json) join the same dropdown. BU-scoped users
8350
  # don't see them: a saved query carries its own team_id, so a consolidated view would
@@ -8373,54 +8833,27 @@ def main():
8373
  cur = registry.BY_KEY.get(_fk, {}).get('label') if _fk else (
8374
  w_labels[0] if w_labels else '__settings__')
8375
  st.session_state['nav_cur'] = cur
8376
- # ── NAVIGATION: a FOLDER TREE, not a dropdown (owner items 10 + 22, wave 8) ──────
8377
- # The dropdown is deleted outright, and so is the "Workflows" micro-label above it
8378
- # ("the font is really ugly... remove it completely"). Two reasons beyond taste: a
8379
- # <select> hides every destination behind a click, and it could not express the one
8380
- # thing the owner asked for β€” that a module WITH sub-modules reads as a FOLDER, opening
8381
- # to reveal its children in place, with the active child visibly nested under it.
 
 
 
 
 
 
 
 
 
8382
  #
8383
- # Rules (all derived from the registry, so a new module needs no code here):
8384
- # Β· a module with visible children renders as a FOLDER row. Clicking it TOGGLES β€”
8385
- # it never navigates and never collapses the sidebar. A folder that also jumped
8386
- # somewhere would make the disclosure triangle a lie, and a folder that collapsed
8387
- # the sidebar would hide the children it just revealed.
8388
- # Β· the family's own page (when the parent row is itself a page) is listed as the
8389
- # FIRST child, so "open the folder" and "open the family's page" stay distinct acts.
8390
- # Β· a LEAF row navigates and then collapses the sidebar (owner item 17).
8391
- # Β· the folder holding the active page is force-opened, so the tree can never render
8392
- # in a state that hides where you are.
8393
- _fam_kids = {}
8394
- for _m in registry.REGISTRY:
8395
- _pk = _m.get('parent')
8396
- if _pk and not _m.get('archived') and may_open(_m['key']):
8397
- _fam_kids.setdefault(_pk, []).append(_m)
8398
-
8399
- # display-only rename (owner 2026-07-23): inside its own family the parent page is
8400
- # 'Dashboard', not the family noun repeated.
8401
- _SUB_LABEL = {'customers': 'Dashboard'}
8402
- _MOD_ICON = {'customers': ':material/dashboard:', 'customer_data': ':material/table:',
8403
- 'cohort': ':material/bookmarks:'}
8404
-
8405
- if 'nav_open' not in st.session_state:
8406
- st.session_state['nav_open'] = set()
8407
  _cur_label = st.session_state.get('nav_cur')
8408
- _cur_row = next((m for m in registry.REGISTRY if m.get('label') == _cur_label), None)
8409
- # Auto-open the active page's family ON ARRIVAL β€” and only on arrival. Doing this on
8410
- # every rerun (the first build) silently made the folder UNCLOSABLE: the toggle removed
8411
- # the key, the rerun put it straight back, and the chevron animated over a folder that
8412
- # never actually shut. Landing on a page should reveal where you are; after that the
8413
- # disclosure belongs to the user.
8414
- if _cur_row and st.session_state.get('_nav_opened_for') != _cur_label:
8415
- st.session_state['nav_open'].add(_cur_row.get('parent') or _cur_row['key'])
8416
- st.session_state['_nav_opened_for'] = _cur_label
8417
-
8418
- def _folder_toggle(k):
8419
- _o = st.session_state['nav_open']
8420
- if k in _o:
8421
- _o.remove(k)
8422
- else:
8423
- _o.add(k)
8424
 
8425
  def _nav_leaf(lbl, k, saved=False):
8426
  st.session_state['nav_cur'] = lbl
@@ -8437,58 +8870,62 @@ def main():
8437
  # DOM nudge after the sidebar is drawn.
8438
  st.session_state['_nav_collapse'] = True
8439
 
8440
- def _nav_row(label, key, active, icon=None, child=False, saved=False):
8441
  st.button(label, width='stretch', icon=icon,
8442
- key=('navon_' if active else 'navrow_') + ('sub_' if child else '') + key,
8443
  on_click=_nav_leaf, args=(label, key, saved))
8444
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8445
  with st.container(key='navtree'):
8446
  for _m in nav:
8447
- _kids = _fam_kids.get(_m['key'], [])
8448
- if not _kids:
8449
- _nav_row(_m['label'], _m['key'], _m['label'] == _cur_label,
8450
- icon=_MOD_ICON.get(_m['key']))
8451
- continue
8452
- _is_open = _m['key'] in st.session_state['nav_open']
8453
- _holds_cur = (_cur_row is not None
8454
- and (_cur_row.get('parent') or _cur_row['key']) == _m['key'])
8455
- st.button(
8456
- _m['label'], width='stretch',
8457
- icon=':material/keyboard_arrow_down:' if _is_open else ':material/chevron_right:',
8458
- key=('navfolon_' if _holds_cur else 'navfol_') + _m['key'],
8459
- on_click=_folder_toggle, args=(_m['key'],))
8460
- # ⚠ The container is entered UNCONDITIONALLY and left EMPTY when closed β€”
8461
- # never `if _is_open:` around the container itself. Streamlit replaces elements
8462
- # POSITIONALLY, so a sometimes-there container shifts the index of everything
8463
- # after it and the previous run's DOM is not replaced but ORPHANED. The retired
8464
- # sub-nav carried this exact warning ("a sometimes-there sub-nav shifts every
8465
- # element below it... then ghosts the whole account group") and the first build
8466
- # of this tree reintroduced it: closing a folder ghosted a stray `None` into the
8467
- # TOP OF THE MAIN PAGE, nowhere near the sidebar that caused it. Keep the
8468
- # container; vary only its CONTENTS.
8469
- with st.container(key='navkids_' + _m['key']):
8470
- if _is_open:
8471
- # the parent page itself leads its own family, then the children
8472
- _fam = ([_m] if not _m.get('group_only') else []) + _kids
8473
- for _c in _fam:
8474
- _nav_row(_SUB_LABEL.get(_c['key'], _c['label']), _c['key'],
8475
- _c['label'] == _cur_label,
8476
- icon=_MOD_ICON.get(_c['key']), child=True)
8477
- # Analyst-spawned dashboards get their own folder rather than a bare unlabelled
8478
- # list β€” with the "Workflows" caption gone, an ungrouped tail of rows would read as
8479
- # more modules.
8480
- if sd_labels:
8481
- _sd_open = '__saved__' in st.session_state['nav_open']
8482
- st.button(
8483
- 'Saved dashboards', width='stretch',
8484
- icon=':material/keyboard_arrow_down:' if _sd_open else ':material/chevron_right:',
8485
- key='navfol_saved', on_click=_folder_toggle, args=('__saved__',))
8486
- with st.container(key='navkids_saved'): # unconditional β€” see above
8487
- if _sd_open:
8488
- for _sl in sd_labels:
8489
- _nav_row(_sl, _sl[len(SAVED_PFX):], _sl == _cur_label,
8490
- icon=':material/insert_chart_outlined:',
8491
- child=True, saved=True)
8492
 
8493
  def _nav_sentinel(sent, param):
8494
  st.session_state['nav_cur'] = sent
@@ -8512,7 +8949,16 @@ def main():
8512
  # first granted module. Keyed on allowed_modules() (NOT the nav list, which fails OPEN when
8513
  # empty) so a mis-scoped user can never fall through to a page they may not open.
8514
  _am_guard = allowed_modules()
8515
- if (_am_guard is not None and not may_open(choice_key)
 
 
 
 
 
 
 
 
 
8516
  and choice_key not in ('settings', 'feedback')):
8517
  _fk = first_allowed_module() or 'sales'
8518
  if choice_key != _fk:
@@ -8539,55 +8985,62 @@ def main():
8539
  # Symbols (an icon font β€” not emojis), sized/muted via CSS.
8540
  if _PREWARM['running']:
8541
  _prewarm_indicator()
8542
- if st.button('Refresh data', width='stretch', icon=':material/refresh:',
8543
- help='Pull everything fresh from Odoo in the background β€” the '
8544
- 'dashboards keep serving the current data and switch to '
8545
- 'the new pull as each module completes. Days to pay is the one '
8546
- 'slow statistic (~5 min); it refreshes on its own thread and the '
8547
- 'column updates when it lands.'):
8548
- st.cache_data.clear()
8549
- custlist_pool.clear() # W1: the pool bundle moved off st.cache_data
8550
- prewarm_reset()
8551
- maybe_sync_store(force=True)
8552
- _refresh_dtp_async()
8553
- st.rerun()
8554
- st.button('Settings', width='stretch', icon=':material/settings:',
8555
- on_click=_nav_sentinel, args=('__settings__', 'settings'),
8556
- help='Your scope (Business Unit, Data basis) and which modules appear '
8557
- 'in your menu.')
8558
- if is_admin():
8559
- if st.button('Manage users', width='stretch', icon=':material/group:'):
8560
- users_dialog()
8561
- st.button('Feedback', width='stretch', icon=':material/feedback:',
8562
- on_click=_nav_sentinel, args=('__feedback__', 'feedback'),
8563
- help='Feature requests, feedback and bug reports β€” accumulated for staging '
8564
- 'into the build workflow.')
8565
- # USER CARD (owner 2026-07-23, Claude/ChatGPT bottom-card pattern): identity as
8566
- # its OWN section at the very bottom β€” monogram avatar + name/role + a quiet
8567
- # logout icon on the right.
8568
  u = current_user()
8569
  _uname = u.get('name') or u.get('username') or 'β€”'
8570
  _login = u.get('username', '')
8571
- _sub = ('' if (not _login or _login.lower() == str(_uname).lower())
8572
- else f"<div class='side-user-sub'>{_html.escape(_login)}</div>")
8573
- _initials = (''.join(w[0] for w in str(_uname).split()[:2]).upper()
8574
- or (_login[:1].upper() if _login else 'U'))
8575
  with st.container(key='side_user_card'):
8576
- _cc = st.columns([0.85, 4.0, 0.95], gap='small', vertical_alignment='center')
8577
- _cc[0].markdown(f"<div class='avatar-mono'>{_initials}</div>",
8578
- unsafe_allow_html=True)
8579
- _role = '<span class=side-role>admin</span>' if is_admin() else ''
8580
- _subbits = ' Β· '.join(x for x in
8581
- [_html.escape(_login) if _login and
8582
- _login.lower() != str(_uname).lower() else '', ]
8583
- if x)
8584
- _cc[1].markdown(f"<div class='side-user'>{_html.escape(_uname)}</div>"
8585
- f"<div class='side-user-sub'>{_subbits}"
8586
- f"{' ' if _subbits and _role else ''}{_role}</div>",
8587
- unsafe_allow_html=True)
8588
- with _cc[2]:
8589
- if st.button('', icon=':material/logout:', key='side_logout',
8590
- help='Log out'):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8591
  st.session_state.clear()
8592
  st.rerun()
8593
  # ---- I17: fold the navigation away after a terminal nav choice ---------------------------
@@ -8599,6 +9052,10 @@ def main():
8599
  # ONE-SHOT: the flag is consumed here, so this never fires on an ordinary rerun (a nudge that
8600
  # ran every rerun would make the sidebar impossible to keep open). height=0 keeps the helper
8601
  # iframe out of the layout, and the guard means an already-collapsed sidebar is left alone.
 
 
 
 
8602
  if st.session_state.pop('_nav_collapse', False):
8603
  import streamlit.components.v1 as _components
8604
  _components.html(
@@ -8645,7 +9102,13 @@ def main():
8645
  _tel.error(f'coldwarm:{choice_key}', _ce) # page still surfaces the error
8646
  with body.container(): # atomically replaces the skeleton / prior page
8647
  try:
8648
- PAGE_FUNCS[choice_key]()
 
 
 
 
 
 
8649
  except Exception as _pe:
8650
  _tel.error(f'page:{choice_key}', _pe,
8651
  user=(current_user() or {}).get('username', ''))
 
27
  import core.periods as P
28
  import core.context as ctxlib
29
  import core.registry as registry
30
+ import core.user_tables as user_tables # wave-9 I8/C6: blank databases the user creates
31
  import core.users as users
32
  import core.store as store
33
+ import core.table_store as _tstore # wave-9 I17: the shared-view authorisation predicates
34
  import modules.sales as sales_mod
35
  import modules.inventory as inv_mod
36
  import modules.ar as ar_mod
 
133
 
134
 
135
  def _loopable_svg(px):
136
+ """THE MARK β€” two CONCENTRIC rings (wave-9 I4). ONE geometry source for every size.
137
+
138
+ The owner's brief: *"simple, symmetrical vertically and horizontally... our name is Loop,
139
+ maybe one circle inside another, but make sure the two circles are very close so from far
140
+ away it looks like a circle"* β€” Airtable / Tableau / Slack as the register.
141
+
142
+ The wave-8 mark was two circles offset on the DIAGONAL. That reads as an interlock, and it
143
+ is symmetric about neither axis β€” the owner was right to call it out. Concentric rings share
144
+ one centre, so double-axis symmetry is true BY CONSTRUCTION rather than by measurement,
145
+ which also means the mark cannot drift out of alignment the way the diagonal pair could.
146
+
147
+ THE GAP IS THE WHOLE IDEA. Outer inner-edge sits at 11.4-1.2 = 10.2; inner outer-edge at
148
+ 7.8+1.2 = 9.0 β€” a 1.2-unit channel in a 32-unit box. That renders ~1.0px at the 26px rail
149
+ size and ~1.65px on the 44px login card (legible as two rings), and ~0.6px in a 16px
150
+ favicon, where it closes up and reads as a single thick ring. That is not a defect at small
151
+ sizes; it is precisely the "from far away it looks like a circle" the brief asked for.
152
+
153
+ Two rings, two colours, no third element: 'simple' was a constraint, and the yellow stays in
154
+ the palette rather than being crowded into a 32-unit box.
155
+ """
156
  return (f"<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 32 32' width='{px}' "
157
  f"height='{px}' fill='none' role='img' aria-label='Loopable'>"
158
+ f"<circle cx='16' cy='16' r='11.4' stroke='{_LP_BLUE_D}' stroke-width='2.4'/>"
159
+ f"<circle cx='16' cy='16' r='7.8' stroke='{_LP_GREEN_D}' stroke-width='2.4'/>"
 
160
  "</svg>")
161
 
162
 
 
191
  SEMANTICS: blue = interactive / selected / active nav. green = positive. red = negative +
192
  destructive. yellow = attention / brand accent rules. */
193
  --lp-ink:#202433; --lp-muted:#6B7280; --lp-line:#E6E9EF;
194
+
195
+ /* ---- TYPE SCALE + RADII (wave-9 I9/I20, contract C1) -------------------------------------
196
+ THE MEASURED REASON THIS EXISTS. Before this wave `_CSS` carried **32 distinct font-size
197
+ values** and **6 distinct border-radius values** (a 7th lived in .streamlit/config.toml).
198
+ There was no scale β€” there were 32 one-off decisions β€” and that, not the palette, is why
199
+ the owner reported the app reading "rigid and daunting". The fix is a CONSOLIDATION, not a
200
+ repaint: 32 sizes -> 7 steps, 7 radii -> 4.
201
+
202
+ The owner's brief was "fonts slightly larger and not too sharp... friendly and warm, but
203
+ professional" (Omni Analytics / Airtable as the reference). So: the body step moves up to
204
+ 14px from a ~12.8px norm, the default corner softens 4px -> 6px, and line-height is
205
+ tokenised at all β€” warmth is carried by leading at least as much as by size, and it was
206
+ the one axis nothing controlled.
207
+
208
+ ⚠ A NEW RULE MUST USE THESE TOKENS. A literal `font-size:.82rem` is how the last 32 got
209
+ here; the full rationale + component recipes live in wiki/research/design-schema.md. */
210
+ --lp-fs-3xs:.6875rem; /* 11px micro labels, badges */
211
+ --lp-fs-2xs:.75rem; /* 12px captions, table meta */
212
+ --lp-fs-xs:.8125rem; /* 13px dense table text */
213
+ --lp-fs-sm:.875rem; /* 14px BODY DEFAULT (the "slightly larger") */
214
+ --lp-fs-md:1rem; /* 16px section headers */
215
+ --lp-fs-lg:1.25rem; /* 20px page titles */
216
+ --lp-fs-xl:1.75rem; /* 28px KPI values */
217
+ --lp-lh:1.5; --lp-lh-tight:1.3;
218
+ --lp-r-sm:4px; /* inputs, small chips */
219
+ --lp-r-md:6px; /* buttons, cards β€” the NEW default (was 4) */
220
+ --lp-r-lg:10px; /* dialogs, panels */
221
+ --lp-r-pill:999px;
222
+ /* Surfaces nudged off cool-blue toward warm-neutral. The identity (the blues) is untouched:
223
+ "warm" here is a few points of hue on the GREYS, not a new palette. */
224
+ --lp-surface:#FFFFFF; --lp-surface-2:#F7F7F6;
225
+
226
  --lp-blue:#9DBFF2; --lp-blue-t:#EDF3FD; --lp-blue-d:#5B8FD9;
227
  --lp-yellow:#F5D989; --lp-yellow-t:#FBF4E0; --lp-yellow-d:#D9A93A;
228
  --lp-red:#F0A8A0; --lp-red-t:#FCEEEC; --lp-red-d:#C4564A;
 
259
  section[data-testid="stMain"]:has(.aios-grid-host-marker) .block-container{
260
  width:100%; max-width:none; padding-left:1rem; padding-right:1rem;
261
  /* owner item 10 (2026-07-27): no page title on the table pages β€” reclaim the dashboard
262
+ paddings so the grid starts at the top and runs the viewport.
263
+ wave-9 I6: reclaimed again. C7's measurement put 34.4px of chrome above the toolbar with
264
+ the CLIENT contributing exactly 0.0 β€” `.cg-toolbar` already starts at the iframe's own top
265
+ edge β€” so every recoverable pixel is on this side and this is where the item lands. */
266
+ padding-top:.2rem; padding-bottom:.4rem;
267
  }
268
  section[data-testid="stMain"]:has(.aios-grid-host-marker) [data-testid="stVerticalBlock"]{
269
+ gap:.2rem;
270
  }
271
+ /* wave-9 I6: the first element in the column still carried a top margin from the flat-list
272
+ rhythm, which on a table page is dead space above a work surface rather than air between
273
+ two cards. Zeroed for the grid host only β€” the dashboards keep their rhythm. */
274
+ section[data-testid="stMain"]:has(.aios-grid-host-marker)
275
+ [data-testid="stVerticalBlock"] > [data-testid="stElementContainer"]:first-child{
276
+ margin-top:0 !important; }
277
  /* Full-height grid (owner item 10). The element-style height comes from the component's
278
  setFrameHeight handshake; this !important wins, and the React shell (100%-height + a
279
  ResizeObserver) follows the box it is given. Offset measured against the page chrome that
 
444
  [data-testid="stSidebar"] [data-testid="stBaseButton-headerNoPadding"]::after{
445
  content:''; width:26px; height:26px; display:block;
446
  background:url('__LOGO_URI__') center/contain no-repeat; }
447
+ /* ---- wave-9 I5: the WORDMARK beside the mark in the nav -----------------------------------
448
+ Owner: "where we have the logo in our navigation, the full name of our company should appear
449
+ to its right." It hangs off the HEADER, not the logo button, on purpose: the button is the
450
+ collapse control (wave-8 I17 β€” one element paints the mark in both states), and putting text
451
+ inside it would make the wordmark part of the click target and stretch the 34px square that
452
+ the rail's centre line is measured from. As a sibling ::after on the flex header it simply
453
+ sits next to the button and changes nothing about the geometry the brand gate asserts.
454
+ EXPANDED ONLY β€” a 56px rail has no room for it, and letting it overflow is the wave-7 clipped
455
+ -logo scar in a new costume (pointer-events:none so it can never eat the toggle's click). */
456
+ section[data-testid="stSidebar"][aria-expanded="true"] [data-testid="stSidebarHeader"]::after{
457
+ content:'Loopable'; align-self:center; margin-left:9px; pointer-events:none;
458
+ font-size:1.02rem; font-weight:600; letter-spacing:-.02em; color:var(--lp-ink);
459
+ line-height:1; white-space:nowrap; }
460
  /* group micro-labels (benchmark: 10-11px upper, letterspaced, AIR BEFORE each group). The label's
461
  element container collapses to ~3px in Streamlit's flex column (text overflowed onto the widget
462
  below) β€” pin a real min-height on the container so the rhythm is honest. */
 
610
  the container, not per-row, so it cannot break between rows β€” and the per-row hairlines are
611
  REMOVED inside a family, because the guide already groups them and two kinds of rule in the
612
  same 3 rows is exactly the busy-ness the owner asked to get rid of. */
613
+ /* ---- wave-9 I8: the SOURCE BADGE ------------------------------------------------------------
614
+ Owner: "to the right of it, we have a light grey subtle label 'Odoo'". The nav-family indent
615
+ rules that used to live here went with the folder tree.
616
+
617
+ The badge is a ::after whose `content` is emitted per module key from the registry (see the
618
+ `_badge_css` block in main()) β€” a Streamlit button label is plain text, so a second styled
619
+ token cannot live inside it. `margin-left:auto` pushes it to the row's right edge; it is
620
+ deliberately quiet (muted, small, tabular) because it is provenance, not a value: the eye
621
+ should find the module NAME first and read the source only when it is looking for it. */
622
+ [data-testid="stSidebar"] .st-key-navtree button[kind="secondary"]::after{
623
+ margin-left:auto; padding-left:10px; color:var(--lp-muted);
624
+ font-size:var(--lp-fs-3xs); font-weight:500; letter-spacing:.02em; opacity:.85; }
625
  /* ACTIVE page */
626
  [data-testid="stSidebar"] .st-key-navtree [class*="st-key-navon_"] button[kind="secondary"]{
627
  background:var(--lp-blue-t); color:var(--lp-ink); font-weight:600; }
 
666
  border-top:1px solid #E3E8EE; padding-top:12px; padding-bottom:12px; margin-top:4px; }
667
  [data-testid="stSidebar"] .st-key-side_user_card [data-testid="stHorizontalBlock"]{
668
  flex-wrap:nowrap; align-items:center; gap:8px; }
669
+ .side-user-sub{ font-size:var(--lp-fs-2xs); color:#64748D; white-space:nowrap; }
 
 
 
670
  [data-testid="stSidebar"] .st-key-side_user_card .side-user{
671
  white-space:nowrap; overflow:hidden; text-overflow:ellipsis; }
672
+ /* ---- I1 (wave 9): the account POPOVER trigger IS the user's name ---------------------------
673
+ Owner: remove the avatar circle and the ADMIN chip, "just remove it and align the name of the
674
+ user to the left". Streamlit centres a button label by default, so the left alignment has to
675
+ be asserted here β€” and on the INNER label, not just the button, or the icon and the text
676
+ centre as a pair inside a stretched button and the name still floats. */
677
  [data-testid="stSidebar"] .st-key-side_user_card button{
678
+ border-bottom:none !important; min-height:38px; height:38px; padding:2px 8px;
679
+ justify-content:flex-start !important; text-align:left; }
680
+ [data-testid="stSidebar"] .st-key-side_user_card button > div,
681
+ [data-testid="stSidebar"] .st-key-side_user_card button p{
682
+ justify-content:flex-start !important; text-align:left; width:100%;
683
+ font-weight:600; font-size:var(--lp-fs-sm); color:#1A2332; }
684
+ /* The account MENU itself: full-width quiet rows, left-aligned, no borders between them.
685
+ ⚠ The popover body renders in a PORTAL, OUTSIDE the sidebar β€” so every
686
+ `[data-testid="stSidebar"] …` rule in this stylesheet stops applying and Streamlit's own
687
+ centred default takes over. Hence the `button[kind="secondary"]` attribute selector: the same
688
+ specificity trick the nav tree uses above, for the same reason (win on specificity, not on
689
+ position in the file). Targeting the bare `button` was not enough β€” measured, not assumed. */
690
+ [data-testid="stPopoverBody"] button[kind="secondary"]{
691
+ justify-content:flex-start !important; text-align:left; border:none !important;
692
+ box-shadow:none !important; background:transparent; }
693
+ /* ⚠ The button reported justify-content:flex-start and STILL painted centred β€” because the
694
+ flex container that matters is the INNER content wrapper, not the button. Icon x-positions
695
+ varied with label length, which is the giveaway for centred content. Both levels need it. */
696
+ [data-testid="stPopoverBody"] button[kind="secondary"] > div{
697
+ justify-content:flex-start !important; width:100%; }
698
+ [data-testid="stPopoverBody"] button[kind="secondary"] p{
699
+ text-align:left !important; font-weight:450; font-size:var(--lp-fs-sm); }
700
+ [data-testid="stPopoverBody"] button[kind="secondary"]:hover{ background:var(--lp-blue-t); }
701
  [data-testid="stSidebar"] .st-key-side_user_card [data-testid="stElementContainer"]:has(button){
702
  margin-top:0; } /* the flat-list -0.45rem lift must not tilt the card row */
703
  [data-testid="stSidebar"] .st-key-side_user_card [data-testid="stElementContainer"]:has(.side-user){
 
803
  font-size:.72rem; color:#64748D; }
804
  /* sidebar captions must not inherit the main-area muted gray (mud on navy) */
805
  [data-testid="stSidebar"] [data-testid="stCaptionContainer"] p{ color:#64748D!important; }
806
+ .side-user{ font-weight:600; color:#1A2332; font-size:var(--lp-fs-sm); line-height:1.3; }
807
+ /* `.side-role` (the ADMIN chip) and `.avatar-mono` (the monogram circle) were DELETED with
808
+ wave-9 I1 β€” the owner asked for both to go. Their rules are removed rather than left orphaned
809
+ so the next reader does not resurrect a badge by re-adding one markup line and finding it
810
+ already styled. The .side-user rule stays: the collapsed-rail and drawer surfaces still use
811
+ it. */
812
 
813
  /* ---- AI assistant chat surface (ChatGPT/Claude-style centred reading column) ---- */
814
  section[data-testid="stMain"] [data-testid="stChatMessage"]{
 
932
  border:1px solid var(--line); border-top:3px solid var(--gold);
933
  border-radius:8px; padding:26px 28px 18px; box-shadow:var(--shadow-overlay); }
934
  .login-mark svg{ display:block; }
935
+ /* wave-9 I5: the wordmark sits to the RIGHT of the mark, not under it β€” on the login card and
936
+ in the nav alike, so the lockup is the same object in both places. */
937
+ .login-brand{ display:flex; align-items:center; gap:12px; }
938
+ .login-brand svg{ display:block; flex:0 0 auto; }
939
+ /* ⚠ SUPERSEDES wave-8 item 7 ("make the font for this logo thin", weight 250). Wave-9 I4 asks
940
+ for Airtable / Tableau / Slack as the register, and all three set their wordmark MEDIUM-to-
941
+ BOLD and TIGHT β€” a 250 weight reads as a startup splash, not a product mark. The self-hosted
942
+ Inter is the VARIABLE face (wght 100-900), so 600 is interpolated exactly. Tracking flips
943
+ with the weight for the same reason it was positive before: thin type needs air, set type
944
+ needs closing up. Recorded rather than silently reversed. */
945
+ .login-logo{ font-size:1.5rem; font-weight:600; color:var(--lp-ink); letter-spacing:-.02em;
946
+ line-height:1.15; }
947
  /* Sign-in-with-Google (W10 template): Google's button spec β€” white, bordered, the G mark.
948
  Rendered only when configured (core/auth_google.configured()). */
949
  .login-or{ text-align:center; color:var(--faint); font-size:.74rem; margin:.55rem 0 .3rem; }
 
999
  """.replace("__FONT__", _FONT).replace("__LOGO_URI__", _loopable_data_uri())
1000
 
1001
 
1002
+ def _source_badge_css():
1003
+ """wave-9 I8 β€” one `::after {content:'<source>'}` rule per module that HAS a source.
1004
+
1005
+ Generated from the registry rather than hand-written so a new connector needs no CSS, and
1006
+ emitted with the MAIN stylesheet rather than as its own `st.markdown` inside the sidebar:
1007
+ a `<style>` block rendered from within the sidebar never reached the DOM at all (measured β€”
1008
+ zero matching style tags), and folding it in here also spares the sidebar an element, which
1009
+ the positional-replacement law rewards. The registry is static, so nothing about this needs
1010
+ to be per-render.
1011
+ """
1012
+ out = []
1013
+ for m in registry.REGISTRY:
1014
+ src = str(m.get('source') or '').replace("'", '').replace('\\', '')
1015
+ if not src or m.get('archived'):
1016
+ continue
1017
+ out.append(f".st-key-navrow_{m['key']} button::after,"
1018
+ f".st-key-navon_{m['key']} button::after{{content:'{src}';}}")
1019
+ return ''.join(out)
1020
+
1021
+
1022
  def inject_css():
1023
  # One stylesheet: the design system (sidebar compaction, totals row and all component
1024
  # styles live in _CSS itself β€” keeping a single source of truth for the tokens).
1025
+ # ⚠ The badge rules are spliced INSIDE the existing <style> block, not appended as a SECOND
1026
+ # one. Streamlit's markdown sanitiser keeps only the first style element in a given string,
1027
+ # so `_CSS + '<style>…</style>'` silently dropped every rule β€” the generator was correct
1028
+ # (534 chars) and the DOM had zero matching tags. Measured twice before it was believed:
1029
+ # once as a separate st.markdown inside the sidebar, once appended here.
1030
+ st.markdown(_CSS.replace('</style>', _source_badge_css() + '</style>', 1),
1031
+ unsafe_allow_html=True)
1032
 
1033
 
1034
  # ----------------------------------------------------------------- auth (per-user accounts)
 
1062
  st.markdown("<div style='height:12vh'></div>", unsafe_allow_html=True)
1063
  with st.container(border=True, key='logincard'):
1064
  st.markdown(
1065
+ f"<div class='login-brand'>{_loopable_svg(44)}"
1066
+ "<span class='login-logo'>Loopable</span></div>", unsafe_allow_html=True)
1067
  st.markdown("<div style='height:12px'></div>", unsafe_allow_html=True)
1068
  fails = st.session_state.get('login_fails', 0)
1069
  # Wave-5 item 4 (owner: "it blips twice when I enter my user name"). A bare
 
2777
 
2778
 
2779
 
2780
+ # The agent question has TWO answers because Odoo holds two agent sources that name different
2781
+ # people ([[invoice-line-agent-commission]]). ONE three-way control, not two switches: the
2782
+ # source Γ— include-salespeople product has a fourth state ("invoice line, and count the
2783
+ # salespeople as agents") that is simply the wrong answer, and a user should not be able to
2784
+ # reach it by accident.
2785
+ _AGENT_SOURCES = ['Customer book (orders)', 'Invoice-line agents', 'Invoice line + salespeople']
2786
+
2787
+
2788
+ def _agent_invoice_view(tid, include_salespeople=False):
2789
+ """Per-line commission attribution β€” the basis that can answer 'what is NOT allocated'."""
2790
+ r = agent_mod.invoice_line_rollup(team_id=tid, include_salespeople=include_salespeople)
2791
+ if r.get('error'):
2792
+ st.warning('The invoice-line basis reads the tenant data store, which is not ready yet '
2793
+ f"β€” {r['error']}")
2794
+ return
2795
+ tot, alloc = r['total'], r['allocated']
2796
+ section('Agent allocation (invoice basis)',
2797
+ 'Posted customer-invoice PRODUCT lines, net of credit notes, for the YTD window '
2798
+ f"{r['window'][0]} to {r['window'][1]}. The agent comes from the commission record on "
2799
+ 'each invoice line, NOT from the customer record β€” so these totals will not match the '
2800
+ 'customer-book view, and neither is wrong. Basis: ' + r['basis'] + '.')
2801
+ kpi_row([
2802
+ {'label': 'Invoiced lines (net)', 'value': money(tot)},
2803
+ {'label': 'Allocated to an agent', 'value': money(alloc),
2804
+ 'delta': f"{pct(alloc / tot * 100 if tot else 0)} of invoiced", 'delta_color': 'off'},
2805
+ {'label': 'NOT allocated to an agent', 'value': money(r['unallocated']),
2806
+ 'delta': f"{pct(r['unallocated'] / tot * 100 if tot else 0)} of invoiced",
2807
+ 'delta_color': 'off'},
2808
+ {'label': 'No commission record at all', 'value': money(r['strict_none']),
2809
+ 'delta': 'excludes salesperson-covered', 'delta_color': 'off'},
2810
+ ])
2811
+ # Do NOT describe either figure as "the narrower reading": the salesperson bucket can be
2812
+ # NEGATIVE (a window where its credit notes exceed its sales), and then the no-commission
2813
+ # figure is the LARGER of the two. State the relationship, never the ordering.
2814
+ _sp = r['salesperson_only']
2815
+ insight_strip([
2816
+ 'Two defensible readings of "not allocated": <b>' + money(r['unallocated']) + '</b> counts '
2817
+ 'salesperson-covered business as unallocated; <b>' + money(r['strict_none']) + '</b> counts '
2818
+ 'only lines with no commission record at all. They differ by the '
2819
+ + money(_sp) + ' on lines carrying an internal salesperson rather than an agent'
2820
+ + (' β€” negative in this window, because that bucket\'s credit notes outweigh its sales, '
2821
+ 'which is why the second figure is the larger one.' if _sp < 0 else '.'),
2822
+ 'A customer is not all-or-nothing β€” many have some lines carrying an agent and some not, '
2823
+ 'so "sales BY agent-assigned customers" is a larger number than "sales ALLOCATED to an '
2824
+ 'agent". These cards report ALLOCATION.',
2825
+ ])
2826
+ section('Allocation split', 'The three buckets are mutually exclusive and sum to the invoiced '
2827
+ 'total β€” no line is counted twice and none is dropped.')
2828
+ # Share is emitted PRE-FORMATTED as text, not as a pct kind: show_df's TOTAL row AVERAGES
2829
+ # ratio columns, and averaging a partition's shares gives 33% instead of 100% β€” a wrong
2830
+ # number sitting under a table whose whole job is to show the parts summing to the whole.
2831
+ show_df([{'bucket': b['bucket'], 'revenue': b['revenue'],
2832
+ 'share': f"{(b['revenue'] / tot * 100) if tot else 0:.1f}%"}
2833
+ for b in r['allocation']],
2834
+ cols={'bucket': ('text', 'Bucket'), 'revenue': ('money', 'Invoiced $ (net)'),
2835
+ 'share': ('text', 'Share')})
2836
+ section('By name (invoice basis)',
2837
+ 'Revenue on lines carrying each name. '
2838
+ + ('Includes internal SALESPEOPLE as well as agents β€” the role is not distinguished '
2839
+ 'here, so do not read this as an agent league table.'
2840
+ if include_salespeople else
2841
+ 'Real agents only (res.partner.agent = True); internal salespeople are excluded '
2842
+ 'and their revenue sits in the unallocated bucket above.'))
2843
+ _list_export_row(r['by_agent'], [('agent', 'Name'), ('revenue', 'Invoiced $ (net)')],
2844
+ 'aginv', 'agent_invoice_basis')
2845
+ show_df([{'agent': x['agent'], 'revenue': x['revenue'],
2846
+ 'share': f"{(x['revenue'] / tot * 100) if tot else 0:.1f}%"} for x in r['by_agent']],
2847
+ cols={'agent': ('text', 'Name'), 'revenue': ('money', 'Invoiced $ (net)'),
2848
+ 'share': ('text', 'Share of invoiced')})
2849
+
2850
+
2851
  def page_agent():
2852
  tid = brand_team()
2853
  b = agent_rollup_c(tid, cur_doc_mode())
 
2870
  if sel and sel != 'All agents (overview)':
2871
  _agent_body(sel, tid, in_drawer=False)
2872
  else:
2873
+ _src = st.radio('Attribution basis', _AGENT_SOURCES, key='agent_src', horizontal=True,
2874
+ help='There are TWO agent sources in Odoo and they name different people. '
2875
+ 'CUSTOMER BOOK = the agent assigned on the customer record, over '
2876
+ 'confirmed sales orders (every other page uses this). INVOICE LINE = '
2877
+ 'the commission agent recorded on each invoice line β€” the only basis '
2878
+ 'that can say what is NOT allocated to an agent. The third option '
2879
+ 'folds in internal salespeople who carry commission lines but are '
2880
+ 'not agents; use it for payout questions, never for "our agents".')
2881
+ if _src != _AGENT_SOURCES[0]:
2882
+ _agent_invoice_view(tid, include_salespeople=(_src == _AGENT_SOURCES[2]))
2883
+ open_drawer_if_requested(tid)
2884
+ return
2885
  # ---- overview scorecard + the "what changed" read (standard entity-module template) ----
2886
  rows = b['rollup']
2887
  real = [r for r in rows if r['agent'] != '(none)']
 
5133
  st.session_state.get('cl_session_lists', {}).pop(name, None)
5134
 
5135
 
5136
+ def _cl_table_workspace(uname, allowed_pids=None, admin=None):
5137
+ """Durable Airtable-style view/schema/overlay state, with an honest session fallback.
5138
+
5139
+ Wave-9 I17: the returned `views` are this user's OWN views MERGED with every view SHARED
5140
+ with them. Own views win a same-id collision β€” a personal view is the user's own object and
5141
+ must never be shadowed by somebody else's share.
5142
+
5143
+ ⚠ `allowed_pids` is a SECURITY parameter, not a convenience. A shared view carries
5144
+ `memberPids`, which the writer's scope validated on the way IN β€” but the READER may have a
5145
+ narrower scope. Handing a Fisch-scoped user a view whose member list was built by a
5146
+ full-access user would leak the other BU's customers straight through the strict-isolation
5147
+ rule. So membership is re-filtered against the READER on the way OUT. Pass it wherever the
5148
+ result reaches a renderer or an event handler; omitting it drops memberPids entirely rather
5149
+ than trusting the stored list (fail-closed: a smaller view, never a wider one).
5150
+ """
5151
  if store.available():
5152
+ ws = cl_mod.table_workspace(uname)
5153
+ try:
5154
+ shared = cl_mod.shared_table_views(
5155
+ uname, is_admin() if admin is None else bool(admin))
5156
+ except Exception as _se:
5157
+ _tel.error('sharedviews:read', _se)
5158
+ shared = {}
5159
+ if shared:
5160
+ merged = dict(shared)
5161
+ merged.update(ws.get('views') or {}) # own views win the id collision
5162
+ ws['views'] = {vid: _cl_scope_view(v, uname, allowed_pids)
5163
+ for vid, v in merged.items()}
5164
+ return ws
5165
  return st.session_state.setdefault(
5166
  'cl_table_workspace', {}).setdefault(
5167
  uname, {'views': {}, 'fields': {}, 'overlays': {}})
5168
 
5169
 
5170
+ def _cl_scope_view(view, uname, allowed_pids):
5171
+ """Re-scope a view to the READER. A no-op for a view the reader created.
5172
+
5173
+ Two things travel inside a shared view that are SCOPE, not presentation:
5174
+ 1. `memberPids` β€” a customer list. Re-filtered against the reader's permitted pool.
5175
+ 2. cohort conditions β€” a cohort id is a permission handle owned by ONE user. For a reader
5176
+ who does not own it the leaf is UNANSWERABLE, and partial evaluation of an unanswerable
5177
+ leaf WIDENS `is none of` ([[cg-cohort-set-conditions]]) β€” i.e. it would show MORE rows,
5178
+ not fewer. So the whole filter tree is dropped for a foreign reader rather than
5179
+ evaluated with a hole in it. A visibly unfiltered shared view is recoverable; a
5180
+ silently widened one is a leak.
5181
+ """
5182
+ if not isinstance(view, dict) or view.get('createdBy') == uname:
5183
+ return view
5184
+ out = dict(view)
5185
+ cfg = dict(out.get('config') or {})
5186
+ mp = cfg.get('memberPids')
5187
+ if isinstance(mp, list):
5188
+ cfg['memberPids'] = ([p for p in mp if p in (allowed_pids or ())]
5189
+ if allowed_pids is not None else [])
5190
+ if _cl_tree_has_cohort(cfg.get('filters')):
5191
+ cfg['filters'] = []
5192
+ cfg['_scopedOut'] = 'cohort' # the client says so rather than pretending
5193
+ out['config'] = cfg
5194
+ return out
5195
+
5196
+
5197
+ def _cl_tree_has_cohort(node):
5198
+ """True when a filter tree references the Cohorts column anywhere (any depth)."""
5199
+ import aios_grid as _agc
5200
+ col = _agc.COHORT_COLUMN
5201
+ if isinstance(node, list):
5202
+ return any(_cl_tree_has_cohort(n) for n in node)
5203
+ if not isinstance(node, dict):
5204
+ return False
5205
+ if node.get('colId') == col or node.get('field') == col:
5206
+ return True
5207
+ return _cl_tree_has_cohort(node.get('conditions') or node.get('children'))
5208
+
5209
+
5210
  def _measure_leaves(nodes):
5211
  """Every leaf of a filter tree that carries a date WINDOW β€” i.e. every measure condition.
5212
 
 
5437
  return view.get('config') if isinstance(view, dict) else None
5438
 
5439
 
5440
+ def _cl_known_usernames():
5441
+ """Real account names, for C4's fail-closed `users` grant. None = "could not resolve".
5442
+
5443
+ None means DO NOT FILTER, deliberately. Returning an empty set on a transient registry
5444
+ error would silently collapse a user's stored 'specific users' grant to 'personal' on the
5445
+ very next autosave β€” destroying a setting because a read blipped. The grant is inert today
5446
+ anyway (views are per-user; nothing reads it to allow cross-user access), so the honest
5447
+ trade is: never invent access, never destroy a stored intent either.
5448
+ """
5449
+ try:
5450
+ reg = set(users.registry() or {})
5451
+ except Exception as _ue:
5452
+ _tel.error('viewperms:users', _ue)
5453
+ return None
5454
+ # ⚠ EMPTY IS "UNRESOLVED", NOT "NOBODY EXISTS". registry() returns {} rather than raising
5455
+ # when the user store cannot be read (a store blip logs `store:get:users` and hands back an
5456
+ # empty dict) β€” and a working app ALWAYS has at least the bootstrap admin. Treating {} as a
5457
+ # real answer would filter every name out of a stored grant and collapse it to 'personal'
5458
+ # on the next autosave. Caught by testing this in BARE mode with no store token.
5459
+ return reg or None
5460
+
5461
+
5462
  def _cl_handle_one(event, uname, allowed_pids, fields, measure_keys=(),
5463
  resolved_ids=(), cohort_ids=(), measure_offer=(), admin=False,
5464
  scope_key='customer'):
 
5514
  field_by_key = {f['key']: f for f in fields}
5515
  valid_keys = set(field_by_key)
5516
  overlay_keys = {f['key'] for f in fields if f.get('source') == 'overlay'}
5517
+ ws = _cl_table_workspace(uname, allowed_pids=allowed_pids, admin=admin)
5518
 
5519
  def _session_ready():
5520
  ws.setdefault('views', {})
 
5593
  config['frozenCount'] = max(1, min(8, int(cfg['frozenCount'])))
5594
  except (TypeError, ValueError):
5595
  pass
5596
+ # ── wave-9 C3 (lock) + C4 (permissions) ────────────────────────────────────────────
5597
+ # The PRIOR stored view decides both: whether this is a create or an update (C4's
5598
+ # default splits on exactly that) and who is allowed to change the lock (C3).
5599
+ prior = (ws.get('views') or {}).get(view_id) or {}
5600
+ # ⚠ THE SHARED WALL (wave-9 I17). `ws` is already visibility-filtered, so a view the
5601
+ # caller may not SEE reads as absent β€” which would look like a CREATE and let anybody
5602
+ # overwrite somebody else's shared view by guessing its id. Ask the store for the raw
5603
+ # record and refuse before deciding anything else. Fail-closed on both branches.
5604
+ _raw_shared = cl_mod.shared_table_view(view_id) if store.available() else None
5605
+ if _raw_shared is not None and not prior:
5606
+ return False # exists, not visible to this caller: refuse
5607
+ if _raw_shared is not None and not _tstore._may_edit(_raw_shared, uname, admin):
5608
+ return False # visible but not editable by this caller
5609
+ is_new = not prior
5610
+ # C4: the creator is HOST-STAMPED and never read from the browser β€” the same rule as
5611
+ # the field-level createdBy. An existing view keeps whoever made it.
5612
+ creator = prior.get('createdBy') or uname
5613
+ # Only the creator or an admin may change the PERMISSIONS themselves. A collaborator who
5614
+ # could rewrite them could grant themselves sole ownership of someone else's view, or
5615
+ # quietly widen a users-scoped view to everyone β€” privilege escalation by edit.
5616
+ if not is_new and not _tstore._may_administer(prior, uname, admin):
5617
+ raw = dict(raw)
5618
+ raw['permissions'] = prior.get('permissions')
5619
+ raw['locked'] = prior.get('locked')
5620
+ # ⚠ A SYSTEM VIEW IS PER-USER STATE AND MUST NEVER BE SHARED. Caught in the wave-9
5621
+ # integration pass, before deploy: `all-customers` is every user's DEFAULT view and it
5622
+ # carries their own column widths, visible fields and row height. C4's read-default
5623
+ # ('collaborative' when permissions are absent, so nobody's saved view is
5624
+ # retro-restricted) is right for a view somebody AUTHORED β€” but applied to the system
5625
+ # view it routed `all-customers` into the shared bucket, and the first user to resize a
5626
+ # column would have published their layout to everyone. Verified in the store:
5627
+ # shared_table_views() was returning ['all-customers'].
5628
+ # System views are pinned personal, so they stay in each user's own workspace exactly as
5629
+ # before this wave. `kind` is host-validated two lines below; read it here from `raw` and
5630
+ # treat the stored kind as authoritative for an existing view.
5631
+ _kind = (prior.get('kind') if not is_new
5632
+ else (raw.get('kind') if raw.get('kind') in ('system', 'list', 'custom')
5633
+ else 'custom'))
5634
+ if _kind == 'system' or view_id == 'all-customers':
5635
+ perms = {'edit': 'personal'}
5636
+ else:
5637
+ perms = _ag.clean_view_permissions(
5638
+ raw.get('permissions'),
5639
+ default='personal' if is_new else 'collaborative',
5640
+ known_users=_cl_known_usernames())
5641
+ # C3: only the creator or an admin may SET or CLEAR the lock; anyone else keeps whatever
5642
+ # is already stored. Enforced here rather than hidden in the client. This composes with
5643
+ # C4 and does not override it: C4 governs who may edit the CONTENTS, C3 who may freeze
5644
+ # the display MODE.
5645
+ # ⚠ Inert in practice TODAY β€” a user can only ever write their own per-user workspace,
5646
+ # so `uname == creator` always holds. Correct plumbing for shared views, not a live gate.
5647
+ may_lock = admin or uname == creator
5648
+ locked = bool(raw.get('locked')) if may_lock else bool(prior.get('locked'))
5649
+ # C3: the LOCK's actual job β€” a locked view's display mode is frozen, so a locked Kanban
5650
+ # stays Kanban. This half IS live per-user and is the part the owner asked for. Filters,
5651
+ # sorts and columns stay editable by design.
5652
+ if locked and not is_new:
5653
+ was = (prior.get('config') or {}).get('display')
5654
+ now = config.get('display')
5655
+ if (was or {}).get('mode') != (now or {}).get('mode'):
5656
+ if was:
5657
+ config['display'] = was
5658
+ else:
5659
+ config.pop('display', None)
5660
  view = {'id': view_id, 'name': name,
5661
  'kind': raw.get('kind') if raw.get('kind') in ('system', 'list', 'custom')
5662
  else 'custom',
5663
+ 'locked': locked,
5664
+ 'createdBy': creator,
5665
+ 'permissions': perms,
5666
  'note': str(raw.get('note') or '')[:2000],
5667
  'config': config}
5668
  if store.available():
 
5698
  view_id = str(event.get('viewId') or '')[:120]
5699
  if not view_id or view_id == 'all-customers':
5700
  return False
5701
+ # Wave-9 I17: deleting a SHARED view is narrower than editing it β€” creator or admin
5702
+ # only. A collaborator can change what a shared view shows; they cannot destroy
5703
+ # everybody else's copy of it, because there is only one copy.
5704
  if store.available():
5705
+ _raw_shared = cl_mod.shared_table_view(view_id)
5706
+ if _raw_shared is not None and not _tstore._may_administer(
5707
+ _raw_shared, uname, admin):
5708
+ return False
5709
  cl_mod.delete_table_view(uname, view_id)
5710
  else:
5711
  _session_ready()
 
5993
  return None
5994
  if any(f['id'] == fid for f in lst):
5995
  return None
5996
+ row = {'id': fid, 'name': name, 'order': len(lst)}
5997
+ icon = _agf.clean_folder_icon(event.get('icon')) # wave-9 I15 (C5)
5998
+ if icon:
5999
+ row['icon'] = icon
6000
+ lst.append(row)
6001
  elif kind == 'folder_rename':
6002
  name = str(event.get('name') or '').strip()[:_agf.MAX_FOLDER_NAME]
6003
  hit = next((f for f in lst if f['id'] == fid), None)
6004
  if not hit or not name:
6005
  return None
6006
  hit['name'] = name
6007
+ # wave-9 I15 (C5): the rename pane is also where the icon is changed. An event
6008
+ # that carries NO icon key leaves the existing one alone (a rename must not
6009
+ # silently strip a chosen icon); an explicit null clears it back to default.
6010
+ if 'icon' in event:
6011
+ icon = _agf.clean_folder_icon(event.get('icon'))
6012
+ if icon:
6013
+ hit['icon'] = icon
6014
+ else:
6015
+ hit.pop('icon', None)
6016
  elif kind == 'folder_delete':
6017
  if not any(f['id'] == fid for f in lst):
6018
  return None
 
6364
  "re-render from server state", NOT "handled" β€” see _cl_handle_one).
6365
  """
6366
  import aios_grid
 
6367
  pool_pids = {r['pid'] for r in pool_rows}
6368
  grid_pids = {r['pid'] for r in grid_rows}
6369
+ # Wave-9 I17: the POOL is this caller's permitted universe, so it is the correct scope to
6370
+ # re-filter a shared view's memberPids against β€” the same set the write path validates
6371
+ # against on the way in. Ordered after pool_pids for exactly that reason.
6372
+ ws = _cl_table_workspace(uname, allowed_pids=pool_pids)
6373
  # The "Add to list" targets, the `Where [Cohort] ...` vocabulary AND the derived Cohorts
6374
  # column's values β€” ONE array, so what the picker offers, what the engine tests and what
6375
  # the cell says cannot disagree. visible() scopes membership to what this caller may see;
 
8201
 
8202
 
8203
 
8204
+ def page_user_table(table_key):
8205
+ """A user-created blank database (wave-9 I8, contract C6-lite).
8206
+
8207
+ SCOPE, stated rather than implied: this is the HOST-side surface β€” the rows, and an "Add
8208
+ row" form above them. Typing a new row directly INTO the grid is the follow-on (it needs the
8209
+ client's glide append affordance), and the event wire it will use already exists and is
8210
+ already gated. What ships here is a database you can create, add rows to, and delete rows
8211
+ from β€” not the full Airtable surface the Customer table has.
8212
+ """
8213
+ defn = user_tables.get(table_key)
8214
+ if not defn:
8215
+ st.warning('That database no longer exists.')
8216
+ return
8217
+ fields = defn.get('fields') or []
8218
+ rows = defn.get('rows') or {}
8219
+ dash_header('', defn.get('label') or table_key,
8220
+ f"A blank database you created β€” {len(rows):,} "
8221
+ f"row{'' if len(rows) == 1 else 's'}, {len(fields)} "
8222
+ f"column{'' if len(fields) == 1 else 's'}. Not connected to any source, so "
8223
+ f"nothing here syncs and nothing here writes back to Odoo.")
8224
+ with st.form(f'ut_add_{table_key}', border=True):
8225
+ st.caption('Add a row')
8226
+ vals, cols = {}, st.columns(max(1, min(4, len(fields))))
8227
+ for i, f in enumerate(fields):
8228
+ vals[f['key']] = cols[i % len(cols)].text_input(
8229
+ f.get('label') or f['key'], key=f"ut_in_{table_key}_{f['key']}")
8230
+ if st.form_submit_button('Add row', type='primary'):
8231
+ if any(str(v).strip() for v in vals.values()):
8232
+ user_tables.add_row(table_key, vals,
8233
+ (current_user() or {}).get('username', ''))
8234
+ st.rerun()
8235
+ else:
8236
+ st.warning('Fill at least one column.')
8237
+ if not rows:
8238
+ st.info('No rows yet β€” add the first one above.')
8239
+ return
8240
+ import pandas as _pd_ut
8241
+ _df = _pd_ut.DataFrame(
8242
+ [{**{f.get('label') or f['key']: r.get(f['key'], '') for f in fields}, '_id': rid}
8243
+ for rid, r in sorted(rows.items(), key=lambda kv: int(kv[0]) if kv[0].isdigit() else 0)])
8244
+ show_df(_df.drop(columns=['_id']), width='stretch')
8245
+ with st.expander('Delete a row'):
8246
+ _pick = st.selectbox('Row', _df['_id'].tolist(), key=f'ut_del_{table_key}')
8247
+ if st.button('Delete', key=f'ut_delbtn_{table_key}'):
8248
+ user_tables.delete_row(table_key, _pick)
8249
+ st.rerun()
8250
+
8251
+
8252
  PAGE_FUNCS = {
8253
  'customer_data': page_customer_data,
8254
  'cohort': page_cohort,
 
8778
  # ARCHIVED modules (owner 2026-07-27) are invisible to EVERYONE β€” excluded from the
8779
  # nav unconditionally. A stored Settings>Modules selection can only NARROW the active
8780
  # set, never restore an archived module (supersedes the 2026-07-23 restore semantics).
8781
+ # ⚠ WAVE-9 I8 FLIPPED THE FILTER. It used to exclude `parent` rows (children lived
8782
+ # inside their folder) and INCLUDE the folder itself. With the tree gone the two swap:
8783
+ # children are top-level now, and a `group_only` key must be excluded because it names a
8784
+ # family rather than a destination β€” it has no PAGE_FUNCS entry, so rendering a row for
8785
+ # it would be a white screen one click away.
8786
  nav = [m for m in registry.REGISTRY
8787
  if (_allowed_mods is None or m['key'] in _allowed_mods) and m.get('nav', True)
8788
+ and not m.get('group_only') and not m.get('archived')
8789
  and (_lib_enabled is None or m['key'] in _lib_enabled)]
8790
  if not nav:
8791
  # a stored selection that deselects everything β€” fall back to the user's full
8792
  # PERMITTED active set (fail-closed: never wider than allowed_modules).
8793
  nav = [m for m in registry.REGISTRY
8794
  if (_allowed_mods is None or m['key'] in _allowed_mods)
8795
+ and m.get('nav', True) and not m.get('group_only')
8796
+ and not m.get('archived')]
8797
+ # wave-9 I8/C6: user-created blank databases join the SAME flat list. They are tenant
8798
+ # data, not registry modules, so they are merged here rather than appended to REGISTRY β€”
8799
+ # and they are never gated by allowed_modules, because a module grant cannot describe a
8800
+ # table that did not exist when the grant was written. Appended last so a new blank
8801
+ # table never reorders the connected databases above it.
8802
+ if store.available():
8803
+ try:
8804
+ nav = nav + user_tables.nav_entries(
8805
+ (current_user() or {}).get('username', ''), is_admin())
8806
+ except Exception as _ute:
8807
+ _tel.error('nav:user-tables', _ute)
8808
  w_labels = [m['label'] for m in nav]
8809
  # Analyst-spawned dashboards (views.json) join the same dropdown. BU-scoped users
8810
  # don't see them: a saved query carries its own team_id, so a consolidated view would
 
8833
  cur = registry.BY_KEY.get(_fk, {}).get('label') if _fk else (
8834
  w_labels[0] if w_labels else '__settings__')
8835
  st.session_state['nav_cur'] = cur
8836
+ # ── NAVIGATION: a FLAT LIST of DATABASES (owner item 8, wave 9) ──────────────────
8837
+ # The folder tree wave 8 built is DELETED. The owner's model changed, not their mind
8838
+ # about trees: *"I don't like the folder idea in our navigation, let's revert back to
8839
+ # each like Sales/Customer/Procurement. Now, the idea is to have multiple of these
8840
+ # piece of database from different sources."* So a nav entry is no longer a page inside
8841
+ # a family β€” it is a DATABASE, and what matters beside its name is where its data comes
8842
+ # from. A folder hierarchy actively hides that.
8843
+ #
8844
+ # Rules, all derived from the registry so a new module still needs no code here:
8845
+ # Β· every visible module renders as ONE flat row: the same database icon, its label,
8846
+ # and a quiet source badge ("Odoo") drawn from the registry's `source` field.
8847
+ # Β· `group_only` keys (the retired Customers dashboard) name a FAMILY, not a
8848
+ # destination β€” they have no PAGE_FUNCS entry, so they must never render a row.
8849
+ # Their children are now top-level, which is exactly what "revert to each" means.
8850
+ # Β· a row navigates and then folds the sidebar away (owner item 17, still true).
8851
  #
8852
+ # ⚠ The `navkids_*` containers, `nav_open`, `_folder_toggle` and the disclosure chevrons
8853
+ # are gone with the tree. The unconditional-container law they carried still applies to
8854
+ # anything added here later: a sometimes-there container shifts every element after it
8855
+ # and ORPHANS the previous run's DOM somewhere else on the page entirely.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8856
  _cur_label = st.session_state.get('nav_cur')
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8857
 
8858
  def _nav_leaf(lbl, k, saved=False):
8859
  st.session_state['nav_cur'] = lbl
 
8870
  # DOM nudge after the sidebar is drawn.
8871
  st.session_state['_nav_collapse'] = True
8872
 
8873
+ def _nav_row(label, key, active, icon=None, saved=False):
8874
  st.button(label, width='stretch', icon=icon,
8875
+ key=('navon_' if active else 'navrow_') + key,
8876
  on_click=_nav_leaf, args=(label, key, saved))
8877
 
8878
+ # The SOURCE BADGE rides CSS, not the label: a Streamlit button label is plain text, so
8879
+ # a second styled token cannot live inside it. One ::after per key, generated from the
8880
+ # registry β€” a module with no `source` (Metric Dictionary) simply gets no rule and no
8881
+ # badge, because it is not a database.
8882
+ # ---- I8: "+ New" β€” connect a source, or start a blank database --------------------
8883
+ # Owner: a "+ New" at the top of the navigation just below AI assistant, offering
8884
+ # either an Odoo connection ("we can only connect to Customer right now, and if we
8885
+ # already connected it, show it as already integrated so you can't add that again")
8886
+ # or a blank database the user can type rows into.
8887
+ with st.container(key='nav_new'):
8888
+ with st.popover('New', width='stretch', icon=':material/add:'):
8889
+ st.caption('Connect a source')
8890
+ # ⚠ The Odoo branch is deliberately HONEST about being finished, not disabled
8891
+ # for effect: Customer IS connected, so the row states that and refuses rather
8892
+ # than offering a second copy. [[connector-onboarding]] β€” Odoo has no delegated
8893
+ # OAuth, so a real second connector is a credential FORM, not a redirect; there
8894
+ # is nothing to prompt for until that lands, and a live-looking button that
8895
+ # cannot work is worse than a plain statement.
8896
+ st.button('Odoo Β· Customer', width='stretch', disabled=True,
8897
+ icon=':material/check_circle:', key='new_odoo_customer',
8898
+ help='Already integrated β€” this database is connected and syncing.')
8899
+ st.caption('Or create your own')
8900
+ _newname = st.text_input('Database name', key='new_blank_name',
8901
+ placeholder='e.g. Suppliers',
8902
+ label_visibility='collapsed')
8903
+ if st.button('Blank database', width='stretch',
8904
+ icon=':material/table:', key='new_blank_go'):
8905
+ _k = user_tables.create(
8906
+ _newname, (current_user() or {}).get('username', ''))
8907
+ if _k:
8908
+ st.session_state['nav_cur'] = (_newname or '').strip()
8909
+ _sync_page_param(_k)
8910
+ st.rerun()
8911
+ else:
8912
+ st.warning('Give it a name that is not already taken.')
8913
+
8914
+ # (the per-key `content` rules ride the main stylesheet β€” see _source_badge_css())
8915
  with st.container(key='navtree'):
8916
  for _m in nav:
8917
+ _nav_row(_m['label'], _m['key'], _m['label'] == _cur_label,
8918
+ # ONE icon for every database, by owner instruction ("for Customer/
8919
+ # Sales/Procurement, let's have the same icon database"). The
8920
+ # per-module icon map went with the tree: what distinguishes these
8921
+ # rows now is the SOURCE badge, not a decorative glyph each.
8922
+ icon=':material/database:')
8923
+ # Analyst-spawned dashboards join the same flat list, with a chart icon so they do
8924
+ # not read as another connected database.
8925
+ for _sl in sd_labels:
8926
+ _nav_row(_sl, _sl[len(SAVED_PFX):], _sl == _cur_label,
8927
+ icon=':material/insert_chart_outlined:', saved=True)
8928
+
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8929
 
8930
  def _nav_sentinel(sent, param):
8931
  st.session_state['nav_cur'] = sent
 
8949
  # first granted module. Keyed on allowed_modules() (NOT the nav list, which fails OPEN when
8950
  # empty) so a mis-scoped user can never fall through to a page they may not open.
8951
  _am_guard = allowed_modules()
8952
+ # wave-9 I8/C6: a user table is not a module, so allowed_modules cannot describe it β€”
8953
+ # it carries its OWN fail-closed rule (creator or admin). Checked FIRST so the module
8954
+ # gate below never sees a `ut_` key and never redirects a legitimate owner away from
8955
+ # their own table.
8956
+ if str(choice_key).startswith(user_tables.KEY_PREFIX):
8957
+ if not user_tables.may_open(choice_key,
8958
+ (current_user() or {}).get('username', ''), is_admin()):
8959
+ choice_key = first_allowed_module() or 'sales'
8960
+ st.session_state['nav_cur'] = registry.BY_KEY.get(choice_key, {}).get('label')
8961
+ elif (_am_guard is not None and not may_open(choice_key)
8962
  and choice_key not in ('settings', 'feedback')):
8963
  _fk = first_allowed_module() or 'sales'
8964
  if choice_key != _fk:
 
8985
  # Symbols (an icon font β€” not emojis), sized/muted via CSS.
8986
  if _PREWARM['running']:
8987
  _prewarm_indicator()
8988
+ # ---- I1: the ACCOUNT MENU (wave 9) ------------------------------------------------
8989
+ # Owner: "Refresh data / Settings / Manage users / Feedback should all be part of
8990
+ # when you click the account username at the bottom." So the four standalone rows
8991
+ # collapse into ONE popover whose trigger is the user's own name β€” the pattern
8992
+ # Claude and ChatGPT use, and the reason their bottom rail stays quiet.
8993
+ #
8994
+ # Also gone, by name: the monogram AVATAR CIRCLE and the "ADMIN" role chip. The
8995
+ # owner is looking at their own account; a badge telling them who they are is
8996
+ # furniture. The name left-aligns into the space both used to take.
8997
+ #
8998
+ # LOG OUT MOVES IN TOO. Not in the owner's list, but it is an account action and it
8999
+ # was the last thing left orphaned outside β€” leaving one lone icon beside the name
9000
+ # would have kept exactly the clutter this item removes. Called out here rather than
9001
+ # slipped in.
 
 
 
 
 
 
 
 
 
 
 
 
9002
  u = current_user()
9003
  _uname = u.get('name') or u.get('username') or 'β€”'
9004
  _login = u.get('username', '')
 
 
 
 
9005
  with st.container(key='side_user_card'):
9006
+ with st.popover(_uname, width='stretch', icon=':material/person:'):
9007
+ if st.button('Refresh data', width='stretch', icon=':material/refresh:',
9008
+ key='acct_refresh',
9009
+ help='Pull everything fresh from Odoo in the background β€” the '
9010
+ 'dashboards keep serving the current data and switch to '
9011
+ 'the new pull as each module completes. Days to pay is '
9012
+ 'the one slow statistic (~5 min); it refreshes on its own '
9013
+ 'thread and the column updates when it lands.'):
9014
+ st.cache_data.clear()
9015
+ custlist_pool.clear() # W1: the pool bundle moved off st.cache_data
9016
+ prewarm_reset()
9017
+ maybe_sync_store(force=True)
9018
+ _refresh_dtp_async()
9019
+ st.rerun()
9020
+ st.button('Settings', width='stretch', icon=':material/settings:',
9021
+ key='acct_settings',
9022
+ on_click=_nav_sentinel, args=('__settings__', 'settings'),
9023
+ help='Your scope (Business Unit, Data basis) and which modules '
9024
+ 'appear in your menu.')
9025
+ if is_admin():
9026
+ # ⚠ DEFERRED, not called here. st.dialog opened from inside a TRANSIENT
9027
+ # container never renders β€” the same law that put the entity drawers
9028
+ # outside the body slot and outside st.spinner. A popover is exactly
9029
+ # such a container, so the click only raises a flag and main() opens the
9030
+ # dialog at the top level after the sidebar is drawn.
9031
+ st.button('Manage users', width='stretch', icon=':material/group:',
9032
+ key='acct_users',
9033
+ on_click=lambda: st.session_state.__setitem__(
9034
+ '_open_users_dialog', True))
9035
+ st.button('Feedback', width='stretch', icon=':material/feedback:',
9036
+ key='acct_feedback',
9037
+ on_click=_nav_sentinel, args=('__feedback__', 'feedback'),
9038
+ help='Feature requests, feedback and bug reports β€” accumulated '
9039
+ 'for staging into the build workflow.')
9040
+ if _login and _login.lower() != str(_uname).lower():
9041
+ st.caption(f'Signed in as {_login}')
9042
+ if st.button('Log out', width='stretch', icon=':material/logout:',
9043
+ key='acct_logout'):
9044
  st.session_state.clear()
9045
  st.rerun()
9046
  # ---- I17: fold the navigation away after a terminal nav choice ---------------------------
 
9052
  # ONE-SHOT: the flag is consumed here, so this never fires on an ordinary rerun (a nudge that
9053
  # ran every rerun would make the sidebar impossible to keep open). height=0 keeps the helper
9054
  # iframe out of the layout, and the guard means an already-collapsed sidebar is left alone.
9055
+ # I1: the account popover's "Manage users" only raised a flag β€” a dialog opened inside a
9056
+ # transient container never renders. Open it HERE, at the top level, after the sidebar.
9057
+ if st.session_state.pop('_open_users_dialog', False):
9058
+ users_dialog()
9059
  if st.session_state.pop('_nav_collapse', False):
9060
  import streamlit.components.v1 as _components
9061
  _components.html(
 
9102
  _tel.error(f'coldwarm:{choice_key}', _ce) # page still surfaces the error
9103
  with body.container(): # atomically replaces the skeleton / prior page
9104
  try:
9105
+ # wave-9 I8/C6: a user-created table has no PAGE_FUNCS entry (it did not exist when
9106
+ # the map was written), so it dispatches by KEY PREFIX. Checked before the map so a
9107
+ # `ut_` key can never reach a KeyError, which is a white screen.
9108
+ if str(choice_key).startswith(user_tables.KEY_PREFIX):
9109
+ page_user_table(choice_key)
9110
+ else:
9111
+ PAGE_FUNCS[choice_key]()
9112
  except Exception as _pe:
9113
  _tel.error(f'page:{choice_key}', _pe,
9114
  user=(current_user() or {}).get('username', ''))
core/registry.py CHANGED
@@ -24,8 +24,17 @@ Fields:
24
  pricing, inventory, vendor, warehouse, returns, outreach, complexity, health.
25
  note one-line scope note shown in the UI / docs
26
  """
 
 
 
 
 
 
 
 
 
27
  REGISTRY = [
28
- {'key': 'sales', 'label': 'Sales', 'brand': True, 'hq': False, 'validate': True,
29
  'note': 'Revenue, YoY, seasonality, reps, customers, SKUs β€” by BU.'},
30
  # ARCHIVED AS A PAGE (owner item 14, wave 8): "archive the current form of the Customer
31
  # dashboard completely, i want to redesign it, exactly with the backend we have". So the
@@ -49,7 +58,7 @@ REGISTRY = [
49
  # myday->customer_list was done. The STORE keys are deliberately NOT renamed:
50
  # 'customer_table_workspace' and 'customer_lists' hold real user data, and renaming them
51
  # would orphan every saved view. Label-only changes need none of that machinery.
52
- {'key': 'customer_data', 'label': 'Customer', 'brand': True, 'hq': False, 'validate': False, 'parent': 'customers',
53
  'note': 'Build, filter and save customer lists: the whole scoped book with per-customer '
54
  'metrics; saved lists are visible, editable formulas (Call list and Win-back ship '
55
  'as templates) plus hand-picked members. Sub-module of Customers (owner nav redesign 2026-07-23; replaced My Day).'},
@@ -58,11 +67,11 @@ REGISTRY = [
58
  # data moves, a cohort only changes when a person edits it. validate:False because
59
  # there is no Odoo aggregate to reconcile a hand-picked list against; its metrics are
60
  # the customers module's, already validated there.
61
- {'key': 'cohort', 'label': 'Cohort', 'brand': True, 'hq': False, 'validate': False, 'parent': 'customers',
62
  'note': 'Hand-curated, unchanging customer lists. Same grid as Data (filter, sort, '
63
  'group, custom columns) but the SET is fixed: it changes only when someone '
64
  'adds or removes a member. Populated from a view via ... > Add to list.'},
65
- {'key': 'agent', 'label': 'Agents', 'brand': True, 'hq': False, 'validate': True,
66
  'note': 'Per-agent book: sales (custom dates), returns, top SKUs, full customer list incl. inactive. Returns consolidated.'},
67
  {'key': 'products', 'label': 'SKU', 'brand': True, 'hq': False, 'validate': True, 'archived': True,
68
  'note': 'SKU movers, zombies, velocity, coverage, drawers β€” by BU (sales-derived).'},
@@ -77,13 +86,14 @@ REGISTRY = [
77
  'note': 'Operating-model management income statements (FFS/RI/GD/BU-M) reproduced from raw Odoo, Sep-2024+.'},
78
  {'key': 'inventory', 'label': 'Inventory', 'brand': False, 'hq': False, 'validate': True, 'archived': True,
79
  'note': 'On-hand stock is physically consolidated (shared warehouse); not DBA-split.'},
80
- {'key': 'procurement', 'label': 'Procurement', 'brand': False, 'hq': False, 'validate': True,
81
  'note': 'Biweekly buy list: lead-time-cover trigger, 8-month demand baseline + YTD trend, by supplier.'},
82
  {'key': 'vendor', 'label': 'Vendors', 'brand': False, 'hq': False, 'validate': False, 'archived': True,
83
  'note': 'Vendor master data + the SKUs each supplies; multiple-vendor / cheapest-price view.'},
84
  {'key': 'warehouse', 'label': 'Warehouse', 'brand': False, 'hq': False, 'validate': True, 'archived': True,
85
  'note': 'Movement & efficiency: on-time ship, Pick-Pack-Ship cycle times, throughput, backlog age, shrinkage. Physical ops (consolidated).'},
86
  {'key': 'ar', 'label': 'Collections', 'brand': False, 'hq': True, 'validate': True,
 
87
  'note': 'Receivables are company-level (consolidated).'},
88
  {'key': 'returns', 'label': 'Returns', 'brand': False, 'hq': True, 'validate': True, 'archived': True,
89
  'note': 'Credit-note lens: refund concentration by SKU (quality) and customer (behavior). Company-level.'},
 
24
  pricing, inventory, vendor, warehouse, returns, outreach, complexity, health.
25
  note one-line scope note shown in the UI / docs
26
  """
27
+ # WAVE-9 I8 β€” `'source'`: which connected system a module's data comes from.
28
+ #
29
+ # The owner's model: every nav entry is "a piece of database from a source", so the nav shows the
30
+ # source beside the name ("Sales Β· Odoo"). It is a REGISTRY FACT rather than a string in the nav
31
+ # code precisely so the nav needs no edit when a second connector lands β€” a user-created blank
32
+ # table simply carries a different source, and a module with no `source` (Metric Dictionary,
33
+ # Settings, the Analyst) renders no badge because it is not a database at all.
34
+ # See [[connector-onboarding]]: the plug-in seam is datastore.py, and Odoo has no delegated
35
+ # OAuth, so the "+ New" connect flow is the credential-form shape, not an OAuth redirect.
36
  REGISTRY = [
37
+ {'key': 'sales', 'label': 'Sales', 'brand': True, 'hq': False, 'validate': True, 'source': 'Odoo',
38
  'note': 'Revenue, YoY, seasonality, reps, customers, SKUs β€” by BU.'},
39
  # ARCHIVED AS A PAGE (owner item 14, wave 8): "archive the current form of the Customer
40
  # dashboard completely, i want to redesign it, exactly with the backend we have". So the
 
58
  # myday->customer_list was done. The STORE keys are deliberately NOT renamed:
59
  # 'customer_table_workspace' and 'customer_lists' hold real user data, and renaming them
60
  # would orphan every saved view. Label-only changes need none of that machinery.
61
+ {'key': 'customer_data', 'label': 'Customer', 'brand': True, 'hq': False, 'validate': False, 'source': 'Odoo', 'parent': 'customers',
62
  'note': 'Build, filter and save customer lists: the whole scoped book with per-customer '
63
  'metrics; saved lists are visible, editable formulas (Call list and Win-back ship '
64
  'as templates) plus hand-picked members. Sub-module of Customers (owner nav redesign 2026-07-23; replaced My Day).'},
 
67
  # data moves, a cohort only changes when a person edits it. validate:False because
68
  # there is no Odoo aggregate to reconcile a hand-picked list against; its metrics are
69
  # the customers module's, already validated there.
70
+ {'key': 'cohort', 'label': 'Cohort', 'brand': True, 'hq': False, 'validate': False, 'source': 'Odoo', 'parent': 'customers',
71
  'note': 'Hand-curated, unchanging customer lists. Same grid as Data (filter, sort, '
72
  'group, custom columns) but the SET is fixed: it changes only when someone '
73
  'adds or removes a member. Populated from a view via ... > Add to list.'},
74
+ {'key': 'agent', 'label': 'Agents', 'brand': True, 'hq': False, 'validate': True, 'source': 'Odoo',
75
  'note': 'Per-agent book: sales (custom dates), returns, top SKUs, full customer list incl. inactive. Returns consolidated.'},
76
  {'key': 'products', 'label': 'SKU', 'brand': True, 'hq': False, 'validate': True, 'archived': True,
77
  'note': 'SKU movers, zombies, velocity, coverage, drawers β€” by BU (sales-derived).'},
 
86
  'note': 'Operating-model management income statements (FFS/RI/GD/BU-M) reproduced from raw Odoo, Sep-2024+.'},
87
  {'key': 'inventory', 'label': 'Inventory', 'brand': False, 'hq': False, 'validate': True, 'archived': True,
88
  'note': 'On-hand stock is physically consolidated (shared warehouse); not DBA-split.'},
89
+ {'key': 'procurement', 'label': 'Procurement', 'brand': False, 'hq': False, 'validate': True, 'source': 'Odoo',
90
  'note': 'Biweekly buy list: lead-time-cover trigger, 8-month demand baseline + YTD trend, by supplier.'},
91
  {'key': 'vendor', 'label': 'Vendors', 'brand': False, 'hq': False, 'validate': False, 'archived': True,
92
  'note': 'Vendor master data + the SKUs each supplies; multiple-vendor / cheapest-price view.'},
93
  {'key': 'warehouse', 'label': 'Warehouse', 'brand': False, 'hq': False, 'validate': True, 'archived': True,
94
  'note': 'Movement & efficiency: on-time ship, Pick-Pack-Ship cycle times, throughput, backlog age, shrinkage. Physical ops (consolidated).'},
95
  {'key': 'ar', 'label': 'Collections', 'brand': False, 'hq': True, 'validate': True,
96
+ 'source': 'Odoo',
97
  'note': 'Receivables are company-level (consolidated).'},
98
  {'key': 'returns', 'label': 'Returns', 'brand': False, 'hq': True, 'validate': True, 'archived': True,
99
  'note': 'Credit-note lens: refund concentration by SKU (quality) and customer (behavior). Company-level.'},
core/table_store.py CHANGED
@@ -17,6 +17,60 @@ A LIST (membership/formula semantics) is deliberately a different store from a V
17
  """
18
  import core.store as store
19
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
20
 
21
  class TableStore:
22
  """The six store operations for one table object's workspace, closed over its store key."""
@@ -76,16 +130,77 @@ class TableStore:
76
  ws['itemFolders'] = dict(item_folders or {})
77
  self._update(username, _set)
78
 
79
- def save_view(self, username, view):
80
- """Upsert a serializable SavedView by stable id."""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
81
  view_id = str((view or {}).get('id') or '').strip()
82
  if not view_id:
83
  raise ValueError('view id is required')
84
- self._update(username, lambda ws: ws['views'].__setitem__(view_id, dict(view)))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
85
 
86
  def delete_view(self, username, view_id):
87
- """Delete a custom/list view override. The system all-rows view is guarded by caller."""
88
- self._update(username, lambda ws: ws['views'].pop(str(view_id), None))
 
 
 
 
 
 
 
 
 
 
 
89
 
90
  def save_field(self, username, field):
91
  """Persist a column note or a user-created (custom_/measure_) field definition."""
 
17
  """
18
  import core.store as store
19
 
20
+ #: Wave-9 I17 β€” the SHARED bucket. Views whose permissions make them visible to anyone but
21
+ #: their creator live here instead of in a personal workspace, under a key that cannot collide
22
+ #: with a username (usernames come from core/users.py and are never dunder-wrapped; `is_shared`
23
+ #: guards it anyway). ONE HOME PER VIEW, never both: a view moved to personal is REMOVED from
24
+ #: here, and a view shared is removed from its creator's workspace. Two homes would mean two
25
+ #: divergent copies the moment either was edited.
26
+ SHARED_KEY = '__shared__'
27
+
28
+
29
+ def _may_see(view, viewer, is_admin=False):
30
+ """Visibility for ONE shared view, fail-closed.
31
+
32
+ 'collaborative' = everyone who can already open the module (the caller has gated that).
33
+ 'users' = the named users, plus the creator, plus admins β€” an admin who could not
34
+ see a view could not administer it either.
35
+ Anything unrecognised returns False rather than defaulting open: an unreadable permission
36
+ must never widen access ([[aios-permissioning]] β€” no fail-open defaults).
37
+ """
38
+ if not isinstance(view, dict):
39
+ return False
40
+ if view.get('createdBy') == viewer or is_admin:
41
+ return True
42
+ perms = view.get('permissions') or {}
43
+ edit = perms.get('edit')
44
+ if edit == 'collaborative':
45
+ return True
46
+ if edit == 'users':
47
+ return viewer in set(perms.get('users') or ())
48
+ return False # 'personal', absent, or junk
49
+
50
+
51
+ def _may_edit(view, viewer, is_admin=False):
52
+ """Who may WRITE a shared view. Same set as visibility today β€” the owner's item asks 'who
53
+ can edit' and lists who 'can have access', i.e. seeing and editing are one grant. Kept as a
54
+ separate function so they can diverge (a future read-only share) without hunting callers."""
55
+ return _may_see(view, viewer, is_admin)
56
+
57
+
58
+ def _may_administer(view, viewer, is_admin=False):
59
+ """Who may change a view's PERMISSIONS, or delete it: the creator or an admin ONLY.
60
+
61
+ Deliberately narrower than _may_edit. If a collaborator could rewrite `permissions` they
62
+ could grant themselves sole ownership of somebody else's view, or quietly widen a
63
+ users-scoped view to everyone β€” the classic privilege-escalation-by-edit hole.
64
+ """
65
+ if not isinstance(view, dict):
66
+ return False
67
+ return bool(is_admin) or view.get('createdBy') == viewer
68
+
69
+
70
+ def is_shared(view):
71
+ """A view belongs in the shared bucket when its permissions reach beyond its creator."""
72
+ return ((view or {}).get('permissions') or {}).get('edit') in ('collaborative', 'users')
73
+
74
 
75
  class TableStore:
76
  """The six store operations for one table object's workspace, closed over its store key."""
 
130
  ws['itemFolders'] = dict(item_folders or {})
131
  self._update(username, _set)
132
 
133
+ def shared_views(self, viewer, is_admin=False):
134
+ """Every SHARED view this viewer may see, by id (wave-9 I17).
135
+
136
+ Read-only and independent of the viewer's own workspace: the caller merges. Returns
137
+ only what `_may_see` allows, so a caller cannot accidentally render somebody else's
138
+ personal view by forgetting to filter.
139
+ """
140
+ try:
141
+ bucket = ((store.get(self.table_key) or {}).get(SHARED_KEY) or {}).get('views') or {}
142
+ except Exception:
143
+ return {}
144
+ return {vid: dict(v) for vid, v in bucket.items()
145
+ if _may_see(v, viewer, is_admin)}
146
+
147
+ def shared_view(self, view_id):
148
+ """One shared view RAW β€” no visibility filter. For authorisation decisions only: a
149
+ caller must know a view exists and who owns it before it can decide whether the actor
150
+ may touch it. Never hand the result to a renderer without checking `_may_see`."""
151
+ try:
152
+ return ((store.get(self.table_key) or {}).get(SHARED_KEY) or {}
153
+ ).get('views', {}).get(str(view_id))
154
+ except Exception:
155
+ return None
156
+
157
+ def save_view(self, username, view, shared=None):
158
+ """Upsert a SavedView into its ONE home β€” personal workspace or the shared bucket.
159
+
160
+ `shared` defaults to reading the view's own permissions (`is_shared`). Whichever home
161
+ it lands in, the view is REMOVED from the other, so a view can never exist as two
162
+ copies that diverge on the next edit.
163
+
164
+ ⚠ AUTHORISATION IS THE CALLER'S JOB and must happen BEFORE this is called β€” this layer
165
+ moves data and does not know who is asking. `_cl_handle_one` is the wall.
166
+ """
167
  view_id = str((view or {}).get('id') or '').strip()
168
  if not view_id:
169
  raise ValueError('view id is required')
170
+ if username == SHARED_KEY:
171
+ raise ValueError('reserved username')
172
+ to_shared = is_shared(view) if shared is None else bool(shared)
173
+ payload = dict(view)
174
+
175
+ def _up(data):
176
+ if to_shared:
177
+ bucket = data.setdefault(SHARED_KEY, {})
178
+ bucket.setdefault('views', {})[view_id] = payload
179
+ # it may have lived in the creator's workspace before being shared
180
+ owner = data.get(payload.get('createdBy') or username) or {}
181
+ (owner.get('views') or {}).pop(view_id, None)
182
+ else:
183
+ ws = data.setdefault(username, {})
184
+ ws.setdefault('views', {})[view_id] = payload
185
+ (data.get(SHARED_KEY, {}).get('views') or {}).pop(view_id, None)
186
+ return data
187
+
188
+ store.update(self.table_key, _up, flush='async')
189
 
190
  def delete_view(self, username, view_id):
191
+ """Delete a custom/list view override. The system all-rows view is guarded by caller.
192
+
193
+ Removes from BOTH homes: the caller has already authorised the delete, and leaving a
194
+ stale copy in the other bucket would resurrect the view on the next read.
195
+ """
196
+ vid = str(view_id)
197
+
198
+ def _up(data):
199
+ (data.get(username, {}).get('views') or {}).pop(vid, None)
200
+ (data.get(SHARED_KEY, {}).get('views') or {}).pop(vid, None)
201
+ return data
202
+
203
+ store.update(self.table_key, _up, flush='async')
204
 
205
  def save_field(self, username, field):
206
  """Persist a column note or a user-created (custom_/measure_) field definition."""
core/user_tables.py ADDED
@@ -0,0 +1,179 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """USER-CREATED TABLES (wave-9 I8 / contract C6) β€” databases that are not a connector.
2
+
3
+ The owner's "+ New" flow has two branches: connect a SOURCE (Odoo today) or *"create a completely
4
+ new database blank, where this time the user can actually insert row that they want."* The first
5
+ branch is the connector seam and lives in `harness/datastore.py`; THIS module is the second.
6
+
7
+ WHY A SEPARATE STORE AND NOT A REGISTRY ROW. `core/registry.py` is a static Python list read at
8
+ import time β€” it is the catalogue of modules the PRODUCT ships, and a tenant cannot append to it
9
+ at runtime without editing code. A user-created table is tenant data, so it lives in the tenant
10
+ store and is MERGED into the nav beside the registry rows. That also keeps the archived/allowed
11
+ machinery honest: a user table is never "archived", it is deleted, and it is never in
12
+ `allowed_modules` because it is not a module.
13
+
14
+ SHAPE (one store key, `user_tables`):
15
+
16
+ {table_key: {'key', 'label', 'source', 'createdBy', 'created', 'fields': [...], 'rows': {...}}}
17
+
18
+ `source` is deliberately NOT 'Odoo' β€” the nav badge is generated from it, so a blank table reads
19
+ "Blank" and can never be mistaken for connected data. `rows` is `{row_id: {field_key: value}}`,
20
+ which is the same overlay shape `TableStore` already uses, so the grid's write path needs no new
21
+ storage concept.
22
+
23
+ ⚠ ROW WRITES ARE ONLY EVER LEGAL HERE. An Odoo-sourced table is READ-ONLY at the source and
24
+ `_cl_handle_one`'s row_add / row_delete refuse unless `is_user_table(key)` β€” a user must not be
25
+ able to invent a customer in Odoo by typing into a grid.
26
+ """
27
+ import datetime as _dt
28
+ import re
29
+
30
+ import core.store as store
31
+
32
+ STORE_KEY = 'user_tables'
33
+ MAX_TABLES = 40
34
+ MAX_LABEL = 60
35
+ MAX_ROWS = 5000
36
+ #: the badge the nav paints for a table with no connector behind it
37
+ BLANK_SOURCE = 'Blank'
38
+ #: every user table's key is prefixed, so it can never collide with a registry module key
39
+ KEY_PREFIX = 'ut_'
40
+
41
+
42
+ def _slug(label):
43
+ s = re.sub(r'[^a-z0-9]+', '_', str(label or '').strip().lower()).strip('_')
44
+ return (s or 'table')[:40]
45
+
46
+
47
+ def all_tables():
48
+ """{key: definition} β€” every user-created table in this tenant."""
49
+ try:
50
+ return dict(store.get(STORE_KEY) or {})
51
+ except Exception:
52
+ return {}
53
+
54
+
55
+ def get(table_key):
56
+ return all_tables().get(str(table_key))
57
+
58
+
59
+ def is_user_table(table_key):
60
+ """THE permission predicate for row writes. Cheap and total: a key that is not in this store
61
+ is not a user table, so it cannot accept invented rows."""
62
+ return str(table_key or '').startswith(KEY_PREFIX) and get(table_key) is not None
63
+
64
+
65
+ def create(label, username, fields=None):
66
+ """Create a blank table. Returns its key, or None if refused.
67
+
68
+ Refuses rather than raises on the ordinary conditions (no name, duplicate, cap reached) β€”
69
+ the caller is a UI form and a refusal is a message, not an exception.
70
+ """
71
+ label = str(label or '').strip()[:MAX_LABEL]
72
+ if not label:
73
+ return None
74
+ existing = all_tables()
75
+ if len(existing) >= MAX_TABLES:
76
+ return None
77
+ key = KEY_PREFIX + _slug(label)
78
+ if key in existing: # a second table of the same name gets a suffix
79
+ for n in range(2, 50):
80
+ if f'{key}_{n}' not in existing:
81
+ key = f'{key}_{n}'
82
+ break
83
+ else:
84
+ return None
85
+ # A blank table still needs ONE column to be a table at all: a row with no fields cannot be
86
+ # displayed, edited or identified. 'name' is the identity column, the same role `customer`
87
+ # plays in the Customer table.
88
+ defn = {
89
+ 'key': key,
90
+ 'label': label,
91
+ 'source': BLANK_SOURCE,
92
+ 'createdBy': username,
93
+ 'created': _dt.datetime.now().strftime('%Y-%m-%dT%H:%M:%S'),
94
+ 'fields': list(fields or [{'key': 'name', 'label': 'Name', 'type': 'text',
95
+ 'source': 'overlay', 'default': True}]),
96
+ 'rows': {},
97
+ }
98
+
99
+ def _add(cur):
100
+ cur[key] = defn
101
+ return cur
102
+
103
+ store.update(STORE_KEY, _add, flush='sync') # a creation is not a hot path; commit it
104
+ return key
105
+
106
+
107
+ def delete(table_key):
108
+ def _drop(cur):
109
+ cur.pop(str(table_key), None)
110
+ return cur
111
+ store.update(STORE_KEY, _drop, flush='sync')
112
+
113
+
114
+ def add_row(table_key, values=None, username=None):
115
+ """Append one row. Returns the new row id, or None if refused."""
116
+ if not is_user_table(table_key):
117
+ return None # ⚠ never on a connector-backed table
118
+ defn = get(table_key) or {}
119
+ rows = defn.get('rows') or {}
120
+ if len(rows) >= MAX_ROWS:
121
+ return None
122
+ rid = str(max((int(r) for r in rows if str(r).isdigit()), default=0) + 1)
123
+ valid = {f['key'] for f in (defn.get('fields') or [])}
124
+ clean = {k: v for k, v in (values or {}).items() if k in valid}
125
+
126
+ def _add(cur):
127
+ t = cur.get(str(table_key))
128
+ if t is not None:
129
+ t.setdefault('rows', {})[rid] = clean
130
+ return cur
131
+
132
+ store.update(STORE_KEY, _add, flush='async')
133
+ return rid
134
+
135
+
136
+ def delete_row(table_key, row_id):
137
+ if not is_user_table(table_key):
138
+ return False
139
+
140
+ def _drop(cur):
141
+ t = cur.get(str(table_key))
142
+ if t is not None:
143
+ (t.get('rows') or {}).pop(str(row_id), None)
144
+ return cur
145
+
146
+ store.update(STORE_KEY, _drop, flush='async')
147
+ return True
148
+
149
+
150
+ def may_open(table_key, viewer, is_admin=False):
151
+ """FAIL-CLOSED visibility: the creator, or an admin. Nothing else.
152
+
153
+ A user table cannot be gated by `allowed_modules` β€” a module grant written last month cannot
154
+ describe a table created this morning β€” so it needs its own rule, and the safe rule is the
155
+ narrow one. Tables are stored tenant-wide under one key, so without this ANY user (including
156
+ a BU-scoped sales agent) could open a table somebody else created just by knowing its key.
157
+ Sharing a user table with named colleagues is a follow-on, and it should reuse the shared-
158
+ VIEW vocabulary rather than inventing a second one.
159
+ """
160
+ t = get(table_key)
161
+ if not t:
162
+ return False
163
+ return bool(is_admin) or t.get('createdBy') == viewer
164
+
165
+
166
+ def nav_entries(viewer=None, is_admin=False):
167
+ """Registry-SHAPED dicts so the nav can render user tables beside real modules with no
168
+ special-casing: the same keys the flat nav reads (`key`, `label`, `source`).
169
+
170
+ Filtered by `may_open`, so the nav cannot offer a row the dispatcher would refuse.
171
+ """
172
+ out = []
173
+ for key, t in sorted(all_tables().items(), key=lambda kv: (kv[1].get('label') or '').lower()):
174
+ if viewer is not None and not may_open(key, viewer, is_admin):
175
+ continue
176
+ out.append({'key': key, 'label': t.get('label') or key,
177
+ 'source': t.get('source') or BLANK_SOURCE,
178
+ 'user_table': True, 'nav': True, 'validate': False})
179
+ return out
harness/datastore.py CHANGED
@@ -44,7 +44,14 @@ ENTITIES = {
44
  },
45
  "res_partner": {
46
  "model": "res.partner", "archivable": True,
47
- "fields": ["name", "team_id", "city", "state_id", "country_id", "active", "write_date"],
 
 
 
 
 
 
 
48
  # m2m fields land as <base>_id (the FIRST linked id β€” the Customers-module convention:
49
  # a customer's assigned agent is agent_ids[0], ~one per customer, MECE) + <field> as a
50
  # JSON list of ALL ids. Declared explicitly: a 2-element m2m read would otherwise be
@@ -64,8 +71,35 @@ ENTITIES = {
64
  },
65
  "account_move_line": {
66
  "model": "account.move.line", "archivable": False,
 
 
 
 
 
 
 
 
67
  "fields": ["move_id", "account_id", "partner_id", "date", "debit", "credit",
68
- "balance", "write_date"],
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
69
  },
70
  "account_account": {
71
  # NOTE: no `active` field on account.account in this Odoo version (learned 2026-07-11 β€”
@@ -77,6 +111,14 @@ ENTITIES = {
77
 
78
  BATCH = 2000
79
 
 
 
 
 
 
 
 
 
80
 
81
  import threading as _thr
82
 
@@ -230,7 +272,7 @@ def _flatten(rec, fields, m2m=()):
230
  out[f"{f.removesuffix('_id')}_name"] = str(v[1])
231
  elif isinstance(v, (list, tuple)):
232
  out[f] = json.dumps(v)
233
- elif v is False and f not in ("active",): # Odoo False = NULL for non-bool fields
234
  out[f] = None
235
  else:
236
  out[f] = v
@@ -243,11 +285,11 @@ def _cols(spec):
243
  base = f.removesuffix("_id")
244
  if f.endswith("_id"):
245
  cols += [f"{base}_id BIGINT", f"{base}_name VARCHAR"]
246
- elif f in ("active",):
247
  cols.append(f"{f} BOOLEAN")
248
  elif f in ("amount_untaxed", "amount_untaxed_signed", "amount_residual_signed",
249
  "price_subtotal", "margin", "purchase_price", "product_uom_qty",
250
- "standard_price", "debit", "credit", "balance"):
251
  cols.append(f"{f} DOUBLE")
252
  else:
253
  cols.append(f"{f} VARCHAR")
@@ -274,6 +316,64 @@ def _ensure_columns(con, key, spec):
274
  return added
275
 
276
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
277
  def _backfill_m2m(con, key, spec, log=print):
278
  """One-time targeted backfill after a schema migration: existing rows never re-sync (their
279
  write_date didn't move when WE added a column), so pull every record where the m2m field is
@@ -285,9 +385,20 @@ def _backfill_m2m(con, key, spec, log=print):
285
  if con.execute("SELECT 1 FROM _sync_state WHERE entity=?", [marker]).fetchone():
286
  continue
287
  base = f.removesuffix("_ids")
288
- recs = O.search_read(spec["model"], _base_domain(spec) + [(f, "!=", False)], [f],
289
- limit=100000)
290
- rows = [(r[f][0], json.dumps(list(r[f])), r["id"]) for r in recs if r.get(f)]
 
 
 
 
 
 
 
 
 
 
 
291
  if rows:
292
  con.executemany(f"UPDATE {key} SET {base}_id=?, {f}=? WHERE id=?", rows)
293
  con.execute("INSERT OR REPLACE INTO _sync_state VALUES (?,?,?,?,?,?)",
@@ -330,6 +441,7 @@ def sync_entity(key, max_batches=200, batch=BATCH, log=print):
330
  con = connect()
331
  _ensure_table(con, key, spec)
332
  _ensure_columns(con, key, spec)
 
333
  _backfill_m2m(con, key, spec, log=log)
334
  st = _state(con, key) or {"phase": "backfill", "last_id": 0, "cursor_wd": None, "rows": 0}
335
  fields = spec["fields"] + list(spec.get("m2m") or [])
 
44
  },
45
  "res_partner": {
46
  "model": "res.partner", "archivable": True,
47
+ # `agent` (bool, labelled "Creditor/Agent") is THE discriminator between a real sales
48
+ # AGENT and an internal SALESPERSON who merely carries commission lines β€” the commission
49
+ # table itself cannot tell them apart. `salesman_as_agent` ("convert salesman into agent")
50
+ # marks agents who came from staff; the owner ruling on whether those count as agents is
51
+ # OUTSTANDING, so both flags are synced and neither reading is baked in.
52
+ "fields": ["name", "team_id", "city", "state_id", "country_id", "active",
53
+ "agent", "salesman_as_agent", "write_date"],
54
+ "backfill_fields": ["agent", "salesman_as_agent"], # added 2026-07-28
55
  # m2m fields land as <base>_id (the FIRST linked id β€” the Customers-module convention:
56
  # a customer's assigned agent is agent_ids[0], ~one per customer, MECE) + <field> as a
57
  # JSON list of ALL ids. Declared explicitly: a 2-element m2m read would otherwise be
 
71
  },
72
  "account_move_line": {
73
  "model": "account.move.line", "archivable": False,
74
+ # display_type/move_type/parent_state/price_subtotal/product_id added 2026-07-28 so the
75
+ # invoice-LINE grain is queryable (topic `invoice_lines`).
76
+ # ⚠ display_type values here are 'product', 'cogs', 'payment_term', 'line_note',
77
+ # 'line_section'. Commission rows attach to 'cogs' lines as well as 'product' ones
78
+ # (96,936 of 147,160 in 2025). Filtering to 'product' is a GRAIN guard: measured
79
+ # 2026-07-29, omitting it does not move revenue (non-product lines carry
80
+ # price_subtotal = 0) but it inflates commission ROW COUNTS ~80% and would corrupt any
81
+ # count-of-lines measure.
82
  "fields": ["move_id", "account_id", "partner_id", "date", "debit", "credit",
83
+ "balance", "display_type", "move_type", "parent_state", "price_subtotal",
84
+ "product_id", "write_date"],
85
+ "backfill_fields": ["display_type", "move_type", "parent_state", "price_subtotal",
86
+ "product_id"], # added 2026-07-28
87
+ # the BU bridge: account.move carries NO business unit (every invoice sits on team 1 β€”
88
+ # see [[invoice-bu-attribution]]), so Fisch/Royal on the invoice basis is only reachable
89
+ # through the originating sale order. sale_line_id (the FIRST linked sale line) is
90
+ # lossless here: ZERO 2025 invoice lines span more than one team (measured).
91
+ "m2m": ["sale_line_ids"],
92
+ },
93
+ "account_invoice_line_agent": {
94
+ # The OCA sale-commission module: one row per (invoice line Γ— agent). This is the SECOND
95
+ # agent source β€” per-line commission attribution β€” and it names a different population
96
+ # than res_partner.agent_ids (the customer-master book). See topic `invoice_lines`.
97
+ # ⚠ TWO similarly-named FKs, do not confuse them:
98
+ # object_id -> account_move_line (THE grain; join on this)
99
+ # invoice_id -> account_move (the parent document)
100
+ "model": "account.invoice.line.agent", "archivable": False,
101
+ "fields": ["agent_id", "commission_id", "amount", "invoice_id", "object_id",
102
+ "invoice_date", "settled", "write_date"],
103
  },
104
  "account_account": {
105
  # NOTE: no `active` field on account.account in this Odoo version (learned 2026-07-11 β€”
 
111
 
112
  BATCH = 2000
113
 
114
+ # Fields that are genuinely BOOLEAN. This list is load-bearing in TWO places: _cols types the
115
+ # column, and _flatten must NOT collapse a real False into NULL. Odoo returns False both for
116
+ # "empty" and for "boolean false", so a bool field missing from here silently becomes NULL β€” and
117
+ # for res_partner.agent that would erase the ONE flag separating an AGENT from a SALESPERSON
118
+ # (see [[invoice-line-agent-commission]]): every row would read "not an agent" indistinguishably
119
+ # from "unknown".
120
+ BOOL_FIELDS = ("active", "agent", "salesman_as_agent", "settled", "commission_free")
121
+
122
 
123
  import threading as _thr
124
 
 
272
  out[f"{f.removesuffix('_id')}_name"] = str(v[1])
273
  elif isinstance(v, (list, tuple)):
274
  out[f] = json.dumps(v)
275
+ elif v is False and f not in BOOL_FIELDS: # Odoo False = NULL for non-bool fields
276
  out[f] = None
277
  else:
278
  out[f] = v
 
285
  base = f.removesuffix("_id")
286
  if f.endswith("_id"):
287
  cols += [f"{base}_id BIGINT", f"{base}_name VARCHAR"]
288
+ elif f in BOOL_FIELDS:
289
  cols.append(f"{f} BOOLEAN")
290
  elif f in ("amount_untaxed", "amount_untaxed_signed", "amount_residual_signed",
291
  "price_subtotal", "margin", "purchase_price", "product_uom_qty",
292
+ "standard_price", "debit", "credit", "balance", "amount"):
293
  cols.append(f"{f} DOUBLE")
294
  else:
295
  cols.append(f"{f} VARCHAR")
 
316
  return added
317
 
318
 
319
+ def _field_cols(f):
320
+ """The store column(s) one spec field materialises into (m2o fields become _id + _name)."""
321
+ if f.endswith("_id"):
322
+ base = f.removesuffix("_id")
323
+ return [f"{base}_id", f"{base}_name"]
324
+ return [f]
325
+
326
+
327
+ def _backfill_columns(con, key, spec, log=print):
328
+ """Scalar/m2o schema evolution β€” the twin of _backfill_m2m, and for the same reason.
329
+
330
+ _ensure_columns ALTERs a new column in, but existing rows NEVER re-sync (WE moved the schema;
331
+ their write_date didn't move), so a newly added field stays NULL forever β€” silently, and NULL
332
+ is indistinguishable from a legitimately empty value. That is how a store starts answering
333
+ 'no rows match' instead of erroring. Re-pull just the affected fields for every row,
334
+ paginated by id, marked durably so a crash retries rather than declaring completion.
335
+
336
+ The fields are DECLARED in the spec (`backfill_fields`), never inferred from "which columns
337
+ did _ensure_columns just add" β€” that inference is wrong on the second run, when the ALTER has
338
+ already happened and the list comes back empty while the data is still missing. Declaring it
339
+ makes the migration re-entrant and reviewable. Leave the entry in place after it completes;
340
+ the durable marker, not the absence of the declaration, is what stops it re-running.
341
+ """
342
+ fields = [f for f in (spec.get("backfill_fields") or []) if f != "write_date"]
343
+ if not fields:
344
+ return
345
+ marker = f"{key}.cols.{','.join(sorted(fields))}"
346
+ st = con.execute("SELECT phase, last_id, rows FROM _sync_state WHERE entity=?",
347
+ [marker]).fetchone()
348
+ if st and st[0] == "done":
349
+ return
350
+ # RESUMABLE, not restart-from-zero: these passes run to ~1M rows, and a migration that loses
351
+ # an hour of work to one dropped connection gets skipped by the next person under time
352
+ # pressure. Progress is checkpointed every page; 'done' is written only at the end, so an
353
+ # interrupted run resumes at the last committed id instead of re-pulling or, worse, declaring
354
+ # completion it never reached.
355
+ last, n = (st[1] or 0, st[2] or 0) if st else (0, 0)
356
+ if last:
357
+ log(f" {key}: column backfill resuming at id {last:,} ({n:,} rows already done)")
358
+ cols = [c for f in fields for c in _field_cols(f)]
359
+ setter = ", ".join(f"{c}=?" for c in cols)
360
+ while True:
361
+ recs = O.search_read(spec["model"], _base_domain(spec) + [("id", ">", last)],
362
+ fields, limit=5000, order="id asc")
363
+ if not recs:
364
+ break
365
+ rows = [_flatten(r, fields) for r in recs]
366
+ con.executemany(f"UPDATE {key} SET {setter} WHERE id=?",
367
+ [[r.get(c) for c in cols] + [r["id"]] for r in rows])
368
+ last, n = recs[-1]["id"], n + len(recs)
369
+ con.execute("INSERT OR REPLACE INTO _sync_state VALUES (?,?,?,?,?,?)",
370
+ [marker, "running", last, None, n, time.strftime("%Y-%m-%d %H:%M:%S")])
371
+ log(f" {key}: column backfill {'+'.join(fields)} -> id {last:,} ({n:,} rows)")
372
+ con.execute("INSERT OR REPLACE INTO _sync_state VALUES (?,?,?,?,?,?)",
373
+ [marker, "done", last, None, n, time.strftime("%Y-%m-%d %H:%M:%S")])
374
+ log(f" {key}: column backfill complete -> {n:,} rows")
375
+
376
+
377
  def _backfill_m2m(con, key, spec, log=print):
378
  """One-time targeted backfill after a schema migration: existing rows never re-sync (their
379
  write_date didn't move when WE added a column), so pull every record where the m2m field is
 
385
  if con.execute("SELECT 1 FROM _sync_state WHERE entity=?", [marker]).fetchone():
386
  continue
387
  base = f.removesuffix("_ids")
388
+ # PAGINATED by id. A single limit=100000 call silently TRUNCATED here: account_move_line
389
+ # has 228,067 rows with sale_line_ids set, so 56% of the BU bridge would have gone
390
+ # missing with no error β€” a partial backfill that reads as a complete one (the
391
+ # [[no-unverifiable-aggregates]] no-silent-caps rule).
392
+ rows, last, page = [], 0, 20000
393
+ while True:
394
+ recs = O.search_read(spec["model"],
395
+ _base_domain(spec) + [(f, "!=", False), ("id", ">", last)],
396
+ [f], limit=page, order="id asc")
397
+ if not recs:
398
+ break
399
+ rows += [(r[f][0], json.dumps(list(r[f])), r["id"]) for r in recs if r.get(f)]
400
+ last = recs[-1]["id"]
401
+ log(f" {key}: m2m {f} scanned to id {last:,} ({len(rows):,} rows)")
402
  if rows:
403
  con.executemany(f"UPDATE {key} SET {base}_id=?, {f}=? WHERE id=?", rows)
404
  con.execute("INSERT OR REPLACE INTO _sync_state VALUES (?,?,?,?,?,?)",
 
441
  con = connect()
442
  _ensure_table(con, key, spec)
443
  _ensure_columns(con, key, spec)
444
+ _backfill_columns(con, key, spec, log=log)
445
  _backfill_m2m(con, key, spec, log=log)
446
  st = _state(con, key) or {"phase": "backfill", "last_id": 0, "cursor_wd": None, "rows": 0}
447
  fields = spec["fields"] + list(spec.get("m2m") or [])
harness/semantic.py CHANGED
@@ -290,8 +290,45 @@ def _v_returns_sign(date_from, date_to, team_id):
290
  return ours, abs(raw)
291
 
292
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
293
  _VALIDATORS = {
294
  "returns_sign": _v_returns_sign,
 
295
  "order_level_revenue": _v_order_level_revenue,
296
  "order_count": _v_order_count,
297
  "gl_opex": _v_gl_opex,
 
290
  return ours, abs(raw)
291
 
292
 
293
+ def _v_line_vs_move_grain(date_from, date_to, team_id):
294
+ """Independent check on the invoice-LINE topic: the store's netted product-line total must
295
+ equal the same figure read straight from LIVE Odoo.
296
+
297
+ Two things this catches that self-consistency cannot. (1) A LOST CREDIT-NOTE NEGATION β€”
298
+ `price_subtotal` is stored POSITIVE on a refund line, so a dropped subtraction inflates
299
+ revenue while every internal check still agrees. (2) A WRONG `display_type` FILTER β€” the
300
+ invoice tables carry 'cogs' and 'payment_term' rows alongside 'product' ones, and including
301
+ them changes the total silently rather than erroring.
302
+
303
+ Company-level (team_id None) uses the strongest possible reference: the MOVE-grain
304
+ `amount_untaxed_signed`, a different table entirely. Per-BU there is no move-grain analogue
305
+ (account.move carries no business unit β€” every invoice sits on team 1), so the reference is
306
+ the live line-level aggregate reached through the sale-order dot path: still an independent
307
+ engine and query path from the DuckDB store, which is what the contract requires.
308
+ """
309
+ ours = (store_query("invoice_lines", ["invoiced_line_sales"],
310
+ date_from=date_from, date_to=date_to, team_id=team_id)
311
+ .get("rows") or [{}])[0].get("invoiced_line_sales") or 0.0
312
+ if team_id is None:
313
+ raw = O.sum_field("account.move",
314
+ [("state", "=", "posted"),
315
+ ("move_type", "in", ["out_invoice", "out_refund"]),
316
+ ("invoice_date", ">=", date_from), ("invoice_date", "<=", date_to)],
317
+ "amount_untaxed_signed")
318
+ return ours, raw
319
+ dom = [("parent_state", "=", "posted"), ("display_type", "=", "product"),
320
+ ("date", ">=", date_from), ("date", "<=", date_to),
321
+ ("sale_line_ids.order_id.team_id", "=", team_id)]
322
+ gross = O.sum_field("account.move.line", dom + [("move_type", "=", "out_invoice")],
323
+ "price_subtotal")
324
+ refunds = O.sum_field("account.move.line", dom + [("move_type", "=", "out_refund")],
325
+ "price_subtotal")
326
+ return ours, (gross or 0) - (refunds or 0)
327
+
328
+
329
  _VALIDATORS = {
330
  "returns_sign": _v_returns_sign,
331
+ "line_vs_move_grain": _v_line_vs_move_grain,
332
  "order_level_revenue": _v_order_level_revenue,
333
  "order_count": _v_order_count,
334
  "gl_opex": _v_gl_opex,
model/metrics/invoice_lines.yml ADDED
@@ -0,0 +1,105 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Metrics: invoice_lines β€” the invoice-LINE lens, with per-line agent allocation (2026-07-28).
2
+ #
3
+ # These make the owner's agent questions resolvable by the Analyst / metric dictionary / grid
4
+ # instead of an ad-hoc script. Slice any of them by the `allocation`, `agent`, `agent_role` or
5
+ # `team` dims on the topic.
6
+ topic: invoice_lines
7
+ metrics:
8
+ - key: invoiced_line_sales_gross
9
+ label: Invoiced line sales (gross)
10
+ agg: sum
11
+ field: price_subtotal
12
+ store_filter_sql: "l.move_type = 'out_invoice'"
13
+ format: usd
14
+ description: "Untaxed invoice-line subtotals, invoices only (before credit notes)."
15
+ ai_context: >-
16
+ A component of `invoiced_line_sales`, not an answer on its own β€” it ignores credit notes.
17
+
18
+ - key: invoiced_line_refunds
19
+ label: Invoiced line refunds
20
+ agg: sum
21
+ field: price_subtotal
22
+ store_filter_sql: "l.move_type = 'out_refund'"
23
+ format: usd
24
+ description: "Untaxed credit-note line subtotals, reported POSITIVE."
25
+ ai_context: >-
26
+ Credit-note `price_subtotal` is stored POSITIVE (unlike the document-level
27
+ amount_untaxed_signed on topic credit_notes), so this metric carries no negation and
28
+ `invoiced_line_sales` subtracts it.
29
+
30
+ - key: invoiced_line_sales
31
+ label: Invoiced line sales (net)
32
+ agg: derived
33
+ expr: "invoiced_line_sales_gross - invoiced_line_refunds"
34
+ format: usd
35
+ description: >-
36
+ THE invoice-line revenue measure: untaxed product-line subtotals of posted customer
37
+ invoices, net of credit notes.
38
+ ai_context: >-
39
+ Use this β€” not the gross component β€” whenever asked for invoice-line sales. Net of credit
40
+ notes. This is NOT `revenue` (order-line based, topic sales_lines); the two differ by
41
+ unbilled orders and billing timing, and on Fisch 2025 they run ~2% apart, which is normal
42
+ and must not be "reconciled" away.
43
+ validate:
44
+ method: line_vs_move_grain
45
+ note: >-
46
+ Independent check: the sum of these product-line subtotals must equal the sum of
47
+ amount_untaxed_signed over the SAME posted customer moves read straight from Odoo.
48
+ Verified 2026-07-28 all-scope 2025: 8,955,776.63 - 149,961.44 = 8,805,815.19 exactly.
49
+ Catches a lost credit-note negation and a wrong display_type filter, neither of which
50
+ self-consistency can see.
51
+
52
+ - key: agent_allocated_sales
53
+ label: Sales allocated to an agent
54
+ agg: sum
55
+ field: price_subtotal
56
+ store_filter_sql: "l.move_type = 'out_invoice' AND ca.is_true_agent"
57
+ format: usd
58
+ description: >-
59
+ Invoice-line sales whose line carries a REAL agent (res.partner.agent = True) β€” excludes
60
+ the internal salespeople who also carry commission lines.
61
+ ai_context: >-
62
+ Gross of credit notes by design (refund lines rarely carry commission rows); for the netted
63
+ view slice `invoiced_line_sales` by the `allocation` dim instead, which is MECE.
64
+ ⚠ This is "sales ALLOCATED to an agent", NOT "sales BY customers who have an agent" β€” 403
65
+ of Fisch's 518 agent customers are mixed, so the two differ by ~$192k on 2025.
66
+
67
+ - key: unallocated_line_sales
68
+ label: Sales not allocated to an agent
69
+ agg: sum
70
+ field: price_subtotal
71
+ store_filter_sql: "l.move_type = 'out_invoice' AND ca.is_true_agent IS NOT TRUE"
72
+ format: usd
73
+ description: >-
74
+ Invoice-line sales with no REAL agent on the line β€” the strict reading, which counts
75
+ salesperson-only lines as unallocated.
76
+ ai_context: >-
77
+ Two defensible readings and this is the WIDER one (salesperson-covered business counts as
78
+ unallocated). The narrower "no commission row at all" figure is this metric sliced to
79
+ allocation = 'none'. On Fisch 2025 the two are $1,447,579.59 vs $1,086,381.35 β€” a material
80
+ gap, so state which reading you gave.
81
+
82
+ - key: agent_line_customers
83
+ label: Customers with an agent on the line
84
+ agg: count_distinct
85
+ field: partner_id
86
+ store_filter_sql: "ca.is_true_agent"
87
+ format: int
88
+ description: "Distinct customers with a real agent on at least one invoice line."
89
+ ai_context: >-
90
+ Fisch 2025 = 518. Counting customers, not revenue: a customer counts here if ANY line
91
+ carries an agent, so pairing this with `agent_allocated_sales` mixes two grains β€” pair it
92
+ with the customers' TOTAL sales if the question is "what do agent-assigned customers
93
+ generate" ($3,187,571 territory), and say which you did.
94
+
95
+ - key: commission_amount
96
+ label: Commission accrued
97
+ agg: sum
98
+ field: amount
99
+ format: usd
100
+ topic: commission_lines
101
+ description: "Commission accrued on invoice lines (the OCA sale-commission `amount`)."
102
+ ai_context: >-
103
+ Resolved on topic `commission_lines` (one row per line Γ— agent) NOT on invoice_lines,
104
+ because a line with two agents carries two commission amounts and the deduplicated join on
105
+ invoice_lines would drop one. Never sum commission through invoice_lines.
model/topics/commission_lines.yml ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Topic: commission_lines β€” the raw commission rows, one per (invoice line Γ— agent).
2
+ #
3
+ # Separate from `invoice_lines` on purpose. `invoice_lines` joins the commission table
4
+ # DEDUPLICATED (at most one agent per line) so that revenue never double-counts. That is right
5
+ # for revenue and WRONG for commission: a line with two agents accrues two commission amounts,
6
+ # and the deduplicated join would drop one. So commission money is summed here, at its own grain.
7
+ #
8
+ # Use `invoice_lines` for revenue-by-agent; use this ONLY for commission accrued / settlement.
9
+ key: commission_lines
10
+ label: Commission lines (agent Γ— invoice line)
11
+ entity: account.invoice.line.agent
12
+
13
+ # STORE-ONLY: no live-path domain builder.
14
+
15
+ scope:
16
+ documents: >-
17
+ every commission row, including those attached to non-product lines. ⚠ 96,936 of the 147,160
18
+ rows with a 2025 invoice_date hang off COGS lines rather than product lines, so a row count
19
+ here is NOT a count of agent-attributed sales lines.
20
+ basis: "commission amount in company currency (`amount`)"
21
+ date_field: "invoice_date"
22
+
23
+ grain: "one row per (invoice line Γ— agent); a line with two agents produces two rows"
24
+
25
+ store:
26
+ table: account_invoice_line_agent
27
+ alias: a
28
+ # object_id -> account_move_line (the LINE), invoice_id -> account_move (the DOCUMENT).
29
+ # Two similarly named FKs; joining the wrong one silently changes the grain.
30
+ join: >-
31
+ LEFT JOIN res_partner ap ON ap.id = a.agent_id
32
+ LEFT JOIN account_move_line l ON l.id = a.object_id
33
+ LEFT JOIN sale_order_line sol ON sol.id = l.sale_line_id
34
+ LEFT JOIN sale_order so ON so.id = sol.order_id
35
+ date_col: "a.invoice_date"
36
+ team_col: "so.team_id"
37
+ scope_sql: "1 = 1"
38
+ dims:
39
+ commission_name: {col: "a.agent_id", name_col: "a.agent_name", label: "Commission name"}
40
+ plan: {col: "a.commission_id", name_col: "a.commission_name", label: "Commission plan"}
41
+ settled: {col: "a.settled", name_col: "CASE WHEN a.settled THEN 'Settled' ELSE 'Unsettled' END", label: "Settled"}
42
+ agent_role:
43
+ col: "CASE WHEN COALESCE(ap.agent, FALSE) THEN 'agent' ELSE 'salesperson' END"
44
+ name_col: "CASE WHEN COALESCE(ap.agent, FALSE) THEN 'Agent' ELSE 'Salesperson (not an agent)' END"
45
+ label: "Role"
46
+ line_type:
47
+ col: "l.display_type"
48
+ name_col: "l.display_type"
49
+ label: "Invoice line type"
50
+ team:
51
+ col: "so.team_id"
52
+ name_col: "CASE so.team_id WHEN 5 THEN 'Fisch' WHEN 6 THEN 'Royal' WHEN 7 THEN 'Giftware Deals (Amazon)' WHEN 1 THEN 'Sales (generic)' ELSE 'No sale order' END"
53
+ label: "Business unit"
54
+
55
+ ai_context: >
56
+ Raw commission rows from the OCA sale-commission module β€” one row per invoice line per agent.
57
+ Use ONLY for commission money ("what commission did X accrue", settlement status, plan mix).
58
+ For revenue by agent use topic `invoice_lines`, which joins this table deduplicated so revenue
59
+ is not double-counted.
60
+ ⚠ ROW COUNTS HERE ARE NOT SALES-LINE COUNTS: commission rows attach to COGS lines as well as
61
+ product lines (96,936 of 147,160 rows dated 2025 are COGS). Filter `line_type` = 'product'
62
+ before comparing anything here to a sales figure.
63
+ ⚠ A NAME HERE IS NOT NECESSARILY AN AGENT β€” "Anna" and "Shantal Erlich" are internal
64
+ salespeople (res.partner.agent = False) who carry commission rows. Use the `agent_role` dim to
65
+ separate them; never call them agents.
66
+ Commission PLANS observed: 6.5% (Martin Pasternak), 8%, 5%, 2%, 1%, and a named "Jacob" plan.
model/topics/invoice_lines.yml ADDED
@@ -0,0 +1,141 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Topic: invoice_lines β€” posted customer-invoice lines at LINE grain, carrying the per-line
2
+ # COMMISSION agent (the OCA sale-commission module).
3
+ #
4
+ # WHY THIS EXISTS (owner ask, 2026-07-28): "which FISCH customers are assigned to an Agent based
5
+ # on the invoice line, what do they generate, and what sales are NOT allocated to an agent."
6
+ # Neither `sales_lines` (order grain, customer-master agent) nor `customer_invoices` (document
7
+ # grain, no agent at all) can answer that β€” the agent lives on the invoice LINE, and the
8
+ # unallocated bucket is precisely the lines that have no commission row.
9
+ #
10
+ # ⚠ THIS IS A SECOND AGENT SOURCE AND IT DISAGREES WITH `sales_lines.agent`. That one is the
11
+ # CUSTOMER-MASTER book (res.partner.agent_ids); this one is per-line commission attribution.
12
+ # They name different people. Always state which source a number came from.
13
+ key: invoice_lines
14
+ label: Customer invoice lines (with commission agent)
15
+ entity: account.move.line
16
+
17
+ # STORE-ONLY: no live-path domain builder. The live equivalent is a dot-path domain on
18
+ # account.move.line; it is deliberately not bound here because the agent join has no live analogue
19
+ # that stays honest about the unallocated bucket.
20
+
21
+ scope:
22
+ documents: "posted customer invoices AND credit notes (move_type out_invoice/out_refund, parent_state posted)"
23
+ lines: >-
24
+ PRODUCT lines only (display_type = 'product'). Commission rows attach to 'cogs' lines too β€”
25
+ 96,936 of the 147,160 rows with a 2025 invoice_date. ⚠ MEASURED 2026-07-29, and NOT what it
26
+ first appears: dropping this filter does NOT move revenue or the customer count, because
27
+ non-product lines ('cogs', 'payment_term', 'line_note') all carry price_subtotal = 0 and
28
+ those customers already have product lines. The ~80% inflation is real for commission ROW
29
+ COUNTS (147,160 vs 50,191 product-line rows) and would corrupt any count-of-LINES measure β€”
30
+ it is a GRAIN guard, not a money guard. Keep it; just don't claim it protects the totals.
31
+ channels: >-
32
+ business unit comes from the ORIGINATING SALE ORDER (Fisch=5, Royal=6), because
33
+ account.move carries no BU (every invoice sits on team 1 "Sales"). Lines with no sale order
34
+ (direct invoices) have a NULL business unit and are KEPT, not dropped.
35
+ excluded: >-
36
+ Nothing is excluded by partner. GIFTWARE DEALS (Amazon) sits on its own team (7), so a
37
+ Fisch or Royal filter already excludes it β€” no partner-name exclusion needed here.
38
+ basis: "untaxed line subtotals (price_subtotal); credit-note lines are NEGATED by the metric"
39
+ date_field: "line date (= invoice date)"
40
+
41
+ grain: >-
42
+ one row per posted customer-invoice product line. The commission table is one row per
43
+ (line Γ— agent), so it is joined DEDUPLICATED to at most one row per line β€” otherwise the 74
44
+ two-agent lines would double-count revenue.
45
+
46
+ store:
47
+ table: account_move_line
48
+ alias: l
49
+ # LEFT JOIN from the LINE side is load-bearing: the whole point is the lines with NO commission
50
+ # row. An inner join would silently delete the unallocated bucket β€” the second half of the
51
+ # question β€” and still look correct.
52
+ #
53
+ # ca = at most ONE commission row per line, preferring a TRUE agent over a salesperson, then
54
+ # the lowest agent id for determinism.
55
+ join: >-
56
+ LEFT JOIN res_partner rp ON rp.id = l.partner_id
57
+ LEFT JOIN sale_order_line sol ON sol.id = l.sale_line_id
58
+ LEFT JOIN sale_order so ON so.id = sol.order_id
59
+ LEFT JOIN (
60
+ SELECT object_id, agent_id, agent_name, is_true_agent, is_converted_salesman
61
+ FROM (
62
+ SELECT a.object_id, a.agent_id, a.agent_name,
63
+ COALESCE(ap.agent, FALSE) AS is_true_agent,
64
+ COALESCE(ap.salesman_as_agent, FALSE) AS is_converted_salesman,
65
+ ROW_NUMBER() OVER (PARTITION BY a.object_id
66
+ ORDER BY COALESCE(ap.agent, FALSE) DESC, a.agent_id) AS rn
67
+ FROM account_invoice_line_agent a
68
+ LEFT JOIN res_partner ap ON ap.id = a.agent_id
69
+ ) ranked WHERE rn = 1
70
+ ) ca ON ca.object_id = l.id
71
+ date_col: "l.date"
72
+ team_col: "so.team_id"
73
+ scope_sql: >-
74
+ l.parent_state = 'posted' AND l.move_type IN ('out_invoice','out_refund')
75
+ AND l.display_type = 'product'
76
+ dims:
77
+ partner: {col: "l.partner_id", name_col: "l.partner_name", label: "Customer"}
78
+ product: {col: "l.product_id", name_col: "l.product_name", label: "Product"}
79
+ team:
80
+ col: "so.team_id"
81
+ name_col: "CASE so.team_id WHEN 5 THEN 'Fisch' WHEN 6 THEN 'Royal' WHEN 7 THEN 'Giftware Deals (Amazon)' WHEN 1 THEN 'Sales (generic)' ELSE 'No sale order' END"
82
+ label: "Business unit"
83
+ # THE agent dim β€” real agents ONLY. A salesperson-only line lands here as NULL, which is
84
+ # correct: it is not allocated to an agent.
85
+ agent:
86
+ col: "CASE WHEN ca.is_true_agent THEN ca.agent_id END"
87
+ name_col: "CASE WHEN ca.is_true_agent THEN ca.agent_name END"
88
+ label: "Agent (invoice line)"
89
+ # Whoever is on the commission line, agent or not β€” for commission/payout questions.
90
+ commission_name:
91
+ col: "ca.agent_id"
92
+ name_col: "ca.agent_name"
93
+ label: "Commission name (agent OR salesperson)"
94
+ agent_role:
95
+ col: "CASE WHEN ca.agent_id IS NULL THEN 'none' WHEN ca.is_true_agent THEN 'agent' ELSE 'salesperson' END"
96
+ name_col: "CASE WHEN ca.agent_id IS NULL THEN 'Nobody' WHEN ca.is_true_agent THEN 'Agent' ELSE 'Salesperson (not an agent)' END"
97
+ label: "Role on the line"
98
+ # The partition the owner asked for. These three values are MECE and sum to the total.
99
+ allocation:
100
+ col: "CASE WHEN ca.is_true_agent THEN 'agent' WHEN ca.agent_id IS NOT NULL THEN 'salesperson' ELSE 'none' END"
101
+ name_col: "CASE WHEN ca.is_true_agent THEN 'Allocated to an agent' WHEN ca.agent_id IS NOT NULL THEN 'Salesperson only' ELSE 'Not allocated' END"
102
+ label: "Agent allocation"
103
+ # The OUTSTANDING OWNER RULING (2026-07-28): 4 of the 11 agents carry salesman_as_agent =
104
+ # True ("convert salesman into agent"). Exposed as a dim so BOTH readings are queryable and
105
+ # neither is baked into the definition of `agent`.
106
+ agent_origin:
107
+ col: "CASE WHEN ca.is_true_agent AND ca.is_converted_salesman THEN 'converted' WHEN ca.is_true_agent THEN 'external' END"
108
+ name_col: "CASE WHEN ca.is_true_agent AND ca.is_converted_salesman THEN 'Agent (converted salesman)' WHEN ca.is_true_agent THEN 'Agent (external)' END"
109
+ label: "Agent origin"
110
+
111
+ ai_context: >
112
+ Posted customer-invoice PRODUCT lines with the per-line commission agent. Use this topic for:
113
+ "which customers are assigned to an agent based on the invoice line", "what sales are NOT
114
+ allocated to an agent", commission questions, and any agent question phrased about invoices or
115
+ billing. Use `sales_lines` instead for "sales" in the ordinary sense (confirmed order lines) and
116
+ for book/relationship ownership.
117
+ ⚠ TWO AGENT SOURCES, DIFFERENT PEOPLE β€” say which you used. Here = per-line commission
118
+ (account.invoice.line.agent). There (`sales_lines.agent`) = the customer-master book
119
+ (res.partner.agent_ids). JACOB BRISK, Samuel Shif, Yuda Stern and Billy Petruccelli appear ONLY
120
+ on invoice lines; Moishe Rubenstein, Avi Ash and Sang Ching ONLY on the customer master.
121
+ ⚠ A NAME ON A COMMISSION LINE IS NOT NECESSARILY AN AGENT. "Anna" and "Shantal Erlich" are
122
+ internal SALESPEOPLE (res.partner.agent = False, each with an Odoo login, salesperson of record
123
+ on 1,253 / 184 confirmed orders) who carry commission lines anyway. The `agent` dim already
124
+ excludes them β€” they show up under `commission_name` with agent_role 'salesperson'. NEVER
125
+ report them as agents; if a question says "agent", they are not one.
126
+ THE ALLOCATION PARTITION: the `allocation` dim is MECE and sums to the total β€” 'Allocated to an
127
+ agent' / 'Salesperson only' / 'Not allocated'. When asked "what is not allocated to an agent",
128
+ give the strict figure (salesperson + none) AND say what the narrower no-commission-at-all
129
+ figure is, because the two readings differ materially and the questioner may mean either.
130
+ BUSINESS UNIT comes from the originating sale order, so a line with no sale order has a NULL
131
+ business unit β€” present that as "no sale order (direct invoice)" and keep it in company totals.
132
+ Fisch is team 5. CREDIT NOTES are included and the revenue metric negates them; a positive
133
+ refund total means the negation was lost.
134
+ MEASURED BASELINE for FISCH 2025 (use to sanity-check any answer): total $4,443,244.34 over
135
+ 68,540 lines and 979 customers, splitting exactly into $2,995,664.75 allocated to agents,
136
+ $361,198.24 salesperson-only, and $1,086,381.35 not allocated. 518 customers have a real agent
137
+ on at least one line. Martin Pasternak alone is $2,155,660.64.
138
+ A CUSTOMER IS NOT ALL-OR-NOTHING: 403 of those 518 customers are MIXED (some lines carry an
139
+ agent, some do not), so "sales BY agent-assigned customers" ($3,187,771.31) is a different
140
+ number from "sales ALLOCATED to an agent" ($2,995,664.75). Answer whichever was asked and say
141
+ which one it is; they do not subtract to each other.
model/topics/sales_lines.yml CHANGED
@@ -53,6 +53,13 @@ store:
53
  # 2026-07-17: the salesperson/agent dimension (the #1 logged Analyst gap). Agent = the
54
  # CUSTOMER's assigned sales agent (res.partner.agent_ids[0] β€” the Customers-module
55
  # convention, MECE), synced as res_partner.agent_id; names via self-join alias ag.
 
 
 
 
 
 
 
56
  agent: {col: "rp.agent_id", name_col: "ag.name", label: "Agent"}
57
 
58
  ai_context: >
@@ -74,7 +81,23 @@ ai_context: >
74
  (book attribution β€” every order of that customer counts toward their agent), not a per-order
75
  salesperson. Resolve agent names with get_field_values on agent before filtering; customers
76
  with no assigned agent appear as a NULL agent group β€” present it as "no agent assigned" and
77
- keep it in totals. Never approximate an agent from customer names. Category
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
78
  questions use the `category` dim (the product's category). DATA CAVEAT: many products sit in the root
79
  category literally named "All" (master-data hygiene) β€” when ranking categories, mention that
80
  "All" is the uncategorized bucket, not a real category. The `state` dim can be NULL (customer
 
53
  # 2026-07-17: the salesperson/agent dimension (the #1 logged Analyst gap). Agent = the
54
  # CUSTOMER's assigned sales agent (res.partner.agent_ids[0] β€” the Customers-module
55
  # convention, MECE), synced as res_partner.agent_id; names via self-join alias ag.
56
+ #
57
+ # ⚠ 2026-07-28: this is the CUSTOMER-MASTER (book) source, and it is ONE OF THREE. A second,
58
+ # per-INVOICE-LINE source exists (`account.invoice.line.agent`, the OCA sale-commission
59
+ # module) and names a DIFFERENT population β€” see topic `invoice_lines`. This dim is VERIFIED
60
+ # CLEAN: all 10 partners linked through agent_ids carry res.partner.agent = True, and 0 of
61
+ # 2,056 customers have a non-agent as agent_ids[0]. Do NOT "fix" it by reading the commission
62
+ # table, which mixes agents and salespeople.
63
  agent: {col: "rp.agent_id", name_col: "ag.name", label: "Agent"}
64
 
65
  ai_context: >
 
81
  (book attribution β€” every order of that customer counts toward their agent), not a per-order
82
  salesperson. Resolve agent names with get_field_values on agent before filtering; customers
83
  with no assigned agent appear as a NULL agent group β€” present it as "no agent assigned" and
84
+ keep it in totals. Never approximate an agent from customer names.
85
+ ⚠ THERE ARE TWO AGENT SOURCES IN THIS ODOO AND THEY DISAGREE β€” always say which one you used.
86
+ (a) THIS dim = the customer-master book (res.partner.agent_ids). (b) Topic `invoice_lines` =
87
+ the per-INVOICE-LINE commission agent (account.invoice.line.agent, the OCA sale-commission
88
+ module). They name DIFFERENT PEOPLE: JACOB BRISK, Samuel Shif, Yuda Stern and Billy Petruccelli
89
+ appear ONLY on invoice lines; Moishe Rubenstein, Avi Ash and Sang Ching appear ONLY on the
90
+ customer master. Martin Pasternak dominates invoice-line revenue while Naomi Linnell Rivera
91
+ holds the largest customer-master book β€” so "revenue by agent" gets a materially different
92
+ ranking depending on the source. Use THIS dim for "whose book is this customer in / who owns
93
+ the relationship"; use `invoice_lines` for "what was actually credited to an agent on the
94
+ billing", for commission questions, and for "what sales are NOT allocated to an agent"
95
+ (this topic cannot answer that β€” book attribution has no unallocated concept beyond a NULL agent).
96
+ ⚠ A NAME ON A COMMISSION LINE IS NOT NECESSARILY AN AGENT. The flag is res.partner.agent
97
+ (bool). "Anna" and "Shantal Erlich" are internal SALESPEOPLE (agent = False, each with an Odoo
98
+ user login, and the salesperson of record on 1,253 / 184 confirmed orders) who nonetheless
99
+ carry commission lines. They are correctly ABSENT from this dim. If the owner asks about
100
+ "agents", never report them as agents β€” report them separately as salespeople. Category
101
  questions use the `category` dim (the product's category). DATA CAVEAT: many products sit in the root
102
  category literally named "All" (master-data hygiene) β€” when ranking categories, mention that
103
  "All" is the uncategorized bucket, not a real category. The `state` dim can be NULL (customer
modules/agent.py CHANGED
@@ -215,3 +215,63 @@ def validate(t=None, team_id=None):
215
  checks.append({'check': f'Agent "{sample}": scorecard YTD == headline YTD', 'a': round(sc_ytd, 2),
216
  'b': round(hl, 2), 'gap': round(sc_ytd - hl, 2), 'ok': abs(sc_ytd - hl) <= 1.0})
217
  return checks
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
215
  checks.append({'check': f'Agent "{sample}": scorecard YTD == headline YTD', 'a': round(sc_ytd, 2),
216
  'b': round(hl, 2), 'gap': round(sc_ytd - hl, 2), 'ok': abs(sc_ytd - hl) <= 1.0})
217
  return checks
218
+
219
+
220
+ # ------------------------------------------------------------ INVOICE-LINE ATTRIBUTION (2026-07-28)
221
+ # A SECOND agent source. Everything above this line attributes by BOOK β€” the customer's assigned
222
+ # agent (res.partner.agent_ids) β€” over confirmed SALES ORDERS. This section attributes per INVOICE
223
+ # LINE, from the OCA sale-commission module, via the semantic layer (topics invoice_lines /
224
+ # commission_lines). The two disagree on purpose and answer different questions:
225
+ #
226
+ # book -> "whose customer is this / who owns the relationship" (order basis)
227
+ # invoice -> "what was actually credited to an agent on the billing" + the ONLY source that can
228
+ # say what is NOT allocated to an agent (invoice basis)
229
+ #
230
+ # ⚠ A NAME ON A COMMISSION LINE IS NOT NECESSARILY AN AGENT β€” `res.partner.agent` is the flag.
231
+ # "Anna" and "Shantal Erlich" are internal SALESPEOPLE who carry commission lines; the `agent`
232
+ # dim excludes them and `include_salespeople` folds them back in as a clearly-labelled variant.
233
+ # See [[invoice-line-agent-commission]].
234
+
235
+ _ALLOC_LABEL = {'agent': 'Allocated to an agent', 'salesperson': 'Salesperson only',
236
+ 'none': 'Not allocated'}
237
+
238
+
239
+ def invoice_line_rollup(t=None, team_id=None, include_salespeople=False):
240
+ """Per-name invoice-line revenue + the MECE allocation split, for a YTD window.
241
+
242
+ Returns {'by_agent': [...], 'allocation': [...], 'total': float, 'allocated': float,
243
+ 'unallocated': float, 'basis': str} β€” or {'error': msg} when the tenant store is not
244
+ ready (this path is store-only; there is no live fallback that stays honest about the
245
+ unallocated bucket).
246
+ """
247
+ import harness.semantic as S
248
+ t = t or P.today()
249
+ yf, yt = P.ytd(t)
250
+ dim = 'commission_name' if include_salespeople else 'agent'
251
+ try:
252
+ by = S.store_query('invoice_lines', ['invoiced_line_sales'], group_by=[dim],
253
+ date_from=yf, date_to=yt, team_id=team_id, limit=200).get('rows') or []
254
+ alloc = S.store_query('invoice_lines', ['invoiced_line_sales'], group_by=['allocation'],
255
+ date_from=yf, date_to=yt, team_id=team_id, limit=10).get('rows') or []
256
+ tot = (S.store_query('invoice_lines', ['invoiced_line_sales'], date_from=yf, date_to=yt,
257
+ team_id=team_id).get('rows') or [{}])[0].get('invoiced_line_sales') or 0.0
258
+ except Exception as e: # store not ready / model error β€” say so, don't fake
259
+ return {'error': str(e)}
260
+ # store_query row shape: the DIM KEY carries the display NAME and `<dim>_id` the raw value
261
+ # (allocation -> 'Salesperson only', allocation_id -> 'salesperson'). Reading `<dim>_name`
262
+ # returns None for every row and silently renders the whole table as "no agent".
263
+ rows = [{'agent': (r.get(dim) or '(no agent on the line)'),
264
+ 'revenue': r.get('invoiced_line_sales') or 0.0} for r in by]
265
+ rows.sort(key=lambda r: -r['revenue'])
266
+ amap = {r.get('allocation_id') or 'none': (r.get('invoiced_line_sales') or 0.0) for r in alloc}
267
+ allocated = amap.get('agent', 0.0)
268
+ return {
269
+ 'by_agent': rows,
270
+ 'allocation': [{'bucket': _ALLOC_LABEL[k], 'revenue': amap.get(k, 0.0)}
271
+ for k in ('agent', 'salesperson', 'none') if k in amap or True],
272
+ 'total': tot, 'allocated': allocated, 'unallocated': tot - allocated,
273
+ 'strict_none': amap.get('none', 0.0), 'salesperson_only': amap.get('salesperson', 0.0),
274
+ 'window': (yf, yt),
275
+ 'basis': ('invoice line Β· commission names incl. salespeople' if include_salespeople
276
+ else 'invoice line Β· real agents only'),
277
+ }
modules/customer_data.py CHANGED
@@ -509,6 +509,8 @@ def delete_list(username, name):
509
  _TSTORE = table_store.make(TABLE_KEY)
510
 
511
  table_workspace = _TSTORE.workspace
 
 
512
  save_table_view = _TSTORE.save_view
513
  delete_table_view = _TSTORE.delete_view
514
  save_table_field = _TSTORE.save_field
 
509
  _TSTORE = table_store.make(TABLE_KEY)
510
 
511
  table_workspace = _TSTORE.workspace
512
+ shared_table_views = _TSTORE.shared_views # wave-9 I17: views shared WITH this viewer
513
+ shared_table_view = _TSTORE.shared_view # ...and one raw, for authorisation only
514
  save_table_view = _TSTORE.save_view
515
  delete_table_view = _TSTORE.delete_view
516
  save_table_field = _TSTORE.save_field