system-prompts-and-models-o.../dealix/core/utils.py
Dealix Builder e34cc729aa feat(dealix): py3.10/3.11 compat shim + 54 unit tests for business/innovation/ai
PROBLEM
The codebase used Python 3.11+ stdlib features (`from datetime import UTC`,
`from enum import StrEnum`) in 22 files, breaking local dev on Python 3.10
(Windows users) and any pytest run that imports the affected modules.

SOLUTION
1. New `core/_py_compat.py` providing UTC + StrEnum shims that:
   - On 3.11+ re-export the stdlib names (zero overhead)
   - On 3.10 fall back to `timezone.utc` and a (str, Enum) backport

2. All 22 affected files patched to import from the shim:
   - core/utils.py, core/config/models.py
   - api/routers/admin.py
   - auto_client_acquisition/{ai/model_router, agents/{intake,icp_matcher},
     v3/{memory,agents,compliance_os,market_radar},
     personal_operator/{operator,memory,launch_report},
     innovation/{proof_ledger_repo,command_feed_live}}.py
   - autonomous_growth/agents/sector_intel.py
   - dealix/{trust/{approval,tool_verification,policy},
     observability/cost_tracker,
     contracts/{evidence_pack,event_envelope,audit_log,decision},
     classifications/__init__,
     governance/approvals}.py

3. Three new test suites for previously-untested layers (54 tests):
   - tests/unit/test_business_suite.py — gtm_plan, launch_metrics,
     market_positioning, pricing_strategy, proof_pack, unit_economics,
     verticals (28 tests covering plan recommendation, performance fee,
     ROI math, account health grading, vertical playbook structure)
   - tests/unit/test_innovation_suite.py — aeo_radar, command_feed,
     deal_rooms, experiments, growth_missions, proof_ledger, ten_in_ten
     (18 tests covering deterministic reproducibility, card type taxonomy,
     pending-approval invariant, kill-mission visibility)
   - tests/unit/test_ai_model_router.py — ModelTask + get_model_route +
     estimate_model_cost_class + requires_guardrail (8 tests covering
     enum integrity, route round-trip, guardrail bool contract)

VERIFICATION
- ast.parse green on all 22 patched files
- pytest tests/unit/ → 477 passed, 2 skipped (provider smoke needs API keys)
  on Python 3.10.12 venv with project requirements installed
- No behavior change on 3.11+: the shim re-exports stdlib symbols

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

98 lines
2.9 KiB
Python

"""Utility helpers | دوال مساعدة."""
from __future__ import annotations
import hashlib
import re
import uuid
from datetime import datetime
from typing import Any
from core._py_compat import UTC
import phonenumbers
def generate_id(prefix: str = "id") -> str:
"""Generate a short unique id | وَلِّد معرفاً فريداً قصيراً."""
return f"{prefix}_{uuid.uuid4().hex[:12]}"
def utcnow() -> datetime:
"""Current UTC time | الوقت الحالي UTC."""
return datetime.now(UTC)
def hash_text(text: str) -> str:
"""Stable hash for dedup | بصمة نصية للتكرار."""
return hashlib.sha256(text.encode("utf-8")).hexdigest()[:16]
def is_arabic(text: str) -> bool:
"""Detect if text is primarily Arabic | اكتشف إذا كان النص عربياً."""
if not text:
return False
arabic_range = re.compile(r"[\u0600-\u06FF\u0750-\u077F]")
arabic_chars = len(arabic_range.findall(text))
total_chars = len([c for c in text if c.isalpha()])
return total_chars > 0 and arabic_chars / total_chars > 0.3
def detect_locale(text: str) -> str:
"""Return 'ar' or 'en' based on script | لغة النص."""
return "ar" if is_arabic(text) else "en"
def normalize_phone(phone: str, default_country: str = "SA") -> str | None:
"""
Normalize phone to E.164 (e.g. +966501234567).
وحّد رقم الهاتف بصيغة E.164.
"""
if not phone:
return None
try:
parsed = phonenumbers.parse(phone, default_country)
if phonenumbers.is_valid_number(parsed):
return phonenumbers.format_number(parsed, phonenumbers.PhoneNumberFormat.E164)
except phonenumbers.NumberParseException:
return None
return None
def normalize_email(email: str) -> str | None:
"""Lowercase + strip, basic validity check."""
if not email:
return None
email = email.strip().lower()
if re.match(r"^[^@\s]+@[^@\s]+\.[^@\s]+$", email):
return email
return None
def safe_dict(obj: Any) -> dict[str, Any]:
"""Best-effort convert object to a JSON-safe dict."""
if isinstance(obj, dict):
return {k: _safe_value(v) for k, v in obj.items()}
if hasattr(obj, "__dict__"):
return {k: _safe_value(v) for k, v in obj.__dict__.items() if not k.startswith("_")}
return {"value": str(obj)}
def _safe_value(v: Any) -> Any:
if isinstance(v, (str, int, float, bool)) or v is None:
return v
if isinstance(v, datetime):
return v.isoformat()
if isinstance(v, (list, tuple)):
return [_safe_value(i) for i in v]
if isinstance(v, dict):
return {k: _safe_value(x) for k, x in v.items()}
return str(v)
def truncate(text: str, max_length: int = 200, suffix: str = "") -> str:
"""Truncate text politely | اختصار نصي."""
if not text or len(text) <= max_length:
return text
return text[: max_length - len(suffix)] + suffix