fsanyoto commited on
Commit
cd033e6
·
verified ·
1 Parent(s): 3d66855

Deploy CFO OS (redesigned UI)

Browse files
Files changed (2) hide show
  1. app.py +170 -124
  2. core/registry.py +1 -1
app.py CHANGED
@@ -190,7 +190,7 @@ def gate():
190
 
191
  def money(x, dp=0):
192
  try:
193
- return f"${x:,.{dp}f}"
194
  except Exception:
195
  return '—'
196
 
@@ -279,12 +279,65 @@ def _pretty(name):
279
  return (s[:1].upper() + s[1:]) if s else s
280
 
281
 
282
- def show_df(rows, cols=None, height=None):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
283
  """Standardized table with clean headers. `cols` maps column name → a format key
284
  ('money'|'money2'|'pct'|'pct0'|'int'|'num'|'x'|'days') or a (key, 'Label') tuple.
285
- Any column without an explicit label gets a prettified header automatically."""
286
  df = rows if isinstance(rows, pd.DataFrame) else pd.DataFrame(rows)
287
  cols = cols or {}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
288
  cfg = {}
289
  for name in df.columns:
290
  spec = cols.get(name)
@@ -297,7 +350,6 @@ def show_df(rows, cols=None, height=None):
297
  cfg[name] = st.column_config.NumberColumn(label, format=_FMT[kind])
298
  else:
299
  cfg[name] = st.column_config.Column(label)
300
- kw = {'height': height} if height is not None else {}
301
  st.dataframe(df, hide_index=True, width='stretch', column_config=cfg, **kw)
302
 
303
 
@@ -327,10 +379,15 @@ def _themed(ch, height=300):
327
 
328
  def chart_yoy_bars(trend):
329
  df = pd.DataFrame(trend)
 
 
 
 
 
330
  long = df.melt(id_vars='month', value_vars=['revenue_ly', 'revenue'],
331
  var_name='series', value_name='val')
332
  long['series'] = long['series'].map({'revenue_ly': 'Last year', 'revenue': 'This year'})
333
- ch = alt.Chart(long).mark_bar(cornerRadiusTopLeft=3, cornerRadiusTopRight=3).encode(
334
  x=alt.X('month:N', title=None, axis=alt.Axis(labelAngle=0)),
335
  xOffset=alt.XOffset('series:N'),
336
  y=alt.Y('val:Q', title=None, axis=alt.Axis(format='$~s')),
@@ -339,7 +396,11 @@ def chart_yoy_bars(trend):
339
  legend=alt.Legend(orient='top')),
340
  tooltip=[alt.Tooltip('month:N', title='Month'), 'series:N',
341
  alt.Tooltip('val:Q', title='Revenue', format='$,.0f')])
342
- st.altair_chart(_themed(ch, 300))
 
 
 
 
343
 
344
 
345
  def chart_margin_line(trend):
@@ -391,7 +452,7 @@ def chart_group_yoy(rows, label_key='group', n=15):
391
  'Last year': r.get('revenue_ly', 0.0)} for r in data])
392
  long = df.melt(id_vars='group', value_vars=['Last year', 'This year'],
393
  var_name='series', value_name='val')
394
- ch = alt.Chart(long).mark_bar(cornerRadiusTopRight=3, cornerRadiusBottomRight=3).encode(
395
  y=alt.Y('group:N', title=None, sort=order, axis=alt.Axis(labelLimit=150)),
396
  x=alt.X('val:Q', title=None, axis=alt.Axis(format='$~s')),
397
  yOffset=alt.YOffset('series:N'),
@@ -400,7 +461,15 @@ def chart_group_yoy(rows, label_key='group', n=15):
400
  legend=alt.Legend(orient='top')),
401
  tooltip=[alt.Tooltip('group:N', title='Group'), 'series:N',
402
  alt.Tooltip('val:Q', title='Revenue', format='$,.0f')])
403
- st.altair_chart(_themed(ch, max(240, len(data) * 28)))
 
 
 
 
 
 
 
 
404
 
405
 
406
  def chart_group_brand(rows, n=15):
@@ -651,31 +720,25 @@ def render_customer_detail(pid, team_id):
651
  {'label': 'Orders (LTM)', 'value': f"{d['orders_ltm']:,}", 'delta': f"AOV {money(d['aov_ltm'])}"},
652
  {'label': 'Gross margin % (LTM)', 'value': f"{d['ltm_gm_pct']:.1f}%", 'delta': money(d['ltm_margin'])},
653
  ])
654
- lc, rc = st.columns([1.35, 1])
655
- with lc:
656
- st.markdown('**Monthly revenue — this year vs last**')
657
- chart_yoy_bars(d['monthly'])
658
- with rc:
659
- st.markdown('**Top categories bought (LTM)**')
660
- show_df(d['top_categories'], cols={'category': ('text', 'Category'), 'revenue': 'money'}, height=250)
661
- sc1, sc2 = st.columns(2)
662
- with sc1:
663
- st.markdown('**Top SKUs bought (LTM)**')
664
- show_df(d['top_skus'], cols={'product': ('text', 'SKU'), 'revenue': ('money', '$'),
665
- 'qty': ('num', 'Qty'), 'margin': ('money', 'GM $')}, height=300)
666
- with sc2:
667
- st.markdown('**Recent orders**')
668
- show_df(d['recent_orders'], cols={'order': ('text', 'Order'), 'date': ('text', 'Date'),
669
- 'amount': ('money', '$'), 'status': ('text', 'Status')}, height=300)
670
 
671
 
672
  def page_customers():
673
  tid = brand_team()
674
  b = cust_bundle(tid)
675
  br = b['bridge']
676
- dash_header('', "Customers — what's driving the brand divergence",
677
  f"Live from Odoo · pulled {b['pulled_at']} · {brand_caption('customers')} · "
678
- "YTD vs same period last year, RI+FFS, excluded accounts removed.",
679
  refresh=('refresh_cust', [cust_bundle, cust_lists, cust_rollup, cust_directory, cust_detail]))
680
  kpi_row([
681
  {'label': 'Active customers (YTD)', 'value': f"{br['active_this']:,}",
@@ -685,64 +748,55 @@ def page_customers():
685
  {'label': 'Retained', 'value': f"{br['retained_n']:,}"},
686
  ])
687
 
688
- section('Revenue bridge — how the YoY change breaks down',
689
- 'Decomposes the revenue change vs the same period last year into four MECE drivers: '
690
- 'New/reactivated customers (+), Expansion from growing accounts (+), Contraction from '
691
- 'shrinking accounts (−), and Lost/churned customers (−). The four sum exactly from '
692
- 'last year to this year.')
693
  comp = [
694
  {'component': 'New', 'amount': br['new']['rev']},
695
  {'component': 'Expansion', 'amount': br['expansion']['rev']},
696
  {'component': 'Contraction', 'amount': br['contraction']['rev']},
697
  {'component': 'Lost', 'amount': br['lost']['rev']},
698
  ]
699
- bl, brr = st.columns([1.2, 1])
700
- with bl:
701
- chart_bridge(comp)
702
- brr.markdown(
703
- f"**Last year:** {money(br['last_total'])} \n"
704
- f"**+ New:** {money(br['new']['rev'])} ({br['new']['n']}) \n"
705
- f"**+ Expansion:** {money(br['expansion']['rev'])} ({br['expansion']['n']}) \n"
706
- f"**− Contraction:** {money(br['contraction']['rev'])} ({br['contraction']['n']}) \n"
707
- f"**− Lost:** {money(br['lost']['rev'])} ({br['lost']['n']}) \n"
708
- f"**= This year:** {money(br['this_total'])} ({br['change']:+,.0f})")
709
-
710
- section('The brand split — bridge mirrored for Fisch and Royal',
711
- 'The same revenue-bridge drivers computed separately for each DBA. Fisch reads as a '
712
- 'retention problem (won new accounts but lost more to contraction + churn); Royal grows '
713
- 'on new logos. Each brand row reconciles last→this independently.')
714
- show_df(b['by_brand'], cols={k: 'money' for k in
715
- ['last', 'this', 'change', 'new', 'expansion', 'contraction', 'lost']})
716
-
717
- section('Customer value pyramid (MECE, LTM)',
718
- 'Every active customer placed in exactly one value tier by trailing-12-month revenue. '
719
- 'A small share of customers (Whale + Large) drives most revenue; the long Small tail is '
720
- 'a minor share. Tiers and shares sum to 100%.')
721
  show_df(b['segments'], cols={'revenue': 'money', 'avg_rev': ('money', 'avg $/cust'),
722
  'rev_share': ('pct', 'rev %'), 'cust_share': ('pct', 'cust %')})
723
 
724
- section('Win-back & new-customer lists',
725
- 'At-risk = customers who bought materially last year but are down or gone this year, '
726
- 'ranked by dollars at risk (the win-back target list). New = customers acquired or '
727
- 'reactivated this year. Both honour the Brand (DBA) filter.')
728
  scope = st.session_state.get('brand', 'All') # driven by the global DBA selector
729
  lists = cust_lists(scope)
730
- wl, nl = st.columns(2)
731
- with wl:
732
- st.markdown(f'**At-risk / win-back — {scope}** (ranked by dollars at risk)')
733
- show_df(lists['at_risk'], cols={'rev_ly': ('money', 'LY $'), 'rev_ytd': ('money', 'YTD $'),
734
- 'at_risk': ('money', 'at risk $')}, height=320)
735
- with nl:
736
- st.markdown(f'**New / reactivated this year — {scope}**')
737
- show_df(lists['new'], cols={'rev_ytd': ('money', 'YTD $')}, height=320)
738
 
739
  # -------------------------------------------------- sum-level: dimensional rollups
740
  st.divider()
741
  consolidated = tid is None
742
- section('Customer rollups — slice revenue by dimension',
743
- 'Group YTD revenue (vs last year) by any customer attribute. MECE — each active '
744
- 'customer is in exactly one group, so the groups sum to total revenue. With Brand=All '
745
- 'each group also shows its Fisch and Royal split (the HQ→brand mirror).')
746
  dcol, scol, mcol = st.columns([1.2, 1.2, 1])
747
  dim_label = dcol.selectbox('Group by', list(cust_mod.DIMENSIONS.values()), key='cust_dim')
748
  dim = next(k for k, v in cust_mod.DIMENSIONS.items() if v == dim_label)
@@ -754,31 +808,27 @@ def page_customers():
754
  help='Hide groups below this YTD revenue.')
755
  shown = [r for r in roll
756
  if (not flt or flt.lower() in str(r['group']).lower()) and r['revenue'] >= minrev]
757
- rc1, rc2 = st.columns([1.25, 1])
758
- with rc1:
759
- if consolidated:
760
- show_df(shown, cols={'group': ('text', dim_label), 'revenue': ('money', 'Total YTD'),
761
- 'fisch': ('money', 'Fisch'), 'royal': ('money', 'Royal'),
762
- 'revenue_ly': ('money', 'LY $'), 'yoy_pct': ('pct', 'YoY %'),
763
- 'customers': ('int', '# cust'), 'avg_per_customer': ('money', 'avg $/cust')},
764
- height=400)
765
- else:
766
- show_df(shown, cols={'group': ('text', dim_label), 'revenue': ('money', 'YTD $'),
767
- 'revenue_ly': ('money', 'LY $'), 'yoy_pct': ('pct', 'YoY %'),
768
- 'customers': ('int', '# cust'), 'orders': ('int', '# orders'),
769
- 'avg_per_customer': ('money', 'avg $/cust')}, height=400)
770
- with rc2:
771
- (chart_group_brand if consolidated else chart_group_yoy)(shown, n=15)
772
- st.caption(f'{len(shown):,} of {len(roll):,} {dim_label.lower()} groups shown'
773
  + (' · bars split Fisch (navy) vs Royal (gold)' if consolidated
774
- else ' · bars show this year vs last'))
775
 
776
  # -------------------------------------------------- granular: click-through drill-down
777
  st.divider()
778
- section('Customer drill-down — filter, then click any customer',
779
- 'A filterable, searchable directory of every customer. Click a row to open the full '
780
- 'profile: KPIs, the Fisch/Royal mix, monthly trend, top SKUs and categories, and recent '
781
- 'orders. Honours the Brand (DBA) filter plus the filters below.')
782
  directory = cust_directory(tid)
783
  dir_pids = {r['pid'] for r in directory}
784
  states = sorted({r['state'] for r in directory})
@@ -865,7 +915,7 @@ def page_products():
865
  tid = brand_team()
866
  b = prod_bundle(tid)
867
  mv = b['movers']
868
- dash_header('', 'Products / SKU — SKU health',
869
  f"Live from Odoo · pulled {b['pulled_at']} · {brand_caption('products')} · YTD vs same "
870
  "period LY · services excluded · duplicate/re-coded SKUs merged by code (incl. archived).",
871
  refresh=('refresh_prod', [prod_bundle, prod_coverage]))
@@ -1053,7 +1103,9 @@ def page_sales():
1053
  # year-end forecast
1054
  fc = b['forecast']
1055
  company = next((r for r in fc if r['scope'] == 'Company'), fc[0])
1056
- st.markdown('#### Where we land in December (forecast)')
 
 
1057
  fcc = st.columns(3)
1058
  fcc[0].metric('Full-year 2026 forecast', money(company['forecast_full_year']),
1059
  f"{company['forecast_yoy_pct']:+.1f}% vs {company['ly_full_year']/1e6:.2f}M last year")
@@ -1064,49 +1116,42 @@ def page_sales():
1064
  'FY forecast': r['forecast_full_year'], 'LY full year': r['ly_full_year'],
1065
  'forecast YoY %': r['forecast_yoy_pct']} for r in fc],
1066
  cols={'YTD actual': 'money', 'projected H2': 'money', 'FY forecast': 'money',
1067
- 'LY full year': 'money', 'forecast YoY %': 'pct'})
1068
- st.caption('Method: actual YTD + last year\'s remaining months (the seasonal shape) scaled by '
1069
- 'the current YoY pace. Assumes the present run-rate holds — a baseline, not a target.')
1070
 
1071
- # seasonality / YoY trend
1072
- st.markdown('#### Monthly revenue — this year vs last year')
1073
  chart_yoy_bars(b['trend'])
1074
 
1075
- # revenue by category (YTD vs LY) — which categories drive/drag the number
1076
- st.markdown('#### Revenue by category — YTD vs last year')
1077
- st.caption('Which product categories are growing or shrinking. Switch the Brand (DBA) '
1078
- 'selector to see, e.g., which categories Fisch is losing.')
1079
  show_df(b['by_category'], cols={'revenue': ('money', 'revenue'), 'revenue_ly': ('money', 'LY revenue'),
1080
- 'change': ('money', 'Δ vs LY'), 'yoy_pct': ('pct', 'YoY %')}, height=320)
 
1081
 
1082
- # reorder behaviour (LTM)
1083
  cad = b['cadence']
1084
- st.markdown('#### Reorder behaviour (LTM) — are customers coming back?')
1085
- cc = st.columns([1.2, 1.2, 1.2, 2.4])
 
 
1086
  cc[0].metric('Repeat-purchase rate', f"{cad['repeat_rate']:.0f}%",
1087
  f"{cad['repeat_customers']:,} of {cad['customers']:,}", delta_color='off')
1088
  cc[1].metric('Avg orders / customer', f"{cad['avg_orders']:.1f}")
1089
  cc[2].metric('Orders (LTM)', f"{cad['total_orders']:,}")
1090
- with cc[3]:
1091
- show_df(cad['distribution'], cols={'customers': ('int', 'customers'), 'pct': ('pct0', '% of base')})
1092
- st.caption('A low repeat rate or a base skewed to "1 order" signals weak retention — '
1093
- 'cross-check the Customers win-back list.')
1094
 
1095
- left, right = st.columns(2)
1096
- with left:
1097
- st.markdown('#### By sales rep (YTD)')
1098
- show_df(b['by_rep'], cols={'revenue': 'money'})
1099
- with right:
1100
- st.markdown('#### Top customers (YTD)')
1101
- show_df(b['top_customers'], cols={'revenue': 'money'})
1102
 
1103
- st.markdown('#### Top SKUs (YTD)')
 
 
 
1104
  show_df(b['top_skus'], cols={'revenue': 'money', 'qty': 'num'}, height=300)
1105
 
1106
  con = b['concentration']
1107
- st.markdown(f"**Customer concentration** — top 10 = {con['top10_pct']:.0f}%, "
1108
- f"top 50 = {con['top50_pct']:.0f}%, top 100 = {con['top100_pct']:.0f}% "
1109
- f"of YTD revenue across {con['n_customers']:,} customers.")
1110
 
1111
  validation_panel(b['validation'], 'All sales metrics tie out to Odoo ground truth.')
1112
 
@@ -1181,16 +1226,17 @@ def main():
1181
  "<div class='brand-sub'>Royal Imports · Fisch Floral</div>",
1182
  unsafe_allow_html=True)
1183
  st.divider()
1184
- labels = [m['label'] for m in registry.REGISTRY]
1185
- choice = st.radio('Section', labels, label_visibility='collapsed')
1186
- choice_key = next(m['key'] for m in registry.REGISTRY if m['label'] == choice)
1187
- st.divider()
1188
  st.markdown("<div class='brand-sub'>Brand (DBA)</div>", unsafe_allow_html=True)
1189
  st.radio('Brand (DBA)', list(ctxlib.BRANDS.keys()), key='brand', horizontal=True,
1190
  label_visibility='collapsed',
1191
  help='Filters operational dashboards by doing-business-as (Fisch / Royal). '
1192
  'Company-level pages (Collections/AR, Data Health) stay consolidated.')
1193
  st.divider()
 
 
 
 
1194
  if st.button('Refresh ALL data from Odoo', width='stretch'):
1195
  st.cache_data.clear()
1196
  st.session_state['data_refreshed_at'] = dt.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
 
190
 
191
  def money(x, dp=0):
192
  try:
193
+ return f"-${abs(x):,.{dp}f}" if x < 0 else f"${x:,.{dp}f}"
194
  except Exception:
195
  return '—'
196
 
 
279
  return (s[:1].upper() + s[1:]) if s else s
280
 
281
 
282
+ # delta-cell background tints — light green for up (positive), light red for down (negative)
283
+ _BG_UP, _BG_DOWN = 'background-color:#E3F4E9', 'background-color:#FBE7E6'
284
+
285
+
286
+ def _fmt_cell(kind, v):
287
+ """Format one value for the Styler path (mirrors the NumberColumn presets used elsewhere)."""
288
+ if v is None or (isinstance(v, float) and pd.isna(v)):
289
+ return '—'
290
+ try:
291
+ if kind in ('money', 'money2'):
292
+ return money(v)
293
+ if kind == 'pct':
294
+ return f"{v:.1f}%"
295
+ if kind == 'pct0':
296
+ return f"{v:.0f}%"
297
+ if kind in ('int', 'num'):
298
+ return f"{v:,.0f}"
299
+ if kind == 'x':
300
+ return f"{v:.1f}x"
301
+ if kind == 'days':
302
+ return f"{v:.0f}"
303
+ except (TypeError, ValueError):
304
+ return v
305
+ return v
306
+
307
+
308
+ def show_df(rows, cols=None, height=None, highlight=None):
309
  """Standardized table with clean headers. `cols` maps column name → a format key
310
  ('money'|'money2'|'pct'|'pct0'|'int'|'num'|'x'|'days') or a (key, 'Label') tuple.
311
+ `highlight` = column names whose cells get a light green/red background by sign (deltas)."""
312
  df = rows if isinstance(rows, pd.DataFrame) else pd.DataFrame(rows)
313
  cols = cols or {}
314
+ kw = {'height': height} if height is not None else {}
315
+
316
+ if highlight and not df.empty:
317
+ # Styler path: format in-cell and tint delta cells by sign (red down / green up).
318
+ order = list(df.columns)
319
+ labelmap, kindmap = {}, {}
320
+ for name in order:
321
+ spec = cols.get(name)
322
+ kind, label = spec if isinstance(spec, tuple) else (spec, None)
323
+ labelmap[name] = label or _pretty(name)
324
+ kindmap[name] = kind
325
+ disp = df.rename(columns=labelmap)
326
+ fmtd = {labelmap[n]: (lambda v, k=kindmap[n]: _fmt_cell(k, v)) for n in order}
327
+ sty = disp.style.format(fmtd)
328
+
329
+ def _bg(v):
330
+ try:
331
+ x = float(v)
332
+ except (TypeError, ValueError):
333
+ return ''
334
+ return _BG_UP if x > 0 else (_BG_DOWN if x < 0 else '')
335
+ hl = [labelmap[c] for c in highlight if c in df.columns]
336
+ if hl:
337
+ sty = sty.map(_bg, subset=hl)
338
+ st.dataframe(sty, hide_index=True, width='stretch', **kw)
339
+ return
340
+
341
  cfg = {}
342
  for name in df.columns:
343
  spec = cols.get(name)
 
350
  cfg[name] = st.column_config.NumberColumn(label, format=_FMT[kind])
351
  else:
352
  cfg[name] = st.column_config.Column(label)
 
353
  st.dataframe(df, hide_index=True, width='stretch', column_config=cfg, **kw)
354
 
355
 
 
379
 
380
  def chart_yoy_bars(trend):
381
  df = pd.DataFrame(trend)
382
+ df['yoy'] = df.apply(lambda r: ((r['revenue'] - r['revenue_ly']) / r['revenue_ly'] * 100)
383
+ if r['revenue_ly'] else None, axis=1)
384
+ df['top'] = df[['revenue', 'revenue_ly']].max(axis=1)
385
+ df['lbl'] = df['yoy'].apply(lambda y: f"{y:+.0f}%" if pd.notna(y) else '')
386
+ df['up'] = df['yoy'].apply(lambda y: bool(pd.notna(y) and y >= 0))
387
  long = df.melt(id_vars='month', value_vars=['revenue_ly', 'revenue'],
388
  var_name='series', value_name='val')
389
  long['series'] = long['series'].map({'revenue_ly': 'Last year', 'revenue': 'This year'})
390
+ bars = alt.Chart(long).mark_bar(cornerRadiusTopLeft=3, cornerRadiusTopRight=3).encode(
391
  x=alt.X('month:N', title=None, axis=alt.Axis(labelAngle=0)),
392
  xOffset=alt.XOffset('series:N'),
393
  y=alt.Y('val:Q', title=None, axis=alt.Axis(format='$~s')),
 
396
  legend=alt.Legend(orient='top')),
397
  tooltip=[alt.Tooltip('month:N', title='Month'), 'series:N',
398
  alt.Tooltip('val:Q', title='Revenue', format='$,.0f')])
399
+ # YoY % printed above each month's pair, coloured by direction
400
+ text = alt.Chart(df).mark_text(dy=-6, fontSize=10, fontWeight='bold').encode(
401
+ x=alt.X('month:N'), y=alt.Y('top:Q'), text='lbl:N',
402
+ color=alt.condition('datum.up', alt.value(_UP), alt.value(_DOWN)))
403
+ st.altair_chart(_themed(alt.layer(bars, text), 300))
404
 
405
 
406
  def chart_margin_line(trend):
 
452
  'Last year': r.get('revenue_ly', 0.0)} for r in data])
453
  long = df.melt(id_vars='group', value_vars=['Last year', 'This year'],
454
  var_name='series', value_name='val')
455
+ bars = alt.Chart(long).mark_bar(cornerRadiusTopRight=3, cornerRadiusBottomRight=3).encode(
456
  y=alt.Y('group:N', title=None, sort=order, axis=alt.Axis(labelLimit=150)),
457
  x=alt.X('val:Q', title=None, axis=alt.Axis(format='$~s')),
458
  yOffset=alt.YOffset('series:N'),
 
461
  legend=alt.Legend(orient='top')),
462
  tooltip=[alt.Tooltip('group:N', title='Group'), 'series:N',
463
  alt.Tooltip('val:Q', title='Revenue', format='$,.0f')])
464
+ # YoY % at the end of each group's bars, coloured by direction
465
+ gdf = pd.DataFrame([{'group': str(r[label_key]), 'top': max(r['revenue'], r.get('revenue_ly', 0.0)),
466
+ 'up': bool(r.get('yoy_pct') is not None and r['yoy_pct'] >= 0),
467
+ 'lbl': (f"{r['yoy_pct']:+.0f}%" if r.get('yoy_pct') is not None else '')}
468
+ for r in data])
469
+ text = alt.Chart(gdf).mark_text(dx=4, align='left', fontSize=10, fontWeight='bold').encode(
470
+ y=alt.Y('group:N', sort=order), x=alt.X('top:Q'), text='lbl:N',
471
+ color=alt.condition('datum.up', alt.value(_UP), alt.value(_DOWN)))
472
+ st.altair_chart(_themed(alt.layer(bars, text), max(240, len(data) * 28)))
473
 
474
 
475
  def chart_group_brand(rows, n=15):
 
720
  {'label': 'Orders (LTM)', 'value': f"{d['orders_ltm']:,}", 'delta': f"AOV {money(d['aov_ltm'])}"},
721
  {'label': 'Gross margin % (LTM)', 'value': f"{d['ltm_gm_pct']:.1f}%", 'delta': money(d['ltm_margin'])},
722
  ])
723
+ st.markdown('**Monthly revenue — this year vs last**')
724
+ chart_yoy_bars(d['monthly'])
725
+ st.markdown('**Top SKUs bought (LTM)**')
726
+ show_df(d['top_skus'], cols={'product': ('text', 'SKU'), 'revenue': ('money', '$'),
727
+ 'qty': ('num', 'Qty'), 'margin': ('money', 'GM $')}, height=300)
728
+ st.markdown('**Top categories bought (LTM)**')
729
+ show_df(d['top_categories'], cols={'category': ('text', 'Category'), 'revenue': 'money'}, height=250)
730
+ st.markdown('**Recent orders**')
731
+ show_df(d['recent_orders'], cols={'order': ('text', 'Order'), 'date': ('text', 'Date'),
732
+ 'amount': ('money', '$'), 'status': ('text', 'Status')}, height=300)
 
 
 
 
 
 
733
 
734
 
735
  def page_customers():
736
  tid = brand_team()
737
  b = cust_bundle(tid)
738
  br = b['bridge']
739
+ dash_header('', 'Customer Dashboard',
740
  f"Live from Odoo · pulled {b['pulled_at']} · {brand_caption('customers')} · "
741
+ "YTD vs same period last year",
742
  refresh=('refresh_cust', [cust_bundle, cust_lists, cust_rollup, cust_directory, cust_detail]))
743
  kpi_row([
744
  {'label': 'Active customers (YTD)', 'value': f"{br['active_this']:,}",
 
748
  {'label': 'Retained', 'value': f"{br['retained_n']:,}"},
749
  ])
750
 
751
+ section('Revenue bridge', 'Decomposes the revenue change vs the same period last year into '
752
+ 'four MECE drivers — New/reactivated (+), Expansion (+), Contraction (−), Lost (−). '
753
+ 'They sum exactly from last year to this year.')
 
 
754
  comp = [
755
  {'component': 'New', 'amount': br['new']['rev']},
756
  {'component': 'Expansion', 'amount': br['expansion']['rev']},
757
  {'component': 'Contraction', 'amount': br['contraction']['rev']},
758
  {'component': 'Lost', 'amount': br['lost']['rev']},
759
  ]
760
+ chart_bridge(comp)
761
+ _bridge_line = (
762
+ f"Last year {money(br['last_total'])} → +New {money(br['new']['rev'])} ({br['new']['n']}) · "
763
+ f"+Expansion {money(br['expansion']['rev'])} ({br['expansion']['n']}) · "
764
+ f"−Contraction {money(br['contraction']['rev'])} ({br['contraction']['n']}) · "
765
+ f"−Lost {money(br['lost']['rev'])} ({br['lost']['n']}) → This year {money(br['this_total'])} "
766
+ f"({br['change']:+,.0f})")
767
+ st.caption(_bridge_line.replace('$', r'\$')) # escape $ so Streamlit doesn't read it as LaTeX
768
+
769
+ section('Brand split', 'The same revenue-bridge drivers computed separately for each DBA. '
770
+ 'Each brand row reconciles last→this independently.')
771
+ show_df(b['by_brand'],
772
+ cols={'last': ('money', 'last'), 'this': ('money', 'this'), 'change': ('money', 'change'),
773
+ 'new': ('money', 'new'), 'expansion': ('money', 'expansion'),
774
+ 'contraction': ('money', 'contraction'), 'lost': ('money', 'lost')},
775
+ highlight=['change', 'new', 'expansion', 'contraction', 'lost'])
776
+
777
+ section('Value tiers', 'Every active customer placed in exactly one value tier by trailing-12-'
778
+ 'month revenue. A small share (Whale + Large) drives most revenue; tiers and shares '
779
+ 'sum to 100%.')
 
 
780
  show_df(b['segments'], cols={'revenue': 'money', 'avg_rev': ('money', 'avg $/cust'),
781
  'rev_share': ('pct', 'rev %'), 'cust_share': ('pct', 'cust %')})
782
 
783
+ section('Win-back & new', 'At-risk = bought materially last year but down or gone this year, '
784
+ 'ranked by dollars at risk. New = acquired or reactivated this year. Both honour the '
785
+ 'Brand (DBA) filter.')
 
786
  scope = st.session_state.get('brand', 'All') # driven by the global DBA selector
787
  lists = cust_lists(scope)
788
+ st.markdown(f'**At-risk / win-back — {scope}**')
789
+ show_df(lists['at_risk'], cols={'rev_ly': ('money', 'LY $'), 'rev_ytd': ('money', 'YTD $'),
790
+ 'at_risk': ('money', 'at risk $')}, height=300)
791
+ st.markdown(f'**New / reactivated this year — {scope}**')
792
+ show_df(lists['new'], cols={'rev_ytd': ('money', 'YTD $')}, height=300)
 
 
 
793
 
794
  # -------------------------------------------------- sum-level: dimensional rollups
795
  st.divider()
796
  consolidated = tid is None
797
+ section('Rollups', 'Group YTD revenue (vs last year) by any customer attribute. MECE — each '
798
+ 'active customer is in exactly one group, so the groups sum to total revenue. With '
799
+ 'Brand=All each group also shows its Fisch and Royal split (the HQ→brand mirror).')
 
800
  dcol, scol, mcol = st.columns([1.2, 1.2, 1])
801
  dim_label = dcol.selectbox('Group by', list(cust_mod.DIMENSIONS.values()), key='cust_dim')
802
  dim = next(k for k, v in cust_mod.DIMENSIONS.items() if v == dim_label)
 
808
  help='Hide groups below this YTD revenue.')
809
  shown = [r for r in roll
810
  if (not flt or flt.lower() in str(r['group']).lower()) and r['revenue'] >= minrev]
811
+ if consolidated:
812
+ show_df(shown, cols={'group': ('text', dim_label), 'revenue': ('money', 'Total YTD'),
813
+ 'fisch': ('money', 'Fisch'), 'royal': ('money', 'Royal'),
814
+ 'revenue_ly': ('money', 'LY $'), 'yoy_pct': ('pct', 'YoY %'),
815
+ 'customers': ('int', '# cust'), 'avg_per_customer': ('money', 'avg $/cust')},
816
+ height=380, highlight=['yoy_pct'])
817
+ else:
818
+ show_df(shown, cols={'group': ('text', dim_label), 'revenue': ('money', 'YTD $'),
819
+ 'revenue_ly': ('money', 'LY $'), 'yoy_pct': ('pct', 'YoY %'),
820
+ 'customers': ('int', '# cust'), 'orders': ('int', '# orders'),
821
+ 'avg_per_customer': ('money', 'avg $/cust')}, height=380, highlight=['yoy_pct'])
822
+ (chart_group_brand if consolidated else chart_group_yoy)(shown, n=15)
823
+ st.caption(f'{len(shown):,} of {len(roll):,} {dim_label.lower()} groups'
 
 
 
824
  + (' · bars split Fisch (navy) vs Royal (gold)' if consolidated
825
+ else ' · this year vs last, with YoY %'))
826
 
827
  # -------------------------------------------------- granular: click-through drill-down
828
  st.divider()
829
+ section('Drill-down', 'A filterable, searchable directory of every customer. Click a row to '
830
+ 'open the full profile: KPIs, the Fisch/Royal mix, monthly trend, top SKUs and '
831
+ 'categories, and recent orders. Honours the Brand (DBA) filter plus the filters below.')
 
832
  directory = cust_directory(tid)
833
  dir_pids = {r['pid'] for r in directory}
834
  states = sorted({r['state'] for r in directory})
 
915
  tid = brand_team()
916
  b = prod_bundle(tid)
917
  mv = b['movers']
918
+ dash_header('', 'SKU',
919
  f"Live from Odoo · pulled {b['pulled_at']} · {brand_caption('products')} · YTD vs same "
920
  "period LY · services excluded · duplicate/re-coded SKUs merged by code (incl. archived).",
921
  refresh=('refresh_prod', [prod_bundle, prod_coverage]))
 
1103
  # year-end forecast
1104
  fc = b['forecast']
1105
  company = next((r for r in fc if r['scope'] == 'Company'), fc[0])
1106
+ section('Forecast', "Seasonality-aware full-year projection: actual YTD + last year's "
1107
+ 'remaining months (the seasonal shape) scaled by the current YoY pace. A baseline, '
1108
+ 'not a target.')
1109
  fcc = st.columns(3)
1110
  fcc[0].metric('Full-year 2026 forecast', money(company['forecast_full_year']),
1111
  f"{company['forecast_yoy_pct']:+.1f}% vs {company['ly_full_year']/1e6:.2f}M last year")
 
1116
  'FY forecast': r['forecast_full_year'], 'LY full year': r['ly_full_year'],
1117
  'forecast YoY %': r['forecast_yoy_pct']} for r in fc],
1118
  cols={'YTD actual': 'money', 'projected H2': 'money', 'FY forecast': 'money',
1119
+ 'LY full year': 'money', 'forecast YoY %': 'pct'}, highlight=['forecast YoY %'])
 
 
1120
 
1121
+ section('Monthly revenue', 'This year vs the same month last year, with the YoY % on each '
1122
+ 'month. Floral is seasonal, so compare YoY same-period, not month-over-month.')
1123
  chart_yoy_bars(b['trend'])
1124
 
1125
+ section('By category', 'Which product categories are growing or shrinking, YTD vs last year. '
1126
+ 'Switch the Brand (DBA) selector to see, e.g., which categories Fisch is losing.')
 
 
1127
  show_df(b['by_category'], cols={'revenue': ('money', 'revenue'), 'revenue_ly': ('money', 'LY revenue'),
1128
+ 'change': ('money', 'change'), 'yoy_pct': ('pct', 'YoY %')},
1129
+ height=320, highlight=['change', 'yoy_pct'])
1130
 
 
1131
  cad = b['cadence']
1132
+ section('Reorder behaviour', 'LTM repeat-purchase rate and order-frequency distribution. A '
1133
+ 'low repeat rate or a base skewed to "1 order" signals weak retention — cross-check '
1134
+ 'the win-back list.')
1135
+ cc = st.columns(3)
1136
  cc[0].metric('Repeat-purchase rate', f"{cad['repeat_rate']:.0f}%",
1137
  f"{cad['repeat_customers']:,} of {cad['customers']:,}", delta_color='off')
1138
  cc[1].metric('Avg orders / customer', f"{cad['avg_orders']:.1f}")
1139
  cc[2].metric('Orders (LTM)', f"{cad['total_orders']:,}")
1140
+ show_df(cad['distribution'], cols={'customers': ('int', 'customers'), 'pct': ('pct0', '% of base')})
 
 
 
1141
 
1142
+ section('By sales rep', 'YTD revenue per salesperson on the order.')
1143
+ show_df(b['by_rep'], cols={'revenue': 'money'})
 
 
 
 
 
1144
 
1145
+ section('Top customers', 'Largest customers by YTD revenue.')
1146
+ show_df(b['top_customers'], cols={'revenue': 'money'})
1147
+
1148
+ section('Top SKUs', 'Largest SKUs by YTD revenue (line-level).')
1149
  show_df(b['top_skus'], cols={'revenue': 'money', 'qty': 'num'}, height=300)
1150
 
1151
  con = b['concentration']
1152
+ st.caption(f"Customer concentration — top 10 = {con['top10_pct']:.0f}%, "
1153
+ f"top 50 = {con['top50_pct']:.0f}%, top 100 = {con['top100_pct']:.0f}% "
1154
+ f"of YTD revenue across {con['n_customers']:,} customers.")
1155
 
1156
  validation_panel(b['validation'], 'All sales metrics tie out to Odoo ground truth.')
1157
 
 
1226
  "<div class='brand-sub'>Royal Imports · Fisch Floral</div>",
1227
  unsafe_allow_html=True)
1228
  st.divider()
1229
+ # Brand (DBA) filter at the TOP — it scopes most pages, so it leads the sidebar.
 
 
 
1230
  st.markdown("<div class='brand-sub'>Brand (DBA)</div>", unsafe_allow_html=True)
1231
  st.radio('Brand (DBA)', list(ctxlib.BRANDS.keys()), key='brand', horizontal=True,
1232
  label_visibility='collapsed',
1233
  help='Filters operational dashboards by doing-business-as (Fisch / Royal). '
1234
  'Company-level pages (Collections/AR, Data Health) stay consolidated.')
1235
  st.divider()
1236
+ labels = [m['label'] for m in registry.REGISTRY]
1237
+ choice = st.radio('Section', labels, label_visibility='collapsed')
1238
+ choice_key = next(m['key'] for m in registry.REGISTRY if m['label'] == choice)
1239
+ st.divider()
1240
  if st.button('Refresh ALL data from Odoo', width='stretch'):
1241
  st.cache_data.clear()
1242
  st.session_state['data_refreshed_at'] = dt.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
core/registry.py CHANGED
@@ -22,7 +22,7 @@ REGISTRY = [
22
  'note': 'Gross margin by DBA/category/SKU. Cash-conversion cycle is HQ-consolidated.'},
23
  {'key': 'customers', 'label': 'Customers', 'brand': True, 'hq': False, 'validate': True,
24
  'note': 'Revenue bridge, segments, win-back — by DBA.'},
25
- {'key': 'products', 'label': 'Products / SKU', 'brand': True, 'hq': False, 'validate': True,
26
  'note': 'SKU movers, zombies, velocity, coverage — by DBA (sales-derived).'},
27
  {'key': 'inventory', 'label': 'Inventory', 'brand': False, 'hq': False, 'validate': True,
28
  'note': 'On-hand stock is physically consolidated (shared warehouse); not DBA-split.'},
 
22
  'note': 'Gross margin by DBA/category/SKU. Cash-conversion cycle is HQ-consolidated.'},
23
  {'key': 'customers', 'label': 'Customers', 'brand': True, 'hq': False, 'validate': True,
24
  'note': 'Revenue bridge, segments, win-back — by DBA.'},
25
+ {'key': 'products', 'label': 'SKU', 'brand': True, 'hq': False, 'validate': True,
26
  'note': 'SKU movers, zombies, velocity, coverage — by DBA (sales-derived).'},
27
  {'key': 'inventory', 'label': 'Inventory', 'brand': False, 'hq': False, 'validate': True,
28
  'note': 'On-hand stock is physically consolidated (shared warehouse); not DBA-split.'},