fsanyoto commited on
Commit
ab8be9f
Β·
verified Β·
1 Parent(s): cd033e6

Deploy CFO OS (redesigned UI)

Browse files
Files changed (5) hide show
  1. README.md +6 -5
  2. app.py +171 -64
  3. core/registry.py +1 -1
  4. modules/customers.py +105 -3
  5. modules/sales.py +5 -1
README.md CHANGED
@@ -1,15 +1,16 @@
1
  ---
2
- title: Royal Imports CFO OS
3
  emoji: "πŸ“Š"
4
  colorFrom: blue
5
  colorTo: indigo
6
  sdk: docker
7
  app_port: 7860
8
  pinned: false
9
- short_description: Internal CFO dashboards (private, password-gated)
10
  ---
11
 
12
- # CFO Operating System β€” Royal Imports / Fisch Floral Supply
13
 
14
- Private internal dashboards, live from Odoo (read-only). Password-gated.
15
- Six dashboards: Sales, Inventory, Collections/AR, Financial, Customers, Products/SKU.
 
 
1
  ---
2
+ title: Royal Imports OS
3
  emoji: "πŸ“Š"
4
  colorFrom: blue
5
  colorTo: indigo
6
  sdk: docker
7
  app_port: 7860
8
  pinned: false
9
+ short_description: Internal operating-system dashboards (password-gated)
10
  ---
11
 
12
+ # Royal Imports OS β€” Royal Imports / Fisch Floral Supply
13
 
14
+ Internal operating-system dashboards, live from Odoo (read-only). Password-gated;
15
+ Business-Unit scoping (Fisch / Royal) supports per-user permissioning.
16
+ Dashboards: Sales, Financial, Customers, SKU, Inventory, Collections/AR, Data Health.
app.py CHANGED
@@ -29,7 +29,7 @@ import modules.customers as cust_mod
29
  import modules.products as prod_mod
30
  import modules.health as health_mod
31
 
32
- st.set_page_config(page_title='CFO OS Β· Royal Imports',
33
  layout='wide', initial_sidebar_state='expanded')
34
  PRIMARY = '#1F4E78'
35
  ACCENT = '#C8A24B'
@@ -195,8 +195,17 @@ def money(x, dp=0):
195
  return 'β€”'
196
 
197
 
 
 
 
 
 
 
 
 
 
198
  def brand_team():
199
- """The current DBA (brand) filter from the sidebar selector.
200
  Returns a team_id: None = All/consolidated, 5 = Fisch, 6 = Royal."""
201
  return ctxlib.BRANDS.get(st.session_state.get('brand', 'All'))
202
 
@@ -210,9 +219,9 @@ def brand_caption(key):
210
  """Honest scope note for a page header."""
211
  b = st.session_state.get('brand', 'All')
212
  if key in _BRAND_WIRED:
213
- return 'All DBAs (Fisch + Royal)' if b == 'All' else f'DBA: {b} only'
214
  if registry.brand_filterable(key):
215
- return 'Consolidated Β· per-DBA filter rolls out as this module is deepened'
216
  return 'Consolidated Β· company-level (HQ)'
217
 
218
 
@@ -641,7 +650,7 @@ def page_financial():
641
 
642
  st.markdown('#### Cash conversion cycle (working capital) β€” company-level')
643
  st.caption('Working capital is a company-level (HQ) view β€” shown consolidated across both '
644
- 'DBAs regardless of the brand filter.')
645
  ccc = b['ccc']
646
  cc = st.columns(4)
647
  cc[0].metric('Days inventory (DIO)', f"{ccc['dio_days']:.0f}d")
@@ -670,7 +679,8 @@ def page_financial():
670
  def cust_bundle(team_id=None):
671
  return {
672
  'bridge': cust_mod.revenue_bridge(team_id=team_id),
673
- 'by_brand': cust_mod.bridge_by_brand(), # always both DBAs β€” it IS the comparison
 
674
  'segments': cust_mod.segments(team_id=team_id),
675
  'validation': cust_mod.validate(),
676
  'pulled_at': dt.datetime.now().strftime('%Y-%m-%d %H:%M'),
@@ -699,8 +709,51 @@ def cust_detail(pid, team_id=None):
699
  return cust_mod.customer_detail(pid, team_id=team_id)
700
 
701
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
702
  def render_customer_detail(pid, team_id):
703
- """The granular per-customer drill-down panel (rendered when a directory row is clicked)."""
 
704
  d = cust_detail(pid, team_id)
705
  loc = ' Β· '.join(x for x in [d['city'], d['state'], d['country']] if x and x != '(none)')
706
  sp = d['salesperson'] if d['salesperson'] != '(none)' else 'β€”'
@@ -708,18 +761,52 @@ def render_customer_detail(pid, team_id):
708
  unsafe_allow_html=True)
709
  rec = f" Β· last order {d['last_order']}" + (f" ({d['recency_days']}d ago)"
710
  if d['recency_days'] is not None else '')
711
- fr = d['ytd_fisch'] + d['ytd_royal']
712
  st.caption(f"{loc or 'No location on file'} Β· Salesperson: {sp} Β· "
713
  f"customer since {d['first_order'] or 'β€”'}{rec}")
714
- mix_delta = (f"{d['ytd_fisch']/fr*100:.0f}% / {d['ytd_royal']/fr*100:.0f}%" if fr > 0 else None)
715
- kpi_row([
716
- {'label': 'YTD revenue', 'value': money(d['ytd_rev']),
717
- 'delta': (f"{d['yoy_pct']:+.1f}% vs LY" if d['yoy_pct'] is not None else 'new this year')},
718
- {'label': 'Fisch / Royal (YTD)', 'value': f"{money(d['ytd_fisch'])} / {money(d['ytd_royal'])}",
719
- 'delta': mix_delta},
 
 
 
 
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)**')
@@ -744,35 +831,29 @@ def page_customers():
744
  {'label': 'Active customers (YTD)', 'value': f"{br['active_this']:,}",
745
  'delta': f"{br['active_this'] - br['active_last']:+,} vs LY"},
746
  {'label': 'New / reactivated', 'value': f"{br['new']['n']:,}", 'delta': money(br['new']['rev'])},
747
- {'label': 'Lost', 'value': f"{br['lost']['n']:,}", 'delta': money(br['lost']['rev']), 'delta_color': 'inverse'},
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 '
@@ -782,8 +863,8 @@ def page_customers():
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 $'),
@@ -826,11 +907,10 @@ def page_customers():
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})
835
  reps = sorted({r['salesperson'] for r in directory})
836
  fc1, fc2, fc3, fc4 = st.columns([1.4, 1.3, 1, 1.1])
@@ -842,6 +922,22 @@ def page_customers():
842
  key='dir_move', help='Filter by year-over-year direction.')
843
  q = st.text_input('Search', key='cust_search', placeholder='name, city, state, or salesperson…')
844
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
845
  def _keep(r):
846
  if q and q.lower() not in f"{r['customer']} {r['city']} {r['state']} {r['salesperson']}".lower():
847
  return False
@@ -851,6 +947,8 @@ def page_customers():
851
  return False
852
  if r['revenue'] < f_min:
853
  return False
 
 
854
  y = r['yoy_pct']
855
  if f_move == 'Up vs LY' and not (y is not None and y > 0):
856
  return False
@@ -860,12 +958,13 @@ def page_customers():
860
  return False
861
  return True
862
  rows = [r for r in directory if _keep(r)]
 
863
  ddf = pd.DataFrame([{'Customer': r['customer'], 'YTD $': r['revenue'], 'YoY %': r['yoy_pct'],
864
  'Orders': r['orders'], 'Last order': r['last_order'], 'City': r['city'],
865
  'State': r['state'], 'Salesperson': r['salesperson'], '_pid': r['pid']}
866
- for r in rows[:300]])
867
- st.caption(f"{len(rows):,} of {len(directory):,} customers"
868
- + (" (top 300 by revenue shown)" if len(rows) > 300 else "") + " β€” click a row to drill in.")
869
  if ddf.empty:
870
  st.info('No customers match that search.')
871
  else:
@@ -1049,7 +1148,7 @@ def _live_briefing():
1049
  in the (potentially public) repo. Used when the static CFO_BRIEFING.md is not deployed."""
1050
  b = briefing_bundle()
1051
  sh, fh, ar = b['sales'], b['fin'], b['ar']
1052
- st.caption(f"Live from Odoo Β· pulled {b['pulled_at']} Β· consolidated (all DBAs) Β· YTD vs same period last year")
1053
  kpi_row([
1054
  {'label': 'YTD revenue', 'value': money(sh['ytd_revenue']),
1055
  'delta': f"{sh['yoy_pct']:+.1f}% vs LY" if sh['yoy_pct'] is not None else None},
@@ -1058,18 +1157,19 @@ def _live_briefing():
1058
  'delta': f"{ar['pct_overdue']:.0f}% overdue", 'delta_color': 'inverse'},
1059
  {'label': 'DSO', 'value': f"{ar['dso_days']:.0f}d" if ar['dso_days'] else 'β€”'},
1060
  ])
1061
- st.markdown('#### Revenue by DBA β€” YTD vs last year')
1062
  rows = [{'brand': tm, 'ytd': d['ytd'], 'ytd_ly': d['ytd_ly'], 'yoy_pct': P.yoy_pct(d['ytd'], d['ytd_ly'])}
1063
  for tm, d in sh['by_team'].items()]
1064
- show_df(rows, cols={'brand': ('text', 'DBA'), 'ytd': ('money', 'YTD'),
1065
- 'ytd_ly': ('money', 'last year'), 'yoy_pct': ('pct', 'YoY %')})
 
1066
  st.markdown('Drill in with the dashboards on the left β€” Sales, Financial, Customers, '
1067
- 'Products/SKU, Collections/AR, and the Data Health close cockpit. Use the '
1068
- '**Brand (DBA)** filter to scope the operational views to Fisch or Royal.')
1069
 
1070
 
1071
  def page_briefing():
1072
- dash_header('', 'CFO Daily Briefing')
1073
  f = HERE / 'CFO_BRIEFING.md'
1074
  if f.exists():
1075
  st.markdown(f.read_text(encoding='utf-8')) # local rich narrative (NOT deployed)
@@ -1094,11 +1194,13 @@ def page_sales():
1094
  {'label': 'AOV', 'value': money(h['aov'])},
1095
  ])
1096
 
1097
- # brand split (always shows both DBAs β€” it IS the comparison)
1098
- bt = st.columns(len(h['by_team']))
1099
- for i, (tm, d) in enumerate(h['by_team'].items()):
1100
- yoy = (d['ytd'] - d['ytd_ly']) / d['ytd_ly'] * 100 if d['ytd_ly'] else 0
1101
- bt[i].metric(f'{tm} YTD', money(d['ytd']), f'{yoy:+.1f}% vs LY')
 
 
1102
 
1103
  # year-end forecast
1104
  fc = b['forecast']
@@ -1123,7 +1225,7 @@ def page_sales():
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'])
@@ -1222,16 +1324,21 @@ def main():
1222
  if not gate():
1223
  return
1224
  with st.sidebar:
1225
- st.markdown("<div class='brand'>CFO OS</div>"
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')
 
29
  import modules.products as prod_mod
30
  import modules.health as health_mod
31
 
32
+ st.set_page_config(page_title='Royal Imports OS',
33
  layout='wide', initial_sidebar_state='expanded')
34
  PRIMARY = '#1F4E78'
35
  ACCENT = '#C8A24B'
 
195
  return 'β€”'
196
 
197
 
198
+ def allowed_bus():
199
+ """Business Units the current session may view. Future: set at login from the user's role β€”
200
+ a Royal-only user gets ['Royal'] (no 'All', so Fisch data is never reachable). Default: all."""
201
+ allowed = st.session_state.get('allowed_bus')
202
+ if allowed:
203
+ return [b for b in ctxlib.BRANDS if b in allowed]
204
+ return list(ctxlib.BRANDS.keys()) # ['All', 'Fisch', 'Royal']
205
+
206
+
207
  def brand_team():
208
+ """The current Business Unit filter from the sidebar selector.
209
  Returns a team_id: None = All/consolidated, 5 = Fisch, 6 = Royal."""
210
  return ctxlib.BRANDS.get(st.session_state.get('brand', 'All'))
211
 
 
219
  """Honest scope note for a page header."""
220
  b = st.session_state.get('brand', 'All')
221
  if key in _BRAND_WIRED:
222
+ return 'All business units (Fisch + Royal)' if b == 'All' else f'{b} only'
223
  if registry.brand_filterable(key):
224
+ return 'Consolidated Β· per-business-unit filter rolls out as this module is deepened'
225
  return 'Consolidated Β· company-level (HQ)'
226
 
227
 
 
650
 
651
  st.markdown('#### Cash conversion cycle (working capital) β€” company-level')
652
  st.caption('Working capital is a company-level (HQ) view β€” shown consolidated across both '
653
+ 'Business Units regardless of the filter.')
654
  ccc = b['ccc']
655
  cc = st.columns(4)
656
  cc[0].metric('Days inventory (DIO)', f"{ccc['dio_days']:.0f}d")
 
679
  def cust_bundle(team_id=None):
680
  return {
681
  'bridge': cust_mod.revenue_bridge(team_id=team_id),
682
+ # Per-BU split only when consolidated β€” never compute the other BU for a scoped user.
683
+ 'by_brand': cust_mod.bridge_by_brand() if team_id is None else None,
684
  'segments': cust_mod.segments(team_id=team_id),
685
  'validation': cust_mod.validate(),
686
  'pulled_at': dt.datetime.now().strftime('%Y-%m-%d %H:%M'),
 
709
  return cust_mod.customer_detail(pid, team_id=team_id)
710
 
711
 
712
+ @st.cache_data(ttl=900, show_spinner=False)
713
+ def cust_winback(pid, team_id=None):
714
+ return cust_mod.customer_winback(pid, team_id=team_id)
715
+
716
+
717
+ @st.cache_data(ttl=3600, show_spinner=False)
718
+ def cust_categories():
719
+ return cust_mod.main_categories()
720
+
721
+
722
+ @st.cache_data(ttl=900, show_spinner=False)
723
+ def cust_sku_buyers(query, team_id=None):
724
+ return cust_mod.sku_buyers(query, team_id=team_id)
725
+
726
+
727
+ @st.cache_data(ttl=900, show_spinner=False)
728
+ def cust_cat_buyers(category, team_id=None):
729
+ return cust_mod.category_buyers(category, team_id=team_id)
730
+
731
+
732
+ def _winback_points(d, wb):
733
+ """Data-driven talking points for the win-back playbook."""
734
+ pts = []
735
+ rec = d['recency_days']
736
+ if rec is not None:
737
+ tone = 'recently active' if rec <= 60 else ('cooling off' if rec <= 180 else 'gone quiet')
738
+ pts.append(f"Last ordered **{rec} days ago** β€” {tone}.")
739
+ if wb['lapsed']:
740
+ names = ', '.join(x['sku'] for x in wb['lapsed'][:3])
741
+ ly = sum(x['ly_rev'] for x in wb['lapsed'])
742
+ pts.append(f"Stopped buying **{wb['n_lapsed']} SKUs** worth {money(ly)} last year β€” "
743
+ f"lead the pitch with {names}.")
744
+ if wb['lapsed_categories']:
745
+ c = wb['lapsed_categories'][0]
746
+ pts.append(f"Biggest category gap: **{c['category']}** ({money(c['change'])} vs last year).")
747
+ if wb['declined']:
748
+ pts.append(f"**{wb['n_declined']} SKUs** still buying but down YoY β€” protect these alongside the re-pitch.")
749
+ if not pts or (not wb['lapsed'] and not wb['declined']):
750
+ pts.append('No material drop-off vs last year β€” this customer is holding or growing.')
751
+ return pts
752
+
753
+
754
  def render_customer_detail(pid, team_id):
755
+ """The per-customer drill-down drawer: profile, KPIs, a win-back playbook, then the trend
756
+ and purchase tables. Rendered when a directory row is clicked."""
757
  d = cust_detail(pid, team_id)
758
  loc = ' Β· '.join(x for x in [d['city'], d['state'], d['country']] if x and x != '(none)')
759
  sp = d['salesperson'] if d['salesperson'] != '(none)' else 'β€”'
 
761
  unsafe_allow_html=True)
762
  rec = f" Β· last order {d['last_order']}" + (f" ({d['recency_days']}d ago)"
763
  if d['recency_days'] is not None else '')
 
764
  st.caption(f"{loc or 'No location on file'} Β· Salesperson: {sp} Β· "
765
  f"customer since {d['first_order'] or 'β€”'}{rec}")
766
+ kpis = [{'label': 'YTD revenue', 'value': money(d['ytd_rev']),
767
+ 'delta': (f"{d['yoy_pct']:+.1f}% vs LY" if d['yoy_pct'] is not None else 'new this year')}]
768
+ if team_id is None and d['ytd_fisch'] is not None: # BU split only in consolidated view
769
+ fr = d['ytd_fisch'] + d['ytd_royal']
770
+ kpis.append({'label': 'Fisch / Royal (YTD)',
771
+ 'value': f"{money(d['ytd_fisch'])} / {money(d['ytd_royal'])}",
772
+ 'delta': (f"{d['ytd_fisch']/fr*100:.0f}% / {d['ytd_royal']/fr*100:.0f}%" if fr > 0 else None)})
773
+ else:
774
+ kpis.append({'label': 'LTM revenue', 'value': money(d['ltm_rev'])})
775
+ kpis += [
776
  {'label': 'Orders (LTM)', 'value': f"{d['orders_ltm']:,}", 'delta': f"AOV {money(d['aov_ltm'])}"},
777
  {'label': 'Gross margin % (LTM)', 'value': f"{d['ltm_gm_pct']:.1f}%", 'delta': money(d['ltm_margin'])},
778
+ ]
779
+ kpi_row(kpis)
780
+
781
+ # ---- Win-back playbook (the point of the drawer) ----
782
+ wb = cust_winback(pid, team_id)
783
+ with st.container(border=True):
784
+ section('Win-back playbook', 'How to win this customer back, from their own purchase '
785
+ 'history: SKUs they stopped buying (lapsed) or cut back on (declined) vs last '
786
+ 'year, the dollars at risk, and where to lead the re-pitch.')
787
+ wc = st.columns(3)
788
+ wc[0].metric('Dollars at risk', money(wb['lost_dollars']),
789
+ help='Lapsed-SKU revenue + the YoY decline on SKUs they still buy.')
790
+ wc[1].metric('Lapsed SKUs', f"{wb['n_lapsed']:,}", help='Bought last year, zero this year.')
791
+ wc[2].metric('Last order',
792
+ f"{d['recency_days']}d ago" if d['recency_days'] is not None else 'β€”')
793
+ for p in _winback_points(d, wb):
794
+ st.markdown('- ' + p)
795
+ if wb['lapsed']:
796
+ st.markdown('**Lapsed SKUs β€” bought last year, not this year (lead with these)**')
797
+ show_df(wb['lapsed'], cols={'sku': ('text', 'SKU'), 'ly_rev': ('money', 'LY $'),
798
+ 'qty_ly': ('num', 'LY qty')}, height=240)
799
+ if wb['lapsed_categories']:
800
+ st.markdown('**Category gaps (YoY)**')
801
+ show_df(wb['lapsed_categories'], cols={'category': ('text', 'Category'), 'ly_rev': ('money', 'LY $'),
802
+ 'ytd_rev': ('money', 'YTD $'), 'change': ('money', 'change')},
803
+ height=200, highlight=['change'])
804
+ if wb['declined']:
805
+ st.markdown('**Declining SKUs β€” still buying, down YoY**')
806
+ show_df(wb['declined'], cols={'sku': ('text', 'SKU'), 'ly_rev': ('money', 'LY $'),
807
+ 'ytd_rev': ('money', 'YTD $'), 'change': ('money', 'change')},
808
+ height=220, highlight=['change'])
809
+
810
  st.markdown('**Monthly revenue β€” this year vs last**')
811
  chart_yoy_bars(d['monthly'])
812
  st.markdown('**Top SKUs bought (LTM)**')
 
831
  {'label': 'Active customers (YTD)', 'value': f"{br['active_this']:,}",
832
  'delta': f"{br['active_this'] - br['active_last']:+,} vs LY"},
833
  {'label': 'New / reactivated', 'value': f"{br['new']['n']:,}", 'delta': money(br['new']['rev'])},
834
+ {'label': 'Lost', 'value': f"{br['lost']['n']:,}", 'delta': money(br['lost']['rev'])},
835
  {'label': 'Retained', 'value': f"{br['retained_n']:,}"},
836
  ])
837
 
838
  section('Revenue bridge', 'Decomposes the revenue change vs the same period last year into '
839
  'four MECE drivers β€” New/reactivated (+), Expansion (+), Contraction (βˆ’), Lost (βˆ’). '
840
  'They sum exactly from last year to this year.')
841
+ chart_bridge([
842
  {'component': 'New', 'amount': br['new']['rev']},
843
  {'component': 'Expansion', 'amount': br['expansion']['rev']},
844
  {'component': 'Contraction', 'amount': br['contraction']['rev']},
845
  {'component': 'Lost', 'amount': br['lost']['rev']},
846
+ ])
847
+
848
+ # Brand split β€” only in the consolidated (All) view; never expose the other BU when scoped.
849
+ if tid is None and b.get('by_brand'):
850
+ section('Business Unit split', 'The same revenue-bridge drivers computed separately for '
851
+ 'each Business Unit. Each row reconciles last→this independently.')
852
+ show_df(b['by_brand'],
853
+ cols={'last': ('money', 'last'), 'this': ('money', 'this'), 'change': ('money', 'change'),
854
+ 'new': ('money', 'new'), 'expansion': ('money', 'expansion'),
855
+ 'contraction': ('money', 'contraction'), 'lost': ('money', 'lost')},
856
+ highlight=['change', 'new', 'expansion', 'contraction', 'lost'])
 
 
 
 
 
 
857
 
858
  section('Value tiers', 'Every active customer placed in exactly one value tier by trailing-12-'
859
  'month revenue. A small share (Whale + Large) drives most revenue; tiers and shares '
 
863
 
864
  section('Win-back & new', 'At-risk = bought materially last year but down or gone this year, '
865
  'ranked by dollars at risk. New = acquired or reactivated this year. Both honour the '
866
+ 'Business Unit filter.')
867
+ scope = st.session_state.get('brand', 'All') # driven by the global Business Unit selector
868
  lists = cust_lists(scope)
869
  st.markdown(f'**At-risk / win-back β€” {scope}**')
870
  show_df(lists['at_risk'], cols={'rev_ly': ('money', 'LY $'), 'rev_ytd': ('money', 'YTD $'),
 
907
 
908
  # -------------------------------------------------- granular: click-through drill-down
909
  st.divider()
910
+ section('Drill-down', 'A filterable, searchable directory of every customer. Filter by '
911
+ 'attributes or by what they bought (advanced filters), then click any row to open the '
912
+ 'win-back drawer. Honours the Business Unit filter plus the filters below.')
913
  directory = cust_directory(tid)
 
914
  states = sorted({r['state'] for r in directory})
915
  reps = sorted({r['salesperson'] for r in directory})
916
  fc1, fc2, fc3, fc4 = st.columns([1.4, 1.3, 1, 1.1])
 
922
  key='dir_move', help='Filter by year-over-year direction.')
923
  q = st.text_input('Search', key='cust_search', placeholder='name, city, state, or salesperson…')
924
 
925
+ # Advanced: find customers by what they purchased (queries Odoo over the last 24 months).
926
+ adv_pids = None
927
+ with st.expander('Advanced filters β€” find customers by what they bought'):
928
+ ac1, ac2 = st.columns(2)
929
+ sku_q = ac1.text_input('Bought SKU (code or name)', key='adv_sku',
930
+ placeholder='e.g. CYL308 or bottle',
931
+ help='Customers who bought a matching SKU in the last 24 months.')
932
+ cat_sel = ac2.selectbox('Bought in category', ['(any)'] + cust_categories(), key='adv_cat',
933
+ help='Customers who bought from this category in the last 24 months.')
934
+ if sku_q and sku_q.strip():
935
+ s = cust_sku_buyers(sku_q.strip(), tid)
936
+ adv_pids = s if adv_pids is None else (adv_pids & s)
937
+ if cat_sel and cat_sel != '(any)':
938
+ s = cust_cat_buyers(cat_sel, tid)
939
+ adv_pids = s if adv_pids is None else (adv_pids & s)
940
+
941
  def _keep(r):
942
  if q and q.lower() not in f"{r['customer']} {r['city']} {r['state']} {r['salesperson']}".lower():
943
  return False
 
947
  return False
948
  if r['revenue'] < f_min:
949
  return False
950
+ if adv_pids is not None and r['pid'] not in adv_pids:
951
+ return False
952
  y = r['yoy_pct']
953
  if f_move == 'Up vs LY' and not (y is not None and y > 0):
954
  return False
 
958
  return False
959
  return True
960
  rows = [r for r in directory if _keep(r)]
961
+ dir_pids = {r['pid'] for r in rows}
962
  ddf = pd.DataFrame([{'Customer': r['customer'], 'YTD $': r['revenue'], 'YoY %': r['yoy_pct'],
963
  'Orders': r['orders'], 'Last order': r['last_order'], 'City': r['city'],
964
  'State': r['state'], 'Salesperson': r['salesperson'], '_pid': r['pid']}
965
+ for r in rows]) # no cap β€” every matching customer is clickable
966
+ extra = '' if adv_pids is None else ' matching the purchase filter'
967
+ st.caption(f"{len(rows):,} of {len(directory):,} customers{extra} β€” click any row to open the win-back drawer.")
968
  if ddf.empty:
969
  st.info('No customers match that search.')
970
  else:
 
1148
  in the (potentially public) repo. Used when the static CFO_BRIEFING.md is not deployed."""
1149
  b = briefing_bundle()
1150
  sh, fh, ar = b['sales'], b['fin'], b['ar']
1151
+ st.caption(f"Live from Odoo Β· pulled {b['pulled_at']} Β· consolidated (all business units) Β· YTD vs same period last year")
1152
  kpi_row([
1153
  {'label': 'YTD revenue', 'value': money(sh['ytd_revenue']),
1154
  'delta': f"{sh['yoy_pct']:+.1f}% vs LY" if sh['yoy_pct'] is not None else None},
 
1157
  'delta': f"{ar['pct_overdue']:.0f}% overdue", 'delta_color': 'inverse'},
1158
  {'label': 'DSO', 'value': f"{ar['dso_days']:.0f}d" if ar['dso_days'] else 'β€”'},
1159
  ])
1160
+ st.markdown('#### Revenue by Business Unit β€” YTD vs last year')
1161
  rows = [{'brand': tm, 'ytd': d['ytd'], 'ytd_ly': d['ytd_ly'], 'yoy_pct': P.yoy_pct(d['ytd'], d['ytd_ly'])}
1162
  for tm, d in sh['by_team'].items()]
1163
+ show_df(rows, cols={'brand': ('text', 'Business Unit'), 'ytd': ('money', 'YTD'),
1164
+ 'ytd_ly': ('money', 'last year'), 'yoy_pct': ('pct', 'YoY %')},
1165
+ highlight=['yoy_pct'])
1166
  st.markdown('Drill in with the dashboards on the left β€” Sales, Financial, Customers, '
1167
+ 'SKU, Collections/AR, and the Data Health close cockpit. Use the '
1168
+ '**Business Unit** filter to scope the operational views to Fisch or Royal.')
1169
 
1170
 
1171
  def page_briefing():
1172
+ dash_header('', 'Daily Briefing')
1173
  f = HERE / 'CFO_BRIEFING.md'
1174
  if f.exists():
1175
  st.markdown(f.read_text(encoding='utf-8')) # local rich narrative (NOT deployed)
 
1194
  {'label': 'AOV', 'value': money(h['aov'])},
1195
  ])
1196
 
1197
+ # Business-Unit split β€” only when consolidated (All). With a single BU selected we show no
1198
+ # other-BU figures anywhere (strict isolation for per-user permissioning).
1199
+ if tid is None:
1200
+ bt = st.columns(len(h['by_team']))
1201
+ for i, (tm, d) in enumerate(h['by_team'].items()):
1202
+ yoy = (d['ytd'] - d['ytd_ly']) / d['ytd_ly'] * 100 if d['ytd_ly'] else 0
1203
+ bt[i].metric(f'{tm} YTD', money(d['ytd']), f'{yoy:+.1f}% vs LY')
1204
 
1205
  # year-end forecast
1206
  fc = b['forecast']
 
1225
  chart_yoy_bars(b['trend'])
1226
 
1227
  section('By category', 'Which product categories are growing or shrinking, YTD vs last year. '
1228
+ 'Switch the Business Unit selector to see, e.g., which categories Fisch is losing.')
1229
  show_df(b['by_category'], cols={'revenue': ('money', 'revenue'), 'revenue_ly': ('money', 'LY revenue'),
1230
  'change': ('money', 'change'), 'yoy_pct': ('pct', 'YoY %')},
1231
  height=320, highlight=['change', 'yoy_pct'])
 
1324
  if not gate():
1325
  return
1326
  with st.sidebar:
1327
+ st.markdown("<div class='brand'>Royal Imports OS</div>"
1328
+ "<div class='brand-sub'>Operating System</div>",
1329
  unsafe_allow_html=True)
1330
  st.divider()
1331
+ # Business Unit filter at the TOP β€” it scopes most pages, so it leads the sidebar.
1332
+ # Options come from allowed_bus() so a future per-user role can restrict which BUs are
1333
+ # selectable (a Royal-only user only ever sees 'Royal'); cross-BU views need 'All'.
1334
+ st.markdown("<div class='brand-sub'>Business Unit</div>", unsafe_allow_html=True)
1335
+ opts = allowed_bus()
1336
+ if st.session_state.get('brand') not in opts:
1337
+ st.session_state['brand'] = opts[0]
1338
+ st.radio('Business Unit', opts, key='brand', horizontal=True, label_visibility='collapsed',
1339
+ help='Scopes the dashboards to a Business Unit (Fisch / Royal). With a single BU '
1340
+ 'selected, no other-BU data is shown anywhere. Company-level pages '
1341
+ '(Collections/AR, Data Health) stay consolidated.')
1342
  st.divider()
1343
  labels = [m['label'] for m in registry.REGISTRY]
1344
  choice = st.radio('Section', labels, label_visibility='collapsed')
core/registry.py CHANGED
@@ -14,7 +14,7 @@ Fields:
14
  note one-line scope note shown in the UI / docs
15
  """
16
  REGISTRY = [
17
- {'key': 'briefing', 'label': 'CFO Daily Briefing', 'brand': False, 'hq': True, 'validate': False,
18
  'note': 'Synthesised morning read (renders CFO_BRIEFING.md).'},
19
  {'key': 'sales', 'label': 'Sales', 'brand': True, 'hq': False, 'validate': True,
20
  'note': 'Revenue, YoY, seasonality, reps, customers, SKUs β€” by DBA.'},
 
14
  note one-line scope note shown in the UI / docs
15
  """
16
  REGISTRY = [
17
+ {'key': 'briefing', 'label': 'Daily Briefing', 'brand': False, 'hq': True, 'validate': False,
18
  'note': 'Synthesised morning read (renders CFO_BRIEFING.md).'},
19
  {'key': 'sales', 'label': 'Sales', 'brand': True, 'hq': False, 'validate': True,
20
  'note': 'Revenue, YoY, seasonality, reps, customers, SKUs β€” by DBA.'},
modules/customers.py CHANGED
@@ -281,9 +281,13 @@ def customer_detail(pid, t=None, team_id=None, n_months=13, top=12):
281
 
282
  ytd_rev = O.sum_field('sale.order', _order_dom(pid, yf, yt, team_id), 'amount_untaxed')
283
  ytd_rev_ly = O.sum_field('sale.order', _order_dom(pid, lf, lt, team_id), 'amount_untaxed')
284
- # True Fisch/Royal mix (always both brands, regardless of any active filter) β€” mirrors HQ.
285
- ytd_fisch = O.sum_field('sale.order', _order_dom(pid, yf, yt, 5), 'amount_untaxed')
286
- ytd_royal = O.sum_field('sale.order', _order_dom(pid, yf, yt, 6), 'amount_untaxed')
 
 
 
 
287
  ltm_rev = O.sum_field('sale.order', _order_dom(pid, mf, mt, team_id), 'amount_untaxed')
288
  orders_ltm = O.get_odoo().search_count('sale.order', _order_dom(pid, mf, mt, team_id))
289
  orders_ytd = O.get_odoo().search_count('sale.order', _order_dom(pid, yf, yt, team_id))
@@ -353,6 +357,104 @@ def customer_detail(pid, t=None, team_id=None, n_months=13, top=12):
353
  }
354
 
355
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
356
  # ----------------------------------------------------------- VALIDATION
357
  def validate(t=None):
358
  t = t or P.today()
 
281
 
282
  ytd_rev = O.sum_field('sale.order', _order_dom(pid, yf, yt, team_id), 'amount_untaxed')
283
  ytd_rev_ly = O.sum_field('sale.order', _order_dom(pid, lf, lt, team_id), 'amount_untaxed')
284
+ # Fisch/Royal mix only when consolidated (team_id=None). When a single BU is selected we never
285
+ # compute or expose the other BU β€” strict isolation for per-BU permissioning.
286
+ if team_id is None:
287
+ ytd_fisch = O.sum_field('sale.order', _order_dom(pid, yf, yt, 5), 'amount_untaxed')
288
+ ytd_royal = O.sum_field('sale.order', _order_dom(pid, yf, yt, 6), 'amount_untaxed')
289
+ else:
290
+ ytd_fisch = ytd_royal = None
291
  ltm_rev = O.sum_field('sale.order', _order_dom(pid, mf, mt, team_id), 'amount_untaxed')
292
  orders_ltm = O.get_odoo().search_count('sale.order', _order_dom(pid, mf, mt, team_id))
293
  orders_ytd = O.get_odoo().search_count('sale.order', _order_dom(pid, yf, yt, team_id))
 
357
  }
358
 
359
 
360
+ # ====================================================================== ADVANCED FILTERS
361
+ # "Find customers who bought X" β€” resolve a SKU query / category to the set of partner ids that
362
+ # purchased it, so the directory can be filtered by purchase behaviour (not just attributes).
363
+
364
+ def _buyer_window(t):
365
+ """24-month look-back for 'who bought this' β€” catches recent AND lapsed buyers (win-back)."""
366
+ t = t or P.today()
367
+ return (t - dt.timedelta(days=730)).isoformat(), t.isoformat()
368
+
369
+
370
+ def sku_buyers(query, t=None, team_id=None):
371
+ """Set of partner ids who bought any SKU whose code/name matches `query` (last 24 months).
372
+ Returns None when the query is blank (= no filter)."""
373
+ q = (query or '').strip()
374
+ if not q:
375
+ return None
376
+ df, dtt = _buyer_window(t)
377
+ prods = O.search_read('product.product', ['|', ('default_code', 'ilike', q), ('name', 'ilike', q)],
378
+ ['id'], limit=3000)
379
+ pids = [p['id'] for p in prods]
380
+ if not pids:
381
+ return set()
382
+ g = O.read_group('sale.order.line',
383
+ O.sale_line_domain(df, dtt, team_id, extra=[('product_id', 'in', pids)]),
384
+ ['order_partner_id'], ['order_partner_id'], lazy=False)
385
+ return {O.m2o_id(r.get('order_partner_id')) for r in g if r.get('order_partner_id')}
386
+
387
+
388
+ def category_buyers(category, t=None, team_id=None):
389
+ """Set of partner ids who bought from a main category (last 24 months). None = no filter."""
390
+ if not category or category == '(any)':
391
+ return None
392
+ df, dtt = _buyer_window(t)
393
+ catmap = sales_mod._product_cat()
394
+ prod_ids = [pid for pid, c in catmap.items() if c == category]
395
+ if not prod_ids:
396
+ return set()
397
+ g = O.read_group('sale.order.line',
398
+ O.sale_line_domain(df, dtt, team_id, extra=[('product_id', 'in', prod_ids)]),
399
+ ['order_partner_id'], ['order_partner_id'], lazy=False)
400
+ return {O.m2o_id(r.get('order_partner_id')) for r in g if r.get('order_partner_id')}
401
+
402
+
403
+ def main_categories():
404
+ """Sorted list of main category names (for the 'bought in category' selector)."""
405
+ return sorted(set(sales_mod._product_cat().values()))
406
+
407
+
408
+ # ====================================================================== WIN-BACK
409
+ def customer_winback(pid, t=None, team_id=None, top=8):
410
+ """How to win this customer back, from their purchase history. Compares this year (YTD) to the
411
+ same period last year at SKU + category level to surface:
412
+ lapsed β€” SKUs bought last year, zero this year (the re-pitch hooks), ranked by lost $
413
+ declined β€” SKUs still bought but down YoY, ranked by $ drop
414
+ lapsed_categories β€” category-level gaps
415
+ plus the total dollars at risk (lapsed + declined drop)."""
416
+ t = t or P.today()
417
+ yf, yt = P.ytd(t)
418
+ lf, lt = P.ytd_last_year(t)
419
+
420
+ def sku_map(df, dtt):
421
+ g = O.read_group('sale.order.line', _line_dom(pid, df, dtt, team_id),
422
+ ['price_subtotal:sum', 'product_uom_qty:sum'], ['product_id'], lazy=False)
423
+ return {O.m2o_id(r['product_id']): {'name': O.m2o_name(r.get('product_id')),
424
+ 'rev': r.get('price_subtotal') or 0.0, 'qty': r.get('product_uom_qty') or 0.0}
425
+ for r in g if r.get('product_id')}
426
+
427
+ this, last = sku_map(yf, yt), sku_map(lf, lt)
428
+ lapsed = sorted([{'sku': v['name'], 'ly_rev': v['rev'], 'qty_ly': v['qty']}
429
+ for p, v in last.items() if p not in this and v['rev'] > 0],
430
+ key=lambda x: -x['ly_rev'])
431
+ # 'change' is signed (ytd βˆ’ ly): negative = decline, so the UI tints it red like everywhere else.
432
+ declined = sorted([{'sku': last[p]['name'], 'ly_rev': last[p]['rev'], 'ytd_rev': this[p]['rev'],
433
+ 'change': this[p]['rev'] - last[p]['rev']}
434
+ for p in (set(this) & set(last)) if this[p]['rev'] < last[p]['rev']],
435
+ key=lambda x: x['change'])
436
+
437
+ cat = sales_mod._product_cat()
438
+
439
+ def cat_rev(m):
440
+ agg = {}
441
+ for p, v in m.items():
442
+ agg[cat.get(p, '(uncategorized)')] = agg.get(cat.get(p, '(uncategorized)'), 0.0) + v['rev']
443
+ return agg
444
+ tcat, lcat = cat_rev(this), cat_rev(last)
445
+ lapsed_categories = sorted([{'category': c, 'ly_rev': lcat[c], 'ytd_rev': tcat.get(c, 0.0),
446
+ 'change': tcat.get(c, 0.0) - lcat[c]}
447
+ for c in lcat if lcat[c] > tcat.get(c, 0.0)],
448
+ key=lambda x: x['change'])
449
+ lost_dollars = sum(x['ly_rev'] for x in lapsed) - sum(x['change'] for x in declined)
450
+ return {
451
+ 'lapsed': lapsed[:top], 'declined': declined[:top], 'lapsed_categories': lapsed_categories[:6],
452
+ 'n_lapsed': len(lapsed), 'n_declined': len(declined), 'lost_dollars': lost_dollars,
453
+ 'this_total': sum(v['rev'] for v in this.values()),
454
+ 'last_total': sum(v['rev'] for v in last.values()),
455
+ }
456
+
457
+
458
  # ----------------------------------------------------------- VALIDATION
459
  def validate(t=None):
460
  t = t or P.today()
modules/sales.py CHANGED
@@ -6,6 +6,7 @@ sale.order.line (price_subtotal). Each public metric has a paired validate_* tha
6
  reconciles against an independent Odoo aggregate.
7
  """
8
  import sys
 
9
  from pathlib import Path
10
  sys.path.insert(0, str(Path(__file__).resolve().parents[1])) # cfo_os/
11
  import core.odoo as O
@@ -137,8 +138,11 @@ def top_skus(t=None, limit=25, team_id=None):
137
  return rows[:limit]
138
 
139
 
 
140
  def _product_cat():
141
- """product_id β†’ main category name (reuses inventory's category resolver)."""
 
 
142
  catmap = inv_mod._cat_main_map()
143
  prods = O.search_read('product.product', [('default_code', '!=', False)], ['id', 'categ_id'])
144
  return {p['id']: (catmap.get(O.m2o_id(p.get('categ_id'))) or '(uncategorized)') for p in prods}
 
6
  reconciles against an independent Odoo aggregate.
7
  """
8
  import sys
9
+ from functools import lru_cache
10
  from pathlib import Path
11
  sys.path.insert(0, str(Path(__file__).resolve().parents[1])) # cfo_os/
12
  import core.odoo as O
 
138
  return rows[:limit]
139
 
140
 
141
+ @lru_cache(maxsize=1)
142
  def _product_cat():
143
+ """product_id β†’ main category name (reuses inventory's category resolver).
144
+ Cached for the process β€” the category taxonomy is structural and rarely changes; this avoids
145
+ re-reading the whole product master on every customer drill-down / win-back."""
146
  catmap = inv_mod._cat_main_map()
147
  prods = O.search_read('product.product', [('default_code', '!=', False)], ['id', 'categ_id'])
148
  return {p['id']: (catmap.get(O.m2o_id(p.get('categ_id'))) or '(uncategorized)') for p in prods}