- listPersonas: compute per-user my_outcome for ALL roles; always set the key (default 'not_tried') so the all-roles UI never sees undefined (fixes global super_admin without org showing every persona as trained) - start_session/mode lookups (send/finish/resume/authorize): no preview mode; every role creates one-shot 'trainee' sessions. The one-shot lock (1 persona chat per user; many users per persona) now applies to all roles - Chat.vue: always start in trainee mode, remove preview label - Personas.vue: unified branches - show 'แชท' when untrained, 'สรุปผล'+variant when trained, for all roles - Rewrite test_admin_preview.py to assert the new no-preview one-shot behavior
839 lines
32 KiB
Python
839 lines
32 KiB
Python
"""Group API: create, analyze (sales kit + personas), read, edit, report."""
|
|
from __future__ import annotations
|
|
|
|
import functools
|
|
import math
|
|
import threading
|
|
import uuid
|
|
from pathlib import Path
|
|
|
|
from flask import Blueprint, Response, current_app, jsonify, request
|
|
from werkzeug.exceptions import RequestEntityTooLarge
|
|
|
|
from ..config import Config
|
|
from ..llm import LLMClient, LLMError
|
|
from ..services.groups import GroupStore
|
|
from ..services.store import (
|
|
PERSONA_CHANNELS,
|
|
ensure_persona_shape,
|
|
revealable_view,
|
|
validate_persona_traits,
|
|
)
|
|
from ..storage.store import contains_control_characters
|
|
from .helpers import (
|
|
ApiError,
|
|
current_user,
|
|
internal_error,
|
|
is_valid_tenant_id,
|
|
request_json_object,
|
|
require_auth,
|
|
require_roles,
|
|
)
|
|
|
|
groups_bp = Blueprint("groups", __name__)
|
|
|
|
|
|
def _group_analysis_lock(fn):
|
|
"""Serialize analysis and prevent stale LLM results from overwriting a group."""
|
|
@functools.wraps(fn)
|
|
def wrapped(gid: str, *args, **kwargs):
|
|
s = _stores()
|
|
with s["groups"].record_lock(gid):
|
|
return fn(gid, *args, **kwargs)
|
|
return wrapped
|
|
|
|
# Fields that encode the "formula"/process of a persona. Only super_admin may see/edit
|
|
# them; admins get the persona but NOT these — so a casual copy yields inferior results.
|
|
SECRET_PERSONA_FIELDS = {
|
|
"pains", "objections", "negotiation_levers", "opener",
|
|
"rootCause", "resolutionConditions", "tolerance",
|
|
}
|
|
|
|
# Tenant admins receive the approved review/edit surface, not arbitrary fields that
|
|
# may be added to the persona schema later. Add new fields deliberately.
|
|
ADMIN_VISIBLE_PERSONA_FIELDS = {
|
|
"id", "name", "tier", "initiation_mode", "channel", "profession", "age_group",
|
|
"location", "product_context", "background", "income", "lifestyle", "personality",
|
|
"communication_style", "budget", "decision_timeline", "goal", "difficulty", "notes",
|
|
"recontact",
|
|
}
|
|
ADMIN_EDITABLE_PERSONA_FIELDS = ADMIN_VISIBLE_PERSONA_FIELDS - {"id"}
|
|
|
|
# Keep the group envelope closed as well as the nested persona envelope. New
|
|
# internal fields must be deliberately added here before they can cross the API.
|
|
GROUP_VISIBLE_FIELDS = {
|
|
"id", "org_id", "creator_id", "owner_user_id", "title", "status",
|
|
"created_at", "updated_at", "input", "sales_kit", "personas", "report", "error",
|
|
}
|
|
|
|
|
|
def strip_secret_fields(persona: dict) -> dict:
|
|
"""Return only explicitly approved tenant-admin persona fields."""
|
|
return {
|
|
field: persona[field]
|
|
for field in ADMIN_VISIBLE_PERSONA_FIELDS
|
|
if field in persona and field not in SECRET_PERSONA_FIELDS
|
|
}
|
|
|
|
|
|
def serialize_persona(persona: dict, actor: dict) -> dict:
|
|
"""Serialize a persona through the single role-aware policy."""
|
|
shaped = ensure_persona_shape(persona)
|
|
if actor.get("role") == "super_admin":
|
|
return shaped
|
|
if actor.get("role") == "user":
|
|
return revealable_view(shaped)
|
|
return strip_secret_fields(shaped)
|
|
|
|
|
|
def serialize_group(group: dict, actor: dict) -> dict:
|
|
"""Serialize a group without exposing latent persona recipe data."""
|
|
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 []
|
|
view = {
|
|
field: group[field]
|
|
for field in GROUP_VISIBLE_FIELDS
|
|
if field in group
|
|
}
|
|
# Historical groups may contain legacy raw exception text. Normalize at the API
|
|
# boundary so old records cannot leak paths/provider responses either.
|
|
if view.get("error"):
|
|
view["error"] = "analysis_failed" if view.get("status") == "failed" else "operation_failed"
|
|
view["personas"] = [
|
|
serialize_persona(persona, actor) for persona in personas if isinstance(persona, dict)
|
|
]
|
|
if actor.get("role") == "user":
|
|
# Trainees need only the high-level offer context. Do not return uploaded
|
|
# filenames or parsed source text from the admin's group brief.
|
|
view["input"] = {
|
|
key: source[key]
|
|
for key in ("product", "segment", "channel", "language")
|
|
if key in source
|
|
}
|
|
elif actor.get("role") != "super_admin":
|
|
# Tenant admins can manage personas, but uploaded filenames, parsed source
|
|
# text, and future internal input fields remain server-side only.
|
|
view["input"] = {
|
|
key: source[key]
|
|
for key in ("product", "segment", "channel", "language")
|
|
if key in source
|
|
}
|
|
if actor.get("role") != "super_admin":
|
|
view["sales_kit"] = None
|
|
view["report"] = None
|
|
return view
|
|
|
|
_ANALYZE_LOCKS: dict[str, threading.Lock] = {}
|
|
_ANALYZE_GUARD = threading.Lock()
|
|
|
|
|
|
def _stores():
|
|
from flask import current_app
|
|
|
|
return {
|
|
"groups": current_app.extensions.get("group_store"),
|
|
"users": current_app.extensions["user_store"],
|
|
"session_store": current_app.extensions.get("session_store"),
|
|
"llm": current_app.extensions["llm"],
|
|
}
|
|
|
|
|
|
def _authorize_group(group: dict) -> None:
|
|
"""Enforce org-scoped access (IDOR defense). super_admin may access any org.
|
|
|
|
Private/personal groups (owner_user_id set) are only accessible by their owner
|
|
(or super_admin), even within the same org.
|
|
"""
|
|
if not isinstance(group, dict):
|
|
raise ApiError("group state unavailable", 503)
|
|
actor = current_user()
|
|
if actor.get("role") == "super_admin":
|
|
return
|
|
owner_marker_present = "owner_user_id" in group
|
|
owner = group.get("owner_user_id")
|
|
if owner_marker_present and (
|
|
not isinstance(owner, str) or not owner.strip() or owner != actor.get("id")
|
|
):
|
|
raise ApiError("permission denied", 403)
|
|
if not is_valid_tenant_id(actor.get("org_id")) or not is_valid_tenant_id(group.get("org_id")):
|
|
raise ApiError("permission denied", 403)
|
|
if group.get("org_id") != actor.get("org_id"):
|
|
raise ApiError("permission denied", 403)
|
|
|
|
|
|
def _get_owned_group(s, gid: str) -> dict:
|
|
group = s["groups"].get_or_none(gid)
|
|
if group is None:
|
|
raise ApiError("group not found", 404)
|
|
if not isinstance(group, dict):
|
|
raise ApiError("group state unavailable", 503)
|
|
_authorize_group(group)
|
|
if current_user().get("role") == "user" and group.get("status") != "ready":
|
|
raise ApiError("group not ready", 403)
|
|
return group
|
|
|
|
|
|
def _upload_dir():
|
|
d = Config.DATA_DIR / "uploads"
|
|
d.mkdir(parents=True, exist_ok=True)
|
|
return d
|
|
|
|
|
|
def _cleanup_uploads(names: list[str]) -> None:
|
|
for name in names:
|
|
if (
|
|
not isinstance(name, str)
|
|
or not name
|
|
or Path(name).name != name
|
|
or "/" in name
|
|
or "\\" in name
|
|
or any(ord(char) < 32 or ord(char) == 127 for char in name)
|
|
):
|
|
current_app.logger.warning("skipping unsafe uploaded-file cleanup name")
|
|
continue
|
|
try:
|
|
name.encode("utf-8")
|
|
except UnicodeError:
|
|
current_app.logger.warning("skipping invalid uploaded-file cleanup name")
|
|
continue
|
|
try:
|
|
destination = _upload_dir() / name
|
|
destination.resolve(strict=False).relative_to(_upload_dir().resolve(strict=True))
|
|
destination.unlink(missing_ok=True)
|
|
except (UnicodeError, ValueError):
|
|
current_app.logger.warning("skipping uploaded-file cleanup outside upload directory")
|
|
except OSError as exc:
|
|
current_app.logger.error(
|
|
"uploaded-file cleanup failed (error_type=%s)", type(exc).__name__
|
|
)
|
|
|
|
|
|
def _inspect_upload_size(stream) -> int:
|
|
"""Return a known nonnegative upload size; unknown sizes fail closed."""
|
|
try:
|
|
stream.seek(0, 2)
|
|
size = stream.tell()
|
|
stream.seek(0)
|
|
except (OSError, AttributeError, TypeError, ValueError) as exc:
|
|
raise ApiError("could not inspect uploaded file", 400) from exc
|
|
if isinstance(size, bool) or not isinstance(size, int) or size < 0:
|
|
raise ApiError("could not determine uploaded file size", 400)
|
|
return size
|
|
|
|
|
|
def _validate_upload_budget(
|
|
*, content_length: int | None, file_count: int, total_bytes: int
|
|
) -> None:
|
|
"""Fail closed before saving files when the request budget is unknowable/exceeded."""
|
|
max_bytes = Config.UPLOAD_MAX_MB * 1024 * 1024
|
|
if content_length is None:
|
|
raise ApiError("upload request size is unknown", 413)
|
|
if (
|
|
isinstance(content_length, bool)
|
|
or not isinstance(content_length, int)
|
|
or content_length < 0
|
|
or content_length > max_bytes
|
|
):
|
|
raise ApiError("upload request too large", 413)
|
|
if isinstance(file_count, bool) or not isinstance(file_count, int) or file_count < 0:
|
|
raise ApiError("invalid upload file count", 400)
|
|
if file_count > Config.UPLOAD_MAX_FILES:
|
|
raise ApiError("too many uploaded files", 413)
|
|
if isinstance(total_bytes, bool) or not isinstance(total_bytes, int) or total_bytes < 0:
|
|
raise ApiError("invalid upload size", 400)
|
|
if total_bytes > max_bytes:
|
|
raise ApiError("uploaded files too large", 413)
|
|
|
|
|
|
@groups_bp.post("")
|
|
@require_auth
|
|
@require_roles("admin")
|
|
def create_group():
|
|
"""Create a persona group from a setup form + optional files."""
|
|
s = _stores()
|
|
file_text = ""
|
|
saved_files = []
|
|
|
|
try:
|
|
is_multipart = bool(
|
|
request.content_type and "multipart/form-data" in request.content_type
|
|
)
|
|
if is_multipart:
|
|
_validate_upload_budget(
|
|
content_length=request.content_length,
|
|
file_count=0,
|
|
total_bytes=0,
|
|
)
|
|
files = request.files.getlist("files") if is_multipart else []
|
|
total_bytes = 0
|
|
destinations = []
|
|
for file in files:
|
|
raw_name = file.filename or ""
|
|
# Path traversal defense: take only the basename, drop any directory
|
|
# segments and reject empty/unsafe names. Never trust client filename as a path.
|
|
safe_name = Path(raw_name).name
|
|
if (
|
|
not safe_name
|
|
or safe_name in (".", "..", "/", "\\")
|
|
or "/" in raw_name
|
|
or "\\" in raw_name
|
|
or contains_control_characters(safe_name)
|
|
):
|
|
raise ApiError("invalid file name")
|
|
ext = safe_name.rsplit(".", 1)[-1].lower()
|
|
if ext not in Config.ALLOWED_UPLOAD_EXTS:
|
|
raise ApiError("unsupported file type")
|
|
max_bytes = Config.UPLOAD_MAX_MB * 1024 * 1024
|
|
size = _inspect_upload_size(file.stream)
|
|
if size > max_bytes:
|
|
raise ApiError("uploaded file too large", 413)
|
|
total_bytes += size
|
|
_validate_upload_budget(
|
|
content_length=request.content_length,
|
|
file_count=len(files),
|
|
total_bytes=total_bytes,
|
|
)
|
|
dest = _upload_dir() / (
|
|
f"{current_user()['id'].replace('@','_')}__{uuid.uuid4().hex[:12]}__{safe_name}"
|
|
)
|
|
# Ensure resolved path stays inside the upload dir (defense in depth).
|
|
try:
|
|
dest.resolve(strict=False).relative_to(_upload_dir().resolve(strict=True))
|
|
except ValueError:
|
|
raise ApiError("invalid file path")
|
|
# Register the destination before saving so a partial write is also
|
|
# removed if the storage operation raises.
|
|
destinations.append((file, dest))
|
|
for file, dest in destinations:
|
|
saved_files.append(dest.name)
|
|
file.save(dest)
|
|
except RequestEntityTooLarge:
|
|
_cleanup_uploads(saved_files)
|
|
raise
|
|
except ApiError:
|
|
_cleanup_uploads(saved_files)
|
|
raise
|
|
except Exception as exc:
|
|
_cleanup_uploads(saved_files)
|
|
raise internal_error("could not save uploaded file", exc, 400)
|
|
|
|
keep_uploads = False
|
|
try:
|
|
try:
|
|
if request.content_type and "multipart/form-data" in request.content_type:
|
|
data = request.form.to_dict()
|
|
else:
|
|
data = request_json_object()
|
|
except RequestEntityTooLarge:
|
|
raise
|
|
except Exception as exc:
|
|
raise internal_error("invalid upload request", exc, 400)
|
|
|
|
# Keep parser import and every post-save parse operation inside the same
|
|
# cleanup-safe boundary. Import failures can happen after files are saved.
|
|
try:
|
|
from ..services.file_parser import ParseError, parse_document
|
|
|
|
max_chars = Config.UPLOAD_MAX_EXTRACTED_CHARS
|
|
for name in saved_files:
|
|
parsed = parse_document(_upload_dir() / name)
|
|
if not isinstance(parsed, str):
|
|
raise ValueError("parser returned non-text output")
|
|
remaining = max_chars - len(file_text) - 2
|
|
if remaining < 0 or len(parsed) > remaining:
|
|
raise ParseError("extracted text too large")
|
|
file_text += "\n\n" + parsed
|
|
except Exception as exc:
|
|
raise internal_error("could not parse uploaded file", exc, 400)
|
|
|
|
string_fields = {"product": "", "segment": "", "description": "", "channel": "facebook", "language": "th"}
|
|
for field, default in string_fields.items():
|
|
value = data.get(field)
|
|
if value is not None and not isinstance(value, str):
|
|
raise ApiError(f"{field} must be a string", 400)
|
|
string_fields[field] = (value if value is not None else default).strip()
|
|
product = string_fields["product"]
|
|
if product == "" and not file_text.strip():
|
|
raise ApiError("provide product info in the form or via file upload")
|
|
actor_org_id = current_user().get("org_id")
|
|
if not is_valid_tenant_id(actor_org_id):
|
|
raise ApiError("permission denied", 403)
|
|
|
|
try:
|
|
group = s["groups"].create(
|
|
org_id=actor_org_id,
|
|
creator_id=current_user()["id"],
|
|
title=(product or file_text[:80] or "Untitled group").strip()[:200],
|
|
)
|
|
s["groups"].update(
|
|
group["id"],
|
|
input={
|
|
"product": product,
|
|
"segment": string_fields["segment"],
|
|
"description": string_fields["description"],
|
|
"channel": string_fields["channel"],
|
|
"language": string_fields["language"],
|
|
"files": saved_files,
|
|
"file_text": file_text[:60000],
|
|
},
|
|
)
|
|
except Exception as exc:
|
|
raise internal_error("could not create group", exc, 500)
|
|
response = jsonify({
|
|
"group": serialize_group(s["groups"].get(group["id"]), current_user())
|
|
})
|
|
keep_uploads = True
|
|
return response, 201
|
|
finally:
|
|
if not keep_uploads:
|
|
_cleanup_uploads(saved_files)
|
|
|
|
|
|
@groups_bp.get("")
|
|
@require_auth
|
|
def list_groups():
|
|
s = _stores()
|
|
actor = current_user()
|
|
if actor.get("role") != "super_admin" and (
|
|
not is_valid_tenant_id(actor.get("org_id"))
|
|
):
|
|
raise ApiError("invalid tenant context", 403)
|
|
visible = s["groups"].list_visible_to(
|
|
role=actor.get("role"),
|
|
# Platform super-admins need the cross-tenant group index; all other
|
|
# roles remain constrained to the authenticated organization's scope.
|
|
org_id=None if actor.get("role") == "super_admin" else actor.get("org_id"),
|
|
user_id=actor.get("id"),
|
|
)
|
|
# ``list_visible_to`` applies the trainee owner/redaction policy at the
|
|
# service boundary; keep this route limited to lightweight summaries.
|
|
# Lightweight summaries only — never send the full personas/sales_kit/report to a
|
|
# list view (huge, heavy, leaks the recipe). Training shows title + persona count.
|
|
summaries = []
|
|
for g in visible:
|
|
raw_personas = g.get("personas")
|
|
personas = raw_personas if isinstance(raw_personas, list) else []
|
|
raw_input = g.get("input")
|
|
group_input = raw_input if isinstance(raw_input, dict) else {}
|
|
summaries.append({
|
|
"id": g.get("id"),
|
|
"title": g.get("title", ""),
|
|
"status": g.get("status", "draft"),
|
|
"channel": group_input.get("channel"),
|
|
"org_id": g.get("org_id"),
|
|
"persona_count": len(personas),
|
|
"input": {"product": group_input.get("product", "")},
|
|
})
|
|
return jsonify({"groups": summaries})
|
|
|
|
|
|
@groups_bp.post("/<gid>/analyze")
|
|
@require_auth
|
|
@require_roles("admin")
|
|
@_group_analysis_lock
|
|
def analyze_group(gid: str):
|
|
"""Run one deterministic analysis: sales kit + exactly 15 personas."""
|
|
s = _stores()
|
|
group = _get_owned_group(s, gid)
|
|
if request.args.get("append") == "true":
|
|
raise ApiError("append mode is no longer supported", 400)
|
|
|
|
inp = group.get("input", {})
|
|
if not s["llm"]:
|
|
raise ApiError("LLM not configured", 500)
|
|
|
|
from ..services.analyzer import Analyzer
|
|
from ..services.persona_generator import PersonaGenerator
|
|
|
|
s["groups"].update(gid, status="analyzing", error=None)
|
|
try:
|
|
sales_kit = Analyzer(s["llm"]).analyze(
|
|
product=inp.get("product", ""),
|
|
segment=inp.get("segment", ""),
|
|
description=inp.get("description", ""),
|
|
file_text=inp.get("file_text", ""),
|
|
channel=inp.get("channel", "social"),
|
|
)
|
|
except Exception as exc:
|
|
s["groups"].update(gid, status="failed", error="analysis_failed")
|
|
raise internal_error("analysis failed", exc)
|
|
try:
|
|
personas = PersonaGenerator(s["llm"]).generate(
|
|
sales_kit=sales_kit,
|
|
language=inp.get("language", "th"),
|
|
channel=inp.get("channel") if inp.get("channel") in PERSONA_CHANNELS else "facebook",
|
|
)
|
|
except Exception as exc:
|
|
s["groups"].update(gid, status="failed", error="analysis_failed")
|
|
raise internal_error("analysis failed", exc)
|
|
|
|
from ..services.report import build_report
|
|
|
|
try:
|
|
report = build_report(sales_kit=sales_kit, personas=personas, language=inp.get("language", "th"))
|
|
except Exception as exc:
|
|
s["groups"].update(gid, status="failed", error="analysis_failed")
|
|
raise internal_error("analysis failed", exc)
|
|
# Publish the completed analysis as one atomic record replacement. Readers
|
|
# do not take the group mutation lock, so status must never become ready
|
|
# before personas/report/sales_kit are visible together.
|
|
published = s["groups"].get(gid)
|
|
published.update(
|
|
sales_kit=sales_kit,
|
|
personas=personas,
|
|
report=report,
|
|
status="ready",
|
|
error=None,
|
|
)
|
|
s["groups"].groups.replace(gid, published)
|
|
serialized = serialize_group(published, current_user())
|
|
return jsonify({
|
|
"group": serialized,
|
|
"sales_kit": serialized.get("sales_kit"),
|
|
"personas": serialized["personas"],
|
|
})
|
|
|
|
|
|
@groups_bp.get("/<gid>")
|
|
@require_auth
|
|
def get_group(gid: str):
|
|
s = _stores()
|
|
group = _get_owned_group(s, gid)
|
|
actor = current_user()
|
|
|
|
return jsonify({"group": serialize_group(group, actor)})
|
|
|
|
|
|
def _report_scalar(value, *, limit: int = 1000) -> str | None:
|
|
"""Allow only bounded scalar report values; never stringify nested internals."""
|
|
if isinstance(value, bool):
|
|
return None
|
|
if isinstance(value, int):
|
|
text = str(value)
|
|
elif isinstance(value, float):
|
|
if not math.isfinite(value):
|
|
return None
|
|
text = str(value)
|
|
elif isinstance(value, str):
|
|
text = value.strip()
|
|
else:
|
|
return None
|
|
return text[:limit] if text else None
|
|
|
|
|
|
def _report_scalar_list(value) -> list[str]:
|
|
if not isinstance(value, list):
|
|
return []
|
|
return [
|
|
scalar
|
|
for item in value[:20]
|
|
if (scalar := _report_scalar(item)) is not None
|
|
]
|
|
|
|
|
|
@groups_bp.get("/<gid>/report")
|
|
@require_auth
|
|
@require_roles("admin")
|
|
def group_report(gid: str):
|
|
"""Return a human-readable report without latent persona recipe fields."""
|
|
s = _stores()
|
|
group = _get_owned_group(s, gid)
|
|
raw_sales_kit = group.get("sales_kit")
|
|
sales_kit: dict = raw_sales_kit if isinstance(raw_sales_kit, dict) else {}
|
|
raw_group_input = group.get("input")
|
|
group_input: dict = raw_group_input if isinstance(raw_group_input, dict) else {}
|
|
title = _report_scalar(group.get("title"), limit=200) or "Sales training report"
|
|
product = (
|
|
_report_scalar(sales_kit.get("productName"), limit=1000)
|
|
or _report_scalar(group_input.get("product"), limit=1000)
|
|
or "-"
|
|
)
|
|
lines = [
|
|
f"# {title}",
|
|
"",
|
|
"## Sales Kit",
|
|
f"- Product: {product}",
|
|
]
|
|
for label, key in (("Category", "category"), ("Value props", "valueProps"), ("Features", "features"), ("Pricing", "pricingAnchors")):
|
|
value = sales_kit.get(key)
|
|
if isinstance(value, list):
|
|
values = _report_scalar_list(value)
|
|
if values:
|
|
lines.append(f"- {label}: {', '.join(values)}")
|
|
else:
|
|
scalar = _report_scalar(value)
|
|
if scalar is not None:
|
|
lines.append(f"- {label}: {scalar}")
|
|
audience = sales_kit.get("targetAudience")
|
|
if isinstance(audience, dict):
|
|
segment = _report_scalar(audience.get("segment"))
|
|
if segment is not None:
|
|
lines.append(f"- Target segment: {segment}")
|
|
lines.extend(["", "## Personas"])
|
|
persona_fields = (
|
|
"name", "tier", "difficulty", "profession", "age_group", "location",
|
|
"product_context", "goal", "decision_timeline", "channel", "initiation_mode",
|
|
)
|
|
raw_personas = group.get("personas")
|
|
persona_records = raw_personas if isinstance(raw_personas, list) else []
|
|
for persona in persona_records:
|
|
if not isinstance(persona, dict):
|
|
continue
|
|
name = _report_scalar(persona.get("name"), limit=200) or "Persona"
|
|
lines.append(f"### {name}")
|
|
for field in persona_fields[1:]:
|
|
scalar = _report_scalar(persona.get(field))
|
|
if scalar is not None:
|
|
lines.append(f"- {field}: {scalar}")
|
|
lines.append("")
|
|
markdown = "\n".join(lines).strip() + "\n"
|
|
if request.args.get("format") == "json":
|
|
title = _report_scalar(group.get("title"), limit=200) or "Sales training report"
|
|
return jsonify({"title": title, "markdown": markdown})
|
|
return Response(
|
|
markdown,
|
|
mimetype="text/markdown",
|
|
headers={"Content-Disposition": "attachment; filename=sales-training-report.md"},
|
|
)
|
|
|
|
|
|
@groups_bp.get("/<gid>/personas")
|
|
@require_auth
|
|
def list_personas(gid: str):
|
|
s = _stores()
|
|
group = _get_owned_group(s, gid)
|
|
actor = current_user()
|
|
raw_personas = group.get("personas")
|
|
persona_records = raw_personas if isinstance(raw_personas, list) else []
|
|
if actor.get("role") == "user":
|
|
if group.get("status") != "ready":
|
|
raise ApiError("group not ready", 403)
|
|
personas = [serialize_persona(p, actor) for p in persona_records if isinstance(p, dict)]
|
|
elif actor.get("role") == "super_admin":
|
|
personas = [serialize_persona(p, actor) for p in persona_records if isinstance(p, dict)]
|
|
else:
|
|
# admin: see persona but not the secret/process fields (IP protection)
|
|
personas = [serialize_persona(p, actor) for p in persona_records if isinstance(p, dict)]
|
|
# Attach per-user status (won/lost/not-tried) for EVERY role. The one-shot
|
|
# rule is per (user, persona): each user may chat a persona once, but the
|
|
# same persona can be trained by many different users. So my_outcome reflects
|
|
# THIS user's own finished sessions, regardless of admin/trainee role.
|
|
# Always set the key (default 'not_tried') so the frontend's all-roles logic
|
|
# never sees an undefined value; a global super_admin without an org simply
|
|
# has no org-scoped sessions and correctly shows every persona as untrained.
|
|
sess = s.get("session_store")
|
|
store = sess.sessions if sess else None
|
|
outcome_by_pid = {}
|
|
if store and isinstance(actor.get("org_id"), str):
|
|
mine = store.where(
|
|
lambda r: isinstance(r, dict)
|
|
and r.get("org_id") == actor.get("org_id")
|
|
and r.get("user_id") == actor["id"]
|
|
and r.get("group_id") == gid
|
|
and (r.get("mode") or "trainee") == "trainee"
|
|
and r.get("status") == "finished"
|
|
and r.get("outcome") in {"won", "lost"}
|
|
)
|
|
outcome_by_pid = {r.get("persona_id"): r.get("outcome") for r in mine}
|
|
for p in personas:
|
|
p["my_outcome"] = outcome_by_pid.get(p.get("id"), "not_tried")
|
|
return jsonify({"personas": personas, "tiers": ["A", "B", "C"]})
|
|
|
|
|
|
@groups_bp.get("/<gid>/personas/<pid>")
|
|
@require_auth
|
|
def get_persona(gid: str, pid: str):
|
|
s = _stores()
|
|
group = _get_owned_group(s, gid)
|
|
p = s["groups"].get_persona(gid, pid)
|
|
if not p:
|
|
raise ApiError("persona not found", 404)
|
|
actor = current_user()
|
|
# Trainees may only view personas from ready groups (parity with list_personas).
|
|
if actor.get("role") == "user" and group.get("status") != "ready":
|
|
raise ApiError("group not ready", 403)
|
|
ensure = ensure_persona_shape(p)
|
|
return jsonify({"persona": serialize_persona(ensure, actor)})
|
|
|
|
|
|
@groups_bp.put("/<gid>/personas/<pid>")
|
|
@require_auth
|
|
@require_roles("admin")
|
|
@_group_analysis_lock
|
|
def update_persona(gid: str, pid: str):
|
|
s = _stores()
|
|
_get_owned_group(s, gid)
|
|
data = request_json_object()
|
|
actor = current_user()
|
|
# IP protection: only super_admin may set/alter secret formula fields.
|
|
if actor.get("role") != "super_admin":
|
|
unknown = sorted(set(data) - ADMIN_EDITABLE_PERSONA_FIELDS)
|
|
if unknown:
|
|
raise ApiError(f"field '{unknown[0]}' is locked (super_admin only)", 403)
|
|
current = s["groups"].get_persona(gid, pid)
|
|
if current is None:
|
|
raise ApiError("persona not found", 404)
|
|
try:
|
|
validate_persona_traits(ensure_persona_shape({**current, **data, "id": pid}))
|
|
except ValueError:
|
|
raise ApiError("invalid persona traits", 400)
|
|
try:
|
|
updated = s["groups"].update_persona(gid, pid, data)
|
|
except ValueError as exc:
|
|
raise internal_error("persona not found", exc, 404)
|
|
raw_personas = updated.get("personas") if isinstance(updated, dict) else None
|
|
persona = next(
|
|
(
|
|
candidate
|
|
for candidate in raw_personas or []
|
|
if isinstance(candidate, dict) and candidate.get("id") == pid
|
|
),
|
|
None,
|
|
) if isinstance(raw_personas, list) else None
|
|
if persona is None:
|
|
raise internal_error("persona update unavailable", ValueError("updated persona missing"))
|
|
full = ensure_persona_shape(persona)
|
|
return jsonify({"persona": serialize_persona(full, actor)})
|
|
|
|
|
|
@groups_bp.post("/<gid>/personas/<pid>/variant")
|
|
@require_auth
|
|
@_group_analysis_lock
|
|
def create_persona_variant(gid: str, pid: str):
|
|
"""Create a NEW persona cloned from an existing one (fresh identity, same core traits).
|
|
|
|
Lets a trainee practice the SAME selling challenge repeatedly even though each persona
|
|
can only be chatted once — the variant is a different person with the same pain points /
|
|
personality / temperament, so the training repeats but never as an identical copy.
|
|
Anyone who has access to the group can create a variant (admin or trainee).
|
|
"""
|
|
s = _stores()
|
|
group = _get_owned_group(s, gid)
|
|
if group.get("status") != "ready":
|
|
raise ApiError("group not ready", 403)
|
|
raw_personas = group.get("personas")
|
|
persona_records = raw_personas if isinstance(raw_personas, list) else []
|
|
src = next((p for p in persona_records if isinstance(p, dict) and p.get("id") == pid), None)
|
|
if src is None:
|
|
raise ApiError("persona not found", 404)
|
|
|
|
lang = (group.get("input") or {}).get("language", "th")
|
|
try:
|
|
from ..services.persona_generator import PersonaGenerator
|
|
variant = PersonaGenerator(s["llm"]).generate_variant(
|
|
source=src,
|
|
sales_kit=group.get("sales_kit") or {},
|
|
language=lang,
|
|
)
|
|
except Exception as exc:
|
|
raise internal_error("variant failed", exc)
|
|
|
|
# Assign a unique id. Trainee-created variants belong to the trainee's private
|
|
# group; only admin-created variants extend the shared admin pool.
|
|
import uuid as _uuid
|
|
variant["id"] = f"persona-{_uuid.uuid4().hex[:10]}"
|
|
variant["source_persona_id"] = pid
|
|
actor = current_user()
|
|
target_group_id = gid
|
|
if actor.get("role") == "user":
|
|
actor_org_id = actor.get("org_id")
|
|
if not is_valid_tenant_id(actor_org_id):
|
|
raise ApiError("permission denied", 403)
|
|
try:
|
|
private_group = s["groups"].get_or_create_private_group(
|
|
org_id=actor_org_id,
|
|
owner_user_id=actor["id"],
|
|
owner_name=actor.get("name", "User"),
|
|
input_data=group.get("input") or None,
|
|
sales_kit=group.get("sales_kit") or None,
|
|
)
|
|
except ValueError as exc:
|
|
raise internal_error("private group unavailable", exc, 409)
|
|
target_group_id = private_group["id"]
|
|
# Re-read while holding the target record lock. The snapshot returned by
|
|
# get_or_create_private_group may be stale when two trainee requests append
|
|
# variants concurrently.
|
|
with s["groups"].record_lock(target_group_id):
|
|
current_private = s["groups"].get(target_group_id)
|
|
raw_private_personas = current_private.get("personas")
|
|
private_personas = (
|
|
[p for p in raw_private_personas if isinstance(p, dict)]
|
|
if isinstance(raw_private_personas, list)
|
|
else []
|
|
)
|
|
s["groups"].set_personas(
|
|
target_group_id, private_personas + [variant]
|
|
)
|
|
else:
|
|
# Admin variants extend the shared group. Serialize and re-read the
|
|
# append so concurrent admins cannot overwrite one another.
|
|
with s["groups"].record_lock(gid):
|
|
current_group = s["groups"].get(gid)
|
|
raw_current_personas = current_group.get("personas")
|
|
current_personas = (
|
|
[p for p in raw_current_personas if isinstance(p, dict)]
|
|
if isinstance(raw_current_personas, list)
|
|
else []
|
|
)
|
|
s["groups"].update(gid, personas=current_personas + [variant])
|
|
full = ensure_persona_shape(variant)
|
|
|
|
persona_out = serialize_persona(full, actor)
|
|
return jsonify({
|
|
"persona": persona_out,
|
|
"group_id": target_group_id,
|
|
"source_group_id": gid,
|
|
}), 201
|
|
|
|
|
|
@groups_bp.delete("/<gid>")
|
|
@require_auth
|
|
@require_roles("admin")
|
|
def delete_group(gid: str):
|
|
"""Delete a persona group (admin only, own org)."""
|
|
s = _stores()
|
|
# Hold the group lock while checking/deleting the group and every related
|
|
# session. Session start also takes this lock, so it cannot publish a new
|
|
# session after the cascade's snapshot and before group deletion.
|
|
with s["groups"].record_lock(gid):
|
|
group = _get_owned_group(s, gid) # also enforces tenant org (super_admin global)
|
|
raw_input = group.get("input")
|
|
upload_names = (
|
|
[name for name in raw_input.get("files", []) if isinstance(name, str)]
|
|
if isinstance(raw_input, dict) and isinstance(raw_input.get("files"), list)
|
|
else []
|
|
)
|
|
sess = s.get("session_store")
|
|
group_org_id = group.get("org_id")
|
|
if sess and hasattr(sess, "sessions"):
|
|
for r in sess.sessions.all():
|
|
if (
|
|
not isinstance(r, dict)
|
|
or r.get("group_id") != gid
|
|
or r.get("org_id") != group_org_id
|
|
):
|
|
continue
|
|
key = r.get("id") or r.get("sid")
|
|
if not key:
|
|
continue
|
|
with sess.sessions.record_lock(key):
|
|
current = sess.sessions.get_or_none(key)
|
|
if (
|
|
isinstance(current, dict)
|
|
and current.get("group_id") == gid
|
|
and current.get("org_id") == group_org_id
|
|
):
|
|
sess.sessions.delete(key)
|
|
s["groups"].delete(gid)
|
|
_cleanup_uploads(upload_names)
|
|
return jsonify({"ok": True, "deleted": gid})
|
|
|
|
|
|
@groups_bp.post("/<gid>/reanalyze")
|
|
@require_auth
|
|
@require_roles("admin")
|
|
def reanalyze_group(gid: str):
|
|
return analyze_group(gid)
|