system-prompts-and-models-o.../dealix/auto_client_acquisition/revenue_graph/proof_pack.py
2026-05-01 14:03:52 +03:00

269 lines
10 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

"""
Dealix Proof Pack — monthly evidence-based ROI report per customer.
Generated automatically at end of every month, exportable as Markdown
(feeds into PDF). Shows what Dealix did, the leads/meetings/pipeline/revenue,
benchmark comparisons, top messages, and recommendations for next month.
Proof Pack = renewal insurance + executive ammunition for the customer's
internal champion to defend the budget.
"""
from __future__ import annotations
from dataclasses import dataclass, field
from datetime import datetime, timezone
from typing import Any
@dataclass
class ProofPackInputs:
"""All raw metrics the proof pack consumes."""
customer_id: str
customer_name: str
sector: str
month_label: str # e.g. "إبريل 2026"
plan: str # Starter / Growth / Scale
monthly_price_sar: float
# Activity
leads_discovered: int
leads_enriched: int
drafts_created: int
drafts_sent: int
whatsapp_sent: int
emails_sent: int
linkedin_sent: int
replies_received: int
positive_replies: int
meetings_booked: int
proposals_sent: int
deals_won: int
pipeline_added_sar: float
revenue_won_sar: float
# Quality
avg_response_minutes: int
bounce_rate: float
opt_outs: int
compliance_blocks: int
# Benchmarks (sector p50 from Pulse)
sector_reply_rate_p50: float
sector_meeting_rate_p50: float
sector_win_rate_p50: float
# Top performers
best_message_subject: str | None = None
best_message_reply_rate: float | None = None
best_sector_played: str | None = None
worst_bottleneck_ar: str | None = None
@dataclass
class ProofPack:
customer_id: str
customer_name: str
period_label: str
headline_metric: str # one-liner for the cover
grade: str # A+ / A / B / C / D — pilot's quick read
tldr_ar: str # 3 lines for executives
# Sections (each is structured for both UI render + markdown export)
activity_summary: dict[str, Any]
pipeline_impact: dict[str, Any]
quality_score: dict[str, Any]
benchmark_comparison: dict[str, Any]
top_performers: dict[str, Any]
recommendations_next_month_ar: list[str]
roi_breakdown: dict[str, Any]
generated_at: str = field(default_factory=lambda: datetime.now(timezone.utc).isoformat())
def to_markdown(self) -> str:
lines = [
f"# Dealix Proof Pack — {self.customer_name}",
f"**الفترة:** {self.period_label}",
f"**التقييم:** {self.grade}",
"",
f"## TL;DR",
self.tldr_ar,
"",
f"## النشاط",
*(f"- {k}: {v}" for k, v in self.activity_summary.items()),
"",
f"## الأثر على Pipeline",
*(f"- {k}: {v}" for k, v in self.pipeline_impact.items()),
"",
f"## مقارنة بالقطاع",
*(f"- {k}: {v}" for k, v in self.benchmark_comparison.items()),
"",
f"## ROI",
*(f"- {k}: {v}" for k, v in self.roi_breakdown.items()),
"",
f"## التوصيات للشهر القادم",
*(f"{i+1}. {r}" for i, r in enumerate(self.recommendations_next_month_ar)),
"",
f"_Generated by Dealix at {self.generated_at}_",
]
return "\n".join(lines)
# ── Grading — pilot's quick read on the month ────────────────────
def _grade_month(*, pipeline_sar: float, plan_cost: float, win_count: int) -> str:
if plan_cost <= 0:
return "B"
multiple = pipeline_sar / plan_cost
if multiple >= 20 and win_count >= 3:
return "A+"
if multiple >= 10:
return "A"
if multiple >= 5:
return "B"
if multiple >= 2:
return "C"
return "D"
def _vs_benchmark_label(actual: float, p50: float) -> str:
if p50 <= 0:
return ""
if actual >= p50 * 1.5:
return f"{actual*100:.1f}% (أعلى من المعدل القطاعي بـ 50%+)"
if actual >= p50 * 1.1:
return f"{actual*100:.1f}% (فوق المتوسط القطاعي)"
if actual >= p50 * 0.9:
return f"{actual*100:.1f}% (متوسط القطاع)"
if actual >= p50 * 0.5:
return f"{actual*100:.1f}% (تحت المتوسط — فرصة تحسين)"
return f"{actual*100:.1f}% (يحتاج تدخل عاجل)"
def generate_proof_pack(inputs: ProofPackInputs) -> ProofPack:
"""Compose the full Proof Pack from raw metrics."""
reply_rate = inputs.replies_received / max(1, inputs.drafts_sent)
meeting_rate = inputs.meetings_booked / max(1, inputs.replies_received) if inputs.replies_received else 0
win_rate = inputs.deals_won / max(1, inputs.proposals_sent) if inputs.proposals_sent else 0
plan_cost = inputs.monthly_price_sar
payback_multiple = inputs.pipeline_added_sar / max(1, plan_cost)
grade = _grade_month(
pipeline_sar=inputs.pipeline_added_sar,
plan_cost=plan_cost,
win_count=inputs.deals_won,
)
headline = (
f"{inputs.pipeline_added_sar:,.0f} ريال pipeline جديد + "
f"{inputs.meetings_booked} اجتماع في {inputs.month_label}"
)
tldr = (
f"خلال {inputs.month_label}، Dealix أنتج لـ {inputs.customer_name} "
f"{inputs.leads_discovered:,} lead، أرسل {inputs.drafts_sent} رسالة "
f"عبر WhatsApp + إيميل، تلقّى {inputs.replies_received} رد، حجز "
f"{inputs.meetings_booked} اجتماع، وأضاف "
f"{inputs.pipeline_added_sar:,.0f} ريال pipeline جديد. "
f"العائد: {payback_multiple:.1f}× تكلفة الباقة."
)
activity_summary = {
"leads مكتشفة": f"{inputs.leads_discovered:,}",
"leads مُثرّاة (enrichment كامل)": f"{inputs.leads_enriched:,}",
"drafts مُولّدة": f"{inputs.drafts_created:,}",
"WhatsApp مُرسلة": f"{inputs.whatsapp_sent:,}",
"إيميل مُرسل": f"{inputs.emails_sent:,}",
"LinkedIn مُرسل": f"{inputs.linkedin_sent:,}",
"ردود مستلمة": f"{inputs.replies_received:,} ({reply_rate*100:.1f}%)",
"ردود إيجابية": f"{inputs.positive_replies:,}",
"اجتماعات محجوزة": str(inputs.meetings_booked),
}
pipeline_impact = {
"اجتماعات → عروض": f"{inputs.meetings_booked}{inputs.proposals_sent}",
"صفقات مكتسبة": str(inputs.deals_won),
"Pipeline مضاف": f"{inputs.pipeline_added_sar:,.0f} ريال",
"إيراد محسوم هذا الشهر": f"{inputs.revenue_won_sar:,.0f} ريال",
"متوسط قيمة الصفقة": (
f"{inputs.revenue_won_sar / inputs.deals_won:,.0f} ريال"
if inputs.deals_won else ""
),
}
quality_score = {
"متوسط زمن الرد": f"{inputs.avg_response_minutes} دقيقة",
"Bounce rate": f"{inputs.bounce_rate*100:.1f}%",
"Opt-outs": str(inputs.opt_outs),
"Compliance blocks (PDPL محمي)": str(inputs.compliance_blocks),
}
benchmark_comparison = {
"Reply rate": _vs_benchmark_label(reply_rate, inputs.sector_reply_rate_p50),
"Meeting rate": _vs_benchmark_label(meeting_rate, inputs.sector_meeting_rate_p50),
"Win rate": _vs_benchmark_label(win_rate, inputs.sector_win_rate_p50),
}
top_performers = {
"أفضل subject line": inputs.best_message_subject or "",
"معدل ردها": f"{(inputs.best_message_reply_rate or 0)*100:.1f}%",
"أفضل قطاع لعبت فيه": inputs.best_sector_played or inputs.sector,
"أكبر اختناق": inputs.worst_bottleneck_ar or "متوازن — لا اختناقات حادة",
}
# Recommendations — heuristic-driven
recommendations: list[str] = []
if reply_rate < inputs.sector_reply_rate_p50 * 0.8:
recommendations.append(
"أعد كتابة أول جملتين في الـ template الأساسي — معدل الرد تحت المتوسط القطاعي."
)
if meeting_rate < 0.25 and inputs.replies_received >= 10:
recommendations.append(
"حسّن الـ qualification في الرد الأول — كثير ردود ولكن قليل اجتماعات."
)
if inputs.avg_response_minutes > 60:
recommendations.append(
f"وقت الرد {inputs.avg_response_minutes} دقيقة عالي — فعّل WhatsApp auto-acknowledge."
)
if inputs.deals_won == 0 and inputs.proposals_sent >= 3:
recommendations.append(
"أرسلت 3+ عروض بدون إغلاق — جدولة call مع Deal Coach Agent لمراجعة العروض."
)
if not recommendations:
recommendations.append(
"الشهر متوازن — ركّز على scale: زد عدد الـ leads بنسبة 30%."
)
# Always add a forward-looking one
recommendations.append(
"ابدأ شهر جديد بـ Pulse القطاعي + 3 إشارات شراء جديدة من Why-Now Engine."
)
roi_breakdown = {
"تكلفة الباقة هذا الشهر": f"{plan_cost:,.0f} ريال",
"Pipeline مضاف": f"{inputs.pipeline_added_sar:,.0f} ريال",
"Multiple": f"{payback_multiple:.1f}×",
"Pay-per-Lead المعادل": (
f"{plan_cost / inputs.replies_received:.0f} ريال/lead مؤهل"
if inputs.replies_received else ""
),
"Pay-per-Meeting المعادل": (
f"{plan_cost / inputs.meetings_booked:.0f} ريال/اجتماع"
if inputs.meetings_booked else ""
),
}
return ProofPack(
customer_id=inputs.customer_id,
customer_name=inputs.customer_name,
period_label=inputs.month_label,
headline_metric=headline,
grade=grade,
tldr_ar=tldr,
activity_summary=activity_summary,
pipeline_impact=pipeline_impact,
quality_score=quality_score,
benchmark_comparison=benchmark_comparison,
top_performers=top_performers,
recommendations_next_month_ar=recommendations,
roi_breakdown=roi_breakdown,
)