fsanyoto commited on
Commit
23f07cc
Β·
verified Β·
1 Parent(s): 23c7452

Deploy Data Management Platform (rename + sales forecast removed)

Browse files
.streamlit/config.toml CHANGED
@@ -51,3 +51,8 @@ gatherUsageStats = false
51
  # full, so there is nothing to miss on reconnect. Removes the failure mode entirely; the extra
52
  # bandwidth is negligible for an internal dashboard (2026-07-21).
53
  minCachedMessageSize = 1000000000
 
 
 
 
 
 
51
  # full, so there is nothing to miss on reconnect. Removes the failure mode entirely; the extra
52
  # bandwidth is negligible for an internal dashboard (2026-07-21).
53
  minCachedMessageSize = 1000000000
54
+
55
+ [server]
56
+ # Self-hosted Inter (static/fonts/) β€” the Google @import caused a first-paint FOUT: the login
57
+ # and loading screens painted in Segoe before the network fetch landed (owner wave-2 item 1).
58
+ enableStaticServing = true
aios_grid.py CHANGED
@@ -83,7 +83,10 @@ def _round(v):
83
  # select β€” a single-select with its own `options` (the "Status" a user wants to add; distinct
84
  # from the Odoo-sourced `status` lifecycle, which is not user-defined)
85
  # user β€” an assignee, whose choices come from the HOST's real user list, never from here
86
- CUSTOM_FIELD_TYPES = {"text", "select", "user", "int", "currency", "pct", "date"}
 
 
 
87
  MAX_FIELD_OPTIONS = 50
88
 
89
  #: Key prefix of a FORMULA-MEASURE column (owner item 7, 2026-07-27): a user-created field that
@@ -241,6 +244,19 @@ def fields_from_workspace(workspace=None, cohorts=False):
241
  field = dict(base)
242
  if isinstance(meta.get("note"), str):
243
  field["note"] = meta["note"][:2000]
 
 
 
 
 
 
 
 
 
 
 
 
 
244
  out.append(field)
245
  for key, field in saved.items():
246
  if key in base_keys or not isinstance(field, dict):
@@ -271,8 +287,9 @@ def fields_from_workspace(workspace=None, cohorts=False):
271
  if field.get("type") not in CUSTOM_FIELD_TYPES:
272
  continue
273
  ftype = field["type"]
274
- options = _clean_options(field.get("options")) if ftype == "select" else []
275
- if ftype == "select" and not options:
 
276
  # A select with no surviving choices can never hold a value. Dropping the COLUMN
277
  # would lose the user's data; degrading it to text keeps every stored value
278
  # readable and lets them re-add choices.
@@ -286,7 +303,10 @@ def fields_from_workspace(workspace=None, cohorts=False):
286
  "custom": True,
287
  "agg": field.get("agg") if field.get("agg") in {"sum"} else None,
288
  "note": str(field.get("note") or "")[:2000],
289
- **({"options": options} if ftype == "select" else {}),
 
 
 
290
  })
291
  if cohorts:
292
  out.append(cohort_field())
 
83
  # select β€” a single-select with its own `options` (the "Status" a user wants to add; distinct
84
  # from the Odoo-sourced `status` lifecycle, which is not user-defined)
85
  # user β€” an assignee, whose choices come from the HOST's real user list, never from here
86
+ #: `multiselect` (wave-2 item 5, 2026-07-27): the Airtable-style MULTI select β€” declared
87
+ #: options like `select`, but the cell holds a comma-joined SET and the row belongs to every
88
+ #: member of it (the `multi` grouping/cell contract the Cohorts column established).
89
+ CUSTOM_FIELD_TYPES = {"text", "select", "multiselect", "user", "int", "currency", "pct", "date"}
90
  MAX_FIELD_OPTIONS = 50
91
 
92
  #: Key prefix of a FORMULA-MEASURE column (owner item 7, 2026-07-27): a user-created field that
 
244
  field = dict(base)
245
  if isinstance(meta.get("note"), str):
246
  field["note"] = meta["note"][:2000]
247
+ # PRESET measure fields (wave-2 item 8, 2026-07-27): the frozen derived columns
248
+ # (revenue_ytd / revenue_ly / orders_24m) became measure-carrying fields whose PERIOD
249
+ # the user can change from the column menu. The KEY is a permanent alias β€” saved
250
+ # views/filters/widths keep working β€” and the saved stratum may override ONLY the
251
+ # window (+ the auto-renamed label). The MEASURE key is pinned to the base's: a preset
252
+ # can change period, never what it measures (fail closed).
253
+ if base.get("preset") and isinstance(base.get("measure"), dict):
254
+ saved_measure = meta.get("measure") if isinstance(meta.get("measure"), dict) else {}
255
+ window = _clean_window(saved_measure.get("window"))
256
+ if window is not None:
257
+ field["measure"] = {"key": base["measure"]["key"], "window": window}
258
+ if isinstance(meta.get("label"), str) and meta["label"].strip():
259
+ field["label"] = meta["label"][:120]
260
  out.append(field)
261
  for key, field in saved.items():
262
  if key in base_keys or not isinstance(field, dict):
 
287
  if field.get("type") not in CUSTOM_FIELD_TYPES:
288
  continue
289
  ftype = field["type"]
290
+ options = (_clean_options(field.get("options"))
291
+ if ftype in ("select", "multiselect") else [])
292
+ if ftype in ("select", "multiselect") and not options:
293
  # A select with no surviving choices can never hold a value. Dropping the COLUMN
294
  # would lose the user's data; degrading it to text keeps every stored value
295
  # readable and lets them re-add choices.
 
303
  "custom": True,
304
  "agg": field.get("agg") if field.get("agg") in {"sum"} else None,
305
  "note": str(field.get("note") or "")[:2000],
306
+ **({"options": options} if ftype in ("select", "multiselect") else {}),
307
+ # comma-joined SET semantics (the Cohorts column's contract): the row belongs to
308
+ # every member, groups count it under each, the toolbar count stays distinct.
309
+ **({"multi": True} if ftype == "multiselect" else {}),
310
  })
311
  if cohorts:
312
  out.append(cohort_field())
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
 
aios_grid_fields.json CHANGED
@@ -97,30 +97,42 @@
97
  },
98
  {
99
  "key": "revenue_ytd",
100
- "label": "YTD $",
101
  "type": "currency",
102
  "source": "odoo",
103
  "default": true,
104
  "agg": "sum",
105
- "filterable": false
 
 
 
 
106
  },
107
  {
108
  "key": "revenue_ly",
109
- "label": "LY $",
110
  "type": "currency",
111
  "source": "odoo",
112
  "default": true,
113
  "agg": "sum",
114
- "filterable": false
 
 
 
 
115
  },
116
  {
117
  "key": "orders_24m",
118
- "label": "Orders 24M",
119
  "type": "int",
120
  "source": "odoo",
121
  "default": true,
122
  "agg": "sum",
123
- "filterable": false
 
 
 
 
124
  },
125
  {
126
  "key": "last_order",
 
97
  },
98
  {
99
  "key": "revenue_ytd",
100
+ "label": "Sales Β· year to date",
101
  "type": "currency",
102
  "source": "odoo",
103
  "default": true,
104
  "agg": "sum",
105
+ "filterable": false,
106
+ "preset": true,
107
+ "derived": true,
108
+ "measure": {"key": "revenue", "window": {"kind": "ytd"}},
109
+ "note": "Pre-set measure: Sales over an editable period (column menu > Period). Computed live from line-level data; the key is a permanent alias so saved views survive."
110
  },
111
  {
112
  "key": "revenue_ly",
113
+ "label": "Sales Β· last year to date",
114
  "type": "currency",
115
  "source": "odoo",
116
  "default": true,
117
  "agg": "sum",
118
+ "filterable": false,
119
+ "preset": true,
120
+ "derived": true,
121
+ "measure": {"key": "revenue", "window": {"kind": "ytd_last_year"}},
122
+ "note": "Pre-set measure: Sales over an editable period (column menu > Period). Computed live from line-level data; the key is a permanent alias so saved views survive."
123
  },
124
  {
125
  "key": "orders_24m",
126
+ "label": "Orders Β· the last 730 days",
127
  "type": "int",
128
  "source": "odoo",
129
  "default": true,
130
  "agg": "sum",
131
+ "filterable": false,
132
+ "preset": true,
133
+ "derived": true,
134
+ "measure": {"key": "orders", "window": {"kind": "last_n_days", "n": 730}},
135
+ "note": "Pre-set measure: order count over an editable period (column menu > Period). 730 days is the closest window to the old fixed 24 months."
136
  },
137
  {
138
  "key": "last_order",
app.py CHANGED
@@ -110,7 +110,15 @@ HERE = Path(__file__).parent
110
  _FONT = "'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif"
111
  _CSS = """
112
  <style>
113
- @import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&display=swap');
 
 
 
 
 
 
 
 
114
  :root{
115
  /* 3-ink navy-undertone neutral system (Stripe/Mercury-calibrated) + brand navy/gold */
116
  --navy:#1F4E78; --navy-d:#16385a; --navy-x:#102842; --ink:#1A2332; --ink-2:#42526B;
@@ -142,14 +150,12 @@ section[data-testid="stMain"]:has(.aios-grid-host-marker) [data-testid="stVertic
142
  }
143
  /* Full-height grid (owner item 10). The element-style height comes from the component's
144
  setFrameHeight handshake; this !important wins, and the React shell (100%-height + a
145
- ResizeObserver) follows the box it is given. Offsets measured against the page chrome that
146
- remains: Customer = padding only; Cohort = the pills row above the table. */
 
147
  section[data-testid="stMain"]:has(.aios-grid-host-marker) iframe[title*="aios_customer_grid"]{
148
  height:calc(100vh - 46px) !important; min-height:480px;
149
  }
150
- section[data-testid="stMain"]:has(.aios-grid-host-cohort) iframe[title*="aios_customer_grid"]{
151
- height:calc(100vh - 106px) !important;
152
- }
153
  /* Cohort with nothing in it (owner item 6): a near-empty, low-text state β€” no info box. */
154
  .cohort-empty{ display:flex; flex-direction:column; align-items:center; justify-content:center;
155
  min-height:62vh; gap:.4rem; color:var(--ink-2); font-weight:600; font-size:1.04rem; }
@@ -237,6 +243,12 @@ h1,h2,h3,h4,h5{ font-family:__FONT__; color:var(--navy); letter-spacing:-.012em;
237
 
238
  /* ---- sidebar: native [theme.sidebar] paints bg/text/widgets; CSS adds structure only ---- */
239
  [data-testid="stSidebar"]{ border-right:1px solid #E3E8EE; } /* visible light-grey border (owner) */
 
 
 
 
 
 
240
  [data-testid="stSidebar"] .brand{ font-weight:700; font-size:1.12rem; color:#1A2332;
241
  letter-spacing:.01em; padding-left:2px; }
242
  [data-testid="stSidebar"] .brand-sub{ font-size:.62rem; color:#64748D; letter-spacing:.05em;
@@ -501,7 +513,8 @@ ul[data-testid="stSelectboxVirtualDropdown"] li[aria-selected="true"]{
501
  [data-testid="stSidebar"] [role="radiogroup"] label p{ font-weight:600; font-size:.8rem;
502
  color:#1A2332; white-space:nowrap; }
503
  /* sidebar SECONDARY buttons = a FLAT NAV LIST (owner 2026-07-12): left-aligned text, no box β€”
504
- items separated by ONE hairline, no vertical gaps. The Analyst (primary) keeps its fill. */
 
505
  [data-testid="stSidebar"] .stButton button[kind="secondary"]{ background:transparent;
506
  color:#42526B; border:none; border-radius:0; font-weight:500; width:100%;
507
  justify-content:flex-start; text-align:left; padding:.42rem .15rem; min-height:0;
@@ -5531,7 +5544,19 @@ def _cl_handle_one(event, uname, allowed_pids, fields, measure_keys=(),
5531
  if field is None:
5532
  return False
5533
  elif key in field_by_key and not key.startswith('custom_'):
5534
- field = {**field_by_key[key], 'note': str(raw.get('note') or '')[:2000]}
 
 
 
 
 
 
 
 
 
 
 
 
5535
  elif (key.startswith('custom_') and raw.get('source') == 'overlay'
5536
  and raw.get('type') in _ag2.CUSTOM_FIELD_TYPES):
5537
  field = {'key': key, 'label': str(raw.get('label') or 'Untitled')[:120],
@@ -5539,10 +5564,10 @@ def _cl_handle_one(event, uname, allowed_pids, fields, measure_keys=(),
5539
  'custom': True, 'note': str(raw.get('note') or '')[:2000]}
5540
  if raw.get('agg') == 'sum':
5541
  field['agg'] = 'sum'
5542
- # A `select` carries its own vocabulary; a `user` does NOT β€” its choices are the
5543
- # tenant's accounts, resolved fresh on every render, so persisting a snapshot here
5544
- # would go stale the moment somebody joins or leaves.
5545
- if raw['type'] == 'select':
5546
  field['options'] = _ag2._clean_options(raw.get('options'))
5547
  if not field['options']:
5548
  return False # a select with no choices can never hold a value
@@ -5558,6 +5583,42 @@ def _cl_handle_one(event, uname, allowed_pids, fields, measure_keys=(),
5558
  ws['fields'][key] = field
5559
  return True
5560
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5561
  if kind == 'field_delete':
5562
  # Delete a USER-CREATED column outright (owner gap closed 2026-07-27). The prefix IS
5563
  # the permission: only the created strata (`custom_` overlay fields, `measure_` formula
@@ -5762,7 +5823,7 @@ def _cl_grid_colcfg(label, extra_help=None):
5762
 
5763
 
5764
  def _table_grid(*, uname, team_id, pool_rows, grid_rows, stamp, defs=None,
5765
- storage_key, grid_key, height, hide_views=False, cohort_variant=False):
5766
  """THE table-page grid block β€” ONE implementation of the Airtable-style work surface
5767
  (the table-page factory, owner directive 2026-07-27: duplicating the Customer table to
5768
  the next object must be a registry row + a config, not a copy of page_customer_data).
@@ -5798,17 +5859,23 @@ def _table_grid(*, uname, team_id, pool_rows, grid_rows, stamp, defs=None,
5798
  # the cell says cannot disagree. visible() scopes membership to what this caller may see;
5799
  # membership is filtered against the caller's WHOLE pool (not this surface's rows) so a
5800
  # condition on ANOTHER cohort stays answerable from every table page.
5801
- cohort_lists = [{'id': cid, 'name': c.get('name') or cid,
5802
- 'pids': [p for p in (c.get('members') or []) if p in pool_pids]}
5803
- for cid, c in sorted(cohort_mod.visible(uname, pool_pids).items(),
5804
- key=lambda kv: (kv[1].get('name') or '').lower())]
 
 
 
 
 
 
 
 
5805
  fields = aios_grid.fields_from_workspace(ws, cohorts=bool(cohort_lists))
5806
  views = aios_grid.views_from_defs(defs or {}, ws.get('views'), fields)
5807
  # Page-scoped CSS sentinel: removes the dashboard max-width so the component follows the
5808
- # main column; the cohort variant subtracts the sub-rail's extra height (-106px).
5809
- st.markdown("<span class='aios-grid-host-marker%s'></span>"
5810
- % (' aios-grid-host-cohort' if cohort_variant else ''),
5811
- unsafe_allow_html=True)
5812
  # CG-8 measure conditions β€” resolved HERE, server-side, to a pid set per condition; the
5813
  # client engine treats each as a membership test, so the table's counts stay its own.
5814
  # The pending event is read from the component's OWN return value at the top of this run,
@@ -5824,6 +5891,11 @@ def _table_grid(*, uname, team_id, pool_rows, grid_rows, stamp, defs=None,
5824
  workspace = {'storageKey': storage_key, 'views': views, 'lists': cohort_lists}
5825
  if hide_views:
5826
  workspace['hideViews'] = True
 
 
 
 
 
5827
  ev = aios_grid.render(
5828
  aios_grid.rows_from_pool(grid_rows, fields, ws.get('overlays'), derived=derived),
5829
  fields, workspace=workspace, key=grid_key, height=height,
@@ -5843,20 +5915,18 @@ def _table_grid(*, uname, team_id, pool_rows, grid_rows, stamp, defs=None,
5843
 
5844
 
5845
  def page_cohort():
5846
- """Cohort β€” the SAME table as Customer over a FIXED set of customers.
5847
-
5848
- The one difference, and the reason the module exists: membership is not a query. A saved view
5849
- re-populates as the data moves ("who is overdue today"); a cohort does not ("the 40 accounts
5850
- we agreed to call in Q3"). You can still filter, sort, group and add columns β€” those narrow
5851
- what is DISPLAYED; only a person adds or removes a member.
5852
-
5853
- REDESIGNED to the owner's spec 2026-07-27 (items 4/6/10): NO page title, NO cohort dropdown,
5854
- NO "New cohort" button β€” cohorts are BORN on the Customer table (check rows β†’ "Add to
5855
- cohort", or a view's Β·Β·Β· menu β†’ "Add to list"), so this page only ever shows lists that
5856
- exist. Switching is a row of pills; rename/membership/delete live in one compact "Manage"
5857
- popover; with no cohorts the page is a near-empty, low-text state. The grid hides its Views
5858
- sidebar (`hideViews`) β€” the cohort IS the row set, so an "All customers" tab beside it would
5859
- name a set this table does not hold.
5860
  """
5861
  u = current_user()
5862
  uname = u.get('username', '')
@@ -5865,91 +5935,35 @@ def page_cohort():
5865
  with st.spinner('Building the customer pool…'):
5866
  b = custlist_pool(agent, team_id)
5867
  rows = b['rows']
5868
- by_pid = {r['pid']: r for r in rows}
5869
- # Membership is filtered against the pool the CURRENT user may see, on read β€” so a scope
5870
- # change takes effect immediately without rewriting anyone's stored cohort.
5871
- books = cohort_mod.visible(uname, set(by_pid))
5872
 
5873
  if not store.available():
5874
  st.caption('Cohort persistence is unavailable (no HF_TOKEN configured) β€” anything you '
5875
  'create here lasts only for this session.')
5876
 
5877
- if not books:
5878
- # Owner item 6: a very clean, low-text empty state β€” no info box, no chrome.
 
 
5879
  st.markdown(
5880
  "<div class='cohort-empty'>No cohorts yet"
5881
  "<span>Select customers on the Customer table and choose Add to cohort.</span>"
5882
  "</div>", unsafe_allow_html=True)
5883
  return
5884
 
5885
- ids = sorted(books, key=lambda c: (books[c].get('name') or '').lower())
5886
- labels = {c: f"{books[c].get('name') or c} Β· {len(books[c]['members'])}" for c in ids}
5887
- prev = st.session_state.get('_cohort_last')
5888
- head = st.columns([5.2, 0.8], vertical_alignment='center')
5889
- with head[0]:
5890
- # Pills, not a dropdown (owner item 4): every cohort visible in one click. The widget is
5891
- # stateless-keyed; `default` restores the last-open cohort across reruns of this page.
5892
- active = st.pills('Cohort', ids, format_func=lambda c: labels[c],
5893
- default=(prev if prev in books else ids[0]),
5894
- key='cohort_pills', label_visibility='collapsed')
5895
- active = active if active in books else ids[0]
5896
- st.session_state['_cohort_last'] = active
5897
- c = books[active]
5898
- crows, missing = cohort_mod.rows_for(c, rows)
5899
-
5900
- with head[1].popover('Manage', width='stretch'):
5901
- # Everything that EDITS the cohort, in one place: add / remove / rename / delete.
5902
- # (Adding is also on the Customer table via row selection β€” this is the in-place path.)
5903
- add = st.multiselect(
5904
- 'Add customers', [p for p in by_pid if p not in set(c['members'])],
5905
- format_func=lambda p: by_pid[p]['customer'], key=f'coh_add_{active}',
5906
- placeholder='Search the book…')
5907
- if st.button('Add to cohort', key=f'coh_add_go_{active}', disabled=not add):
5908
- cohort_mod.add_members(uname, active, add)
5909
- st.rerun()
5910
- drop = st.multiselect(
5911
- 'Remove customers', [p for p in c['members'] if p in by_pid],
5912
- format_func=lambda p: by_pid[p]['customer'], key=f'coh_del_{active}',
5913
- placeholder='Pick members to remove…')
5914
- if st.button('Remove from cohort', key=f'coh_del_go_{active}', disabled=not drop):
5915
- cohort_mod.remove_members(uname, active, drop)
5916
- st.rerun()
5917
- rn = st.text_input('Rename', value=c.get('name', ''), key=f'coh_rn_{active}')
5918
- rc = st.columns(2)
5919
- if rc[0].button('Save name', key=f'coh_rn_go_{active}',
5920
- disabled=not rn.strip() or rn == c.get('name')):
5921
- cohort_mod.rename(uname, active, rn)
5922
- st.rerun()
5923
- if rc[1].button('Delete cohort', key=f'coh_rm_{active}', type='tertiary'):
5924
- cohort_mod.delete(uname, active)
5925
- st.session_state.pop('_cohort_last', None)
5926
- st.rerun()
5927
-
5928
- if missing:
5929
- # Rule 8b: a member can drop out of the 24-month pool without the cohort being wrong,
5930
- # and a silently shorter table is exactly the unverifiable count rule forbids. Rendered
5931
- # ONLY when true, so the page stays text-free in the ordinary case.
5932
- st.caption(f"{missing:,} member{'' if missing == 1 else 's'} not active in the last "
5933
- f"24 months, so not shown.")
5934
-
5935
  try:
5936
- # The factory call IS this page's grid (owner items 4/6/10 live in the config):
5937
- # hideViews because the cohort IS the row set β€” an "All customers" tab beside it would
5938
- # name a set this table does not hold; storageKey is per COHORT so one list's filters
5939
- # never leak onto another; measure conditions + formula columns resolve over the
5940
- # COHORT's rows (the zero-group is what this table holds); defs={} β€” legacy list
5941
- # formulas are the Customer page's projection, not this one's.
5942
- if _table_grid(uname=uname, team_id=team_id, pool_rows=rows, grid_rows=crows,
5943
  stamp=b['pulled_at'], defs={},
5944
- storage_key=(f"royal-imports:cohort:{uname}:{active}:"
5945
  f"{team_id if team_id is not None else 'all'}"),
5946
- grid_key=f'cohort_grid_{active}', height=640,
5947
- hide_views=True, cohort_variant=True):
5948
  st.rerun()
5949
  except Exception as _e:
5950
  _tel.error('cohort:grid', _e)
5951
  st.warning('The table could not render. Cohort membership is unaffected β€” '
5952
- 'use Manage above.')
5953
 
5954
 
5955
  def page_customer_data():
@@ -8071,7 +8085,10 @@ def main():
8071
  # The Analyst can query ALL company data in plain language (it is NOT module-scoped), so it
8072
  # is gated like a module: hidden for restricted users (agents, module-limited staff).
8073
  if may_open('analyst'):
8074
- st.button('AIOS Analyst', width='stretch', type='primary', on_click=_nav_analyst,
 
 
 
8075
  help='Chat with your company: ask anything in plain language, or have it '
8076
  'build a dashboard or workflow for you β€” every answer runs through '
8077
  'governed queries with drill-downs.')
 
110
  _FONT = "'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif"
111
  _CSS = """
112
  <style>
113
+ /* SELF-HOSTED Inter (wave-2 item 1, 2026-07-27). The Google @import made every cold first
114
+ paint a FOUT: the login/loading screens rendered in Segoe until the network fetch landed β€”
115
+ "the loading screen font is not the same font as the app". The variable woff2 (wght 100-900,
116
+ full latin coverage β€” verified with fontTools) is the SAME bytes the grid bundle embeds, so
117
+ both documents render identical glyphs; served same-origin via Streamlit static serving it
118
+ loads in milliseconds, and font-display:block means text simply never paints in the wrong
119
+ face. */
120
+ @font-face{ font-family:'Inter'; font-style:normal; font-weight:100 900;
121
+ font-display:block; src:url(/app/static/fonts/Inter-var.woff2) format('woff2'); }
122
  :root{
123
  /* 3-ink navy-undertone neutral system (Stripe/Mercury-calibrated) + brand navy/gold */
124
  --navy:#1F4E78; --navy-d:#16385a; --navy-x:#102842; --ink:#1A2332; --ink-2:#42526B;
 
150
  }
151
  /* Full-height grid (owner item 10). The element-style height comes from the component's
152
  setFrameHeight handshake; this !important wins, and the React shell (100%-height + a
153
+ ResizeObserver) follows the box it is given. Offset measured against the page chrome that
154
+ remains (padding only β€” wave-2 item 2 removed the Cohort page's pills row, so both table
155
+ pages share one geometry). */
156
  section[data-testid="stMain"]:has(.aios-grid-host-marker) iframe[title*="aios_customer_grid"]{
157
  height:calc(100vh - 46px) !important; min-height:480px;
158
  }
 
 
 
159
  /* Cohort with nothing in it (owner item 6): a near-empty, low-text state β€” no info box. */
160
  .cohort-empty{ display:flex; flex-direction:column; align-items:center; justify-content:center;
161
  min-height:62vh; gap:.4rem; color:var(--ink-2); font-weight:600; font-size:1.04rem; }
 
243
 
244
  /* ---- sidebar: native [theme.sidebar] paints bg/text/widgets; CSS adds structure only ---- */
245
  [data-testid="stSidebar"]{ border-right:1px solid #E3E8EE; } /* visible light-grey border (owner) */
246
+ /* the BRAND block sits AT THE TOP (wave-2 item 9): Streamlit reserves a tall header strip for
247
+ the collapse chevron plus ~1.5rem of user-content padding, which floated the title in dead
248
+ space. Shrink both; the chevron keeps its top-right corner. */
249
+ section[data-testid="stSidebar"][aria-expanded="true"] [data-testid="stSidebarHeader"]{
250
+ padding:4px 8px 0; min-height:0; height:30px; }
251
+ [data-testid="stSidebar"] [data-testid="stSidebarUserContent"]{ padding-top:2px; }
252
  [data-testid="stSidebar"] .brand{ font-weight:700; font-size:1.12rem; color:#1A2332;
253
  letter-spacing:.01em; padding-left:2px; }
254
  [data-testid="stSidebar"] .brand-sub{ font-size:.62rem; color:#64748D; letter-spacing:.05em;
 
513
  [data-testid="stSidebar"] [role="radiogroup"] label p{ font-weight:600; font-size:.8rem;
514
  color:#1A2332; white-space:nowrap; }
515
  /* sidebar SECONDARY buttons = a FLAT NAV LIST (owner 2026-07-12): left-aligned text, no box β€”
516
+ items separated by ONE hairline, no vertical gaps. The Analyst joined this list 2026-07-27
517
+ (wave-2 item 9: no solid-navy fill β€” same format as every other sidebar row). */
518
  [data-testid="stSidebar"] .stButton button[kind="secondary"]{ background:transparent;
519
  color:#42526B; border:none; border-radius:0; font-weight:500; width:100%;
520
  justify-content:flex-start; text-align:left; padding:.42rem .15rem; min-height:0;
 
5544
  if field is None:
5545
  return False
5546
  elif key in field_by_key and not key.startswith('custom_'):
5547
+ base = field_by_key[key]
5548
+ field = {**base, 'note': str(raw.get('note') or '')[:2000]}
5549
+ # PRESET measure fields (wave-2 item 8): the browser may change the PERIOD (and the
5550
+ # auto-renamed label) of revenue_ytd / revenue_ly / orders_24m β€” nothing else. The
5551
+ # whitelist IS the base contract: only a field that shipped with preset+measure can
5552
+ # take a window here, and the measure KEY is pinned to the base's (fail closed).
5553
+ if (base.get('preset') and isinstance(base.get('measure'), dict)
5554
+ and isinstance(raw.get('measure'), dict)):
5555
+ window = _ag2._clean_window(raw['measure'].get('window'))
5556
+ if window is not None:
5557
+ field['measure'] = {'key': base['measure']['key'], 'window': window}
5558
+ if isinstance(raw.get('label'), str) and raw['label'].strip():
5559
+ field['label'] = str(raw['label'])[:120]
5560
  elif (key.startswith('custom_') and raw.get('source') == 'overlay'
5561
  and raw.get('type') in _ag2.CUSTOM_FIELD_TYPES):
5562
  field = {'key': key, 'label': str(raw.get('label') or 'Untitled')[:120],
 
5564
  'custom': True, 'note': str(raw.get('note') or '')[:2000]}
5565
  if raw.get('agg') == 'sum':
5566
  field['agg'] = 'sum'
5567
+ # A `select`/`multiselect` carries its own vocabulary; a `user` does NOT β€” its
5568
+ # choices are the tenant's accounts, resolved fresh on every render, so persisting
5569
+ # a snapshot here would go stale the moment somebody joins or leaves.
5570
+ if raw['type'] in ('select', 'multiselect'):
5571
  field['options'] = _ag2._clean_options(raw.get('options'))
5572
  if not field['options']:
5573
  return False # a select with no choices can never hold a value
 
5583
  ws['fields'][key] = field
5584
  return True
5585
 
5586
+ if kind in ('cohort_add', 'cohort_remove', 'cohort_rename', 'cohort_delete'):
5587
+ # Cohort membership/lifecycle edits from the grid's cohort panel (wave-2 item 2 β€”
5588
+ # replaces the retired Manage popover, so rename/delete keep a surface). Fail-closed:
5589
+ # only the caller's OWN cohorts (all_for), and member pids are intersected with the
5590
+ # caller's permitted pool β€” the same guard add_to_list rides.
5591
+ if not store.available():
5592
+ return False
5593
+ cohort_id = str(event.get('cohortId') or '').strip()[:120]
5594
+ if not cohort_id or cohort_id not in cohort_mod.all_for(uname):
5595
+ return False
5596
+ try:
5597
+ if kind == 'cohort_rename':
5598
+ name = str(event.get('name') or '').strip()[:120]
5599
+ if not name:
5600
+ return False
5601
+ cohort_mod.rename(uname, cohort_id, name)
5602
+ elif kind == 'cohort_delete':
5603
+ cohort_mod.delete(uname, cohort_id)
5604
+ else:
5605
+ raw_pids = event.get('pids')
5606
+ if not isinstance(raw_pids, list):
5607
+ return False
5608
+ pids = [p for p in raw_pids if isinstance(p, int) and p in allowed_pids]
5609
+ if not pids:
5610
+ return False
5611
+ if kind == 'cohort_add':
5612
+ cohort_mod.add_members(uname, cohort_id, pids)
5613
+ else:
5614
+ cohort_mod.remove_members(uname, cohort_id, pids)
5615
+ except ValueError as e:
5616
+ _tel.error('cohort:panel-edit', e)
5617
+ return False
5618
+ # True: the lists payload (names, membership, counts) must reflect this on the next
5619
+ # render β€” the panel is showing server truth, not local optimism.
5620
+ return True
5621
+
5622
  if kind == 'field_delete':
5623
  # Delete a USER-CREATED column outright (owner gap closed 2026-07-27). The prefix IS
5624
  # the permission: only the created strata (`custom_` overlay fields, `measure_` formula
 
5823
 
5824
 
5825
  def _table_grid(*, uname, team_id, pool_rows, grid_rows, stamp, defs=None,
5826
+ storage_key, grid_key, height, hide_views=False, cohort_mode=False):
5827
  """THE table-page grid block β€” ONE implementation of the Airtable-style work surface
5828
  (the table-page factory, owner directive 2026-07-27: duplicating the Customer table to
5829
  the next object must be a registry row + a config, not a copy of page_customer_data).
 
5859
  # the cell says cannot disagree. visible() scopes membership to what this caller may see;
5860
  # membership is filtered against the caller's WHOLE pool (not this surface's rows) so a
5861
  # condition on ANOTHER cohort stays answerable from every table page.
5862
+ cohort_lists = []
5863
+ for cid, c in sorted(cohort_mod.visible(uname, pool_pids).items(),
5864
+ key=lambda kv: (kv[1].get('name') or '').lower()):
5865
+ members = [p for p in (c.get('members') or []) if p in pool_pids]
5866
+ entry = {'id': cid, 'name': c.get('name') or cid, 'pids': members}
5867
+ # Rule 8b: a member can drop out of the 24-month pool without the cohort being wrong,
5868
+ # and a silently smaller cohort is exactly what the unverifiable-count rule forbids.
5869
+ # The client's cohort panel discloses this count when it is non-zero.
5870
+ missing = len(c.get('members') or []) - len(members)
5871
+ if missing:
5872
+ entry['missing'] = missing
5873
+ cohort_lists.append(entry)
5874
  fields = aios_grid.fields_from_workspace(ws, cohorts=bool(cohort_lists))
5875
  views = aios_grid.views_from_defs(defs or {}, ws.get('views'), fields)
5876
  # Page-scoped CSS sentinel: removes the dashboard max-width so the component follows the
5877
+ # main column when the owner collapses/opens Streamlit navigation.
5878
+ st.markdown("<span class='aios-grid-host-marker'></span>", unsafe_allow_html=True)
 
 
5879
  # CG-8 measure conditions β€” resolved HERE, server-side, to a pid set per condition; the
5880
  # client engine treats each as a membership test, so the table's counts stay its own.
5881
  # The pending event is read from the component's OWN return value at the top of this run,
 
5891
  workspace = {'storageKey': storage_key, 'views': views, 'lists': cohort_lists}
5892
  if hide_views:
5893
  workspace['hideViews'] = True
5894
+ if cohort_mode:
5895
+ # Wave-2 item 2: the Cohort page IS the Customer surface with the left panel showing
5896
+ # COHORTS instead of views β€” the client narrows the pool to the active cohort's members
5897
+ # and its toolbar count is the cohort's, never the whole book's.
5898
+ workspace['cohortMode'] = True
5899
  ev = aios_grid.render(
5900
  aios_grid.rows_from_pool(grid_rows, fields, ws.get('overlays'), derived=derived),
5901
  fields, workspace=workspace, key=grid_key, height=height,
 
5915
 
5916
 
5917
  def page_cohort():
5918
+ """Cohort β€” the SAME work surface as Customer over FIXED, hand-curated sets (wave-2
5919
+ items 2/5, 2026-07-27 β€” supersedes the same morning's pills + Manage design).
5920
+
5921
+ The one difference from Customer, and the reason the module exists: membership is not a
5922
+ query. A saved view re-populates as the data moves ("who is overdue today"); a cohort does
5923
+ not ("the 40 accounts we agreed to call in Q3"). The LEFT PANEL is the user's cohort list
5924
+ (the grid's cohortMode replaces the Views panel); the grid holds the WHOLE scoped pool and
5925
+ the client narrows to the active cohort's members, so the toolbar count is the cohort's.
5926
+ Membership edits arrive as cohort_add / cohort_remove / cohort_rename / cohort_delete
5927
+ events β€” all fail-closed to the caller's own cohorts in _cl_handle_one. Cohorts are BORN
5928
+ on the Customer table (row selection β†’ Add to cohort, or a view's Β·Β·Β· menu); with none,
5929
+ this page is a near-empty, low-text state.
 
 
5930
  """
5931
  u = current_user()
5932
  uname = u.get('username', '')
 
5935
  with st.spinner('Building the customer pool…'):
5936
  b = custlist_pool(agent, team_id)
5937
  rows = b['rows']
 
 
 
 
5938
 
5939
  if not store.available():
5940
  st.caption('Cohort persistence is unavailable (no HF_TOKEN configured) β€” anything you '
5941
  'create here lasts only for this session.')
5942
 
5943
+ # Membership is filtered against the pool the CURRENT user may see, on read β€” so a scope
5944
+ # change takes effect immediately without rewriting anyone's stored cohort.
5945
+ if not cohort_mod.visible(uname, {r['pid'] for r in rows}):
5946
+ # A very clean, low-text empty state β€” no info box, no chrome (owner, 2026-07-27).
5947
  st.markdown(
5948
  "<div class='cohort-empty'>No cohorts yet"
5949
  "<span>Select customers on the Customer table and choose Add to cohort.</span>"
5950
  "</div>", unsafe_allow_html=True)
5951
  return
5952
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5953
  try:
5954
+ # The factory call IS this page (wave-2 item 2: EXACT Customer layout). ONE storage
5955
+ # key for the page β€” the active cohort is client state inside the grid, not a page
5956
+ # remount; defs={} because legacy list formulas are the Customer page's projection.
5957
+ if _table_grid(uname=uname, team_id=team_id, pool_rows=rows, grid_rows=rows,
 
 
 
5958
  stamp=b['pulled_at'], defs={},
5959
+ storage_key=(f"royal-imports:cohort:{uname}:"
5960
  f"{team_id if team_id is not None else 'all'}"),
5961
+ grid_key='cohort_aios_grid', height=760, cohort_mode=True):
 
5962
  st.rerun()
5963
  except Exception as _e:
5964
  _tel.error('cohort:grid', _e)
5965
  st.warning('The table could not render. Cohort membership is unaffected β€” '
5966
+ 'manage members from the Customer table.')
5967
 
5968
 
5969
  def page_customer_data():
 
8085
  # The Analyst can query ALL company data in plain language (it is NOT module-scoped), so it
8086
  # is gated like a module: hidden for restricted users (agents, module-limited staff).
8087
  if may_open('analyst'):
8088
+ # Same FORMAT as every other sidebar row (wave-2 item 9): the flat-nav secondary
8089
+ # style + a Material icon β€” no solid-navy primary fill setting it apart.
8090
+ st.button('AIOS Analyst', width='stretch', icon=':material/forum:',
8091
+ on_click=_nav_analyst,
8092
  help='Chat with your company: ask anything in plain language, or have it '
8093
  'build a dashboard or workflow for you β€” every answer runs through '
8094
  'governed queries with drill-downs.')
core/table_store.py CHANGED
@@ -68,8 +68,10 @@ class TableStore:
68
  def _save(ws):
69
  # A cleared note on an immutable source field returns to the canonical schema
70
  # instead of leaving a meaningless override row. Custom fields remain even with
71
- # an empty note.
72
- if not field.get('custom') and not str(field.get('note') or '').strip():
 
 
73
  ws['fields'].pop(key, None)
74
  else:
75
  ws['fields'][key] = dict(field)
 
68
  def _save(ws):
69
  # A cleared note on an immutable source field returns to the canonical schema
70
  # instead of leaving a meaningless override row. Custom fields remain even with
71
+ # an empty note β€” and so does a PRESET field carrying a measure-window override
72
+ # (wave-2 item 8): its note may be empty but its period is real user state.
73
+ if (not field.get('custom') and not str(field.get('note') or '').strip()
74
+ and not isinstance(field.get('measure'), dict)):
75
  ws['fields'].pop(key, None)
76
  else:
77
  ws['fields'][key] = dict(field)
static/fonts/Inter-var.woff2 ADDED
Binary file (48.3 kB). View file