Files
sales-trainer/backend/app/services/groups.py
T

230 lines
9.1 KiB
Python

"""Persona group store: groups hold a sale kit + personas + report.
A group is created by an admin from a setup form + optional files. After analyze,
it contains `personas` (15 by default = 5 per tier) and a `report`. Groups are
editable/re-analyzeable by admins. Trainees only read revealable views of personas
and run one-shot sessions (sessions are stored separately).
"""
from __future__ import annotations
import datetime
from pathlib import Path
from typing import Any
from ..auth.users import is_valid_tenant_id
from ..storage.store import JsonStore, new_id
from .store import ensure_persona_shape, revealable_view, validate_persona_traits
DEFAULT_TIERS = ["A", "B", "C"]
PERSONAS_PER_TIER = 5
def _now() -> str:
return datetime.datetime.now(datetime.timezone.utc).isoformat()
class GroupStore:
def __init__(self, data_dir: Path) -> None:
self.groups = JsonStore(data_dir / "groups")
def record_lock(self, gid: str):
"""Hold a group transaction lock across analysis work."""
return self.groups.record_lock(gid)
def create(
self,
*,
org_id: str,
creator_id: str,
title: str,
status: str = "draft",
owner_user_id: str | None = None,
input_data: dict[str, Any] | None = None,
sales_kit: dict[str, Any] | None = None,
) -> dict[str, Any]:
gid = new_id("group")
group = {
"id": gid,
"org_id": org_id,
"creator_id": creator_id,
"title": title or "Untitled group",
"status": status, # draft -> analyzing -> ready | failed
"created_at": _now(),
"updated_at": _now(),
"input": dict(input_data) if isinstance(input_data, dict) else {},
"sales_kit": sales_kit if isinstance(sales_kit, dict) else None,
"personas": [], # full persona dicts
"report": None,
"error": None,
}
if owner_user_id is not None:
group["owner_user_id"] = owner_user_id
return self.groups.create(group, key=gid)
def get(self, gid: str) -> dict[str, Any]:
return self.groups.get(gid)
def get_or_none(self, gid: str) -> dict[str, Any] | None:
return self.groups.get_or_none(gid)
def update(self, gid: str, **fields: Any) -> dict[str, Any]:
fields.setdefault("updated_at", _now())
return self.groups.update(gid, **fields)
def list_for_org(self, org_id: str | None = None) -> list[dict[str, Any]]:
if not is_valid_tenant_id(org_id):
return []
groups = self.groups.all()
return [g for g in groups if isinstance(g, dict) and g.get("org_id") == org_id]
def list_visible_to(
self,
*,
role: str,
org_id: str | None = None,
user_id: str | None = None,
) -> list[dict[str, Any]]:
"""List groups a role/user can see through a role-safe view.
Trainee callers receive only ready groups, only their own private groups,
and revealable persona fields. Keeping this policy here prevents a new
route from accidentally turning a raw group index into an IDOR/data leak.
"""
if role == "super_admin":
groups = [g for g in self.groups.all() if isinstance(g, dict)]
return groups if org_id is None else [g for g in groups if g.get("org_id") == org_id]
if not is_valid_tenant_id(org_id):
return []
groups = [g for g in self.groups.all() if isinstance(g, dict)]
groups = [g for g in groups if g.get("org_id") == org_id]
if role == "user":
groups = [g for g in groups if g.get("status") == "ready"]
if not isinstance(user_id, str) or not user_id:
return []
groups = [
g
for g in groups
if "owner_user_id" not in g
or (isinstance(g.get("owner_user_id"), str) and g.get("owner_user_id") == user_id)
]
return [self._user_visible_group(g) for g in groups]
if role == "admin":
# A tenant admin may inspect shared group summaries, never a trainee's
# private group. An explicit owner marker is private even when malformed.
return [g for g in groups if "owner_user_id" not in g]
return []
@staticmethod
def _user_visible_group(group: dict[str, Any]) -> dict[str, Any]:
"""Return the closed group envelope allowed to a trainee."""
raw_input = group.get("input")
source = raw_input if isinstance(raw_input, dict) else {}
raw_personas = group.get("personas")
personas = raw_personas if isinstance(raw_personas, list) else []
status = group.get("status", "draft")
return {
"id": group.get("id"),
"org_id": group.get("org_id"),
"owner_user_id": group.get("owner_user_id"),
"title": group.get("title", ""),
"status": status,
"created_at": group.get("created_at"),
"updated_at": group.get("updated_at"),
"input": {
key: source[key]
for key in ("product", "segment", "channel", "language")
if key in source
},
"sales_kit": None,
"personas": [
revealable_view(ensure_persona_shape(persona))
for persona in personas
if isinstance(persona, dict)
],
"report": None,
"error": "analysis_failed" if status == "failed" and group.get("error") else None,
}
def get_or_create_private_group(
self,
*,
org_id: str,
owner_user_id: str,
owner_name: str = "User",
input_data: dict[str, Any] | None = None,
sales_kit: dict[str, Any] | None = None,
) -> dict[str, Any]:
"""Return the one private, ready group owned by a trainee.
The lookup and create are one invariant. Keep both inside the
collection lock so concurrent web workers cannot allocate duplicate
private groups for the same ``(org_id, owner_user_id)`` pair.
"""
if not is_valid_tenant_id(org_id):
raise ValueError("organization scope is invalid")
if not isinstance(owner_user_id, str) or not owner_user_id.strip():
raise ValueError("private owner is invalid")
with self.groups.collection_lock():
for group in self.list_for_org(org_id=org_id):
if group.get("owner_user_id") == owner_user_id:
if group.get("status") != "ready":
raise ValueError("private group is not ready")
return group
group = self.create(
org_id=org_id,
creator_id=owner_user_id,
title=f"{owner_name or 'User'}'s private personas",
status="ready",
owner_user_id=owner_user_id,
input_data=input_data or {"channel": "social", "language": "th"},
sales_kit=sales_kit or {
"productName": "personal practice",
"valueProps": [],
"features": [],
},
)
return group
# ── personas ────────────────────────────────────────────────────────
def set_personas(self, gid: str, personas: list[dict[str, Any]]) -> dict[str, Any]:
with self.record_lock(gid):
personas = [ensure_persona_shape(p) for p in personas]
return self.groups.update(gid, personas=personas)
def get_persona(self, gid: str, pid: str) -> dict[str, Any] | None:
group = self.get(gid)
raw_personas = group.get("personas")
personas = raw_personas if isinstance(raw_personas, list) else []
for p in personas:
if not isinstance(p, dict):
continue
if p.get("id") == pid:
return p
return None
def update_persona(self, gid: str, pid: str, patch: dict[str, Any]) -> dict[str, Any]:
with self.record_lock(gid):
group = self.get(gid)
found = False
raw_personas = group.get("personas")
personas = raw_personas if isinstance(raw_personas, list) else []
group["personas"] = personas
for i, p in enumerate(personas):
if not isinstance(p, dict):
continue
if p.get("id") == pid:
merged = {**p, **patch, "id": pid}
normalized = ensure_persona_shape(merged)
validate_persona_traits(normalized)
group["personas"][i] = normalized
found = True
break
if not found:
raise ValueError("persona not found")
return self.groups.replace(gid, group)
def delete(self, gid: str) -> None:
"""Hard-delete a group (personas/report included)."""
with self.record_lock(gid):
self.groups.delete(gid)