Spaces:
Paused
Paused
Deploy Data Management Platform (rename + sales forecast removed)
Browse files- aios_grid.py +87 -0
- aios_grid_component/index.html +0 -0
- aios_grid_embed.html +0 -0
- app.py +222 -90
- core/registry.py +8 -7
- harness/measure_filter.py +42 -0
- ui/primitives.py +10 -13
aios_grid.py
CHANGED
|
@@ -86,6 +86,15 @@ def _round(v):
|
|
| 86 |
CUSTOM_FIELD_TYPES = {"text", "select", "user", "int", "currency", "pct", "date"}
|
| 87 |
MAX_FIELD_OPTIONS = 50
|
| 88 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 89 |
|
| 90 |
def _clean_options(raw):
|
| 91 |
"""Choices for a `select`: strings, trimmed, de-duplicated case-insensitively, capped.
|
|
@@ -160,12 +169,69 @@ def cohort_cells(cohorts, allowed_pids=None):
|
|
| 160 |
return {pid: {COHORT_COLUMN: ', '.join(names)} for pid, names in cells.items()}
|
| 161 |
|
| 162 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 163 |
def fields_from_workspace(workspace=None, cohorts=False):
|
| 164 |
"""Overlay persisted notes/custom fields onto the immutable source-field contract.
|
| 165 |
|
| 166 |
`cohorts=True` appends the derived cohort column β see `cohort_field`. Appended LAST and
|
| 167 |
`default: False`, so it never displaces a column somebody already reads; the Fields menu is
|
| 168 |
where you turn it on.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 169 |
"""
|
| 170 |
saved = dict((workspace or {}).get("fields") or {})
|
| 171 |
out = []
|
|
@@ -179,6 +245,27 @@ def fields_from_workspace(workspace=None, cohorts=False):
|
|
| 179 |
for key, field in saved.items():
|
| 180 |
if key in base_keys or not isinstance(field, dict):
|
| 181 |
continue
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 182 |
if not str(key).startswith("custom_") or field.get("source") != "overlay":
|
| 183 |
continue
|
| 184 |
if field.get("type") not in CUSTOM_FIELD_TYPES:
|
|
|
|
| 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
|
| 90 |
+
#: IS a measure over a window β `Sales Β· the last 90 days` as a column. Mirrors the client's
|
| 91 |
+
#: `measure_` keys in CustomerGrid.createField. Distinct from `custom_` because the two strata
|
| 92 |
+
#: could not be more different: `custom_` is the EDITABLE overlay (user-typed values), while a
|
| 93 |
+
#: measure field is READ-ONLY and its values are computed by the host per render.
|
| 94 |
+
MEASURE_FIELD_PREFIX = "measure_"
|
| 95 |
+
#: The numeric types a measure can render as (semantic._FORMAT_TYPE's range).
|
| 96 |
+
MEASURE_FIELD_TYPES = {"currency", "int", "pct"}
|
| 97 |
+
|
| 98 |
|
| 99 |
def _clean_options(raw):
|
| 100 |
"""Choices for a `select`: strings, trimmed, de-duplicated case-insensitively, capped.
|
|
|
|
| 169 |
return {pid: {COHORT_COLUMN: ', '.join(names)} for pid, names in cells.items()}
|
| 170 |
|
| 171 |
|
| 172 |
+
def clean_measure_field(raw, offered):
|
| 173 |
+
"""Validate one UNTRUSTED formula-measure field (owner item 7) against the caller's OFFER.
|
| 174 |
+
|
| 175 |
+
`offered` is `{measure key: {label, type}}` from `measure_filter.measure_fields(team_id)` β
|
| 176 |
+
the same admission the condition builder uses, so a field can only name a measure this
|
| 177 |
+
caller could also filter by. Returns the canonical stored shape, or None (fail closed).
|
| 178 |
+
|
| 179 |
+
`source:'odoo'` + `derived:True` is the cohort column's read-only mechanism, reused:
|
| 180 |
+
the client keys editability off `source == 'overlay'` and the host accepts cell writes only
|
| 181 |
+
for overlay keys, so a measure column cannot be typed into at either end. `filterable:False`
|
| 182 |
+
because the REPLACEMENT is the measure CONDITION with the same measure and window β the
|
| 183 |
+
governed, gate-proved path (CG-8/CG-12) β not text ops over a derived cell.
|
| 184 |
+
"""
|
| 185 |
+
if not isinstance(raw, dict):
|
| 186 |
+
return None
|
| 187 |
+
key = str(raw.get("key") or "")
|
| 188 |
+
if not key.startswith(MEASURE_FIELD_PREFIX) or len(key) > 80:
|
| 189 |
+
return None
|
| 190 |
+
spec = raw.get("measure")
|
| 191 |
+
if not isinstance(spec, dict):
|
| 192 |
+
return None
|
| 193 |
+
m = (offered or {}).get(spec.get("key"))
|
| 194 |
+
if not m:
|
| 195 |
+
return None # not admitted for this caller -> fail closed
|
| 196 |
+
window = _clean_window(spec.get("window"))
|
| 197 |
+
if window is None:
|
| 198 |
+
return None # a measure column with no period is not a column
|
| 199 |
+
mtype = m.get("type") if m.get("type") in MEASURE_FIELD_TYPES else "currency"
|
| 200 |
+
return {
|
| 201 |
+
"key": key,
|
| 202 |
+
"label": str(raw.get("label") or m.get("label") or "Measure")[:120],
|
| 203 |
+
"type": mtype,
|
| 204 |
+
"source": "odoo",
|
| 205 |
+
"default": True,
|
| 206 |
+
"custom": True,
|
| 207 |
+
"derived": True,
|
| 208 |
+
"filterable": False,
|
| 209 |
+
"agg": "sum" if mtype in ("currency", "int") else None,
|
| 210 |
+
"note": str(raw.get("note") or "")[:2000],
|
| 211 |
+
"measure": {"key": str(spec.get("key"))[:80], "window": window},
|
| 212 |
+
}
|
| 213 |
+
|
| 214 |
+
|
| 215 |
+
def measure_fields_of(fields):
|
| 216 |
+
"""The formula-measure columns among `fields` β the ones whose values the host must compute
|
| 217 |
+
per render (see `rows_from_pool`'s `derived`)."""
|
| 218 |
+
return [f for f in fields or [] if isinstance(f.get("measure"), dict)]
|
| 219 |
+
|
| 220 |
+
|
| 221 |
def fields_from_workspace(workspace=None, cohorts=False):
|
| 222 |
"""Overlay persisted notes/custom fields onto the immutable source-field contract.
|
| 223 |
|
| 224 |
`cohorts=True` appends the derived cohort column β see `cohort_field`. Appended LAST and
|
| 225 |
`default: False`, so it never displaces a column somebody already reads; the Fields menu is
|
| 226 |
where you turn it on.
|
| 227 |
+
|
| 228 |
+
Three saved strata pass through: notes on base fields, `custom_` overlay fields (editable),
|
| 229 |
+
and `measure_` formula-measure fields (read-only, host-computed β owner item 7). A measure
|
| 230 |
+
field was validated against the caller's measure OFFER when it was written
|
| 231 |
+
(`clean_measure_field`); here only its SHAPE is re-checked, because this module has zero
|
| 232 |
+
app-internal imports and cannot know the offer. A measure that has since become
|
| 233 |
+
unanswerable (a BU scope on a company-level measure) degrades to a BLANK column at value
|
| 234 |
+
time, never to an error.
|
| 235 |
"""
|
| 236 |
saved = dict((workspace or {}).get("fields") or {})
|
| 237 |
out = []
|
|
|
|
| 245 |
for key, field in saved.items():
|
| 246 |
if key in base_keys or not isinstance(field, dict):
|
| 247 |
continue
|
| 248 |
+
if (str(key).startswith(MEASURE_FIELD_PREFIX)
|
| 249 |
+
and isinstance(field.get("measure"), dict)):
|
| 250 |
+
window = _clean_window(field["measure"].get("window"))
|
| 251 |
+
mkey = str(field["measure"].get("key") or "")
|
| 252 |
+
if window is None or not mkey:
|
| 253 |
+
continue
|
| 254 |
+
mtype = field.get("type") if field.get("type") in MEASURE_FIELD_TYPES else "currency"
|
| 255 |
+
out.append({
|
| 256 |
+
"key": str(key)[:80],
|
| 257 |
+
"label": str(field.get("label") or "Measure")[:120],
|
| 258 |
+
"type": mtype,
|
| 259 |
+
"source": "odoo",
|
| 260 |
+
"default": bool(field.get("default", True)),
|
| 261 |
+
"custom": True,
|
| 262 |
+
"derived": True,
|
| 263 |
+
"filterable": False,
|
| 264 |
+
"agg": "sum" if mtype in ("currency", "int") else None,
|
| 265 |
+
"note": str(field.get("note") or "")[:2000],
|
| 266 |
+
"measure": {"key": mkey[:80], "window": window},
|
| 267 |
+
})
|
| 268 |
+
continue
|
| 269 |
if not str(key).startswith("custom_") or field.get("source") != "overlay":
|
| 270 |
continue
|
| 271 |
if field.get("type") not in CUSTOM_FIELD_TYPES:
|
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
|
@@ -133,7 +133,31 @@ html, body, .stApp, [class*="css"]{ font-family:__FONT__; color:var(--ink);
|
|
| 133 |
main column gains when Streamlit's navigation collapses. `:has` scopes this to Customer List. */
|
| 134 |
section[data-testid="stMain"]:has(.aios-grid-host-marker) .block-container{
|
| 135 |
width:100%; max-width:none; padding-left:1rem; padding-right:1rem;
|
|
|
|
|
|
|
|
|
|
| 136 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 137 |
/* financial figures read on a grid: tabular numerals wherever numbers stack */
|
| 138 |
[data-testid="stMetricValue"], [data-testid="stMetricDelta"], .rowv, .rowt, .kpi-val, .kpi-delta,
|
| 139 |
[data-testid="stDataFrame"], .hc-impact{ font-variant-numeric:tabular-nums; }
|
|
@@ -5261,9 +5285,97 @@ def _cl_resolve_measures(views, pending_view, team_id, allowed_pids, stamp):
|
|
| 5261 |
return out
|
| 5262 |
|
| 5263 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 5264 |
def _cl_handle_grid_event(event, uname, allowed_pids, fields, measure_keys=(),
|
| 5265 |
-
resolved_ids=(), cohort_ids=()):
|
| 5266 |
-
"""Validate
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 5267 |
|
| 5268 |
Odoo-source fields are never accepted as cell updates. View and schema objects are
|
| 5269 |
user-scoped; row patches additionally require the pid to be in the currently permitted
|
|
@@ -5283,13 +5395,20 @@ def _cl_handle_grid_event(event, uname, allowed_pids, fields, measure_keys=(),
|
|
| 5283 |
field_upsert β changes the FIELD CONTRACT that rows_from_pool projects rows through
|
| 5284 |
overlay_patch β changes row VALUES this page and the entity drawers read
|
| 5285 |
view_delete β rare; kept conservative rather than shaved
|
|
|
|
|
|
|
|
|
|
| 5286 |
"""
|
| 5287 |
if not isinstance(event, dict):
|
| 5288 |
return False
|
| 5289 |
event_id = str(event.get('id') or '')[:180]
|
| 5290 |
-
|
|
|
|
| 5291 |
return False
|
| 5292 |
-
|
|
|
|
|
|
|
|
|
|
| 5293 |
kind = event.get('type')
|
| 5294 |
field_by_key = {f['key']: f for f in fields}
|
| 5295 |
valid_keys = set(field_by_key)
|
|
@@ -5402,7 +5521,14 @@ def _cl_handle_grid_event(event, uname, allowed_pids, fields, measure_keys=(),
|
|
| 5402 |
return False
|
| 5403 |
key = str(raw.get('key') or '')[:80]
|
| 5404 |
import aios_grid as _ag2
|
| 5405 |
-
if key
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 5406 |
field = {**field_by_key[key], 'note': str(raw.get('note') or '')[:2000]}
|
| 5407 |
elif (key.startswith('custom_') and raw.get('source') == 'overlay'
|
| 5408 |
and raw.get('type') in _ag2.CUSTOM_FIELD_TYPES):
|
|
@@ -5611,15 +5737,20 @@ def _cl_grid_colcfg(label, extra_help=None):
|
|
| 5611 |
|
| 5612 |
|
| 5613 |
def page_cohort():
|
| 5614 |
-
"""Cohort
|
| 5615 |
|
| 5616 |
The one difference, and the reason the module exists: membership is not a query. A saved view
|
| 5617 |
re-populates as the data moves ("who is overdue today"); a cohort does not ("the 40 accounts
|
| 5618 |
we agreed to call in Q3"). You can still filter, sort, group and add columns β those narrow
|
| 5619 |
what is DISPLAYED; only a person adds or removes a member.
|
| 5620 |
|
| 5621 |
-
|
| 5622 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 5623 |
"""
|
| 5624 |
u = current_user()
|
| 5625 |
uname = u.get('username', '')
|
|
@@ -5633,43 +5764,67 @@ def page_cohort():
|
|
| 5633 |
# change takes effect immediately without rewriting anyone's stored cohort.
|
| 5634 |
books = cohort_mod.visible(uname, set(by_pid))
|
| 5635 |
|
| 5636 |
-
dash_header('', 'Cohort',
|
| 5637 |
-
f"{u.get('name') or uname} Β· fixed customer lists you curate by hand Β· "
|
| 5638 |
-
f"{len(books)} cohort{'' if len(books) == 1 else 's'} Β· pulled {b['pulled_at']}",
|
| 5639 |
-
refresh=('refresh_cohort', custlist_pool))
|
| 5640 |
if not store.available():
|
| 5641 |
st.caption('Cohort persistence is unavailable (no HF_TOKEN configured) β anything you '
|
| 5642 |
'create here lasts only for this session.')
|
| 5643 |
|
| 5644 |
if not books:
|
| 5645 |
-
|
| 5646 |
-
|
| 5647 |
-
|
|
|
|
|
|
|
|
|
|
| 5648 |
|
| 5649 |
ids = sorted(books, key=lambda c: (books[c].get('name') or '').lower())
|
| 5650 |
labels = {c: f"{books[c].get('name') or c} Β· {len(books[c]['members'])}" for c in ids}
|
| 5651 |
-
|
| 5652 |
-
|
| 5653 |
-
|
| 5654 |
-
|
| 5655 |
-
|
| 5656 |
-
|
| 5657 |
-
|
| 5658 |
-
|
| 5659 |
-
|
| 5660 |
-
|
| 5661 |
-
st.error(str(e))
|
| 5662 |
-
|
| 5663 |
-
if not active:
|
| 5664 |
-
return
|
| 5665 |
c = books[active]
|
| 5666 |
crows, missing = cohort_mod.rows_for(c, rows)
|
| 5667 |
-
|
| 5668 |
-
|
| 5669 |
-
|
| 5670 |
-
|
| 5671 |
-
|
| 5672 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 5673 |
|
| 5674 |
try:
|
| 5675 |
import aios_grid
|
|
@@ -5683,7 +5838,8 @@ def page_cohort():
|
|
| 5683 |
for cid, c in sorted(cohort_mod.visible(uname, _pool_pids).items(),
|
| 5684 |
key=lambda kv: (kv[1].get('name') or '').lower())]
|
| 5685 |
_fields = aios_grid.fields_from_workspace(_ws, cohorts=bool(_cohort_lists))
|
| 5686 |
-
st.markdown("<span class='aios-grid-host-marker'></span>",
|
|
|
|
| 5687 |
# storageKey is per COHORT: view state belongs to the list you are looking at, and one
|
| 5688 |
# shared key would leak one cohort's filters onto every other.
|
| 5689 |
_views = aios_grid.views_from_defs({}, _ws.get('views'), _fields)
|
|
@@ -5692,64 +5848,38 @@ def page_cohort():
|
|
| 5692 |
# autosave here (an unknown colId is dropped) if this page did not know measures exist.
|
| 5693 |
# The zero-group is reconstructed over the COHORT's rows, which is what this table holds.
|
| 5694 |
_measures = _cl_measure_offer(team_id)
|
| 5695 |
-
|
| 5696 |
-
_pend_cfg = (((_pend or {}).get('view') or {}).get('config')
|
| 5697 |
-
if isinstance(_pend, dict) else None)
|
| 5698 |
_cohort_pids = {r['pid'] for r in crows}
|
| 5699 |
_msets = _cl_resolve_measures(_views, _pend_cfg, team_id, _cohort_pids, b['pulled_at'])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 5700 |
ev = aios_grid.render(
|
| 5701 |
-
aios_grid.rows_from_pool(crows, _fields, _ws.get('overlays'),
|
| 5702 |
-
derived=aios_grid.cohort_cells(_cohort_lists)),
|
| 5703 |
_fields,
|
| 5704 |
workspace={'storageKey': (f"royal-imports:cohort:{uname}:{active}:"
|
| 5705 |
f"{team_id if team_id is not None else 'all'}"),
|
| 5706 |
'views': _views,
|
|
|
|
|
|
|
| 5707 |
# Cohort shares its saved views with Data, so a view carrying a cohort
|
| 5708 |
# condition must find its vocabulary here too β otherwise this page's
|
| 5709 |
# next autosave would drop the condition as naming an unknown list.
|
| 5710 |
'lists': _cohort_lists},
|
| 5711 |
-
key=f'cohort_grid_{active}', height=
|
| 5712 |
measures=_measures, measure_sets=_msets, today=str(P.today()))
|
| 5713 |
if _cl_handle_grid_event(ev, uname, set(by_pid), _fields,
|
| 5714 |
measure_keys={m['key'] for m in _measures},
|
| 5715 |
resolved_ids=set(_msets),
|
| 5716 |
-
cohort_ids={c['id'] for c in _cohort_lists}
|
|
|
|
| 5717 |
st.rerun()
|
| 5718 |
except Exception as _e:
|
| 5719 |
_tel.error('cohort:grid', _e)
|
| 5720 |
-
st.warning('The table could not render.
|
| 5721 |
-
|
| 5722 |
-
section('Membership', 'A cohort changes only when somebody edits it β filtering the table '
|
| 5723 |
-
'above narrows what is displayed, never what is in the list.')
|
| 5724 |
-
mc = st.columns(2)
|
| 5725 |
-
with mc[0]:
|
| 5726 |
-
add = st.multiselect(
|
| 5727 |
-
'Add customers', [p for p in by_pid if p not in set(c['members'])],
|
| 5728 |
-
format_func=lambda p: by_pid[p]['customer'], key=f'coh_add_{active}',
|
| 5729 |
-
placeholder='Search the bookβ¦')
|
| 5730 |
-
if st.button('Add to cohort', key=f'coh_add_go_{active}', disabled=not add):
|
| 5731 |
-
cohort_mod.add_members(uname, active, add)
|
| 5732 |
-
st.rerun()
|
| 5733 |
-
with mc[1]:
|
| 5734 |
-
drop = st.multiselect(
|
| 5735 |
-
'Remove customers', [p for p in c['members'] if p in by_pid],
|
| 5736 |
-
format_func=lambda p: by_pid[p]['customer'], key=f'coh_del_{active}',
|
| 5737 |
-
placeholder='Pick members to removeβ¦')
|
| 5738 |
-
if st.button('Remove from cohort', key=f'coh_del_go_{active}', disabled=not drop):
|
| 5739 |
-
cohort_mod.remove_members(uname, active, drop)
|
| 5740 |
-
st.rerun()
|
| 5741 |
-
|
| 5742 |
-
with st.expander('Rename or delete this cohort'):
|
| 5743 |
-
rn = st.text_input('Name', value=c.get('name', ''), key=f'coh_rn_{active}')
|
| 5744 |
-
rc = st.columns(2)
|
| 5745 |
-
if rc[0].button('Save name', key=f'coh_rn_go_{active}',
|
| 5746 |
-
disabled=not rn.strip() or rn == c.get('name')):
|
| 5747 |
-
cohort_mod.rename(uname, active, rn)
|
| 5748 |
-
st.rerun()
|
| 5749 |
-
if rc[1].button('Delete cohort', key=f'coh_rm_{active}', type='tertiary'):
|
| 5750 |
-
cohort_mod.delete(uname, active)
|
| 5751 |
-
st.session_state.pop('cohort_pick', None)
|
| 5752 |
-
st.rerun()
|
| 5753 |
|
| 5754 |
|
| 5755 |
def page_customer_data():
|
|
@@ -5767,21 +5897,18 @@ def page_customer_data():
|
|
| 5767 |
with st.spinner('Building the customer poolβ¦'):
|
| 5768 |
b = custlist_pool(agent, team_id)
|
| 5769 |
rows = b['rows']
|
| 5770 |
-
|
| 5771 |
-
#
|
| 5772 |
-
#
|
| 5773 |
-
# keeps its own heading; two pages must not share one title.
|
| 5774 |
-
dash_header('', 'Customer',
|
| 5775 |
-
f"{u.get('name') or uname} Β· {scope} Β· {len(rows):,} customers active in the "
|
| 5776 |
-
f"last 24 months Β· pulled {b['pulled_at']}",
|
| 5777 |
-
refresh=('refresh_custlist', custlist_pool))
|
| 5778 |
if not store.available():
|
| 5779 |
st.caption('List persistence is unavailable (no HF_TOKEN configured) β lists you save '
|
| 5780 |
'here last only for this session.')
|
| 5781 |
|
| 5782 |
_toast = st.session_state.pop('_cohort_toast', None)
|
| 5783 |
if _toast:
|
| 5784 |
-
|
|
|
|
|
|
|
| 5785 |
|
| 5786 |
defs = _cl_defs(uname)
|
| 5787 |
by_pid = {r['pid']: r for r in rows}
|
|
@@ -5827,14 +5954,18 @@ def page_customer_data():
|
|
| 5827 |
# The pending event is read from the component's OWN return value at the top of this
|
| 5828 |
# run, so a condition the user just typed is answered in the same run that delivers it.
|
| 5829 |
_measures = _cl_measure_offer(team_id)
|
| 5830 |
-
_pending = st.session_state.get('cl_aios_grid')
|
| 5831 |
-
_pending_view = ((_pending or {}).get('view') or {}) if isinstance(_pending, dict) else {}
|
| 5832 |
_measure_sets = _cl_resolve_measures(
|
| 5833 |
-
_grid_views,
|
| 5834 |
team_id, set(by_pid), b['pulled_at'])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 5835 |
_grid_event = aios_grid.render(
|
| 5836 |
aios_grid.rows_from_pool(rows, _grid_fields, _table_ws.get('overlays'),
|
| 5837 |
-
derived=
|
| 5838 |
_grid_fields, workspace=_grid_workspace, key='cl_aios_grid', height=760,
|
| 5839 |
user_options=_assignable_people(),
|
| 5840 |
measures=_measures, measure_sets=_measure_sets, today=str(P.today()))
|
|
@@ -5845,7 +5976,8 @@ def page_customer_data():
|
|
| 5845 |
_grid_event, uname, set(by_pid), _grid_fields,
|
| 5846 |
measure_keys={m['key'] for m in _measures},
|
| 5847 |
resolved_ids=set(_measure_sets),
|
| 5848 |
-
cohort_ids={c['id'] for c in _grid_workspace['lists']}
|
|
|
|
| 5849 |
st.rerun()
|
| 5850 |
except Exception as _grid_error:
|
| 5851 |
_tel.error('customer-list:grid', _grid_error)
|
|
|
|
| 133 |
main column gains when Streamlit's navigation collapses. `:has` scopes this to Customer List. */
|
| 134 |
section[data-testid="stMain"]:has(.aios-grid-host-marker) .block-container{
|
| 135 |
width:100%; max-width:none; padding-left:1rem; padding-right:1rem;
|
| 136 |
+
/* owner item 10 (2026-07-27): no page title on the table pages β reclaim the dashboard
|
| 137 |
+
paddings so the grid starts at the top and runs the viewport. */
|
| 138 |
+
padding-top:.65rem; padding-bottom:.4rem;
|
| 139 |
}
|
| 140 |
+
section[data-testid="stMain"]:has(.aios-grid-host-marker) [data-testid="stVerticalBlock"]{
|
| 141 |
+
gap:.5rem;
|
| 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; }
|
| 156 |
+
.cohort-empty span{ color:var(--muted); font-weight:400; font-size:.85rem; }
|
| 157 |
+
/* Toasts read in the app font (owner item 1 β the add-to-cohort notification). */
|
| 158 |
+
[data-testid="stToast"]{ font-family:__FONT__; }
|
| 159 |
+
[data-testid="stToast"] [data-testid="stMarkdownContainer"] p{
|
| 160 |
+
font-family:__FONT__; font-size:.87rem; color:var(--ink); }
|
| 161 |
/* financial figures read on a grid: tabular numerals wherever numbers stack */
|
| 162 |
[data-testid="stMetricValue"], [data-testid="stMetricDelta"], .rowv, .rowt, .kpi-val, .kpi-delta,
|
| 163 |
[data-testid="stDataFrame"], .hc-impact{ font-variant-numeric:tabular-nums; }
|
|
|
|
| 5285 |
return out
|
| 5286 |
|
| 5287 |
|
| 5288 |
+
def _cl_measure_columns(fields, team_id, allowed_pids, stamp):
|
| 5289 |
+
"""Values for every FORMULA-MEASURE column (owner item 7) -> `{pid: {field key: value}}`.
|
| 5290 |
+
|
| 5291 |
+
Handed to `rows_from_pool(derived=β¦)` beside the cohort cells. Same memo discipline as
|
| 5292 |
+
`_cl_resolve_measures` β keyed on (data stamp, scope, pool identity, measure, window) so a
|
| 5293 |
+
re-render of an unchanged page costs no query, and the pool's identity (not size) is in the
|
| 5294 |
+
key because Cohort passes a different pool per cohort.
|
| 5295 |
+
|
| 5296 |
+
A column that cannot be computed (store down, BU scope on a company-level measure,
|
| 5297 |
+
unresolvable window) degrades to BLANK β the value dict simply omits that field key, and the
|
| 5298 |
+
client renders empty cells, never $0: blank is "could not compute", 0 is a real zero.
|
| 5299 |
+
"""
|
| 5300 |
+
mfields = [f for f in fields if isinstance(f.get('measure'), dict)]
|
| 5301 |
+
if not mfields:
|
| 5302 |
+
return {}
|
| 5303 |
+
from harness import measure_filter as _mf
|
| 5304 |
+
from harness import windows as _wn
|
| 5305 |
+
memo = st.session_state.setdefault('_cl_mcol_memo', {})
|
| 5306 |
+
pool_key = _hashlib.blake2b(
|
| 5307 |
+
repr(sorted(allowed_pids)).encode(), digest_size=8).hexdigest()
|
| 5308 |
+
out = {}
|
| 5309 |
+
for f in mfields:
|
| 5310 |
+
spec = f['measure']
|
| 5311 |
+
w = _wn.normalize(spec.get('window'))
|
| 5312 |
+
key = (stamp, team_id, pool_key, spec.get('key'),
|
| 5313 |
+
None if w is None else tuple(sorted(w.items())))
|
| 5314 |
+
if key not in memo:
|
| 5315 |
+
try:
|
| 5316 |
+
memo[key] = _mf.resolve_values(spec.get('key'), spec.get('window'),
|
| 5317 |
+
str(P.today()), team_id, allowed_pids)
|
| 5318 |
+
except Exception as _e:
|
| 5319 |
+
_tel.error('customer-list:measure-column', _e)
|
| 5320 |
+
memo[key] = None # remembered failure -> blank, not a retry storm
|
| 5321 |
+
vals = memo[key]
|
| 5322 |
+
if vals is None:
|
| 5323 |
+
continue
|
| 5324 |
+
fkey = f['key']
|
| 5325 |
+
for pid, v in vals.items():
|
| 5326 |
+
out.setdefault(pid, {})[fkey] = v
|
| 5327 |
+
if len(memo) > 100:
|
| 5328 |
+
memo.clear()
|
| 5329 |
+
return out
|
| 5330 |
+
|
| 5331 |
+
|
| 5332 |
def _cl_handle_grid_event(event, uname, allowed_pids, fields, measure_keys=(),
|
| 5333 |
+
resolved_ids=(), cohort_ids=(), measure_offer=()):
|
| 5334 |
+
"""Validate the untrusted component value and persist ONLY the external overlay stratum.
|
| 5335 |
+
|
| 5336 |
+
β THE VALUE IS AN EVENT LOG `{'events': [...]}`, NOT ONE EVENT (2026-07-27). A component
|
| 5337 |
+
has exactly one value slot, and two quick emits share it: creating a field emits
|
| 5338 |
+
`field_upsert` and the insertColumn autosave emits `view_upsert` 420ms later β with the
|
| 5339 |
+
server still inside the first rerun, the second write clobbered the slot before any run
|
| 5340 |
+
read it, and the field creation VANISHED with no error anywhere (measured live; the same
|
| 5341 |
+
race sat latent under overlay-field creation, masked by localStorage). The client now
|
| 5342 |
+
sends its recent window of events; each is processed exactly once, keyed by its id. The
|
| 5343 |
+
single-event shape is still accepted β it is what an older client in a stale tab sends.
|
| 5344 |
+
|
| 5345 |
+
Returns True when ANY processed event demands a re-render from server state.
|
| 5346 |
+
"""
|
| 5347 |
+
if isinstance(event, dict) and isinstance(event.get('events'), list):
|
| 5348 |
+
rerun = False
|
| 5349 |
+
for one in event['events'][-24:]:
|
| 5350 |
+
rerun = _cl_handle_one(one, uname, allowed_pids, fields, measure_keys,
|
| 5351 |
+
resolved_ids, cohort_ids, measure_offer) or rerun
|
| 5352 |
+
return rerun
|
| 5353 |
+
return _cl_handle_one(event, uname, allowed_pids, fields, measure_keys,
|
| 5354 |
+
resolved_ids, cohort_ids, measure_offer)
|
| 5355 |
+
|
| 5356 |
+
|
| 5357 |
+
def _cl_pending_view(component_value):
|
| 5358 |
+
"""The freshest `view_upsert` config in the component's CURRENT value, or None.
|
| 5359 |
+
|
| 5360 |
+
What `_cl_resolve_measures` treats as "the view the user just edited". Understands both
|
| 5361 |
+
the event-log shape and the legacy single-event one.
|
| 5362 |
+
"""
|
| 5363 |
+
if not isinstance(component_value, dict):
|
| 5364 |
+
return None
|
| 5365 |
+
events = component_value.get('events')
|
| 5366 |
+
if isinstance(events, list):
|
| 5367 |
+
for one in reversed(events):
|
| 5368 |
+
if isinstance(one, dict) and one.get('type') == 'view_upsert':
|
| 5369 |
+
view = one.get('view')
|
| 5370 |
+
return view.get('config') if isinstance(view, dict) else None
|
| 5371 |
+
return None
|
| 5372 |
+
view = component_value.get('view')
|
| 5373 |
+
return view.get('config') if isinstance(view, dict) else None
|
| 5374 |
+
|
| 5375 |
+
|
| 5376 |
+
def _cl_handle_one(event, uname, allowed_pids, fields, measure_keys=(),
|
| 5377 |
+
resolved_ids=(), cohort_ids=(), measure_offer=()):
|
| 5378 |
+
"""Validate ONE untrusted component event.
|
| 5379 |
|
| 5380 |
Odoo-source fields are never accepted as cell updates. View and schema objects are
|
| 5381 |
user-scoped; row patches additionally require the pid to be in the currently permitted
|
|
|
|
| 5395 |
field_upsert β changes the FIELD CONTRACT that rows_from_pool projects rows through
|
| 5396 |
overlay_patch β changes row VALUES this page and the entity drawers read
|
| 5397 |
view_delete β rare; kept conservative rather than shaved
|
| 5398 |
+
|
| 5399 |
+
The id dedupe is a SET (not a last-id slot): the event log resends the whole recent
|
| 5400 |
+
window on every emit, so every id must stay consumed, not just the latest one.
|
| 5401 |
"""
|
| 5402 |
if not isinstance(event, dict):
|
| 5403 |
return False
|
| 5404 |
event_id = str(event.get('id') or '')[:180]
|
| 5405 |
+
seen = st.session_state.setdefault('_cl_grid_seen_ids', {})
|
| 5406 |
+
if not event_id or event_id in seen:
|
| 5407 |
return False
|
| 5408 |
+
seen[event_id] = True
|
| 5409 |
+
if len(seen) > 400: # a session-lifetime set, kept bounded
|
| 5410 |
+
for stale in list(seen)[:200]:
|
| 5411 |
+
seen.pop(stale, None)
|
| 5412 |
kind = event.get('type')
|
| 5413 |
field_by_key = {f['key']: f for f in fields}
|
| 5414 |
valid_keys = set(field_by_key)
|
|
|
|
| 5521 |
return False
|
| 5522 |
key = str(raw.get('key') or '')[:80]
|
| 5523 |
import aios_grid as _ag2
|
| 5524 |
+
if key.startswith(_ag2.MEASURE_FIELD_PREFIX):
|
| 5525 |
+
# A FORMULA-MEASURE column (owner item 7). Validated against THIS caller's measure
|
| 5526 |
+
# offer β the same admission the condition builder uses β so a field can only name a
|
| 5527 |
+
# measure this user could also filter by. Fail closed on anything else.
|
| 5528 |
+
field = _ag2.clean_measure_field(raw, {m['key']: m for m in measure_offer})
|
| 5529 |
+
if field is None:
|
| 5530 |
+
return False
|
| 5531 |
+
elif key in field_by_key and not key.startswith('custom_'):
|
| 5532 |
field = {**field_by_key[key], 'note': str(raw.get('note') or '')[:2000]}
|
| 5533 |
elif (key.startswith('custom_') and raw.get('source') == 'overlay'
|
| 5534 |
and raw.get('type') in _ag2.CUSTOM_FIELD_TYPES):
|
|
|
|
| 5737 |
|
| 5738 |
|
| 5739 |
def page_cohort():
|
| 5740 |
+
"""Cohort β the SAME table as Customer over a FIXED set of customers.
|
| 5741 |
|
| 5742 |
The one difference, and the reason the module exists: membership is not a query. A saved view
|
| 5743 |
re-populates as the data moves ("who is overdue today"); a cohort does not ("the 40 accounts
|
| 5744 |
we agreed to call in Q3"). You can still filter, sort, group and add columns β those narrow
|
| 5745 |
what is DISPLAYED; only a person adds or removes a member.
|
| 5746 |
|
| 5747 |
+
REDESIGNED to the owner's spec 2026-07-27 (items 4/6/10): NO page title, NO cohort dropdown,
|
| 5748 |
+
NO "New cohort" button β cohorts are BORN on the Customer table (check rows β "Add to
|
| 5749 |
+
cohort", or a view's Β·Β·Β· menu β "Add to list"), so this page only ever shows lists that
|
| 5750 |
+
exist. Switching is a row of pills; rename/membership/delete live in one compact "Manage"
|
| 5751 |
+
popover; with no cohorts the page is a near-empty, low-text state. The grid hides its Views
|
| 5752 |
+
sidebar (`hideViews`) β the cohort IS the row set, so an "All customers" tab beside it would
|
| 5753 |
+
name a set this table does not hold.
|
| 5754 |
"""
|
| 5755 |
u = current_user()
|
| 5756 |
uname = u.get('username', '')
|
|
|
|
| 5764 |
# change takes effect immediately without rewriting anyone's stored cohort.
|
| 5765 |
books = cohort_mod.visible(uname, set(by_pid))
|
| 5766 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 5767 |
if not store.available():
|
| 5768 |
st.caption('Cohort persistence is unavailable (no HF_TOKEN configured) β anything you '
|
| 5769 |
'create here lasts only for this session.')
|
| 5770 |
|
| 5771 |
if not books:
|
| 5772 |
+
# Owner item 6: a very clean, low-text empty state β no info box, no chrome.
|
| 5773 |
+
st.markdown(
|
| 5774 |
+
"<div class='cohort-empty'>No cohorts yet"
|
| 5775 |
+
"<span>Select customers on the Customer table and choose Add to cohort.</span>"
|
| 5776 |
+
"</div>", unsafe_allow_html=True)
|
| 5777 |
+
return
|
| 5778 |
|
| 5779 |
ids = sorted(books, key=lambda c: (books[c].get('name') or '').lower())
|
| 5780 |
labels = {c: f"{books[c].get('name') or c} Β· {len(books[c]['members'])}" for c in ids}
|
| 5781 |
+
prev = st.session_state.get('_cohort_last')
|
| 5782 |
+
head = st.columns([5.2, 0.8], vertical_alignment='center')
|
| 5783 |
+
with head[0]:
|
| 5784 |
+
# Pills, not a dropdown (owner item 4): every cohort visible in one click. The widget is
|
| 5785 |
+
# stateless-keyed; `default` restores the last-open cohort across reruns of this page.
|
| 5786 |
+
active = st.pills('Cohort', ids, format_func=lambda c: labels[c],
|
| 5787 |
+
default=(prev if prev in books else ids[0]),
|
| 5788 |
+
key='cohort_pills', label_visibility='collapsed')
|
| 5789 |
+
active = active if active in books else ids[0]
|
| 5790 |
+
st.session_state['_cohort_last'] = active
|
|
|
|
|
|
|
|
|
|
|
|
|
| 5791 |
c = books[active]
|
| 5792 |
crows, missing = cohort_mod.rows_for(c, rows)
|
| 5793 |
+
|
| 5794 |
+
with head[1].popover('Manage', width='stretch'):
|
| 5795 |
+
# Everything that EDITS the cohort, in one place: add / remove / rename / delete.
|
| 5796 |
+
# (Adding is also on the Customer table via row selection β this is the in-place path.)
|
| 5797 |
+
add = st.multiselect(
|
| 5798 |
+
'Add customers', [p for p in by_pid if p not in set(c['members'])],
|
| 5799 |
+
format_func=lambda p: by_pid[p]['customer'], key=f'coh_add_{active}',
|
| 5800 |
+
placeholder='Search the bookβ¦')
|
| 5801 |
+
if st.button('Add to cohort', key=f'coh_add_go_{active}', disabled=not add):
|
| 5802 |
+
cohort_mod.add_members(uname, active, add)
|
| 5803 |
+
st.rerun()
|
| 5804 |
+
drop = st.multiselect(
|
| 5805 |
+
'Remove customers', [p for p in c['members'] if p in by_pid],
|
| 5806 |
+
format_func=lambda p: by_pid[p]['customer'], key=f'coh_del_{active}',
|
| 5807 |
+
placeholder='Pick members to removeβ¦')
|
| 5808 |
+
if st.button('Remove from cohort', key=f'coh_del_go_{active}', disabled=not drop):
|
| 5809 |
+
cohort_mod.remove_members(uname, active, drop)
|
| 5810 |
+
st.rerun()
|
| 5811 |
+
rn = st.text_input('Rename', value=c.get('name', ''), key=f'coh_rn_{active}')
|
| 5812 |
+
rc = st.columns(2)
|
| 5813 |
+
if rc[0].button('Save name', key=f'coh_rn_go_{active}',
|
| 5814 |
+
disabled=not rn.strip() or rn == c.get('name')):
|
| 5815 |
+
cohort_mod.rename(uname, active, rn)
|
| 5816 |
+
st.rerun()
|
| 5817 |
+
if rc[1].button('Delete cohort', key=f'coh_rm_{active}', type='tertiary'):
|
| 5818 |
+
cohort_mod.delete(uname, active)
|
| 5819 |
+
st.session_state.pop('_cohort_last', None)
|
| 5820 |
+
st.rerun()
|
| 5821 |
+
|
| 5822 |
+
if missing:
|
| 5823 |
+
# Rule 8b: a member can drop out of the 24-month pool without the cohort being wrong,
|
| 5824 |
+
# and a silently shorter table is exactly the unverifiable count rule forbids. Rendered
|
| 5825 |
+
# ONLY when true, so the page stays text-free in the ordinary case.
|
| 5826 |
+
st.caption(f"{missing:,} member{'' if missing == 1 else 's'} not active in the last "
|
| 5827 |
+
f"24 months, so not shown.")
|
| 5828 |
|
| 5829 |
try:
|
| 5830 |
import aios_grid
|
|
|
|
| 5838 |
for cid, c in sorted(cohort_mod.visible(uname, _pool_pids).items(),
|
| 5839 |
key=lambda kv: (kv[1].get('name') or '').lower())]
|
| 5840 |
_fields = aios_grid.fields_from_workspace(_ws, cohorts=bool(_cohort_lists))
|
| 5841 |
+
st.markdown("<span class='aios-grid-host-marker aios-grid-host-cohort'></span>",
|
| 5842 |
+
unsafe_allow_html=True)
|
| 5843 |
# storageKey is per COHORT: view state belongs to the list you are looking at, and one
|
| 5844 |
# shared key would leak one cohort's filters onto every other.
|
| 5845 |
_views = aios_grid.views_from_defs({}, _ws.get('views'), _fields)
|
|
|
|
| 5848 |
# autosave here (an unknown colId is dropped) if this page did not know measures exist.
|
| 5849 |
# The zero-group is reconstructed over the COHORT's rows, which is what this table holds.
|
| 5850 |
_measures = _cl_measure_offer(team_id)
|
| 5851 |
+
_pend_cfg = _cl_pending_view(st.session_state.get(f'cohort_grid_{active}'))
|
|
|
|
|
|
|
| 5852 |
_cohort_pids = {r['pid'] for r in crows}
|
| 5853 |
_msets = _cl_resolve_measures(_views, _pend_cfg, team_id, _cohort_pids, b['pulled_at'])
|
| 5854 |
+
# Formula-measure columns (owner item 7) β values over THIS cohort's rows.
|
| 5855 |
+
_derived = aios_grid.cohort_cells(_cohort_lists)
|
| 5856 |
+
for _pid, _cells in _cl_measure_columns(_fields, team_id, _cohort_pids,
|
| 5857 |
+
b['pulled_at']).items():
|
| 5858 |
+
_derived.setdefault(_pid, {}).update(_cells)
|
| 5859 |
ev = aios_grid.render(
|
| 5860 |
+
aios_grid.rows_from_pool(crows, _fields, _ws.get('overlays'), derived=_derived),
|
|
|
|
| 5861 |
_fields,
|
| 5862 |
workspace={'storageKey': (f"royal-imports:cohort:{uname}:{active}:"
|
| 5863 |
f"{team_id if team_id is not None else 'all'}"),
|
| 5864 |
'views': _views,
|
| 5865 |
+
# Owner items 4+6: the cohort IS the row set β no view switcher here.
|
| 5866 |
+
'hideViews': True,
|
| 5867 |
# Cohort shares its saved views with Data, so a view carrying a cohort
|
| 5868 |
# condition must find its vocabulary here too β otherwise this page's
|
| 5869 |
# next autosave would drop the condition as naming an unknown list.
|
| 5870 |
'lists': _cohort_lists},
|
| 5871 |
+
key=f'cohort_grid_{active}', height=640, user_options=_assignable_people(),
|
| 5872 |
measures=_measures, measure_sets=_msets, today=str(P.today()))
|
| 5873 |
if _cl_handle_grid_event(ev, uname, set(by_pid), _fields,
|
| 5874 |
measure_keys={m['key'] for m in _measures},
|
| 5875 |
resolved_ids=set(_msets),
|
| 5876 |
+
cohort_ids={c['id'] for c in _cohort_lists},
|
| 5877 |
+
measure_offer=_measures):
|
| 5878 |
st.rerun()
|
| 5879 |
except Exception as _e:
|
| 5880 |
_tel.error('cohort:grid', _e)
|
| 5881 |
+
st.warning('The table could not render. Cohort membership is unaffected β '
|
| 5882 |
+
'use Manage above.')
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 5883 |
|
| 5884 |
|
| 5885 |
def page_customer_data():
|
|
|
|
| 5897 |
with st.spinner('Building the customer poolβ¦'):
|
| 5898 |
b = custlist_pool(agent, team_id)
|
| 5899 |
rows = b['rows']
|
| 5900 |
+
# NO page title / caption (owner item 10, 2026-07-27): this page is a work SURFACE, and the
|
| 5901 |
+
# table gets every pixel. The scope facts the caption carried (whose book, row count, pull
|
| 5902 |
+
# time) all live in the table itself β the toolbar count and the sidebar's Refresh data.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 5903 |
if not store.available():
|
| 5904 |
st.caption('List persistence is unavailable (no HF_TOKEN configured) β lists you save '
|
| 5905 |
'here last only for this session.')
|
| 5906 |
|
| 5907 |
_toast = st.session_state.pop('_cohort_toast', None)
|
| 5908 |
if _toast:
|
| 5909 |
+
# A floating toast, not a banner (owner item 1): a banner above a full-height table
|
| 5910 |
+
# shoves the grid down for one run, and st.toast renders in the app font.
|
| 5911 |
+
st.toast(_toast + ' Open Cohort to work with it.')
|
| 5912 |
|
| 5913 |
defs = _cl_defs(uname)
|
| 5914 |
by_pid = {r['pid']: r for r in rows}
|
|
|
|
| 5954 |
# The pending event is read from the component's OWN return value at the top of this
|
| 5955 |
# run, so a condition the user just typed is answered in the same run that delivers it.
|
| 5956 |
_measures = _cl_measure_offer(team_id)
|
|
|
|
|
|
|
| 5957 |
_measure_sets = _cl_resolve_measures(
|
| 5958 |
+
_grid_views, _cl_pending_view(st.session_state.get('cl_aios_grid')),
|
| 5959 |
team_id, set(by_pid), b['pulled_at'])
|
| 5960 |
+
# Formula-measure columns (owner item 7): host-computed values, merged with the cohort
|
| 5961 |
+
# cells into ONE derived dict β the same read-only channel, never the cached pool rows.
|
| 5962 |
+
_derived = aios_grid.cohort_cells(_cohort_lists)
|
| 5963 |
+
for _pid, _cells in _cl_measure_columns(_grid_fields, team_id, set(by_pid),
|
| 5964 |
+
b['pulled_at']).items():
|
| 5965 |
+
_derived.setdefault(_pid, {}).update(_cells)
|
| 5966 |
_grid_event = aios_grid.render(
|
| 5967 |
aios_grid.rows_from_pool(rows, _grid_fields, _table_ws.get('overlays'),
|
| 5968 |
+
derived=_derived),
|
| 5969 |
_grid_fields, workspace=_grid_workspace, key='cl_aios_grid', height=760,
|
| 5970 |
user_options=_assignable_people(),
|
| 5971 |
measures=_measures, measure_sets=_measure_sets, today=str(P.today()))
|
|
|
|
| 5976 |
_grid_event, uname, set(by_pid), _grid_fields,
|
| 5977 |
measure_keys={m['key'] for m in _measures},
|
| 5978 |
resolved_ids=set(_measure_sets),
|
| 5979 |
+
cohort_ids={c['id'] for c in _grid_workspace['lists']},
|
| 5980 |
+
measure_offer=_measures):
|
| 5981 |
st.rerun()
|
| 5982 |
except Exception as _grid_error:
|
| 5983 |
_tel.error('customer-list:grid', _grid_error)
|
core/registry.py
CHANGED
|
@@ -22,13 +22,14 @@ REGISTRY = [
|
|
| 22 |
'note': 'Revenue, YoY, seasonality, reps, customers, SKUs β by BU.'},
|
| 23 |
{'key': 'customers', 'label': 'Customers', 'brand': True, 'hq': False, 'validate': True,
|
| 24 |
'note': 'Revenue bridge, segments, win-back, drawers β by BU.'},
|
| 25 |
-
# LABEL renamed 'Customer List' -> 'Data' (owner 2026-07-25)
|
| 26 |
-
# 'customer_list' -> 'customer_data' (owner 2026-07-26). The key
|
| 27 |
-
# because _LEGACY_KEYS (ui/session.py) migrates grants, Library prefs
|
| 28 |
-
# links ON READ β stored user records are never edited, exactly as
|
| 29 |
-
# was done. The STORE keys are deliberately NOT renamed:
|
| 30 |
-
# 'customer_lists' hold real user data, and renaming them
|
| 31 |
-
|
|
|
|
| 32 |
'note': 'Build, filter and save customer lists: the whole scoped book with per-customer '
|
| 33 |
'metrics; saved lists are visible, editable formulas (Call list and Win-back ship '
|
| 34 |
'as templates) plus hand-picked members. Sub-module of Customers (owner nav redesign 2026-07-23; replaced My Day).'},
|
|
|
|
| 22 |
'note': 'Revenue, YoY, seasonality, reps, customers, SKUs β by BU.'},
|
| 23 |
{'key': 'customers', 'label': 'Customers', 'brand': True, 'hq': False, 'validate': True,
|
| 24 |
'note': 'Revenue bridge, segments, win-back, drawers β by BU.'},
|
| 25 |
+
# LABEL renamed 'Customer List' -> 'Data' (owner 2026-07-25) -> 'Customer' (owner item 5,
|
| 26 |
+
# 2026-07-27); KEY renamed 'customer_list' -> 'customer_data' (owner 2026-07-26). The key
|
| 27 |
+
# rename is safe ONLY because _LEGACY_KEYS (ui/session.py) migrates grants, Library prefs
|
| 28 |
+
# and ?page= deep links ON READ β stored user records are never edited, exactly as
|
| 29 |
+
# myday->customer_list was done. The STORE keys are deliberately NOT renamed:
|
| 30 |
+
# 'customer_table_workspace' and 'customer_lists' hold real user data, and renaming them
|
| 31 |
+
# would orphan every saved view. Label-only changes need none of that machinery.
|
| 32 |
+
{'key': 'customer_data', 'label': 'Customer', 'brand': True, 'hq': False, 'validate': False, 'parent': 'customers',
|
| 33 |
'note': 'Build, filter and save customer lists: the whole scoped book with per-customer '
|
| 34 |
'metrics; saved lists are visible, editable formulas (Call list and Win-back ship '
|
| 35 |
'as templates) plus hand-picked members. Sub-module of Customers (owner nav redesign 2026-07-23; replaced My Day).'},
|
harness/measure_filter.py
CHANGED
|
@@ -529,6 +529,48 @@ def _zero_satisfies(op, value):
|
|
| 529 |
return _CMP[op](0.0, value)
|
| 530 |
|
| 531 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 532 |
def resolve_tree(rules, today, team_id=None, allowed_pids=None):
|
| 533 |
"""{rule_id: sorted pids} for every measure condition in a tree.
|
| 534 |
|
|
|
|
| 529 |
return _CMP[op](0.0, value)
|
| 530 |
|
| 531 |
|
| 532 |
+
def resolve_values(key, window, today, team_id=None, allowed_pids=None):
|
| 533 |
+
"""`{pid: display value}` for one (measure, window) over the caller's pool β the COLUMN
|
| 534 |
+
version of `resolve_rule` (owner item 7, 2026-07-27: a formula-measure FIELD).
|
| 535 |
+
|
| 536 |
+
Same `_totals` the filter conditions and statistics use, so the column and the condition
|
| 537 |
+
cannot disagree. Three display decisions live here, not in the client:
|
| 538 |
+
|
| 539 |
+
* ZERO-FILLED over the pool. A customer with no rows in the window has a measure of 0 β
|
| 540 |
+
the zero-group convention everywhere else β and 0 is a real value the cell shows. Blank
|
| 541 |
+
is reserved for "could not compute" (the caller omits the column entirely on failure).
|
| 542 |
+
* `input_scale` applied OUTWARD. `margin_pct` is a fraction (0-1) internally; the user
|
| 543 |
+
types percentage points into the filter (input divides by 100), so the CELL shows points
|
| 544 |
+
too (value Γ 100) β one boundary, both directions, and `yoy_pct` beside it already reads
|
| 545 |
+
in points.
|
| 546 |
+
* Rounded like every other numeric column: whole numbers for money/counts (the pool's own
|
| 547 |
+
`_round` convention), one decimal for a percent.
|
| 548 |
+
|
| 549 |
+
Raises for anything not admitted / an unresolvable window β the caller degrades that column
|
| 550 |
+
to blank rather than to a number nobody computed.
|
| 551 |
+
"""
|
| 552 |
+
topic_for(key) # raises for anything not admitted
|
| 553 |
+
# The window must RESOLVE before any query runs β same refusal as `_query_parts`, checked
|
| 554 |
+
# here too because a composite's `_totals` path resolves per base and would otherwise raise
|
| 555 |
+
# deeper with a less useful message.
|
| 556 |
+
if _win.resolve(window, today) is None:
|
| 557 |
+
raise _sem.ModelError(
|
| 558 |
+
f"unresolvable window {window!r} for the {key!r} column β refusing rather than "
|
| 559 |
+
f"defaulting to all time")
|
| 560 |
+
pool = _pool_of(allowed_pids)
|
| 561 |
+
con = _sem._store_con()
|
| 562 |
+
try:
|
| 563 |
+
totals = _totals(con, key, window, today, team_id)
|
| 564 |
+
finally:
|
| 565 |
+
con.close()
|
| 566 |
+
scale = ADMITTED.get(key, {}).get('input_scale') or 1.0
|
| 567 |
+
mtype = _sem._FORMAT_TYPE.get(_sem.metrics().get(key, {}).get('format'), 'currency')
|
| 568 |
+
nd = 1 if mtype == 'pct' else None # money/counts whole, percents one decimal
|
| 569 |
+
universe = pool if pool is not None else set(totals)
|
| 570 |
+
# round(x, None) returns an int β exactly the pool's `_round` convention for money/counts.
|
| 571 |
+
return {int(p): round(float(totals.get(p, 0.0)) * scale, nd) for p in universe}
|
| 572 |
+
|
| 573 |
+
|
| 574 |
def resolve_tree(rules, today, team_id=None, allowed_pids=None):
|
| 575 |
"""{rule_id: sorted pids} for every measure condition in a tree.
|
| 576 |
|
ui/primitives.py
CHANGED
|
@@ -64,19 +64,16 @@ _FMT = {'money': 'compact', 'money2': 'dollar', 'pct': '%.1f%%', 'pct0': '%.0f%%
|
|
| 64 |
|
| 65 |
|
| 66 |
def dash_header(icon, title, caption=None, refresh=None):
|
| 67 |
-
"""Page title bar: title
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
for fn in fns:
|
| 78 |
-
fn.clear()
|
| 79 |
-
st.rerun()
|
| 80 |
st.markdown("<div class='page-rule'></div>", unsafe_allow_html=True)
|
| 81 |
if caption:
|
| 82 |
st.caption(caption)
|
|
|
|
| 64 |
|
| 65 |
|
| 66 |
def dash_header(icon, title, caption=None, refresh=None):
|
| 67 |
+
"""Page title bar: title, a hairline rule with a gold head, then the caption.
|
| 68 |
+
|
| 69 |
+
(`icon` is accepted but unused β kept for call compatibility.)
|
| 70 |
+
|
| 71 |
+
`refresh` is ACCEPTED AND IGNORED (owner 2026-07-27): the per-page top-right Refresh button
|
| 72 |
+
is retired on every module β the sidebar's "Refresh data" (rail_refresh) is the ONE refresh
|
| 73 |
+
surface, clearing every cache at once. The parameter stays so ~30 call sites keep compiling;
|
| 74 |
+
do not re-render a button from it.
|
| 75 |
+
"""
|
| 76 |
+
st.markdown(f"<div class='page-title'>{title}</div>", unsafe_allow_html=True)
|
|
|
|
|
|
|
|
|
|
| 77 |
st.markdown("<div class='page-rule'></div>", unsafe_allow_html=True)
|
| 78 |
if caption:
|
| 79 |
st.caption(caption)
|