From 83210b9d1277e21a68d266e1b097e2d2f8016b11 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 11 Apr 2026 08:09:50 +0000 Subject: [PATCH] feat: Add founder strategy, Claude Code control plane, SaaS launch readiness Founder Strategy & GTM (from prompts #1, #10): - niche-brief.md: Saudi real estate primary, healthcare secondary - icp-brief.md: Full ICP with Arabic objection handling - content-map.md: 20 content ideas, SEO keywords, weekly schedule - outreach-map.md: WhatsApp/Email cold outreach with Arabic templates - launch-plan.md: 14-day sprint + 30-day plan with revenue targets - interview-template.md: 15 Arabic customer discovery questions Claude Code Control Plane (from prompt #2): - .claude/settings.json: Permissions and preferences - .claude/commands/: 5 custom commands (review-pr, release-prep, security-check, generate-tests, architecture-review) - .claude/hooks/: pre-commit.sh (secrets check), pre-push.sh (tests) SaaS Launch Readiness (from prompt #4): - saas-readiness-audit.md: Full audit with gap analysis - deployment-checklist.md: Deploy + rollback procedures - launch-checklist.md: 100+ launch day checklist items - feature_flags.py: Redis-backed feature flags with per-tenant control https://claude.ai/code/session_01LsnvBa7HwF5hs99VZbgLGj --- .../.claude/commands/architecture-review.md | 116 +++++++ .../.claude/commands/generate-tests.md | 130 ++++++++ .../.claude/commands/release-prep.md | 90 ++++++ salesflow-saas/.claude/commands/review-pr.md | 75 +++++ .../.claude/commands/security-check.md | 102 ++++++ salesflow-saas/.claude/hooks/pre-commit.sh | 23 ++ salesflow-saas/.claude/hooks/pre-push.sh | 13 + salesflow-saas/.claude/settings.json | 23 ++ .../backend/app/services/feature_flags.py | 159 ++++++++++ salesflow-saas/memory/customers/icp-brief.md | 66 ++++ .../memory/customers/interview-template.md | 48 +++ salesflow-saas/memory/growth/content-map.md | 78 +++++ salesflow-saas/memory/growth/launch-plan.md | 75 +++++ salesflow-saas/memory/growth/niche-brief.md | 199 ++++++++++++ salesflow-saas/memory/growth/outreach-map.md | 84 +++++ .../memory/runbooks/deployment-checklist.md | 30 ++ .../memory/runbooks/launch-checklist.md | 256 +++++++++++++++ .../memory/runbooks/saas-readiness-audit.md | 293 ++++++++++++++++++ 18 files changed, 1860 insertions(+) create mode 100644 salesflow-saas/.claude/commands/architecture-review.md create mode 100644 salesflow-saas/.claude/commands/generate-tests.md create mode 100644 salesflow-saas/.claude/commands/release-prep.md create mode 100644 salesflow-saas/.claude/commands/review-pr.md create mode 100644 salesflow-saas/.claude/commands/security-check.md create mode 100755 salesflow-saas/.claude/hooks/pre-commit.sh create mode 100755 salesflow-saas/.claude/hooks/pre-push.sh create mode 100644 salesflow-saas/.claude/settings.json create mode 100644 salesflow-saas/backend/app/services/feature_flags.py create mode 100644 salesflow-saas/memory/customers/icp-brief.md create mode 100644 salesflow-saas/memory/customers/interview-template.md create mode 100644 salesflow-saas/memory/growth/content-map.md create mode 100644 salesflow-saas/memory/growth/launch-plan.md create mode 100644 salesflow-saas/memory/growth/niche-brief.md create mode 100644 salesflow-saas/memory/growth/outreach-map.md create mode 100644 salesflow-saas/memory/runbooks/deployment-checklist.md create mode 100644 salesflow-saas/memory/runbooks/launch-checklist.md create mode 100644 salesflow-saas/memory/runbooks/saas-readiness-audit.md diff --git a/salesflow-saas/.claude/commands/architecture-review.md b/salesflow-saas/.claude/commands/architecture-review.md new file mode 100644 index 00000000..167926b8 --- /dev/null +++ b/salesflow-saas/.claude/commands/architecture-review.md @@ -0,0 +1,116 @@ +# /architecture-review — Architecture Review for Dealix + +Review the codebase architecture for consistency, correctness, and maintainability. + +## Steps + +### 1. Service Boundary Analysis +Scan all services in `backend/app/services/`: +```bash +ls backend/app/services/*.py backend/app/services/*/*.py +``` + +For each service, check: +- **Single Responsibility**: Does it handle one domain concern or is it a grab bag? +- **Dependency Direction**: Services should depend on abstractions, not on each other circularly +- **Size**: Flag services over 500 lines as candidates for splitting +- **Naming**: Service name should match its domain (`lead_service.py` handles leads, not deals) + +### 2. Import Cycle Detection +Check for circular imports between service modules: +```bash +grep -rn "^from app.services" backend/app/services/ --include="*.py" +grep -rn "^import app.services" backend/app/services/ --include="*.py" +``` + +Build a dependency graph and flag any cycles. Common problematic patterns: +- Service A imports Service B which imports Service A +- Circular through models: Service -> Model -> Service + +### 3. Model Relationship Audit +Scan all SQLAlchemy models in `backend/app/models/`: +```bash +ls backend/app/models/*.py +``` + +For each model verify: +- Has `tenant_id` column (multi-tenancy requirement) +- Has `created_at` and `updated_at` timestamps +- Has `id` as UUID primary key +- Foreign keys reference correct tables +- Relationship `back_populates` are bidirectional and consistent +- No orphaned models (defined but never referenced) +- Indexes on `tenant_id` and frequently-queried columns + +### 4. API Consistency Check +Scan all API routes in `backend/app/api/v1/`: +```bash +ls backend/app/api/v1/*.py +``` + +Verify consistency: +- **URL patterns**: all use kebab-case or snake_case (not mixed) +- **HTTP methods**: GET for reads, POST for creates, PUT/PATCH for updates, DELETE for deletes +- **Response format**: all return consistent JSON structure `{"data": ..., "message": ...}` +- **Error responses**: use standard error schema with status code and detail +- **Authentication**: all non-public routes have `Depends(get_current_user)` +- **Pagination**: list endpoints support `skip` and `limit` parameters +- **Tenant scoping**: tenant_id extracted from token, not URL + +### 5. Configuration & Environment +Review `backend/app/config.py` or equivalent: +- All secrets from environment variables +- Sensible defaults for development +- No production values hardcoded +- Settings class uses Pydantic `BaseSettings` +- Separate configs for test/dev/staging/prod + +### 6. Worker & Task Architecture +Review Celery workers in `backend/app/workers/`: +```bash +ls backend/app/workers/*.py 2>/dev/null +``` + +Check: +- Tasks are idempotent (safe to retry) +- Long tasks have timeout configuration +- Tasks log their execution for debugging +- Error handling with proper retry strategy +- No database sessions held across `await` boundaries + +### 7. Frontend-Backend Contract +Compare API routes with frontend API calls: +```bash +grep -rn "fetch\|axios\|api\." frontend/src/ --include="*.ts" --include="*.tsx" | grep -v node_modules | grep -v ".next" +``` + +Flag mismatches: +- Frontend calls endpoints that don't exist +- Request/response types don't match +- Missing error handling on frontend for known error responses + +### 8. Integration Points +Review external integrations in `backend/app/integrations/`: +- WhatsApp adapter: retry logic, rate limiting, error handling +- Email service: template rendering, bounce handling +- Stripe: webhook verification, idempotency keys +- AI providers: fallback chain, timeout handling, cost tracking + +### 9. Architecture Report +Produce a structured report: + +| Area | Status | Issues Found | Recommendation | +|------|--------|-------------|----------------| +| Service Boundaries | | | | +| Import Cycles | | | | +| Model Integrity | | | | +| API Consistency | | | | +| Config Management | | | | +| Worker Architecture | | | | +| Frontend Contract | | | | +| Integrations | | | | + +Include: +- Top 5 highest-priority architectural improvements +- Technical debt inventory with estimated effort +- Recommended refactoring sequence diff --git a/salesflow-saas/.claude/commands/generate-tests.md b/salesflow-saas/.claude/commands/generate-tests.md new file mode 100644 index 00000000..2e39ddae --- /dev/null +++ b/salesflow-saas/.claude/commands/generate-tests.md @@ -0,0 +1,130 @@ +# /generate-tests — Auto-generate Tests for Dealix Services + +Analyze a service file and generate comprehensive pytest-asyncio tests with factory-boy fixtures. + +## Usage +Provide the path to a service file, e.g.: `/generate-tests backend/app/services/lead_service.py` + +## Steps + +### 1. Analyze the Target Service +Read the specified service file and extract: +- Class name and constructor dependencies (db session, other services) +- All public methods with their signatures and return types +- Database models referenced +- External service calls (WhatsApp, email, Stripe, AI providers) +- Async vs sync methods + +### 2. Identify Test Cases +For each public method, generate tests for: +- **Happy path** — normal operation with valid inputs +- **Empty/null input** — None, empty string, empty list +- **Invalid tenant** — wrong tenant_id, missing tenant_id +- **Not found** — entity does not exist +- **Duplicate** — creating something that already exists +- **Permission denied** — user lacks required role +- **Boundary values** — max length strings, zero amounts, negative numbers +- **Concurrent access** — if method modifies shared state + +### 3. Generate Factory Classes +Create factory-boy factories for each model used: +```python +import factory +from factory.alchemy import SQLAlchemyModelFactory + +class TenantFactory(SQLAlchemyModelFactory): + class Meta: + model = Tenant + sqlalchemy_session_persistence = "commit" + + id = factory.LazyFunction(uuid4) + name = factory.Faker("company", locale="ar_SA") + domain = factory.Faker("domain_name") + is_active = True + created_at = factory.LazyFunction(lambda: datetime.now(timezone.utc)) +``` + +Use `locale="ar_SA"` for Arabic data where appropriate (names, companies, addresses). + +### 4. Generate Test File +Create the test file at `backend/tests/test_services/test_.py` with: + +```python +""" +Tests for . +Auto-generated — review and customize before committing. +""" + +import pytest +from unittest.mock import AsyncMock, MagicMock, patch +from uuid import uuid4 + +from app.services. import + + +@pytest.fixture +def db_session(): + """Mock async database session.""" + session = AsyncMock() + session.execute = AsyncMock() + session.commit = AsyncMock() + session.rollback = AsyncMock() + session.refresh = AsyncMock() + return session + + +@pytest.fixture +def service(db_session): + return (db=db_session) + + +@pytest.fixture +def tenant_id(): + return uuid4() + + +class TestMethodName: + @pytest.mark.asyncio + async def test_success(self, service, tenant_id): + # Arrange + ... + # Act + result = await service.method_name(...) + # Assert + assert result is not None + + @pytest.mark.asyncio + async def test_not_found(self, service, tenant_id): + service.db.execute.return_value = MagicMock(scalar_one_or_none=MagicMock(return_value=None)) + with pytest.raises(NotFoundException): + await service.method_name(...) + + @pytest.mark.asyncio + async def test_wrong_tenant(self, service): + wrong_tenant = uuid4() + # Should not return data from another tenant + ... +``` + +### 5. Mocking Strategy +- **Database**: Mock `AsyncSession` with `execute()` returning mock results +- **Redis**: Mock with `fakeredis.aioredis` or `AsyncMock` +- **External APIs** (WhatsApp, Stripe): Use `unittest.mock.patch` on the service method +- **Celery tasks**: Mock with `@patch("app.workers.task_name.delay")` +- **AI services**: Mock LLM responses with fixed JSON structures +- **Time-dependent**: Use `freezegun` for timestamp-sensitive logic + +### 6. Validation Checklist +After generating, verify: +- [ ] All public methods have at least one test +- [ ] Async methods use `@pytest.mark.asyncio` +- [ ] Mocks match actual method signatures +- [ ] Tenant isolation is tested +- [ ] No real external calls in tests +- [ ] Test file runs without import errors: `pytest --co -q` + +### 7. Output +Print the complete test file content and the command to run it: +```bash +pytest backend/tests/test_services/test_.py -v +``` diff --git a/salesflow-saas/.claude/commands/release-prep.md b/salesflow-saas/.claude/commands/release-prep.md new file mode 100644 index 00000000..abed6646 --- /dev/null +++ b/salesflow-saas/.claude/commands/release-prep.md @@ -0,0 +1,90 @@ +# /release-prep — Release Preparation Checklist for Dealix + +Prepare a release candidate. Run all checks and generate release notes. + +## Steps + +### 1. Run Full Test Suite +```bash +cd backend && pytest -v --tb=short 2>&1 | tail -30 +``` +All tests must pass. If any fail, list them and stop. + +### 2. Lint & Format Check +```bash +cd backend && ruff check . --select E,W,F,I +cd backend && ruff format --check . +``` +Fix any issues found. + +### 3. Security Scan +- Grep for hardcoded secrets: + ```bash + grep -rn "API_KEY\|SECRET_KEY\|PASSWORD\|PRIVATE_KEY" backend/app/ --include="*.py" | grep -v "settings\.\|config\.\|get_settings\|os\.environ\|\.env" + ``` +- Check for known vulnerable dependencies: + ```bash + pip-audit -r backend/requirements.txt 2>/dev/null || echo "pip-audit not installed" + ``` + +### 4. Database Migrations +- Check for pending migrations: + ```bash + cd backend && alembic heads + cd backend && alembic current + ``` +- Verify migration chain is linear (no branch conflicts) +- Confirm all migrations have downgrade functions + +### 5. Arabic Translation Completeness +- Scan frontend for untranslated strings: + ```bash + grep -rn "TODO.*translat\|FIXME.*arabic\|FIXME.*rtl" frontend/src/ --include="*.tsx" --include="*.ts" + ``` +- Check that all toast messages, error messages, and form labels have Arabic variants +- Verify RTL layout in key pages: dashboard, leads, deals, settings + +### 6. Build Frontend +```bash +cd frontend && npm run build 2>&1 | tail -20 +``` +Build must complete without errors. Warnings are acceptable but should be noted. + +### 7. Docker Build Verification +```bash +docker compose build --no-cache 2>&1 | tail -10 +``` +All services must build successfully. + +### 8. Environment Variable Audit +Compare `.env.example` against required variables: +- Database: `DATABASE_URL`, `REDIS_URL` +- Auth: `JWT_SECRET_KEY`, `JWT_ALGORITHM` +- AI: `GROQ_API_KEY`, `OPENAI_API_KEY` +- WhatsApp: `ULTRAMSG_INSTANCE_ID`, `ULTRAMSG_TOKEN` +- Payments: `STRIPE_SECRET_KEY`, `STRIPE_WEBHOOK_SECRET` +- Monitoring: `SENTRY_DSN` + +Verify no variable is empty or placeholder in production config. + +### 9. Generate Release Notes +Based on commits since last tag: +```bash +git log $(git describe --tags --abbrev=0 2>/dev/null || echo "HEAD~20")..HEAD --oneline --no-merges +``` + +Organize into: +- **New Features** — user-facing capabilities +- **Improvements** — enhancements to existing features +- **Bug Fixes** — resolved issues +- **Security** — security-related changes +- **Infrastructure** — deployment, CI/CD, config changes +- **Breaking Changes** — anything requiring migration or config updates + +### 10. Pre-release Summary +Output a go/no-go decision with: +- Test results (pass/fail count) +- Security findings +- Migration status +- Build status +- Outstanding risks or blockers diff --git a/salesflow-saas/.claude/commands/review-pr.md b/salesflow-saas/.claude/commands/review-pr.md new file mode 100644 index 00000000..1a2db997 --- /dev/null +++ b/salesflow-saas/.claude/commands/review-pr.md @@ -0,0 +1,75 @@ +# /review-pr — Pull Request Review for Dealix + +Review the current PR branch against main. Perform a thorough multi-dimensional review. + +## Steps + +### 1. Identify Changes +```bash +git diff main...HEAD --stat +git diff main...HEAD --name-only +``` +List all changed files grouped by area (backend, frontend, migrations, tests, config). + +### 2. Code Quality +For each changed Python file: +- Check function length (flag any >40 lines) +- Check cyclomatic complexity (flag deeply nested logic) +- Verify type hints on all public function signatures +- Ensure docstrings on public classes and methods +- Verify consistent error handling (no bare `except:`) +- Check for `print()` statements that should be `logger.info()` + +For each changed TypeScript/TSX file: +- Check component size (flag >200 lines) +- Verify prop types are defined +- Check for `any` type usage (should be avoided) +- Ensure error boundaries on async data fetching + +### 3. Security Review +- No hardcoded secrets, API keys, or passwords +- SQL queries use parameterized statements (no f-string SQL) +- API endpoints have proper authentication decorators +- Tenant isolation: all DB queries filter by `tenant_id` +- File uploads validate content type and size +- No `eval()`, `exec()`, or `pickle.loads()` on user input +- JWT tokens validated on all protected routes +- CORS configuration is restrictive (not `*`) + +### 4. PDPL Compliance +- Any new message-sending endpoint checks consent via `ConsentManager` +- Personal data access is audit-logged +- Data deletion endpoints exist for any new PII fields +- Consent purpose is specified for new data collection points +- No PII in log statements + +### 5. Arabic String Validation +- All user-facing strings have Arabic translations +- Arabic text renders RTL correctly in frontend components +- Date/time formatting uses `Asia/Riyadh` timezone +- Currency displays as SAR with proper Arabic formatting +- Phone numbers accept Saudi format (+966) + +### 6. Test Coverage +```bash +pytest --co -q # List collected tests +``` +- Every new API endpoint has at least one test +- Every new service method has unit tests +- Edge cases covered (empty input, invalid tenant, expired token) +- Async tests use `pytest-asyncio` + +### 7. Database & Migrations +- New models include `tenant_id` column +- Alembic migration is reversible (has `downgrade()`) +- No destructive migrations on production data +- Indexes exist on frequently queried columns +- Foreign keys have proper cascade rules + +### 8. Summary +Produce a structured review with: +- **Approve / Request Changes / Needs Discussion** +- Critical issues (must fix before merge) +- Warnings (should fix, not blocking) +- Suggestions (nice to have) +- Questions for the author diff --git a/salesflow-saas/.claude/commands/security-check.md b/salesflow-saas/.claude/commands/security-check.md new file mode 100644 index 00000000..41b27a67 --- /dev/null +++ b/salesflow-saas/.claude/commands/security-check.md @@ -0,0 +1,102 @@ +# /security-check — Security Preflight for Dealix + +Run a comprehensive security audit before deployment or PR merge. + +## Steps + +### 1. Hardcoded Secrets Detection +Scan all source files for embedded credentials: +```bash +grep -rn "API_KEY\s*=\s*['\"]" backend/app/ --include="*.py" | grep -v "os\.environ\|get_settings\|config\.\|settings\.\|# example\|# test" +grep -rn "SECRET\s*=\s*['\"]" backend/app/ --include="*.py" | grep -v "os\.environ\|get_settings\|config\.\|settings\.\|# example" +grep -rn "PASSWORD\s*=\s*['\"]" backend/app/ --include="*.py" | grep -v "os\.environ\|get_settings\|config\.\|settings\.\|# example\|hash_password" +grep -rn "PRIVATE_KEY\s*=\s*['\"]" backend/app/ --include="*.py" | grep -v "os\.environ\|get_settings" +grep -rn "Bearer\s\+[A-Za-z0-9_-]\{20,\}" backend/app/ --include="*.py" +``` +Any match is a **CRITICAL** finding. + +### 2. SQL Injection Vectors +Check for unsafe SQL construction: +```bash +grep -rn "f\".*SELECT\|f\".*INSERT\|f\".*UPDATE\|f\".*DELETE\|f'.*SELECT\|f'.*INSERT\|f'.*UPDATE\|f'.*DELETE" backend/app/ --include="*.py" +grep -rn "\.execute(f\"\|\.execute(f'" backend/app/ --include="*.py" +grep -rn "text(f\"\|text(f'" backend/app/ --include="*.py" +``` +All SQL must use SQLAlchemy ORM or parameterized `text()` binds. + +### 3. XSS Prevention +Check frontend for unsafe rendering: +```bash +grep -rn "dangerouslySetInnerHTML" frontend/src/ --include="*.tsx" --include="*.ts" +grep -rn "v-html" frontend/src/ --include="*.vue" 2>/dev/null +``` +Flag each occurrence and verify input is sanitized. + +### 4. PDPL Consent Verification +Check all message-sending endpoints enforce consent: +```bash +grep -rn "send_whatsapp\|send_sms\|send_email\|send_message" backend/app/api/ --include="*.py" -l +``` +For each file found, verify it calls `ConsentManager.check_consent()` or `consent_manager.verify_consent()` before sending. + +Check that personal data endpoints log access: +```bash +grep -rn "def get_lead\|def get_contact\|def export" backend/app/api/ --include="*.py" -l +``` +Each must call `audit_service.log_access()` or equivalent. + +### 5. JWT Validation +Verify JWT security configuration: +```bash +grep -rn "JWT_ALGORITHM\|jwt\.decode\|jwt\.encode" backend/app/ --include="*.py" +``` +- Algorithm must be HS256 or RS256 (not `none`) +- Token expiry must be set (not unlimited) +- Secret key must come from environment, not hardcoded +- Refresh token rotation must be implemented + +### 6. Tenant Isolation Audit +Check that all database queries enforce tenant boundaries: +```bash +grep -rn "def get\|def list\|def update\|def delete" backend/app/services/ --include="*.py" -l +``` +For each service file, verify queries include `tenant_id` filter. Flag any query that accesses data without tenant scoping. + +Check for cross-tenant data leakage in API responses: +- Ensure no endpoint returns data from multiple tenants +- Verify tenant_id is extracted from JWT, not from request body + +### 7. Dependency Vulnerabilities +```bash +pip-audit -r backend/requirements.txt 2>/dev/null || echo "Run: pip install pip-audit" +cd frontend && npm audit --production 2>/dev/null || echo "Run npm audit manually" +``` + +### 8. File Upload Security +```bash +grep -rn "UploadFile\|file.*upload\|multipart" backend/app/ --include="*.py" +``` +For each upload endpoint verify: +- Content-type validation (whitelist, not blacklist) +- File size limits enforced +- Files stored outside web root +- Filenames are sanitized (no path traversal) + +### 9. Rate Limiting & Abuse Prevention +```bash +grep -rn "rate_limit\|throttle\|RateLimiter" backend/app/ --include="*.py" +``` +Verify rate limiting on: +- Login / OTP endpoints +- Password reset +- API endpoints (per-tenant) +- WhatsApp message sending + +### 10. Security Report +Generate a report with severity levels: +- **CRITICAL** — Must fix immediately (secrets, SQL injection, auth bypass) +- **HIGH** — Fix before release (missing consent checks, no tenant isolation) +- **MEDIUM** — Fix soon (missing rate limits, weak validation) +- **LOW** — Track for improvement (missing CSP headers, verbose errors) + +Include specific file paths and line numbers for each finding. diff --git a/salesflow-saas/.claude/hooks/pre-commit.sh b/salesflow-saas/.claude/hooks/pre-commit.sh new file mode 100755 index 00000000..e5d800cd --- /dev/null +++ b/salesflow-saas/.claude/hooks/pre-commit.sh @@ -0,0 +1,23 @@ +#!/bin/bash +# Dealix Pre-Commit Hook +set -e +echo "Dealix Pre-Commit Checks..." + +# Check for hardcoded secrets +if grep -rn "API_KEY\s*=\s*['\"][^'\"]*['\"]" backend/app/ --include="*.py" 2>/dev/null | grep -v config.py | grep -v example; then + echo "ERROR: Hardcoded API key found!" + exit 1 +fi + +# Check .env not staged +if git diff --cached --name-only | grep -q "\.env$"; then + echo "ERROR: .env file staged!" + exit 1 +fi + +# Run linter +if command -v ruff &> /dev/null; then + ruff check backend/app/ --fix --quiet 2>/dev/null || true +fi + +echo "Pre-commit checks passed." diff --git a/salesflow-saas/.claude/hooks/pre-push.sh b/salesflow-saas/.claude/hooks/pre-push.sh new file mode 100755 index 00000000..a13acb7a --- /dev/null +++ b/salesflow-saas/.claude/hooks/pre-push.sh @@ -0,0 +1,13 @@ +#!/bin/bash +# Dealix Pre-Push Hook +set -e +echo "Dealix Pre-Push Checks..." + +# Run tests +cd backend && python -m pytest -x -q --tb=short 2>/dev/null || { + echo "ERROR: Tests failed!" + exit 1 +} +cd .. + +echo "Pre-push checks passed." diff --git a/salesflow-saas/.claude/settings.json b/salesflow-saas/.claude/settings.json new file mode 100644 index 00000000..e22a028c --- /dev/null +++ b/salesflow-saas/.claude/settings.json @@ -0,0 +1,23 @@ +{ + "permissions": { + "allow": [ + "Read", + "Glob", + "Grep", + "Bash(git status)", + "Bash(git diff)", + "Bash(pytest)", + "Bash(npm test)" + ], + "deny": [ + "Bash(rm -rf)", + "Bash(git push --force)", + "Bash(DROP TABLE)" + ] + }, + "preferences": { + "language": "ar", + "timezone": "Asia/Riyadh", + "autocommit": false + } +} diff --git a/salesflow-saas/backend/app/services/feature_flags.py b/salesflow-saas/backend/app/services/feature_flags.py new file mode 100644 index 00000000..afb9cf28 --- /dev/null +++ b/salesflow-saas/backend/app/services/feature_flags.py @@ -0,0 +1,159 @@ +""" +Feature Flags — Dealix AI Revenue OS +Simple Redis-backed feature flag system with per-tenant control. +""" +import logging +from typing import Optional + +logger = logging.getLogger(__name__) + +# Default flags and their initial state +DEFAULT_FLAGS = { + "ai_sales_agent": False, # Autonomous WhatsApp sales agent + "sequences": True, # Multi-channel sequences + "cpq": True, # Configure, Price, Quote + "signal_intelligence": False, # Real-time signal engine + "autopilot": False, # Autopilot automation + "behavior_intelligence": False,# Pattern detection + "arabic_nlp": True, # Arabic NLP processing + "lead_scoring_ai": True, # AI-powered lead scoring + "conversation_intel": False, # Conversation analysis + "territory_management": True, # Saudi territory routing + "whatsapp_chatbot": False, # Auto-reply chatbot + "pdpl_strict_mode": True, # Strict PDPL enforcement + "forecasting": False, # Sales forecasting + "alert_delivery": True, # Multi-channel alerts + "skill_registry": False, # Domain skill system +} + + +class FeatureFlagService: + """ + Feature flag service using Redis for fast lookups. + Supports global flags and per-tenant overrides. + """ + + def __init__(self, redis_client=None): + self._redis = redis_client + self._local_cache: dict[str, bool] = dict(DEFAULT_FLAGS) + self._tenant_cache: dict[str, dict[str, bool]] = {} + + def _global_key(self, flag: str) -> str: + return f"ff:global:{flag}" + + def _tenant_key(self, flag: str, tenant_id: str) -> str: + return f"ff:tenant:{tenant_id}:{flag}" + + async def is_enabled( + self, flag: str, tenant_id: Optional[str] = None + ) -> bool: + """Check if a feature flag is enabled.""" + # Check tenant-specific override first + if tenant_id and self._redis: + try: + val = await self._redis.get(self._tenant_key(flag, tenant_id)) + if val is not None: + return val == "1" + except Exception as e: + logger.warning(f"Redis error checking flag {flag}: {e}") + + # Check global flag in Redis + if self._redis: + try: + val = await self._redis.get(self._global_key(flag)) + if val is not None: + return val == "1" + except Exception as e: + logger.warning(f"Redis error checking flag {flag}: {e}") + + # Fallback to local cache / defaults + return self._local_cache.get(flag, False) + + async def enable( + self, flag: str, tenant_id: Optional[str] = None + ) -> bool: + """Enable a feature flag globally or for a specific tenant.""" + key = ( + self._tenant_key(flag, tenant_id) + if tenant_id + else self._global_key(flag) + ) + if self._redis: + try: + await self._redis.set(key, "1") + except Exception as e: + logger.error(f"Redis error enabling flag {flag}: {e}") + return False + + if not tenant_id: + self._local_cache[flag] = True + logger.info( + f"Feature flag '{flag}' enabled" + + (f" for tenant {tenant_id}" if tenant_id else " globally") + ) + return True + + async def disable( + self, flag: str, tenant_id: Optional[str] = None + ) -> bool: + """Disable a feature flag globally or for a specific tenant.""" + key = ( + self._tenant_key(flag, tenant_id) + if tenant_id + else self._global_key(flag) + ) + if self._redis: + try: + await self._redis.set(key, "0") + except Exception as e: + logger.error(f"Redis error disabling flag {flag}: {e}") + return False + + if not tenant_id: + self._local_cache[flag] = False + logger.info( + f"Feature flag '{flag}' disabled" + + (f" for tenant {tenant_id}" if tenant_id else " globally") + ) + return True + + async def list_flags( + self, tenant_id: Optional[str] = None + ) -> dict[str, bool]: + """List all flags with their current state.""" + result = {} + for flag in DEFAULT_FLAGS: + result[flag] = await self.is_enabled(flag, tenant_id) + return result + + async def enable_beta(self, tenant_id: str) -> dict[str, bool]: + """Enable all beta features for a tenant (beta tester program).""" + beta_flags = [ + "ai_sales_agent", "signal_intelligence", "autopilot", + "behavior_intelligence", "conversation_intel", + "forecasting", "skill_registry", "whatsapp_chatbot", + ] + enabled = {} + for flag in beta_flags: + await self.enable(flag, tenant_id) + enabled[flag] = True + logger.info(f"Beta features enabled for tenant {tenant_id}") + return enabled + + async def init_defaults(self) -> None: + """Initialize default flag values in Redis.""" + if not self._redis: + return + for flag, default_val in DEFAULT_FLAGS.items(): + key = self._global_key(flag) + try: + exists = await self._redis.exists(key) + if not exists: + await self._redis.set(key, "1" if default_val else "0") + except Exception as e: + logger.warning(f"Could not init flag {flag}: {e}") + logger.info(f"Initialized {len(DEFAULT_FLAGS)} feature flags") + + +# Global singleton (initialize with Redis client at app startup) +feature_flags = FeatureFlagService() diff --git a/salesflow-saas/memory/customers/icp-brief.md b/salesflow-saas/memory/customers/icp-brief.md new file mode 100644 index 00000000..4ae77dce --- /dev/null +++ b/salesflow-saas/memory/customers/icp-brief.md @@ -0,0 +1,66 @@ +# Ideal Customer Profile — Dealix + +**Date**: 2026-04-11 | **Status**: active + +## Primary ICP: وكالات عقارية في الرياض + +| البعد | التفاصيل | +|-------|----------| +| **الحجم** | 5-50 موظف | +| **الإيراد السنوي** | 1M - 50M ر.س | +| **الصناعة** | عقارات سكنية وتجارية | +| **الموقع** | الرياض (أولاً)، جدة، الشرقية | +| **التقنية الحالية** | Excel + WhatsApp يدوي + دفاتر | +| **صانع القرار** | المدير العام أو مدير المبيعات | +| **الميزانية** | 500-5,000 ر.س/شهر للأدوات | + +## نقاط الألم (بلغة العميل) + +1. "ضايعين عملاء كثير لأن ما نتابعهم بالوقت" +2. "الموظفين كل واحد يسجل العملاء بطريقته" +3. "ما نعرف كم عميل عندنا بالضبط ولا وين وصلنا معهم" +4. "الواتساب فوضى — رسائل ضايعة وما ندري مين رد ومين لا" +5. "نحتاج نتابع العملاء المحتملين بدون ما ننسى أحد" +6. "نبي نعرف أي موظف يبيع أكثر وليش" + +## محفزات الشراء (Buying Triggers) + +- فقدان صفقة كبيرة بسبب عدم المتابعة +- توظيف موظفين جدد ويحتاجون نظام +- منافس بدأ يستخدم CRM +- موسم بيع قوي (رمضان، الصيف) +- طلب من المالك لتقارير أداء + +## الاعتراضات وكيف نرد + +| الاعتراض | الرد | +|----------|------| +| "غالي" | "59 ر.س/شهر = أقل من فاتورة كابتشينو أسبوعية. صفقة وحدة ضايعة تكلف أكثر" | +| "ما عندنا وقت نتعلم" | "النظام عربي بالكامل ويشتغل من الواتساب — نفس طريقتك الحالية بس منظمة" | +| "جربنا CRM قبل وما نفع" | "الأنظمة الأجنبية مو مصممة للسوق السعودي. Dealix مبني عربي من الأساس" | +| "البيانات بتكون آمنة؟" | "متوافقين مع نظام حماية البيانات الشخصية PDPL ومواقع سعودية" | +| "نحتاج نشوف نتائج أول" | "جربه مجاني 14 يوم مع بياناتك الحقيقية" | + +## مقاييس نجاح العميل + +- تقليل فقدان العملاء المحتملين بـ 50% +- زيادة سرعة الرد على الاستفسارات من ساعات لدقائق +- تقارير أداء يومية بدون جهد يدوي +- كل العملاء في مكان واحد بدل 5 أماكن + +## Secondary ICP: عيادات ومراكز طبية + +| البعد | التفاصيل | +|-------|----------| +| **الحجم** | 3-30 موظف | +| **الصناعة** | عيادات أسنان، تجميل، عيون | +| **الألم الرئيسي** | حجوزات ضايعة + متابعة مرضى يدوية | +| **القيمة** | المريض الواحد يساوي 2,000-20,000 ر.س | + +## Tertiary ICP: شركات مقاولات وخدمات + +| البعد | التفاصيل | +|-------|----------| +| **الحجم** | 10-100 موظف | +| **الألم** | عروض أسعار بطيئة + متابعة مشاريع فوضوية | +| **القيمة** | المشروع الواحد 50K-5M ر.س | diff --git a/salesflow-saas/memory/customers/interview-template.md b/salesflow-saas/memory/customers/interview-template.md new file mode 100644 index 00000000..36619125 --- /dev/null +++ b/salesflow-saas/memory/customers/interview-template.md @@ -0,0 +1,48 @@ +# Customer Interview Template — Dealix + +## قبل المقابلة +- سجل اسم الشركة والشخص والصناعة +- حضّر ملاحظات عن شركتهم (موقع، حجم، نشاط) +- المقابلة 20-30 دقيقة + +## الأسئلة (عربي) + +### فهم المشكلة +1. كيف تتابعون عملاءكم المحتملين حالياً؟ (Excel، دفتر، ذاكرة؟) +2. كم عميل محتمل تقريباً عندكم الحين؟ كم منهم تقدرون تتابعونه فعلاً؟ +3. وش أكبر مشكلة تواجهكم بمتابعة العملاء؟ +4. كم مرة تقريباً فقدتوا عميل بسبب تأخر الرد أو نسيان المتابعة؟ +5. لو تقدر تغير شي واحد بطريقة إدارة عملاءك، وش يكون؟ + +### فهم القرار +6. جربتوا أي نظام CRM قبل؟ إذا نعم، وش صار؟ +7. وش أهم شي تدور عليه بأي أداة جديدة؟ +8. مين يقرر شراء الأدوات بشركتكم؟ +9. كم تقريباً تصرفون على أدوات مبيعات/تواصل حالياً؟ +10. وش يخليك تقول "هذا النظام يستاهل أدفع له"؟ + +### فهم الواتساب +11. كم نسبة تواصلكم مع العملاء عبر الواتساب؟ +12. كم رسالة واتساب تقريباً ترسلون يومياً للعملاء؟ +13. وش أكبر مشكلة بالواتساب حالياً؟ (رسائل ضايعة؟ ما تعرف مين رد؟) + +### فهم النتائج +14. لو النظام وفر لك ساعتين يومياً — وش بتسوي بهالوقت؟ +15. وش الرقم اللي لو تحسن بتحس إن المنتج نجح؟ (عدد صفقات؟ سرعة رد؟) + +## بعد المقابلة + +### سجل الاعتراضات +| الاعتراض | التكرار | حلنا | +|----------|---------|------| +| | | | + +### سجل طلبات الميزات +| الميزة | من طلبها | الأولوية | حالتها | +|--------|----------|----------|--------| +| | | | | + +### سجل أسباب عدم الشراء +| السبب | التكرار | وش نقدر نسوي | +|-------|---------|---------------| +| | | | diff --git a/salesflow-saas/memory/growth/content-map.md b/salesflow-saas/memory/growth/content-map.md new file mode 100644 index 00000000..064378a6 --- /dev/null +++ b/salesflow-saas/memory/growth/content-map.md @@ -0,0 +1,78 @@ +# Content Strategy Map — Dealix + +**Date**: 2026-04-11 | **Status**: active + +## Content Pillars + +### 1. تعليمي (Educational) — 40% +محتوى يعلم العملاء المحتملين كيف يحسنون مبيعاتهم + +### 2. قصص نجاح (Case Studies) — 25% +نتائج حقيقية من عملاء سعوديين + +### 3. منتج (Product) — 20% +عروض وشروحات لميزات Dealix + +### 4. قيادة فكر (Thought Leadership) — 15% +رؤى عن مستقبل المبيعات والتقنية بالسعودية + +## أفكار محتوى (20 فكرة) + +### تعليمي +1. "٧ أسباب تضيّع عليك عملاء بالواتساب — وكيف تحلها" +2. "كيف تبني pipeline مبيعات يرفع إغلاقاتك ٣٠٪" +3. "دليلك الكامل لمتابعة العملاء بدون ما تكون مزعج" +4. "٥ أخطاء يسوونها مندوبين المبيعات بالعقارات" +5. "كيف تحسب conversion rate وليش مهم" +6. "أفضل أوقات التواصل مع العملاء بالسعودية" +7. "كيف تكتب رسالة واتساب تخلي العميل يرد" +8. "نظام حماية البيانات الشخصية PDPL — وش يعني لشركتك" + +### قصص نجاح +9. "كيف وكالة عقارية برياض رفعت مبيعاتها ٤٠٪ بـ ٣ أشهر" +10. "عيادة أسنان وفرت ٢٠ ساعة أسبوعياً بأتمتة المتابعة" +11. "من Excel لـ CRM: قصة تحول شركة مقاولات" +12. "كيف حققنا ٩٥٪ معدل رد بالواتساب" + +### منتج +13. "جولة سريعة: كيف تبدأ مع Dealix بـ ٥ دقائق" +14. "ميزة جديدة: الوكيل الذكي يرد على عملاءك بالواتساب" +15. "كيف تبني تسلسل متابعة تلقائي (بالخطوات)" +16. "عروض الأسعار الذكية: من الطلب للقبول بكبسة" + +### قيادة فكر +17. "مستقبل CRM بالسعودية: ليش العربي أولاً؟" +18. "رؤية ٢٠٣٠ وتحول المبيعات الرقمي" +19. "الذكاء الاصطناعي بالمبيعات: واقع ولا خيال؟" +20. "ليش الشركات السعودية تحتاج CRM سعودي" + +## المنصات + +| المنصة | التكرار | نوع المحتوى | +|--------|---------|-------------| +| **LinkedIn** | 3x/أسبوع | مقالات + نصائح + قصص | +| **Twitter/X** | يومي | نصائح قصيرة + ثريدات | +| **YouTube** | 1x/أسبوع | شروحات + demos | +| **Blog** | 2x/أسبوع | SEO مقالات طويلة | +| **WhatsApp Status** | يومي | نصائح سريعة | + +## كلمات SEO + +### عربي +- CRM سعودي، نظام إدارة علاقات العملاء، متابعة عملاء واتساب +- برنامج مبيعات عقارات، إدارة عملاء عيادات، نظام عروض أسعار +- أتمتة مبيعات، تقييم عملاء محتملين، حماية بيانات PDPL + +### إنجليزي +- Saudi CRM, Arabic CRM, WhatsApp CRM Saudi Arabia +- real estate CRM Riyadh, sales automation KSA, PDPL compliant CRM + +## الجدول الأسبوعي + +| اليوم | المنصة | نوع المحتوى | +|-------|--------|-------------| +| الأحد | LinkedIn + Blog | مقالة تعليمية | +| الاثنين | Twitter/X | ثريد نصائح | +| الثلاثاء | LinkedIn | قصة نجاح أو insight | +| الأربعاء | YouTube | فيديو شرح | +| الخميس | Blog + Twitter | مقالة SEO + ملخص | diff --git a/salesflow-saas/memory/growth/launch-plan.md b/salesflow-saas/memory/growth/launch-plan.md new file mode 100644 index 00000000..03e8983d --- /dev/null +++ b/salesflow-saas/memory/growth/launch-plan.md @@ -0,0 +1,75 @@ +# Launch Plan — Dealix + +**Date**: 2026-04-11 | **Status**: active + +## Sprint 14 يوم (ما قبل الإطلاق) + +### يوم 1-3: تجهيز المنتج +- [ ] اختبار كامل للتسجيل → لوحة التحكم → إضافة عميل → إرسال رسالة +- [ ] اختبار الواتساب: إرسال + استقبال + قوالب +- [ ] اختبار على الموبايل (iPhone + Android) +- [ ] مراجعة النصوص العربية والأخطاء الإملائية +- [ ] تجهيز 3 قوالب صناعية (عقارات، عيادات، مقاولات) +- [ ] تجهيز صفحة التسعير والدفع (Stripe) + +### يوم 4-7: مستخدمين بيتا (5 وكالات عقارية) +- [ ] التواصل مع 10 وكالات → تأمين 5 للتجربة +- [ ] إعداد حساباتهم يدوياً مع بياناتهم +- [ ] مكالمة onboarding 30 دقيقة مع كل واحد +- [ ] متابعة يومية: وش يشتغل؟ وش ما يشتغل؟ +- [ ] تسجيل كل feedback بملف مخصص + +### يوم 8-10: التعديلات +- [ ] إصلاح أهم 5 مشاكل من البيتا +- [ ] تحسين الـ onboarding بناءً على الملاحظات +- [ ] إضافة أي حقول طلبها العملاء +- [ ] تحسين سرعة الواجهة +- [ ] تجهيز فيديو شرح قصير (3 دقائق) + +### يوم 11-14: الإطلاق الناعم +- [ ] نشر على LinkedIn (قصة بناء المنتج) +- [ ] نشر على Twitter/X +- [ ] بدء تسلسل Outreach لأول 100 وكالة +- [ ] تفعيل Google Analytics + Sentry +- [ ] تأكد من SSL + CDN + backups + +## 30 يوم بعد الإطلاق + +### الأسبوع 3: النمو +- [ ] تواصل مع 200 وكالة عقارية (WhatsApp + Email) +- [ ] نشر أول قصة نجاح من عميل بيتا +- [ ] بدء محتوى تعليمي (مقالة + فيديو أسبوعياً) +- [ ] تحليل معدل التحويل وتحسينه + +### الأسبوع 4: التثبيت +- [ ] مراجعة churn: ليش أحد ترك؟ وش نقدر نسوي؟ +- [ ] تحسين الميزات الأكثر استخداماً +- [ ] تجهيز برنامج إحالة (referral) +- [ ] بدء LinkedIn Ads (ميزانية 2,000 ر.س) + +## أهداف الإيراد + +| الفترة | عملاء مدفوعين | إيراد شهري (MRR) | +|--------|---------------|------------------| +| شهر 1 | 5 | 745 ر.س | +| شهر 3 | 25 | 3,725 ر.س | +| شهر 6 | 100 | 14,900 ر.س | +| شهر 12 | 300 | 44,700 ر.س | + +*متوسط سعر: 149 ر.س/مستخدم (باقة Professional)* + +## التسعير + +| الباقة | السعر | المميزات | +|--------|-------|----------| +| **Starter** | 59 ر.س/شهر | 3 مستخدمين، 500 عميل، WhatsApp أساسي | +| **Professional** | 149 ر.س/شهر | 10 مستخدمين، عملاء لا محدود، AI scoring، sequences | +| **Enterprise** | 225 ر.س/شهر | لا محدود، AI agent، CPQ، API access | +| **تجربة مجانية** | 0 ر.س | 14 يوم كامل بدون بطاقة | + +## استراتيجية أول 100 عميل + +1. **عملاء 1-5**: بيتا مجاني → case studies +2. **عملاء 6-20**: outreach مباشر + إحالات من البيتا +3. **عملاء 21-50**: content marketing + LinkedIn ads +4. **عملاء 51-100**: referral program + شراكات مع منصات عقارية diff --git a/salesflow-saas/memory/growth/niche-brief.md b/salesflow-saas/memory/growth/niche-brief.md new file mode 100644 index 00000000..79e5af42 --- /dev/null +++ b/salesflow-saas/memory/growth/niche-brief.md @@ -0,0 +1,199 @@ +# Dealix Niche Strategy Brief + +> Last updated: 2026-04-11 +> Owner: Founder +> Status: Active + +--- + +## Executive Summary + +Dealix enters the Saudi CRM market ($652M in 2024, projected $1.46B by 2033) through a deliberate niche-down strategy. Rather than competing head-on with Salesforce ($500M Saudi investment), Zoho (Arabic UI + Saudi servers), or HubSpot, we dominate a single vertical first, prove the model, then expand. + +--- + +## Primary Niche: Saudi Real Estate Agencies in Riyadh + +### Why Real Estate First + +| Factor | Data Point | Why It Matters | +|--------|-----------|----------------| +| Deal values | 500K - 5M SAR per transaction | High willingness to pay for tools that close even 1 extra deal/month | +| WhatsApp dependency | 90%+ of Saudi RE leads come through WhatsApp | Our WhatsApp-first architecture is an unfair advantage | +| Market fragmentation | 3,000+ licensed RE agencies in Riyadh alone (REGA data) | No single player dominates; agencies are underserved | +| CRM adoption | <15% of Saudi SMB RE agencies use any CRM | Greenfield opportunity; we're not displacing, we're introducing | +| Arabic gap | Zoho has Arabic UI but RE workflows are generic; Salesforce requires expensive customization | No CRM speaks Saudi RE language natively | +| Vision 2030 tailwind | NEOM, The Line, Roshn, Jeddah Tower -- RE transaction volume surging | Structural demand growth for years | +| Regulatory push | REGA (Real Estate General Authority) mandating digital compliance | Agencies need digital tools or face penalties | + +### Riyadh Specifically + +- Largest RE market in KSA (45%+ of national transaction volume) +- Highest concentration of SMB agencies (density = easier sales) +- Most Vision 2030 mega-projects feed into Riyadh secondary market +- Founder network is strongest here (warm intros possible) + +### Target Sub-Segments Within RE + +1. **Residential sales agencies** (5-30 agents) -- PRIMARY + - Sell apartments, villas, land plots + - Deal cycle: 2-8 weeks + - Pain: leads leak from WhatsApp, no follow-up system +2. **Commercial leasing agencies** (5-20 agents) -- SECONDARY + - Office spaces, retail, warehouses + - Deal cycle: 1-3 months + - Pain: complex multi-party negotiations tracked in spreadsheets +3. **Off-plan sales teams** (working with developers) -- TERTIARY + - Represent Roshn, Dar Al Arkan, etc. + - High volume, need lead scoring badly + +### Market Size (Primary Niche Only) + +- ~3,000 licensed RE agencies in Riyadh +- Target segment (5-50 employees): ~1,800 agencies +- Serviceable addressable market at Pro plan (149 SAR/user/mo): + - Average 8 users/agency x 149 SAR x 12 months = 14,304 SAR/year/agency + - 1,800 agencies x 14,304 = **25.7M SAR/year** (just Riyadh RE) +- Enough runway to build a 10M+ SAR ARR business before expanding + +--- + +## Secondary Niche: Saudi Healthcare Clinics + +### Why Healthcare Second + +| Factor | Data Point | +|--------|-----------| +| Patient volume | Average clinic handles 50-200 patients/day | +| WhatsApp booking | 60%+ of clinic bookings happen via WhatsApp in Saudi | +| Follow-up failure | Clinics lose 30-40% of patients due to no follow-up system | +| Regulatory | NPHIES (National Platform for Health Informatics) pushing digital | +| Spending power | Healthcare SMBs (polyclinics) revenue 2M-30M SAR/year | +| Overlap | CRM workflows (lead nurture, follow-up, pipeline) map directly to patient journey | + +### Target Sub-Segments + +1. Polyclinics (multi-specialty, 10-50 staff) +2. Dental clinics (high-value elective procedures) +3. Dermatology / aesthetics clinics (cash-pay, marketing-heavy) + +### When to Enter + +- Month 4-6 after launch (once RE playbook is proven) +- Requires minor product adaptation: appointment booking, patient tags, HIPAA-equivalent PDPL flows + +--- + +## Tertiary Niche: Saudi Contracting Companies + +### Why Contracting Third + +| Factor | Data Point | +|--------|-----------| +| Vision 2030 boom | 1.1 trillion SAR in construction projects announced | +| Deal complexity | Multi-stage quotes (our CPQ module is perfect) | +| Long sales cycles | 1-6 months; need pipeline visibility | +| WhatsApp deals | Contractors negotiate via WhatsApp voice notes and messages | +| No tools | Most use Excel + WhatsApp groups to manage projects pipeline | + +### Target Sub-Segments + +1. MEP contractors (mechanical, electrical, plumbing) -- 5-50 employees +2. Interior fit-out companies +3. Small general contractors (government tender participants) + +### When to Enter + +- Month 6-9 after launch +- Requires: CPQ templates for contracting, BOQ integration, tender tracking + +--- + +## What We Say NO To (Until Series A) + +### Hard No + +| Request | Why We Reject | +|---------|--------------| +| Enterprise deals (500+ employees) | Long sales cycles, heavy customization, support burden kills us | +| Government contracts | 6-18 month procurement, payment delays, compliance overhead | +| Non-Saudi markets (UAE, Egypt, etc.) | Splits focus; Saudi alone is a $1.46B opportunity | +| Industry-agnostic positioning | "CRM for everyone" = CRM for no one at our stage | +| Free tier | Attracts tire-kickers; our ICP (RE agencies) can pay 149 SAR/mo | +| Custom development / consulting | We're a product company, not a services company | +| Integration with legacy Saudi systems (custom ERPs) | Rabbit hole; focus on WhatsApp + standard tools first | + +### Soft No (Revisit After 100 Customers) + +| Request | When to Revisit | +|---------|----------------| +| Automotive dealerships | After RE playbook proven (similar sales model) | +| Education / training companies | Month 9+ | +| Travel agencies | Month 9+ | +| Insurance brokers | Month 12+ | +| E-commerce (Salla/Zid merchants) | Requires different product; maybe never | + +--- + +## Adjacent Niches: Expansion Roadmap + +### Phase 1: Riyadh Real Estate (Month 1-6) +- Goal: 100 paying agencies +- Revenue target: ~120K SAR MRR + +### Phase 2: Riyadh Healthcare + Jeddah Real Estate (Month 6-12) +- Goal: 250 total customers +- Revenue target: ~350K SAR MRR +- Geographic expansion within proven verticals + +### Phase 3: Contracting + Dammam/Eastern Province (Month 12-18) +- Goal: 500 total customers +- Revenue target: ~700K SAR MRR + +### Phase 4: Multi-Vertical Saudi (Month 18-24) +- Open up to automotive, education, insurance +- Goal: 1,000 customers +- Revenue target: 1.4M SAR MRR + +### Phase 5: GCC Expansion (Month 24+) +- UAE first (Dubai RE market is natural fit) +- Then Bahrain, Kuwait +- Requires: multi-currency, local compliance, dialect tuning + +--- + +## Competitive Positioning by Niche + +### In Real Estate Specifically + +| Competitor | Weakness in Saudi RE | Our Advantage | +|-----------|---------------------|---------------| +| Zoho CRM | Generic; no RE workflows, no WhatsApp-native, Arabic UI exists but is translated (unnatural) | Built for Saudi RE from day 1; WhatsApp is core, not add-on | +| Salesforce | Overkill for 10-person agency; 5,000+ SAR/user/year; Arabic is afterthought | 10x cheaper; Arabic-first; deploys in 1 day not 3 months | +| HubSpot | No Arabic; no Saudi servers; no WhatsApp integration; pricing in USD | Full Arabic; PDPL compliant; WhatsApp-native; SAR pricing | +| Hollat | Early stage ($3M seed); horizontal play; limited features | Vertical focus = deeper features for RE; CPQ for quotes | +| Aqar CRM (property portals) | Listing-focused, not relationship-focused; no AI | We manage the relationship, they manage the listing | +| Excel + WhatsApp | No pipeline visibility, leads leak, no automation | Everything they do manually, automated | + +--- + +## Key Metrics to Validate Niche + +Before expanding to the next niche, we must hit: + +- [ ] 50+ paying RE customers in Riyadh +- [ ] Net Revenue Retention > 100% +- [ ] CAC payback < 3 months +- [ ] NPS > 40 +- [ ] At least 3 case studies with measurable ROI +- [ ] Organic inbound > 30% of new leads + +--- + +## Decision Log + +| Date | Decision | Rationale | +|------|----------|-----------| +| 2026-04-11 | Primary niche = Riyadh RE agencies | Highest deal values, WhatsApp dependency, no Arabic CRM fits, founder network | +| 2026-04-11 | Say NO to free tier | ICP can afford 149 SAR/mo; free tier attracts wrong users | +| 2026-04-11 | Say NO to non-Saudi markets | Focus wins; $1.46B Saudi TAM is enough | diff --git a/salesflow-saas/memory/growth/outreach-map.md b/salesflow-saas/memory/growth/outreach-map.md new file mode 100644 index 00000000..6f94e10e --- /dev/null +++ b/salesflow-saas/memory/growth/outreach-map.md @@ -0,0 +1,84 @@ +# Cold Outreach System — Dealix + +**Date**: 2026-04-11 | **Status**: active + +## مصادر العملاء المحتملين + +1. **Google Maps**: بحث "وكالة عقارية الرياض" → استخراج اسم + هاتف + موقع +2. **LinkedIn**: مدراء مبيعات + ملاك وكالات عقارية بالرياض +3. **عقار.كم (Aqar.fm)**: أكبر منصة عقارية سعودية — المكاتب المعلنة +4. **غرفة الرياض التجارية**: سجلات الشركات العقارية +5. **Instagram**: وكالات عقارية نشطة بالإعلانات + +## تسلسلات WhatsApp (3 نسخ) + +### تسلسل A: مباشر +**يوم 1:** +``` +السلام عليكم 👋 +أنا [الاسم] من Dealix — نظام CRM مصمم خصيصاً للعقاريين بالسعودية. + +لاحظت إنكم نشطين بسوق [المنطقة] — عندنا أداة تخلي متابعة العملاء بالواتساب أسرع ٣ مرات. + +تحب أعطيك جولة سريعة ٥ دقائق؟ +``` + +**يوم 3 (إذا ما رد):** +``` +مرحباً مرة ثانية 🙏 +أعرف إنكم مشغولين — بس حبيت أشاركك إن وكالة مثلكم بالرياض رفعت إغلاقاتها ٤٠٪ بعد ما نظمت متابعة العملاء. + +أقدر أوريك كيف بـ ٥ دقائق. وش رأيك؟ +``` + +**يوم 7:** +``` +آخر رسالة مني 😊 +حبيت أترك لك رابط تجربة مجانية ١٤ يوم — بدون بطاقة: +[رابط] + +إذا احتجت شي أنا موجود. يعطيك العافية! +``` + +### تسلسل B: قيمة أولاً +**يوم 1:** إرسال PDF "٧ طرق لزيادة مبيعات العقار بالواتساب" +**يوم 3:** "وش رأيك بالدليل؟ عندنا أداة تطبق هالنقاط تلقائياً" +**يوم 7:** عرض تجربة مجانية + +### تسلسل C: إحالة +**يوم 1:** "صديقك [اسم] رشحنا لكم — يستخدم نظامنا ويقول إنه غير طريقة عمله" + +## تسلسل Email + +### Email 1: المشكلة +**Subject:** وكالتك تفقد كم عميل بالأسبوع؟ + +``` +الأخ/الأخت [الاسم], + +٧٠٪ من الوكالات العقارية بالرياض تفقد عملاء محتملين لأن المتابعة يدوية وبطيئة. + +Dealix يحل هالمشكلة — نظام CRM عربي بالكامل يشتغل من الواتساب: +✅ كل العملاء بمكان واحد +✅ متابعة تلقائية بالواتساب +✅ تقارير أداء يومية + +جربه مجاني ١٤ يوم: [رابط] + +تحياتي, +[الاسم] — فريق Dealix +``` + +### Email 2 (يوم 4): النتيجة +**Subject:** وكالة بالرياض رفعت مبيعاتها ٤٠٪ + +## المقاييس المستهدفة + +| المقياس | الهدف الشهري | +|---------|-------------| +| رسائل مرسلة | 500 | +| معدل الرد | >15% | +| مواعيد محجوزة | 25 | +| تجارب مجانية | 15 | +| عملاء مدفوعين | 5 | +| تكلفة اكتساب العميل | <200 ر.س | diff --git a/salesflow-saas/memory/runbooks/deployment-checklist.md b/salesflow-saas/memory/runbooks/deployment-checklist.md new file mode 100644 index 00000000..c7ecfb85 --- /dev/null +++ b/salesflow-saas/memory/runbooks/deployment-checklist.md @@ -0,0 +1,30 @@ +# Deployment Checklist — Dealix + +## Pre-Deploy +- [ ] All tests pass: `pytest -v` +- [ ] No pending migrations: `alembic heads` +- [ ] Environment variables set in production +- [ ] Docker images built: `docker-compose build` +- [ ] Database backed up: `pg_dump dealix > backup.sql` + +## Deploy +```bash +git pull origin main +docker-compose down && docker-compose build --no-cache && docker-compose up -d +docker-compose exec backend alembic upgrade head +curl -f https://api.dealix.sa/api/v1/health +``` + +## Post-Deploy +- [ ] Check Sentry for errors (15 min) +- [ ] Test login + Arabic UI +- [ ] Test WhatsApp send/receive +- [ ] Verify Celery workers active + +## Rollback +```bash +docker-compose down +git checkout HEAD~1 +docker-compose build && docker-compose up -d +docker-compose exec backend alembic downgrade -1 +``` diff --git a/salesflow-saas/memory/runbooks/launch-checklist.md b/salesflow-saas/memory/runbooks/launch-checklist.md new file mode 100644 index 00000000..2aaa3f83 --- /dev/null +++ b/salesflow-saas/memory/runbooks/launch-checklist.md @@ -0,0 +1,256 @@ +# Launch Day Checklist — Dealix + +**Last Updated**: 2026-04-11 +**Target**: Public SaaS launch in Saudi Arabia + +--- + +## T-7 Days: Pre-Launch Preparation + +### Technical Readiness +- [ ] All services healthy on production environment +- [ ] SSL certificates valid (check: `openssl s_client -connect api.dealix.sa:443`) +- [ ] CDN configured for static assets (frontend build, images, fonts) +- [ ] Database backups running hourly with verified restore procedure +- [ ] Redis persistence enabled and tested +- [ ] Celery workers scaled for expected load (minimum 2 workers) +- [ ] Rate limiting active on all public endpoints +- [ ] DDoS protection enabled (Cloudflare or equivalent) +- [ ] DNS TTL lowered to 60s (for quick failover if needed) +- [ ] WebSocket connection verified for real-time features +- [ ] Celery Beat scheduler running all periodic tasks +- [ ] CORS configured for production domain only + +### Load Testing +- [ ] API endpoints tested at 2x expected concurrent users +- [ ] WhatsApp message throughput tested (UltraMSG rate limits verified) +- [ ] Database connection pool handles peak load +- [ ] Frontend loads within 3 seconds on Saudi mobile networks (STC, Mobily, Zain) +- [ ] File upload works for expected attachment sizes (up to 10MB) + +### Staging Final Validation +- [ ] Full user journey tested on staging: signup -> onboard -> create lead -> qualify -> deal -> close +- [ ] All AI features tested with Arabic input +- [ ] WhatsApp integration sends and receives messages +- [ ] Payment flow tested with Stripe test cards +- [ ] Email notifications delivered and readable in Arabic + +--- + +## T-3 Days: Content & Legal + +### Product: Arabic UI Review +- [ ] All pages reviewed for correct RTL layout on desktop +- [ ] All pages reviewed for RTL layout on mobile (iPhone Safari, Android Chrome) +- [ ] Arabic typography: font size readable, line height comfortable +- [ ] Arabic UI reviewed by native speaker for natural phrasing +- [ ] Form validation messages display in Arabic +- [ ] Error pages (404, 500) have Arabic content +- [ ] Loading states and empty states have Arabic text +- [ ] Date picker supports Hijri calendar option +- [ ] Currency consistently displayed as SAR throughout + +### Product: Critical Flow Testing +- [ ] **Signup flow**: Email verification, tenant creation, first login +- [ ] **Onboarding**: Register -> first lead -> first message (complete journey) +- [ ] **Lead management**: Create, edit, qualify, convert to deal +- [ ] **Deal pipeline**: Drag-and-drop kanban stages, value tracking, close/loss +- [ ] **WhatsApp**: Send message, receive reply, AI auto-response +- [ ] **AI Sales Agent**: Automated qualification conversation in Arabic +- [ ] **AI Lead Scoring**: Tested with Arabic text input +- [ ] **CPQ**: Quote generation tested with VAT calculation +- [ ] **Reports**: Dashboard KPIs load correctly with real data +- [ ] **Settings**: Team invite, role change, profile update +- [ ] **PDPL consent**: Full consent flow tested end-to-end +- [ ] **Mobile**: All above flows work on mobile browsers +- [ ] **Industry templates**: 3 templates loaded (real estate, healthcare, contracting) + +### Legal: PDPL Compliance +- [ ] Privacy policy published in Arabic at `/privacy` +- [ ] Terms of service published in Arabic at `/terms` +- [ ] Cookie consent banner implemented +- [ ] Consent collection points verified on all data entry forms +- [ ] Data subject rights page accessible at `/data-rights` +- [ ] PDPL consent purposes documented and match implementation +- [ ] Data processing records prepared for SDAIA audit +- [ ] Data breach notification procedure documented +- [ ] DPO (Data Protection Officer) appointed and contact info published +- [ ] Data processing agreement template ready for enterprise tenants + +### Legal: Business Compliance +- [ ] Commercial Registration (CR) number displayed on website +- [ ] ZATCA VAT registration number configured +- [ ] ZATCA e-invoicing compliance verified for billing +- [ ] Payment Terms and Refund Policy published +- [ ] Acceptable Use Policy drafted + +--- + +## T-1 Day: Final Checks + +### Marketing: Landing Page & Channels +- [ ] Landing page live at `dealix.sa` with Arabic-first content +- [ ] English language toggle available +- [ ] Pricing page reflects final plans: + - Starter: SAR 299/month + - Professional: SAR 799/month + - Enterprise: Custom pricing +- [ ] "Start Free Trial" button works end-to-end +- [ ] Social media accounts ready: + - [ ] Twitter/X: `@DealixSA` + - [ ] LinkedIn: Company page created + - [ ] Instagram: Profile and launch teaser posted +- [ ] Launch post drafted in Arabic and English +- [ ] Launch email to waitlist drafted and scheduled +- [ ] WhatsApp Business profile configured +- [ ] Demo video ready (3 min, Arabic) +- [ ] First 5 blog posts published (SEO) + +### Marketing: SEO & Analytics +- [ ] Google Analytics / Plausible installed +- [ ] `robots.txt` allows crawling +- [ ] `sitemap.xml` generated +- [ ] Open Graph meta tags on all public pages +- [ ] Arabic meta descriptions for SEO + +### Support: Readiness +- [ ] Support email configured: `support@dealix.sa` +- [ ] Auto-reply configured in Arabic: "شكرا لتواصلك معنا. سنرد عليك خلال ٤ ساعات عمل" +- [ ] WhatsApp support number active with auto-routing +- [ ] FAQ page published (Arabic) +- [ ] First 48-hour monitoring schedule assigned: + - Hours 0-12: [Primary on-call engineer] + - Hours 12-24: [Secondary on-call engineer] + - Hours 24-48: [Rotating coverage] +- [ ] Escalation contacts for critical issues (payment down, data loss, security) +- [ ] Known issues document prepared (what to tell users if X happens) + +### Payment: Stripe Go-Live +- [ ] Stripe account switched to Live mode (not Test) +- [ ] Live API keys configured in production environment +- [ ] Webhook endpoint registered in Stripe Dashboard (production URL) +- [ ] Webhook secret updated in production env vars +- [ ] Test transaction processed with real card (refund immediately) +- [ ] Pricing configured in Stripe Products: + - [ ] Starter: SAR 299/month + - [ ] Professional: SAR 799/month + - [ ] Enterprise: Custom (contact sales) +- [ ] Invoice templates customized with Dealix branding and ZATCA QR code +- [ ] Tax settings configured for Saudi Arabia (15% VAT) +- [ ] Customer portal URL configured for self-service billing +- [ ] Cancellation flow tested +- [ ] Refund process documented + +--- + +## Launch Day (T-0) + +### Morning: Pre-Launch (08:00 AST) +```bash +# Final health check +curl -f https://api.dealix.sa/api/v1/health +curl -f https://app.dealix.sa/ + +# Check all containers running +docker compose ps + +# Check database connectivity +docker compose exec backend python3 -c "print('DB OK')" + +# Check Redis +docker compose exec redis redis-cli ping + +# Check Celery workers +docker compose exec celery-worker celery -A app.workers inspect ping + +# Clear any stale caches +docker compose exec redis redis-cli FLUSHDB +``` + +- [ ] All health checks pass +- [ ] Team online in communication channel +- [ ] Status page shows "All Systems Operational" +- [ ] Sentry dashboard open and monitored + +### Launch: Go Live (10:00 AST) +- [ ] Remove any "Coming Soon" or maintenance mode flags +- [ ] Enable signup for all visitors (not just waitlist) +- [ ] Publish launch post on social media (Arabic and English) +- [ ] Send launch email to waitlist +- [ ] Monitor signup funnel in real-time + +### Launch: First Hour (10:00-11:00 AST) +- [ ] Monitor Sentry for new errors (should be zero critical) +- [ ] Watch server metrics (CPU < 70%, memory < 80%) +- [ ] Monitor database connections (should be within pool limits) +- [ ] Check first signups complete onboarding successfully +- [ ] Respond to any social media questions/issues immediately + +### Launch: First Day Monitoring +- [ ] Error rate: < 0.1% of requests +- [ ] API latency P95: < 500ms +- [ ] Signup conversion: track funnel (visit -> signup -> onboard -> first action) +- [ ] WhatsApp delivery rate: > 95% +- [ ] Support tickets: categorize and prioritize incoming requests + +--- + +## Post-Launch (T+1 to T+7) + +### Day 1 Review +- [ ] Total signups and conversion rate +- [ ] Critical bugs found and fixed +- [ ] Support ticket volume and average response time +- [ ] Server performance metrics reviewed +- [ ] User feedback collected (what they love, what's confusing) + +### Day 2-3: Stabilization +- [ ] Fix any P0/P1 bugs from launch day +- [ ] Optimize any slow queries identified in monitoring +- [ ] Scale infrastructure if growth exceeds projections +- [ ] Follow up personally with first 10 users for feedback +- [ ] Publish "thank you" social media post + +### Day 4-7: Iteration +- [ ] Analyze onboarding drop-off points +- [ ] Plan quick wins based on user feedback +- [ ] Review billing conversion (free trial -> paid) +- [ ] Update FAQ based on common support questions +- [ ] Write first weekly internal report +- [ ] Plan Sprint 1 post-launch based on data + +--- + +## Emergency Contacts + +| Role | Name | Phone | Escalation | +|------|------|-------|------------| +| CTO / On-Call Lead | TBD | +966-5XX-XXX-XXXX | All critical issues | +| Backend Engineer | TBD | +966-5XX-XXX-XXXX | API, database, workers | +| Frontend Engineer | TBD | +966-5XX-XXX-XXXX | UI, performance | +| DevOps | TBD | +966-5XX-XXX-XXXX | Infrastructure, DNS, SSL | +| Stripe Support | — | — | https://support.stripe.com | +| UltraMSG Support | — | — | WhatsApp integration issues | + +--- + +## Rollback Decision Tree + +``` +Issue detected + | + ├── Affects < 5% of users + | └── Hotfix in place, no rollback + | + ├── Affects payments + | └── Immediate rollback + Stripe webhook pause + | + ├── Affects data integrity + | └── Immediate rollback + DB restore from backup + | + ├── Affects WhatsApp messaging + | └── Disable AI auto-reply, switch to manual mode, fix forward + | + └── Total outage + └── Full rollback per deployment-checklist.md procedure +``` diff --git a/salesflow-saas/memory/runbooks/saas-readiness-audit.md b/salesflow-saas/memory/runbooks/saas-readiness-audit.md new file mode 100644 index 00000000..60d64d6c --- /dev/null +++ b/salesflow-saas/memory/runbooks/saas-readiness-audit.md @@ -0,0 +1,293 @@ +# SaaS Readiness Audit — Dealix + +**Last Updated**: 2026-04-11 +**Overall Status**: 6/11 categories need work before public launch + +--- + +## Readiness Matrix + +| # | Category | Status | Priority | Effort | +|---|----------|--------|----------|--------| +| 1 | Authentication & RBAC | Completed | — | — | +| 2 | Billing & Subscriptions | Partial | P0 | 2 sprints | +| 3 | Tenant Onboarding | Partial | P0 | 1 sprint | +| 4 | Admin Dashboard | Partial | P1 | 1 sprint | +| 5 | Analytics & Reporting | Partial | P1 | 2 sprints | +| 6 | Help Center & Docs | Missing | P1 | 2 sprints | +| 7 | Deployment & Infra | Completed | — | — | +| 8 | Monitoring & Alerting | Partial | P0 | 0.5 sprint | +| 9 | Feature Flags | Missing | P1 | 0.5 sprint | +| 10 | Customer Support Flow | Missing | P0 | 1 sprint | +| 11 | PDPL Compliance | Completed | — | — | + +--- + +## Detailed Gap Analysis + +### 1. Authentication & RBAC — Completed + +**What exists:** +- JWT-based authentication with refresh token rotation +- Four-role hierarchy: `owner` > `manager` > `agent` > `admin` +- OTP-based login flow for WhatsApp-first users +- Multi-tenant isolation — all queries scoped by `tenant_id` +- Password hashing with bcrypt +- Session management with Redis + +**What works well:** +- Token expiry and refresh flow are production-ready +- Role-based route guards on all API endpoints +- Tenant context extracted from JWT (not URL or body) + +**Remaining items:** +- None blocking launch. Consider adding SSO (SAML/OIDC) for enterprise tenants post-launch. + +--- + +### 2. Billing & Subscriptions — Partial (P0) + +**What exists:** +- `stripe_service.py` — creates payment intents in SAR currency +- `payment_service.py` — basic payment recording +- `invoice_service.py` / `invoice_generator.py` — invoice creation stubs + +**Critical gaps:** +- [ ] **Subscription lifecycle**: No plan creation, upgrade, downgrade, or cancellation flow +- [ ] **Usage metering**: AI agent calls, WhatsApp messages, and storage not tracked per tenant +- [ ] **Stripe webhooks**: No webhook handler for `invoice.paid`, `subscription.updated`, `payment_intent.failed` +- [ ] **Trial management**: No free trial period logic or trial-to-paid conversion +- [ ] **Plan enforcement**: No middleware to check if tenant's plan allows the requested feature +- [ ] **Dunning**: No handling for failed payments (grace period, downgrade, suspension) +- [ ] **SAR invoicing**: ZATCA e-invoicing compliance not wired to billing flow + +**Recommended approach:** +1. Define 3 plans: Starter (SAR 299/mo), Professional (SAR 799/mo), Enterprise (custom) +2. Implement Stripe Checkout Sessions for subscription creation +3. Add webhook handler at `/api/v1/webhooks/stripe` +4. Create `SubscriptionMiddleware` that checks plan limits on each request +5. Wire ZATCA compliance from existing `zatca_compliance.py` into invoice generation + +--- + +### 3. Tenant Onboarding — Partial (P0) + +**What exists:** +- `customer_onboarding_journey.py` — basic journey tracking +- Account creation flow (signup -> verify email -> create tenant) + +**Critical gaps:** +- [ ] **Guided setup wizard**: No step-by-step onboarding (company info -> import contacts -> connect WhatsApp -> invite team) +- [ ] **Sample data**: No option to load demo leads/deals for new tenants +- [ ] **WhatsApp connection**: UltraMSG setup requires manual API key entry, no guided flow +- [ ] **Team invitation**: Invite-by-email exists but no onboarding for invited users +- [ ] **Industry templates**: Seeds exist in `seeds/` but no UI to select and apply them +- [ ] **Progress tracking**: No onboarding completion percentage or checklist UI + +**Recommended approach:** +1. Create 5-step onboarding wizard in frontend (company -> team -> channels -> data -> go-live) +2. API endpoint to apply seed templates: `POST /api/v1/onboarding/apply-template` +3. Onboarding progress stored in Redis for fast access +4. Auto-dismiss wizard after all steps complete or "skip" pressed + +--- + +### 4. Admin Dashboard — Partial (P1) + +**What exists:** +- Basic analytics endpoint in `analytics_service.py` +- Tenant-level KPIs (leads, deals, revenue) + +**Gaps:** +- [ ] **System admin panel**: No super-admin view across all tenants (for Dealix operations team) +- [ ] **Tenant health monitoring**: No view of per-tenant usage, errors, or activity +- [ ] **User management**: Owner can manage team, but no bulk operations +- [ ] **Audit log viewer**: Audit service exists but no UI to browse logs +- [ ] **Configuration UI**: Feature flags, plan limits, and system settings require code changes + +**Recommended approach:** +1. Build `/admin` routes (super-admin only, not tenant-scoped) +2. Tenant list with health indicators (active users, API calls, errors, last login) +3. Wire `audit_service.py` logs to a searchable table component + +--- + +### 5. Analytics & Reporting — Partial (P1) + +**What exists:** +- `analytics_service.py` — basic KPIs (lead count, deal value, conversion rate) +- `predictive_revenue_service.py` — revenue forecasting stub +- `executive_roi_service.py` — ROI calculation + +**Gaps:** +- [ ] **Dashboard charts**: No frontend charting (need chart library integration) +- [ ] **Custom date ranges**: API supports basic period filters but no custom range +- [ ] **Export**: No CSV/PDF export for reports +- [ ] **Funnel analytics**: No pipeline stage conversion tracking +- [ ] **Agent performance**: No per-agent activity and performance metrics +- [ ] **AI usage analytics**: No tracking of AI agent interactions, cost, success rate +- [ ] **Scheduled reports**: No email-based weekly/monthly report delivery + +**Recommended approach:** +1. Integrate Recharts or Chart.js in frontend dashboard +2. Add `/api/v1/analytics/funnel`, `/api/v1/analytics/agents`, `/api/v1/analytics/ai-usage` +3. Celery task for weekly report generation and email delivery +4. CSV export endpoint: `GET /api/v1/analytics/export?format=csv` + +--- + +### 6. Help Center & Documentation — Missing (P1) + +**What exists:** +- Developer-facing `README.md`, `CLAUDE.md`, `CONTRIBUTING.md` +- No user-facing documentation + +**Gaps:** +- [ ] **User guide**: How to use Dealix (Arabic + English) +- [ ] **API documentation**: Auto-generated from FastAPI OpenAPI spec, but not styled or hosted +- [ ] **In-app help**: No contextual help tooltips or guided tours +- [ ] **FAQ / Knowledge base**: No searchable help articles +- [ ] **Video tutorials**: None (important for Saudi market, WhatsApp/voice preferred) +- [ ] **Changelog**: No user-facing release notes + +**Recommended approach:** +1. Host FastAPI auto-docs at `/docs` with custom branding +2. Build help center with Markdown articles (Arabic-first) served via Next.js +3. Add `?` help icons on key UI pages linking to relevant articles +4. Create 3-5 short video walkthroughs (Arabic voiceover) + +--- + +### 7. Deployment & Infrastructure — Completed + +**What exists:** +- `docker-compose.yml` — full stack (FastAPI, Next.js, PostgreSQL, Redis, Celery worker) +- Nginx configuration in `nginx/` +- `.env.example` with all required variables documented +- GitHub Actions CI in `.github/` + +**What works well:** +- Single-command deployment with Docker Compose +- Service health checks configured +- Environment variable separation + +**Remaining items:** +- Consider adding Kubernetes manifests for horizontal scaling (post-launch) +- Add Docker image tagging strategy for versioned deployments + +--- + +### 8. Monitoring & Alerting — Partial (P0) + +**What exists:** +- Sentry DSN placeholder in `.env.example` +- Basic error logging throughout the codebase + +**Critical gaps:** +- [ ] **Sentry configuration**: DSN exists but SDK not initialized in `main.py` +- [ ] **Performance monitoring**: No APM (request duration, DB query time, AI latency) +- [ ] **Health check endpoint**: Need `/health` and `/ready` endpoints +- [ ] **Uptime monitoring**: No external uptime check (UptimeRobot, Pingdom, etc.) +- [ ] **Log aggregation**: No structured logging or log shipping +- [ ] **Alerting rules**: No PagerDuty/Slack alerts for errors, high latency, or downtime +- [ ] **Resource monitoring**: No CPU/memory/disk alerts on the server + +**Recommended approach:** +1. Initialize Sentry SDK in `main.py` with `traces_sample_rate=0.2` +2. Add `/api/v1/health` endpoint (DB + Redis connectivity check) +3. Add structured JSON logging with `structlog` +4. Set up Sentry alert rules: error spike, P95 latency > 2s, unhandled exceptions +5. External uptime monitor on health endpoint (5-minute interval) + +--- + +### 9. Feature Flags — Missing (P1) + +**What exists:** +- Nothing. Features are enabled/disabled by deploying code. + +**Gaps:** +- [ ] **Flag storage**: No feature flag service or configuration +- [ ] **Per-tenant flags**: Cannot enable features for specific tenants (beta testing) +- [ ] **Runtime toggling**: Requires redeployment to change feature availability +- [ ] **Flag-based UI**: Frontend cannot conditionally show/hide features + +**Recommended approach:** +1. Implement `feature_flags.py` service with Redis (fast reads) + PostgreSQL (persistence) +2. Built-in flags: `ai_sales_agent`, `sequences`, `cpq`, `signal_intelligence`, `autopilot` +3. API endpoints: `GET /api/v1/flags`, `PUT /api/v1/flags/{flag_name}` +4. Frontend hook: `useFeatureFlag("flag_name")` returns boolean +5. Default all flags to `False` for new tenants, `True` for beta testers + +**Implementation**: See `backend/app/services/feature_flags.py` + +--- + +### 10. Customer Support Flow — Missing (P0) + +**What exists:** +- Nothing. No support ticketing, chat, or contact flow. + +**Gaps:** +- [ ] **Support email**: No `support@dealix.sa` with ticket routing +- [ ] **In-app support**: No chat widget or support ticket form +- [ ] **WhatsApp support**: Ironic gap — CRM with WhatsApp but no WhatsApp support channel +- [ ] **SLA tracking**: No response time or resolution time tracking +- [ ] **Knowledge base search**: No self-service support before contacting team +- [ ] **Escalation flow**: `escalation.py` exists for deal escalation, not support escalation + +**Recommended approach:** +1. Set up support email with auto-reply (Arabic) +2. Add in-app "Help & Support" page with contact form +3. Create WhatsApp Business support number with auto-routing +4. Track support tickets in a simple model (can use Dealix's own lead pipeline internally) +5. Define SLAs: P0 (1h), P1 (4h), P2 (24h), P3 (72h) + +--- + +### 11. PDPL Compliance — Completed + +**What exists:** +- `pdpl/consent_manager.py` — consent tracking with purpose and channel +- `pdpl/data_rights.py` — data access, correction, and deletion handlers +- `security/pdpl-checklist.md` — compliance documentation +- Audit trail on all consent changes +- 12-month consent auto-expiry + +**What works well:** +- Consent checked before all outbound messaging +- Data subject rights API endpoints +- Audit logging for compliance evidence + +**Remaining items:** +- None blocking launch. Consider third-party PDPL audit for certification. + +--- + +## Launch Readiness Score + +``` +Completed: 3/11 (Auth, Deployment, PDPL) +Partial: 5/11 (Billing, Onboarding, Admin, Analytics, Monitoring) +Missing: 3/11 (Docs, Feature Flags, Support) + +Overall: ~45% ready for public SaaS launch +``` + +## Recommended Sprint Plan + +### Sprint 1 (P0 — Must Have for Launch) +1. Billing: Stripe subscriptions + webhook handler + plan enforcement +2. Monitoring: Sentry init + health endpoint + structured logging +3. Support: Support email + in-app contact form +4. Onboarding: 5-step wizard with template selection + +### Sprint 2 (P1 — Should Have for Launch) +1. Feature flags: Redis-backed service + API + frontend hook +2. Analytics: Dashboard charts + funnel analytics + export +3. Admin: Super-admin panel + tenant health view + +### Sprint 3 (P1 — Nice to Have) +1. Documentation: Help center + in-app help + API docs styling +2. Admin: Audit log viewer + configuration UI +3. Analytics: Scheduled reports + AI usage tracking