system-prompts-and-models-o.../dealix/api/main.py
Dealix Builder 84f1ad9620 feat(launch+revenue): Private Beta Launch Ops + Revenue Launch — 14 modules + 29 endpoints + 56 tests + scripts/landing/docs
Launch Ops (5 modules) — برج إطلاق الـ Private Beta
- private_beta: 499 SAR × 7-day offer + safety notes + 6-question Arabic FAQ
- demo_flow: 12-minute minute-by-minute Arabic demo + 5 discovery Qs + 6 objection responses + close script
- outreach_messages: 4 segments × 5 prospects = 20 + per-segment Arabic messages + 3-step follow-ups + 6 reply handlers
- go_no_go: 10-gate readiness + 3 critical gates (no_secrets/live_sends_disabled/staging_health) + verdict + next-actions
- launch_scorecard: 11 event types + daily/weekly aggregation + targets (20 outreach/5 replies/3 demos/1 pilot daily)

Revenue Launch (7 modules) — تحويل Dealix إلى دخل
- offer_builder: 4 offers (Private Beta, 499 Pilot, Growth OS Pilot 1.5-3K, Free Case Study) + segment-aware recommend
- pipeline_tracker: 8-stage deterministic pipeline + add/update/summarize + revenue tracking + win rate
- outreach_sequence: re-export single source of truth from launch_ops with revenue-tier wrappers
- demo_closer: re-export from launch_ops
- pilot_delivery: 12-field intake form + 5-phase 24h delivery plan + per-service templates (First 10 / List Intel / Free Diagnostic)
- proof_pack_template: 5-line Arabic client summary + ROI estimate (pipeline_x + closed_won_x) + next-step recommendation (upsell/iterate/extend)
- payment_manual_flow: Moyasar invoice step-by-step (halalas-correct) + Arabic payment-link message + confirmation checklist; NEVER charges via API

Service Tower extensions (2 modules)
- contract_templates: re-export targeting_os contracts + new SLA outline (legal_review_required, PDPL-aware)
- vertical_service_map: 6 verticals (B2B SaaS / agencies / training-consulting / real estate / healthcare-local / retail-ecommerce) with primary+supporting services + buyer roles + common pains + winning offer

Routers (2 new) — 29 endpoints
- /api/v1/launch/* — 11 endpoints (private-beta/offer, demo/flow, outreach/{first-20, message, followup}, go-no-go, readiness, scorecard/{event, daily, weekly, demo})
- /api/v1/revenue-launch/* — 18 endpoints (offers + offers/recommend, outreach/{first-20, followup}, demo-flow, pipeline/{schema, summarize}, pilot-delivery/{intake-form, 24h-plan, first-10, list-intelligence, free-diagnostic}, payment/{invoice-instructions, link-message, confirmation-checklist}, proof-pack/{template, client-summary, next-step})

Tests (2 new files, 56 tests)
- test_launch_ops.py: 25 tests (Private Beta offer essentials + Arabic FAQ; demo flow 12-min structure; first-20 segments × 5; outreach Arabic + drafts only; followup steps differ; reply handlers include unsubscribe; go/no-go critical gates block; scorecard aggregation + verdict)
- test_revenue_launch.py: 31 tests (offers correct prices, no_live_charge=True; segment-aware recommends; pipeline 8 stages + add/update/summarize + win rate; outreach v2 Arabic; intake fields; 24h plan 5 phases; invoice halalas correct; payment confirmation blocks premature delivery; proof pack 5 lines + 3 next-step paths)

Scripts (1 new)
- scripts/launch_readiness_check.py: runs 10 gates locally + optional --staging-url; pretty/JSON output; critical gates determine GO/NO-GO/FIX-THEN-GO verdict

Landing pages (2 new, RTL Arabic)
- list-intelligence.html — List Intelligence service detail (499–1,500 SAR)
- growth-os.html — Growth OS Monthly subscription page (2,999 SAR/month)

Docs (1 new + 1 updated)
- REVENUE_TODAY_PLAYBOOK.md (Arabic) — 12-section playbook: offers, segments, messages, demo, pipeline, 24h delivery, Moyasar manual flow, proof pack, daily targets, go/no-go, what-not-to-do, next-step
- DEALIX_100_PERCENT_LAUNCH_PLAN.md — added §40 Launch Ops + §41 Revenue Launch + §42 Service Tower extensions + §43 Scripts

Test results
- 56/56 new tests pass
- Full suite: 824 passed, 2 skipped (missing API keys, unrelated)
- 0 existing tests broken

Safety integration
- All offers: live_send_allowed=False, no_live_charge=True, approval_required=True
- 10-gate go/no-go BLOCKS launch if no_secrets/live_sends_disabled/staging_health fail
- Moyasar: invoice/payment-link manual only; NEVER calls live charge API
- Payment confirmation checklist blocks delivery before invoice paid status
- All outreach messages: drafts only, follow-ups capped at 3, opt-out honored immediately
- 6 verticals mapped to safe service stacks; LinkedIn always Lead Forms (never scraping)

Integration with previous layers
- Launch Ops uses platform_services tool_gateway, intelligence_layer command_feed, security_curator redaction
- Revenue Launch uses targeting_os contractability + service_tower offers + intelligence_layer simulator
- Pipeline tracker integrates with action_ledger for stage transitions
- Proof Pack template references intelligence_layer proof metrics + service_excellence ROI

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-01 17:28:08 +03:00

212 lines
6.3 KiB
Python

"""
FastAPI application entry point.
نقطة دخول تطبيق FastAPI.
"""
from __future__ import annotations
from collections.abc import AsyncIterator
from contextlib import asynccontextmanager
from fastapi import FastAPI, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse
from api.middleware import RequestIDMiddleware
from api.routers import (
admin,
agent_observability,
agents,
automation,
autonomous,
business,
command_center,
connector_catalog,
customer_success,
data,
dominance,
drafts,
ecosystem,
email_send,
full_os,
growth_curator,
growth_operator,
health,
innovation,
intelligence_layer,
launch_ops,
leads,
meeting_intelligence,
model_router,
outreach,
personal_operator,
platform_services,
pricing,
prospect,
public,
revenue,
revenue_launch,
revenue_os,
sales,
sectors,
security_curator,
service_excellence,
service_tower,
targeting_os,
v3,
webhooks,
)
from api.security import APIKeyMiddleware, setup_rate_limit
from core.config.settings import get_settings
from core.errors import AICompanyError
from core.logging import configure_logging, get_logger
@asynccontextmanager
async def lifespan(_app: FastAPI) -> AsyncIterator[None]:
"""App startup/shutdown hook."""
configure_logging()
log = get_logger(__name__)
settings = get_settings()
log.info(
"app_startup",
app=settings.app_name,
version=settings.app_version,
env=settings.app_env,
)
# Auto-create tables on boot (additive — safe with SQLAlchemy create_all)
try:
from db.session import init_db
await init_db()
log.info("db_init_complete")
except Exception as exc:
log.warning("db_init_skipped", error=str(exc))
yield
log.info("app_shutdown")
def create_app() -> FastAPI:
"""FastAPI factory."""
settings = get_settings()
app = FastAPI(
title=settings.app_name,
version=settings.app_version,
description=(
"Multi-agent AI platform for the Saudi Arabian market.\n\n"
"**Phase 8**: Auto Client Acquisition — intake, ICP match, "
"pain extraction, qualification, CRM sync, booking, proposals.\n\n"
"**Phase 9**: Autonomous Growth — sector intel, content, distribution, "
"enrichment, competitor analysis, market research.\n\n"
"**Phase 10 / v3**: Autonomous Saudi Revenue OS — revenue memory, "
"safe agent runtime, market radar, compliance OS, revenue science, "
"and Sami Personal Strategic Operator."
),
docs_url="/docs",
redoc_url="/redoc",
openapi_url="/openapi.json",
lifespan=lifespan,
)
app.add_middleware(
CORSMiddleware,
allow_origins=settings.cors_origin_list,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
app.add_middleware(RequestIDMiddleware)
app.add_middleware(APIKeyMiddleware)
setup_rate_limit(app)
try:
from dealix.observability import instrument_fastapi, setup_sentry, setup_tracing
setup_sentry()
setup_tracing(service_name=settings.app_name, version=settings.app_version)
instrument_fastapi(app)
except Exception: # pragma: no cover
pass
@app.exception_handler(AICompanyError)
async def ai_company_error_handler(_: Request, exc: AICompanyError) -> JSONResponse:
return JSONResponse(
status_code=400,
content={"error": exc.__class__.__name__, "detail": str(exc)},
)
app.include_router(health.router)
app.include_router(leads.router)
app.include_router(sales.router)
app.include_router(sectors.router)
app.include_router(agents.router)
app.include_router(webhooks.router)
app.include_router(pricing.router)
app.include_router(prospect.router)
app.include_router(autonomous.router)
app.include_router(data.router)
app.include_router(outreach.router)
app.include_router(revenue.router)
app.include_router(automation.router)
app.include_router(email_send.router)
app.include_router(drafts.router)
app.include_router(dominance.router)
app.include_router(full_os.router)
app.include_router(customer_success.router)
app.include_router(ecosystem.router)
app.include_router(command_center.router)
app.include_router(revenue_os.router)
app.include_router(v3.router)
app.include_router(innovation.router)
app.include_router(business.router)
app.include_router(personal_operator.router)
app.include_router(growth_operator.router)
app.include_router(platform_services.router)
app.include_router(intelligence_layer.router)
app.include_router(security_curator.router)
app.include_router(growth_curator.router)
app.include_router(meeting_intelligence.router)
app.include_router(model_router.router)
app.include_router(connector_catalog.router)
app.include_router(agent_observability.router)
app.include_router(targeting_os.router)
app.include_router(service_tower.router)
app.include_router(service_excellence.router)
app.include_router(launch_ops.router)
app.include_router(revenue_launch.router)
app.include_router(public.router)
app.include_router(admin.router)
@app.get("/", tags=["root"])
async def root() -> dict[str, object]:
return {
"name": settings.app_name,
"version": settings.app_version,
"status": "operational",
"env": settings.app_env,
"docs": "/docs",
"health": "/health",
"v3_command_center": "/api/v1/v3/command-center/snapshot",
"personal_operator_daily_brief": "/api/v1/personal-operator/daily-brief",
"personal_operator_launch_report": "/api/v1/personal-operator/launch-report",
"business_pricing": "/api/v1/business/pricing",
"innovation_command_feed_demo": "/api/v1/innovation/command-feed/demo",
}
return app
app = create_app()
if __name__ == "__main__":
import uvicorn
settings = get_settings()
uvicorn.run(
"api.main:app",
host=settings.app_host,
port=settings.app_port,
reload=settings.is_development,
)