-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
executable file
·4366 lines (3771 loc) · 190 KB
/
Copy pathapp.py
File metadata and controls
executable file
·4366 lines (3771 loc) · 190 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
💎 ULTIMATE RevEngine | Predictive RevOps
Fast + Feature-Rich: Best of both worlds!
Performance:
- ⚡ 10X faster with aggressive caching
- 📊 Tab-based architecture (only active tab loads)
- 🧩 Fragment-based sections for instant updates
- 💾 Smart caching (@st.cache_data)
Features:
- 🎯 Dynamic alerts with specific actions
- 💰 Full Plotly commission flow visualization
- 📊 Complete P&L breakdown with categorization
- 🔮 Interactive what-if analysis with sliders
- 📈 Multi-channel GTM analytics
- 💎 Accurate calculations using Deal Economics Manager
"""
import streamlit as st
import pandas as pd
import numpy as np
import plotly.graph_objects as go
from plotly.subplots import make_subplots
import plotly.express as px
import json
from datetime import datetime
import sys
import os
# Setup paths
CURRENT_DIR = os.path.dirname(os.path.abspath(__file__))
DASHBOARDS_DIR = os.path.dirname(CURRENT_DIR)
PROJECT_ROOT = os.path.dirname(DASHBOARDS_DIR)
MODULES_DIR = os.path.join(PROJECT_ROOT, "modules")
for path in [MODULES_DIR, PROJECT_ROOT, CURRENT_DIR]:
if path not in sys.path:
sys.path.insert(0, path)
# ============= TRANSLATIONS =============
TRANSLATIONS = {
'en': {
'language': '🌐 Language',
'english': '🇺🇸 English',
'spanish': '🇪🇸 Español',
},
'es': {
'language': '🌐 Idioma',
'english': '🇺🇸 English',
'spanish': '🇪🇸 Español',
}
}
def t(key, lang='en'):
"""Translation function"""
return TRANSLATIONS.get(lang, TRANSLATIONS['en']).get(key, key)
# Import modules
try:
from deal_economics_manager import DealEconomicsManager
from modules.calculations_improved import (
ImprovedCostCalculator,
ImprovedCompensationCalculator,
ImprovedPnLCalculator
)
from modules.calculations_enhanced import (
EnhancedRevenueCalculator,
HealthScoreCalculator
)
from modules.revenue_retention import MultiChannelGTM
from deal_economics_manager import DealEconomicsManager, CommissionCalculator
# ✨ NEW ARCHITECTURE - Single Source of Truth
from modules.dashboard_adapter import DashboardAdapter
from modules.ui_components import render_dependency_inspector, render_health_score
from modules.scenario import calculate_sensitivity, multi_metric_sensitivity
except ImportError as e:
st.error(f"⚠️ Module import error: {e}")
st.stop()
# ============= PAGE CONFIG =============
st.set_page_config(
page_title="⚡ RevEngine | Predictive RevOps",
page_icon="⚡",
layout="wide",
initial_sidebar_state="collapsed"
)
# ============= CUSTOM CSS =============
st.markdown("""
<style>
/* Tab styling */
.stTabs [data-baseweb="tab-list"] {
gap: 24px;
background-color: transparent;
}
.stTabs [data-baseweb="tab"] {
height: 50px;
padding: 0 24px;
background-color: transparent;
border-radius: 8px 8px 0 0;
font-weight: 600;
}
.stTabs [aria-selected="true"] {
background-color: rgba(151, 166, 195, 0.15);
}
/* Metric cards */
[data-testid="stMetricValue"] {
font-size: 28px;
}
/* Expander styling */
.streamlit-expanderHeader {
font-weight: 600;
font-size: 16px;
}
/* Hide unnecessary elements */
#MainMenu {visibility: hidden;}
footer {visibility: hidden;}
/* Alert styling */
.alert-critical {
background-color: #fee2e2;
border-left: 4px solid #ef4444;
padding: 12px;
margin: 8px 0;
border-radius: 4px;
color: #991b1b;
}
.alert-critical strong {
color: #7f1d1d;
}
.alert-warning {
background-color: #fef3c7;
border-left: 4px solid #f59e0b;
padding: 12px;
margin: 8px 0;
border-radius: 4px;
color: #92400e;
}
.alert-warning strong {
color: #78350f;
}
.alert-success {
background-color: #d1fae5;
border-left: 4px solid #10b981;
padding: 12px;
margin: 8px 0;
border-radius: 4px;
color: #065f46;
}
.alert-success strong {
color: #064e3b;
}
</style>
""", unsafe_allow_html=True)
# ============= INITIALIZE SESSION STATE =============
def initialize_session_state():
"""Initialize all session state variables with defaults"""
defaults = {
'initialized': True,
'prevent_rerun': False, # Flag to prevent unnecessary reruns
# Deal Economics
'avg_deal_value': 50000,
'upfront_payment_pct': 70.0,
'contract_length_months': 12,
'deferred_timing_months': 18,
'commission_policy': 'upfront',
'government_cost_pct': 10.0, # Government fees/taxes
# Deal Calculator Selection & Parameters
'deal_calc_method': '💰 Direct Value',
'monthly_premium': 3000, # Insurance calculator
'insurance_commission_rate': 2.7,
'insurance_contract_years': 18,
'mrr': 5000, # Subscription calculator
'sub_term_months': 12,
'total_contract_value': 100000, # Commission calculator
'contract_commission_pct': 10.0,
'commission_contract_length': 12,
# Team
'num_closers_main': 8,
'num_setters_main': 4,
'num_managers_main': 2,
'num_benchs_main': 2,
# Team Capacity
'meetings_per_closer': 3.0,
'working_days': 20,
'meetings_per_setter': 2.0,
# Compensation (Commission-only model by default for insurance)
'closer_base': 0,
'closer_variable': 0,
'closer_commission_pct': 10.0,
'setter_base': 0,
'setter_variable': 0,
'setter_commission_pct': 5.0,
'manager_base': 0,
'manager_variable': 0,
'manager_commission_pct': 3.0,
'bench_base': 0,
'bench_variable': 0,
# OTE (On-Target Earnings) - Monthly
'closer_ote_monthly': 5000, # Monthly OTE
'setter_ote_monthly': 4000,
'manager_ote_monthly': 7500,
# Quota calculation mode
'quota_calculation_mode': 'Auto (Based on Capacity)',
# Manual quota overrides (only used if mode = Manual)
'closer_quota_deals_manual': 5.0,
'setter_quota_meetings_manual': 40.0,
'manager_quota_team_deals_manual': 40.0,
# Operating Costs
'office_rent': 20000,
'software_costs': 10000,
'other_opex': 5000,
# Profit Distribution
'stakeholder_pct': 10.0,
# GTM Channels
'gtm_channels': [{
'id': 'channel_1',
'name': 'Primary Channel',
'segment': 'SMB',
'monthly_leads': 1000,
'cpl': 50,
'contact_rate': 0.65,
'meeting_rate': 0.4,
'show_up_rate': 0.7,
'close_rate': 0.3,
'avg_deal_value': 50000,
}],
# Other
'grr_rate': 0.90,
'projection_months': 18,
}
for key, value in defaults.items():
if key not in st.session_state:
st.session_state[key] = value
initialize_session_state()
# Clean up old deprecated keys from previous versions
if 'calculated_deal_value' in st.session_state:
del st.session_state['calculated_deal_value']
if 'calculated_contract_length' in st.session_state:
del st.session_state['calculated_contract_length']
# ============= CACHED CALCULATIONS =============
@st.cache_data(ttl=300)
def calculate_gtm_metrics_cached(channels_json: str, deal_econ_json: str):
"""
Cached GTM metrics calculation.
Only recalculates if channels configuration or deal economics changes.
Cache for 5 minutes.
"""
import json
channels = json.loads(channels_json)
deal_econ = json.loads(deal_econ_json)
if not channels:
return {
'monthly_leads': 0,
'monthly_contacts': 0,
'monthly_meetings_scheduled': 0,
'monthly_meetings_held': 0,
'monthly_sales': 0,
'monthly_revenue_immediate': 0,
'blended_close_rate': 0,
'blended_ltv_cac': 0,
}
# Aggregate across channels
total_leads = 0
total_contacts = 0
total_meetings_sched = 0
total_meetings_held = 0
total_sales = 0
total_revenue = 0
total_spend = 0
channels_breakdown = []
for ch in channels:
if not ch.get('enabled', True):
continue
leads = ch.get('monthly_leads', 0)
cpl = ch.get('cpl', 50)
contact_rate = ch.get('contact_rate', 0.6)
meeting_rate = ch.get('meeting_rate', 0.3)
show_up_rate = ch.get('show_up_rate', 0.7)
close_rate = ch.get('close_rate', 0.25)
contacts = leads * contact_rate
meetings_sched = contacts * meeting_rate
meetings_held = meetings_sched * show_up_rate
sales = meetings_held * close_rate
# Use deal economics passed from cache params
revenue = sales * deal_econ['upfront_cash']
# CONVERGENT COST MODEL: Later stages override earlier stages
# This prevents double-counting - you only pay at ONE funnel stage
cost_method = ch.get('cost_method', 'Cost per Lead')
if cost_method == "Cost per Sale" or cost_method == "CPA":
# Pay per sale only (blocks all upstream costs)
cpa = ch.get('cost_per_sale', ch.get('cpl', 50) * 20)
spend = sales * cpa
elif cost_method == "Cost per Meeting" or cost_method == "CPM":
# Pay per meeting only (blocks CPL and CPC)
cpm = ch.get('cost_per_meeting', ch.get('cpl', 50) * 5)
spend = meetings_held * cpm
elif cost_method == "Cost per Contact" or cost_method == "CPC":
# Pay per contact only (blocks CPL)
cpc = ch.get('cost_per_contact', ch.get('cpl', 50) * 2)
spend = contacts * cpc
elif cost_method == "Total Budget":
# Fixed monthly budget
spend = ch.get('monthly_budget', leads * cpl)
else:
# Default: Cost per Lead (CPL)
spend = leads * cpl
# Aggregate
total_leads += leads
total_contacts += contacts
total_meetings_sched += meetings_sched
total_meetings_held += meetings_held
total_sales += sales
total_revenue += revenue
total_spend += spend
# Channel breakdown
channels_breakdown.append({
'name': ch.get('name', 'Channel'),
'segment': ch.get('segment', 'Unknown'),
'leads': leads,
'sales': sales,
'revenue': revenue,
'spend': spend,
'cpa': spend / sales if sales > 0 else 0,
'roas': revenue / spend if spend > 0 else 0,
'close_rate': close_rate
})
cost_per_sale = total_spend / total_sales if total_sales > 0 else 0
blended_close_rate = total_sales / total_meetings_held if total_meetings_held > 0 else 0
return {
'monthly_leads': total_leads,
'monthly_contacts': total_contacts,
'monthly_meetings_scheduled': total_meetings_sched,
'monthly_meetings_held': total_meetings_held,
'monthly_sales': total_sales,
'monthly_revenue_immediate': total_revenue,
'total_marketing_spend': total_spend,
'cost_per_sale': cost_per_sale,
'blended_close_rate': blended_close_rate,
'channels_breakdown': channels_breakdown
}
@st.cache_data(ttl=300)
def calculate_commission_data_cached(sales_count: float, roles_json: str, deal_econ_json: str):
"""Cached commission calculation"""
import json
roles_comp = json.loads(roles_json)
deal_econ = json.loads(deal_econ_json)
return DealEconomicsManager.calculate_monthly_commission(sales_count, roles_comp, deal_econ)
@st.cache_data(ttl=600)
def calculate_deal_cash_splits(deal_value: float, upfront_pct: float):
"""Cached calculation of upfront/deferred cash splits - used everywhere"""
upfront_cash = deal_value * (upfront_pct / 100)
deferred_cash = deal_value * ((100 - upfront_pct) / 100)
deferred_pct = 100 - upfront_pct
return {
'upfront_cash': upfront_cash,
'deferred_cash': deferred_cash,
'upfront_pct': upfront_pct,
'deferred_pct': deferred_pct
}
@st.cache_data(ttl=600)
def calculate_unit_economics_cached(deal_value: float, upfront_pct: float, grr: float, cost_per_sale: float):
"""Cached unit economics"""
cash_splits = calculate_deal_cash_splits(deal_value, upfront_pct)
upfront_cash = cash_splits['upfront_cash']
deferred_cash = cash_splits['deferred_cash']
ltv = upfront_cash + (deferred_cash * grr)
ltv_cac = ltv / cost_per_sale if cost_per_sale > 0 else 0
payback_months = cost_per_sale / (upfront_cash / 12) if upfront_cash > 0 else 999
return {
'ltv': ltv,
'cac': cost_per_sale,
'ltv_cac': ltv_cac,
'payback_months': payback_months,
**cash_splits # Include cash splits in unit economics
}
@st.cache_data(ttl=300)
def calculate_pnl_cached(revenue: float, team_base: float, commissions: float,
marketing: float, opex: float, gov_fees: float):
"""Calculate comprehensive P&L with proper categorization"""
# Revenue
gross_revenue = revenue
net_revenue = gross_revenue - gov_fees
# COGS (Cost of Goods Sold)
cogs = team_base + commissions
gross_profit = net_revenue - cogs
gross_margin = (gross_profit / net_revenue * 100) if net_revenue > 0 else 0
# Operating Expenses
total_opex = marketing + opex
# EBITDA
ebitda = gross_profit - total_opex
ebitda_margin = (ebitda / net_revenue * 100) if net_revenue > 0 else 0
return {
'gross_revenue': gross_revenue,
'gov_fees': gov_fees,
'net_revenue': net_revenue,
'cogs': cogs,
'team_base': team_base,
'commissions': commissions,
'gross_profit': gross_profit,
'gross_margin': gross_margin,
'marketing': marketing,
'opex': opex,
'total_opex': total_opex,
'ebitda': ebitda,
'ebitda_margin': ebitda_margin
}
# ============= DYNAMIC ALERTS =============
def generate_alerts(gtm_metrics, unit_econ, pnl_data):
"""Generate context-aware alerts with specific actions"""
alerts = []
# Critical alerts (red)
if unit_econ['ltv_cac'] < 1.5:
improvement_needed = unit_econ['cac'] - (unit_econ['ltv'] / 3)
alerts.append({
'type': 'error',
'title': '🚨 Unit Economics Unhealthy',
'message': f"LTV:CAC ratio is {unit_econ['ltv_cac']:.2f}:1 (need 3:1 minimum)",
'action': f"Reduce CAC by ${improvement_needed:,.0f} or increase LTV"
})
if pnl_data['ebitda'] < 0:
alerts.append({
'type': 'error',
'title': '🚨 Negative EBITDA',
'message': f"Monthly EBITDA: ${pnl_data['ebitda']:,.0f}",
'action': f"Need ${abs(pnl_data['ebitda']):,.0f} revenue increase or cost reduction"
})
# Warning alerts (yellow)
if unit_econ['payback_months'] > 12:
alerts.append({
'type': 'warning',
'title': '⚠️ Long Payback Period',
'message': f"{unit_econ['payback_months']:.1f} months to break even (target: <12)",
'action': "Negotiate better payment terms or optimize CAC"
})
if pnl_data['gross_margin'] < 60:
alerts.append({
'type': 'warning',
'title': '⚠️ Low Gross Margin',
'message': f"Gross margin at {pnl_data['gross_margin']:.1f}% (target: 70%+)",
'action': "Review commission structure or increase deal value"
})
if gtm_metrics['monthly_sales'] < 10:
alerts.append({
'type': 'warning',
'title': '⚠️ Low Sales Volume',
'message': f"Only {gtm_metrics['monthly_sales']:.1f} sales/month",
'action': "Increase leads or improve conversion rates"
})
# Success alerts (green)
if unit_econ['ltv_cac'] >= 3 and pnl_data['ebitda_margin'] >= 20:
alerts.append({
'type': 'success',
'title': '✅ Healthy Business Metrics',
'message': f"LTV:CAC {unit_econ['ltv_cac']:.1f}:1 • EBITDA Margin {pnl_data['ebitda_margin']:.1f}%",
'action': "Consider scaling investment"
})
return alerts
# ============= HEADER =============
st.title("💎 ULTIMATE RevEngine | Predictive RevOps")
st.caption("⚡ 10X Faster • 📊 Full Features • 🎯 Accurate Calculations")
# Architecture status
col_status, col_refresh = st.columns([4, 1])
with col_status:
st.info("⚙️ **Dashboard v3.7** • Holistic GTM→Team validation • Real-time capacity warnings • Sales cadence-aware")
with col_refresh:
if st.button("🔄 Refresh Metrics", use_container_width=True, help="Force recalculation if values don't update"):
# Clear ALL caches including DashboardAdapter cache
st.cache_data.clear()
# Force DashboardAdapter to recompute on next access by clearing its specific cache
if hasattr(st.session_state, '_dashboard_adapter_last_cache_key'):
del st.session_state._dashboard_adapter_last_cache_key
st.toast("✅ Metrics refreshed! All caches cleared, values preserved.", icon="🔄")
st.rerun()
# ============= ✨ NEW ARCHITECTURE - Single Source of Truth =============
# All calculations now go through the engine for consistency and performance
# Get all business metrics from the new architecture adapter
# This uses: models.py → engine.py → engine_pnl.py (single source of truth)
metrics = DashboardAdapter.get_metrics()
# Extract metrics for backward compatibility with existing UI code
gtm_metrics = {
'monthly_leads': metrics['monthly_leads'],
'monthly_contacts': metrics['monthly_contacts'],
'monthly_meetings_scheduled': metrics['monthly_meetings_scheduled'],
'monthly_meetings_held': metrics['monthly_meetings_held'],
'monthly_sales': metrics['monthly_sales'],
'monthly_revenue_immediate': metrics['monthly_revenue_immediate'],
'total_marketing_spend': metrics['total_marketing_spend'], # ✅ Respects cost method!
'cost_per_sale': metrics['cost_per_sale'],
'blended_close_rate': metrics['blended_close_rate'],
'channels_breakdown': metrics['channels_breakdown'] # ✅ For funnel charts
}
comm_calc = {
'total_commission': metrics['commissions']['total_commission'],
'closer_pool': metrics['commissions']['closer_pool'],
'setter_pool': metrics['commissions']['setter_pool'],
'manager_pool': metrics['commissions']['manager_pool']
}
unit_econ = metrics['unit_economics']
pnl_data = {
'ebitda': metrics['pnl']['ebitda'],
'ebitda_margin': metrics['pnl']['ebitda_margin'],
'gross_profit': metrics['pnl']['gross_profit'],
'gross_margin': metrics['pnl']['gross_margin'],
'net_revenue': metrics['pnl']['net_revenue'],
'cogs': metrics['pnl']['cogs'],
'total_opex': metrics['pnl']['total_opex']
}
# For backward compatibility with deal_econ references
deal_econ = DealEconomicsManager.get_current_deal_economics()
marketing_spend = metrics['total_marketing_spend'] # ✅ Single source of truth!
# Store previous metrics for delta calculation
if 'prev_metrics' not in st.session_state:
st.session_state.prev_metrics = None
# Calculate deltas if we have previous metrics
current_vals = {
'revenue': gtm_metrics['monthly_revenue_immediate'],
'sales': gtm_metrics['monthly_sales'],
'leads': gtm_metrics['monthly_leads'],
'close_rate': gtm_metrics['blended_close_rate'],
'ltv_cac': unit_econ['ltv_cac'],
'payback': unit_econ['payback_months'],
'deal_value': deal_econ['avg_deal_value'],
'commissions': comm_calc['total_commission'],
'marketing': marketing_spend,
'ebitda': pnl_data['ebitda'],
'ebitda_margin': pnl_data['ebitda_margin']
}
# Calculate deltas
deltas = {}
if st.session_state.prev_metrics:
for key, val in current_vals.items():
prev = st.session_state.prev_metrics.get(key, val)
deltas[key] = val - prev if prev != 0 else 0
else:
deltas = {key: None for key in current_vals.keys()}
# Update previous metrics for next comparison
st.session_state.prev_metrics = current_vals.copy()
# TOP KPI ROW - All key metrics visible at once
st.markdown("### 📊 Key Performance Indicators")
kpi_row1 = st.columns(6)
with kpi_row1[0]:
st.metric("💰 Monthly Revenue", f"${current_vals['revenue']:,.0f}",
delta=f"${deltas['revenue']:,.0f}" if deltas['revenue'] is not None else None)
with kpi_row1[1]:
st.metric("📈 Monthly Sales", f"{current_vals['sales']:.1f}",
delta=f"{deltas['sales']:.1f}" if deltas['sales'] is not None else None)
with kpi_row1[2]:
st.metric("📊 Leads", f"{current_vals['leads']:,.0f}",
delta=f"{deltas['leads']:,.0f}" if deltas['leads'] is not None else None)
with kpi_row1[3]:
st.metric("🎯 Close Rate", f"{current_vals['close_rate']:.1%}",
delta=f"{deltas['close_rate']:.1%}" if deltas['close_rate'] is not None else None)
with kpi_row1[4]:
color = "normal" if current_vals['ltv_cac'] >= 3 else "inverse"
st.metric("🎯 LTV:CAC", f"{current_vals['ltv_cac']:.1f}:1",
delta=f"{deltas['ltv_cac']:.1f}" if deltas['ltv_cac'] is not None else None,
delta_color=color)
with kpi_row1[5]:
st.metric("⏱️ Payback", f"{current_vals['payback']:.0f}mo",
delta=f"{deltas['payback']:.0f}mo" if deltas['payback'] is not None else None,
delta_color="inverse") # Lower payback is better
kpi_row2 = st.columns(6)
with kpi_row2[0]:
st.metric("💎 Deal Value", f"${current_vals['deal_value']:,.0f}",
delta=f"${deltas['deal_value']:,.0f}" if deltas['deal_value'] is not None else None)
with kpi_row2[1]:
st.metric("💸 Total Commissions", f"${current_vals['commissions']:,.0f}",
delta=f"${deltas['commissions']:,.0f}" if deltas['commissions'] is not None else None,
delta_color="inverse") # Lower commissions better for margin
with kpi_row2[2]:
st.metric("📣 Marketing", f"${current_vals['marketing']:,.0f}",
delta=f"${deltas['marketing']:,.0f}" if deltas['marketing'] is not None else None)
with kpi_row2[3]:
ebitda_color = "normal" if current_vals['ebitda'] > 0 else "inverse"
st.metric("💎 EBITDA", f"${current_vals['ebitda']:,.0f}",
delta=f"${deltas['ebitda']:,.0f}" if deltas['ebitda'] is not None else None,
delta_color=ebitda_color)
with kpi_row2[4]:
st.metric("📊 EBITDA Margin", f"{current_vals['ebitda_margin']:.1f}%",
delta=f"{deltas['ebitda_margin']:.1f}%" if deltas['ebitda_margin'] is not None else None)
with kpi_row2[5]:
policy = DealEconomicsManager.get_commission_policy()
st.metric("💸 Comm Policy", "Upfront" if policy == 'upfront' else "Full")
# Sales Process & Pipeline Stages
st.markdown("---")
st.markdown("### 🔄 Sales Process & Pipeline Stages")
pipeline_cols = st.columns(6)
with pipeline_cols[0]:
leads = gtm_metrics['monthly_leads']
st.metric(
"📊 Leads",
f"{leads:,.0f}",
help="Top of funnel - total leads generated"
)
with pipeline_cols[1]:
contacts = gtm_metrics['monthly_contacts']
contact_rate = (contacts / leads * 100) if leads > 0 else 0
st.metric(
"📞 Contacts",
f"{contacts:,.0f}",
f"{contact_rate:.0f}% of leads",
help="Leads successfully contacted and engaged"
)
with pipeline_cols[2]:
meetings = gtm_metrics['monthly_meetings_held']
meeting_rate = (meetings / contacts * 100) if contacts > 0 else 0
st.metric(
"🤝 Meetings",
f"{meetings:,.0f}",
f"{meeting_rate:.0f}% of contacts",
help="Meetings held (show-up rate applied)"
)
with pipeline_cols[3]:
sales = gtm_metrics['monthly_sales']
close_rate = (sales / meetings * 100) if meetings > 0 else 0
st.metric(
"✅ Sales",
f"{sales:.1f}",
f"{close_rate:.0f}% of meetings",
help="Closed deals from meetings"
)
with pipeline_cols[4]:
overall_conversion = (sales / leads * 100) if leads > 0 else 0
st.metric(
"🎯 Overall",
f"{overall_conversion:.2f}%",
"Lead → Sale",
help="End-to-end conversion rate"
)
with pipeline_cols[5]:
cac = unit_econ['cac']
cac_benchmark = "✅ Good" if cac < deal_econ['avg_deal_value'] * 0.2 else "⚠️ High"
st.metric(
"💰 CAC",
f"${cac:,.0f}",
cac_benchmark,
help="Customer Acquisition Cost (Marketing + Sales costs per customer)"
)
st.markdown("---")
# ============= 🔍 TRACEABILITY - See How Numbers Flow =============
with st.expander("🔍 **Traceability Inspector** - See Exactly How Your Inputs Flow to Outputs", expanded=False):
st.markdown("#### 📊 Complete Data Flow Visualization")
st.caption("Understand how every slider and input affects your business metrics")
# Get first active channel for example (or aggregate)
channels = st.session_state.get('gtm_channels', [])
active_channels = [ch for ch in channels if ch.get('enabled', True)]
example_channel = active_channels[0] if active_channels else {}
# Build inputs dict from current state
inputs = {
'monthly_leads': metrics['monthly_leads'],
'contact_rate': example_channel.get('contact_rate', 0.65) if example_channel else 0.65,
'meeting_rate': example_channel.get('meeting_rate', 0.30) if example_channel else 0.30,
'show_up_rate': example_channel.get('show_up_rate', 0.70) if example_channel else 0.70,
'close_rate': example_channel.get('close_rate', 0.25) if example_channel else 0.25,
'cost_per_lead': example_channel.get('cpl', 50) if example_channel.get('cost_method') == 'Cost per Lead' else None,
'cost_per_meeting': example_channel.get('cost_per_meeting', 200) if example_channel.get('cost_method') == 'Cost per Meeting' else None,
'avg_deal_value': st.session_state.get('avg_deal_value', 50000),
'upfront_pct': st.session_state.get('upfront_payment_pct', 70.0) / 100,
}
# Build intermediates dict
intermediates = {
'contacts': metrics['monthly_contacts'],
'meetings_scheduled': metrics['monthly_meetings_scheduled'],
'meetings_held': metrics['monthly_meetings_held'],
'sales': metrics['monthly_sales'],
'marketing_spend': metrics['total_marketing_spend'],
'upfront_cash_per_deal': metrics['unit_economics']['upfront_cash'],
'cost_per_sale': metrics['cost_per_sale'],
}
# Build outputs dict
outputs = {
'monthly_revenue': metrics['monthly_revenue_immediate'],
'roas': metrics['monthly_revenue_immediate'] / metrics['total_marketing_spend'] if metrics['total_marketing_spend'] > 0 else 0,
'ltv': metrics['unit_economics']['ltv'],
'cac': metrics['unit_economics']['cac'],
'ltv_cac_ratio': metrics['unit_economics']['ltv_cac'],
'payback_months': metrics['unit_economics']['payback_months'],
'ebitda': metrics['pnl']['ebitda'],
'ebitda_margin': metrics['pnl']['ebitda_margin'],
'gross_margin': metrics['pnl']['gross_margin'],
}
# Render the inspector
render_dependency_inspector(inputs, intermediates, outputs)
# Add health score
st.markdown("---")
st.markdown("#### 💎 Business Health Score")
render_health_score(
ltv_cac=metrics['unit_economics']['ltv_cac'],
payback_months=metrics['unit_economics']['payback_months'],
ebitda_margin=metrics['pnl']['ebitda_margin'],
gross_margin=metrics['pnl']['gross_margin']
)
st.markdown("---")
# ============= SIDEBAR =============
with st.sidebar:
st.markdown("### ⚙️ Dashboard Settings")
st.info("💡 **Tip**: To prevent page refreshes while editing, use the Configuration tab's 'Apply' buttons at the bottom of each section.")
st.markdown("---")
st.markdown("### 🌐 Language / Idioma")
lang = st.selectbox(
"",
options=['en', 'es'],
format_func=lambda x: t('english', x) if x == 'en' else t('spanish', x),
key='language_selector',
label_visibility='collapsed'
)
st.markdown("---")
# ============= TABS =============
tab1, tab2, tab3, tab4, tab5, tab6, tab7 = st.tabs([
"🎯 GTM Command Center" if lang == 'en' else "🎯 Centro GTM",
"💰 Compensation Structure" if lang == 'en' else "💰 Estructura de Compensación",
"📊 Business Performance" if lang == 'en' else "📊 Desempeño del Negocio",
"🔮 What-If Analysis" if lang == 'en' else "🔮 Análisis Hipotético",
"⚙️ Configuration" if lang == 'en' else "⚙️ Configuración",
"👥 Team Performance" if lang == 'en' else "👥 Desempeño del Equipo",
"🧠 AI Strategic Advisor" if lang == 'en' else "🧠 Asesor Estratégico IA"
])
# ============= TAB 1: GTM COMMAND CENTER =============
with tab1:
st.header("🎯 GTM Command Center")
st.caption("Go-to-market metrics, channels, and funnel performance")
# Get fresh deal economics for this tab (for channel preview calculations)
tab1_deal_econ = DealEconomicsManager.get_current_deal_economics()
# Calculate P&L data for alerts
team_base = (st.session_state.closer_base * st.session_state.num_closers_main +
st.session_state.setter_base * st.session_state.num_setters_main +
st.session_state.manager_base * st.session_state.num_managers_main +
st.session_state.bench_base * st.session_state.num_benchs_main)
roles_comp = {
'closer': {'commission_pct': st.session_state.closer_commission_pct},
'setter': {'commission_pct': st.session_state.setter_commission_pct},
'manager': {'commission_pct': st.session_state.manager_commission_pct}
}
comm_calc = DealEconomicsManager.calculate_monthly_commission(
gtm_metrics['monthly_sales'], roles_comp, deal_econ
)
# ✅ Use cached convergent marketing spend (respects cost method)
marketing_spend = gtm_metrics['total_marketing_spend']
# Calculate government costs (% of gross revenue)
gov_cost_pct = st.session_state.get('government_cost_pct', 10.0) / 100
gov_fees = gtm_metrics['monthly_revenue_immediate'] * gov_cost_pct
pnl_data = calculate_pnl_cached(
gtm_metrics['monthly_revenue_immediate'],
team_base,
comm_calc['total_commission'],
marketing_spend,
st.session_state.office_rent + st.session_state.software_costs + st.session_state.other_opex,
gov_fees # Now includes actual government costs
)
# Dynamic Alerts
alerts = generate_alerts(gtm_metrics, unit_econ, pnl_data)
if alerts:
with st.expander(f"⚠️ Alerts & Recommendations ({len(alerts)})", expanded=True):
for alert in alerts:
if alert['type'] == 'error':
st.markdown(f'<div class="alert-critical"><strong>{alert["title"]}</strong><br>{alert["message"]}<br><em>💡 Action: {alert["action"]}</em></div>', unsafe_allow_html=True)
elif alert['type'] == 'warning':
st.markdown(f'<div class="alert-warning"><strong>{alert["title"]}</strong><br>{alert["message"]}<br><em>💡 Action: {alert["action"]}</em></div>', unsafe_allow_html=True)
else:
st.markdown(f'<div class="alert-success"><strong>{alert["title"]}</strong><br>{alert["message"]}<br><em>🚀 {alert["action"]}</em></div>', unsafe_allow_html=True)
st.markdown("---")
# Multi-Channel Configuration
st.markdown("### 📡 Multi-Channel Configuration")
# Channel management buttons
ch_btn_cols = st.columns([1, 1, 2])
with ch_btn_cols[0]:
if st.button("➕ Add Channel", use_container_width=True, key="add_channel_gtm"):
new_id = f"channel_{len(st.session_state.gtm_channels) + 1}"
st.session_state.gtm_channels.append({
'id': new_id,
'name': f'Channel {len(st.session_state.gtm_channels) + 1}',
'segment': 'SMB',
'monthly_leads': 500,
'cpl': 50,
'contact_rate': 0.6,
'meeting_rate': 0.3,
'show_up_rate': 0.7,
'close_rate': 0.25,
'enabled': True
})
st.rerun()
with ch_btn_cols[1]:
if len(st.session_state.gtm_channels) > 1:
if st.button("🗑️ Remove Last", use_container_width=True, key="remove_channel_gtm"):
st.session_state.gtm_channels.pop()
st.rerun()
with ch_btn_cols[2]:
st.info(f"📊 Managing {len(st.session_state.gtm_channels)} channel(s)")
st.markdown("---")
# Configure each channel in expanders
for idx, channel in enumerate(st.session_state.gtm_channels):
with st.expander(f"📊 **{channel['name']}** ({channel['segment']})", expanded=(idx == 0)):
cfg_cols = st.columns(3)
with cfg_cols[0]:
st.markdown("**Channel Info**")
name = st.text_input("Name", value=channel['name'], key=f"ch_name_{channel['id']}")
st.session_state.gtm_channels[idx]['name'] = name
segment = st.selectbox(
"Segment",
['SMB', 'MID', 'ENT', 'Custom'],
index=['SMB', 'MID', 'ENT', 'Custom'].index(channel.get('segment', 'SMB')),
key=f"ch_segment_{channel['id']}"
)
st.session_state.gtm_channels[idx]['segment'] = segment
st.markdown("**Cost Input Method**")
cost_methods = ["Cost per Lead", "Cost per Contact", "Cost per Meeting", "Cost per Sale", "Total Budget"]
current_method = channel.get('cost_method', 'Cost per Lead')
try:
method_index = cost_methods.index(current_method)
except ValueError:
method_index = 0 # Default to Cost per Lead if not found
cost_point = st.selectbox(
"Cost Input Point",
cost_methods,
index=method_index,
key=f"ch_cost_point_{channel['id']}",
help="Choose how you want to input marketing costs"
)
# Initialize cost variables (prevent NameError)
cpl = 0
cost_per_contact = 0
cost_per_meeting = 0
cost_per_sale = 0
total_budget = 0
leads = 0
# Dynamic inputs based on cost point
if cost_point == "Cost per Lead":
cpl = st.number_input(
"Cost per Lead ($)",
min_value=0,
value=int(channel.get('cpl', 50)),
step=5,
key=f"ch_cpl_{channel['id']}"
)
leads = st.number_input(
"Monthly Leads",
min_value=0,
value=int(channel.get('monthly_leads', 500)),
step=50,
key=f"ch_leads_{channel['id']}"
)
elif cost_point == "Cost per Contact":
cost_per_contact = st.number_input(
"Cost per Contact ($)",
min_value=0,
value=int(channel.get('cost_per_contact', 75)),
step=10,
key=f"ch_cpc_{channel['id']}"
)
contacts_target = st.number_input(
"Monthly Contacts Target",
min_value=0,
value=int(channel.get('contacts_target', 300)),
step=50,
key=f"ch_contacts_{channel['id']}"
)
# Will calculate leads after we have contact rate
leads = contacts_target
cpl = cost_per_contact
elif cost_point == "Cost per Meeting":
cost_per_meeting = st.number_input(
"Cost per Meeting ($)",
min_value=0,
value=int(channel.get('cost_per_meeting', 200)),
step=25,
key=f"ch_cpm_{channel['id']}"
)
meetings_target = st.number_input(
"Monthly Meetings Target",
min_value=0,
value=int(channel.get('meetings_target', 20)),
step=5,
key=f"ch_meetings_{channel['id']}"
)
leads = meetings_target * 5 # Rough estimate
cpl = cost_per_meeting / 5
elif cost_point == "Cost per Sale":
cost_per_sale = st.number_input(
"Cost per Sale ($)",
min_value=0,
value=int(channel.get('cost_per_sale', 500)),
step=50,