Files
sales-trainer/backend/app/services/store.py
T
Macky 3c22d88bcd feat: demo SaaS + training flow security hardening (8/8 review gate passed)
- Demo accounts: super_admin-only provisioning into isolated DEMO_ORG_ID tenant,
  30-day UTC trial on first login, revocable, one-time credential delivery via
  optional SES/webhook (never persisted). Adds boto3 dependency.
- Analytics/report/export/privacy: shared bounded scan budget across users/groups/
  sessions, tenant-consistent session/user/group joins, scalar-only CSV export
  (no nested persisted-value stringification).
- Ownership/tenant isolation: canonical owner-tenant predicate for list/read/chat;
  client sees is_owned only, never owner_user_id.
- Lifecycle/races: status transition validation, analyzing is an in-progress gate
  (no duplicate reanalysis), structured-ready publication, stale-variant revalidation.
- Auth/setup/consent/JWT/OAuth/config: fail-closed consent, bounded JWT lifetime,
  provider-subject atomic OAuth identity, repeated-secret rejection, strict Persona
  trait validation.
- Chat/session/privacy: pre-seller opener redaction, corrupt-session recovery,
  role-aware completed-chat dashboard routing.
- Frontend: Training→product→personas→practice flow, demo/role/demo guards,
  is_owned-based ownership display, 320×568 and 500×768 responsive E2E.
- 8 independent exact-five-key review scopes passed; backend 509, frontend 26,
  production build 1775 modules, isolated E2E 15.
2026-08-25 06:39:06 +07:00

133 lines
5.8 KiB
Python

"""Persona data model + shape normalization.
A persona has a canonical schema. Fields are split into:
- revealable: shown to trainees up front (what a real seller could plausibly know)
- latent: hidden until the conversation ends (pain, income, personality, budget,
negotiation levers, hidden opener, etc.)
Every persona also carries an `intent_tier` (A/B/C), an `initiation_mode`
(customer/seller), a `channel` (facebook/line), a set of `pains` with resolution
conditions, `negotiation_levers`, and optional `special` flags (e.g. wrong_text).
"""
from __future__ import annotations
import math
from typing import Any
DEFAULT_TIERS = ["A", "B", "C"]
PERSONA_CHANNELS = ("facebook", "line")
PERSONA_INITIATION_MODES = ("customer", "seller")
def validate_persona_traits(p: dict[str, Any]) -> None:
"""Reject invalid behavior traits instead of silently changing their meaning."""
def _bounded_json(value: object, *, depth: int = 0) -> bool:
if depth > 6:
return False
if value is None or isinstance(value, bool):
return True
if isinstance(value, str):
return len(value) <= 4000
if isinstance(value, (int, float)) and not isinstance(value, bool):
return math.isfinite(value)
if isinstance(value, list):
return len(value) <= 100 and all(
_bounded_json(item, depth=depth + 1) for item in value
)
if isinstance(value, dict):
return len(value) <= 100 and all(
isinstance(key, str)
and len(key) <= 200
and _bounded_json(item, depth=depth + 1)
for key, item in value.items()
)
return False
if not isinstance(p, dict) or not _bounded_json(p):
raise ValueError("persona contains invalid or unbounded data")
if p.get("channel") not in PERSONA_CHANNELS:
raise ValueError("persona channel must be facebook or line")
if p.get("initiation_mode") not in PERSONA_INITIATION_MODES:
raise ValueError("persona initiation_mode must be customer or seller")
scalar_fields = (
"id", "source_persona_id", "name", "tier", "profession", "age_group",
"location", "product_context", "background", "income", "lifestyle",
"personality", "communication_style", "budget", "decision_timeline",
"goal", "opener", "special", "notes",
)
for field in scalar_fields:
value = p.get(field)
if value is not None and (not isinstance(value, str) or len(value) > 4000):
raise ValueError(f"persona {field} must be a bounded string")
for field in ("objections", "pains", "negotiation_levers"):
value = p.get(field)
if not isinstance(value, list) or len(value) > 100:
raise ValueError(f"persona {field} must be a bounded list")
if not isinstance(p.get("recontact"), bool):
raise ValueError("persona recontact must be boolean")
for field in ("difficulty", "tolerance"):
value = p.get(field)
if type(value) is not int or not 1 <= value <= 5:
raise ValueError(f"persona {field} must be between 1 and 5")
def ensure_persona_shape(p: dict[str, Any]) -> dict[str, Any]:
"""Fill defaults so a persona dict is always structurally complete."""
if "tier" in p and p["tier"] not in DEFAULT_TIERS:
raise ValueError("persona tier must be A, B, or C")
if "intent_tier" in p and p["intent_tier"] not in DEFAULT_TIERS:
raise ValueError("persona intent_tier must be A, B, or C")
if "recontact" in p and not isinstance(p["recontact"], bool):
raise ValueError("persona recontact must be boolean")
pid = p.get("id") or p.get("name", "persona")
base = {
"id": pid,
"source_persona_id": p.get("source_persona_id"),
"name": p.get("name", ""),
"tier": p.get("tier", p.get("intent_tier", "B")),
"initiation_mode": p.get("initiation_mode", "customer"), # customer | seller
"channel": p.get("channel", "facebook"), # facebook | line
# revealable
"profession": p.get("profession", ""),
"age_group": p.get("age_group", ""),
"location": p.get("location", ""),
"product_context": p.get("product_context", ""),
# latent (hidden until end)
"background": p.get("background", ""),
"income": p.get("income", ""),
"lifestyle": p.get("lifestyle", ""),
"personality": p.get("personality", ""),
"communication_style": p.get("communication_style", ""),
"budget": p.get("budget", ""),
"decision_timeline": p.get("decision_timeline", ""),
"goal": p.get("goal", ""),
"objections": p.get("objections", []),
"pains": p.get("pains", []),
"negotiation_levers": p.get("negotiation_levers", []),
"opener": p.get("opener", ""),
"special": p.get("special", ""), # e.g. "wrong_text" | ""
"recontact": bool(p.get("recontact")), # returned after researching earlier (pre-qualified, warm)
"difficulty": p.get("difficulty", 1), # 1..5
"tolerance": p.get("tolerance", 3), # misses before this persona walks away (temper)
"notes": p.get("notes", ""),
}
return base
def revealable_view(p: dict[str, Any]) -> dict[str, Any]:
"""Return ONLY the fields a trainee may see before/while chatting."""
return {
"id": p.get("id"),
"name": p.get("name"),
"tier": p.get("tier"),
"initiation_mode": p.get("initiation_mode"),
"channel": p.get("channel"),
"profession": p.get("profession"),
"age_group": p.get("age_group"),
"location": p.get("location"),
"product_context": p.get("product_context"),
}
def full_view(p: dict[str, Any]) -> dict[str, Any]:
return ensure_persona_shape(p)