ceshi
This commit is contained in:
1 parent
1ffead7ee2
commit
5f11926db5
14 files changed
+2031
-94
No files matched your search
@@ -51,13 +51,14 @@ from app.gateway.routers import (
|
||||
models,
|
||||
multi_agent,
|
||||
notifications,
|
||||
notification_templates,
|
||||
open_3qfx,
|
||||
open_chat,
|
||||
parallel_agent_tasks,
|
||||
parallel_agents,
|
||||
position_roundtable,
|
||||
positions,
|
||||
position_roles,
|
||||
parallel_agent_tasks,
|
||||
parallel_agents,
|
||||
position_roundtable,
|
||||
positions,
|
||||
position_roles,
|
||||
public_config,
|
||||
public_embed,
|
||||
public_leaderboard,
|
||||
@@ -858,9 +859,9 @@ async def _concurrency_sampler_loop(app: FastAPI) -> None:
|
||||
logger.info("Concurrency sampler disabled by CONCURRENCY_SAMPLE_ENABLED")
|
||||
return
|
||||
|
||||
store = getattr(app.state, "concurrency_sample_store", None)
|
||||
run_mgr = getattr(app.state, "run_manager", None)
|
||||
concurrency_gate = getattr(app.state, "concurrency_gate", None)
|
||||
store = getattr(app.state, "concurrency_sample_store", None)
|
||||
run_mgr = getattr(app.state, "run_manager", None)
|
||||
concurrency_gate = getattr(app.state, "concurrency_gate", None)
|
||||
if store is None or run_mgr is None:
|
||||
logger.info("Concurrency sampler not started (no store / run manager — memory backend?)")
|
||||
return
|
||||
@@ -881,16 +882,16 @@ async def _concurrency_sampler_loop(app: FastAPI) -> None:
|
||||
try:
|
||||
# Runtime toggle (admin can turn sampling off without a restart).
|
||||
# mtime-cached read, so this is cheap every tick.
|
||||
from deerflow.config.system_settings import get_concurrency_monitor_settings
|
||||
|
||||
if get_concurrency_monitor_settings().enabled:
|
||||
active_count = None
|
||||
if concurrency_gate is not None:
|
||||
active_count = await concurrency_gate.count_active()
|
||||
if active_count is None:
|
||||
active = await run_mgr.list_active()
|
||||
active_count = len(active)
|
||||
await store.record(active_count)
|
||||
from deerflow.config.system_settings import get_concurrency_monitor_settings
|
||||
|
||||
if get_concurrency_monitor_settings().enabled:
|
||||
active_count = None
|
||||
if concurrency_gate is not None:
|
||||
active_count = await concurrency_gate.count_active()
|
||||
if active_count is None:
|
||||
active = await run_mgr.list_active()
|
||||
active_count = len(active)
|
||||
await store.record(active_count)
|
||||
ticks += 1
|
||||
if ticks % purge_every_ticks == 0:
|
||||
from datetime import UTC, datetime, timedelta
|
||||
@@ -1338,18 +1339,18 @@ This gateway provides custom endpoints for models, MCP configuration, skills, an
|
||||
v = os.environ.get("GATEWAY_CORS_ALLOW_ALL", "").strip().lower()
|
||||
return v in ("1", "true", "yes", "on") or is_auth_disabled()
|
||||
|
||||
# The legacy TaskCOP Vue application uses Vite's default development port.
|
||||
# Keep these origins available even when deployments configure additional
|
||||
# origins through GATEWAY_CORS_ORIGINS.
|
||||
taskcop_vite_origins = [
|
||||
"http://localhost:8080",
|
||||
"http://127.0.0.1:8080",
|
||||
]
|
||||
|
||||
cors_origins_env = os.environ.get("GATEWAY_CORS_ORIGINS", "").strip()
|
||||
cors_origins: list[str] = [o.strip() for o in cors_origins_env.split(",") if o.strip()] if cors_origins_env else []
|
||||
if cors_origins:
|
||||
cors_origins = list(dict.fromkeys([*cors_origins, *taskcop_vite_origins]))
|
||||
# The legacy TaskCOP Vue application uses Vite's default development port.
|
||||
# Keep these origins available even when deployments configure additional
|
||||
# origins through GATEWAY_CORS_ORIGINS.
|
||||
taskcop_vite_origins = [
|
||||
"http://localhost:8080",
|
||||
"http://127.0.0.1:8080",
|
||||
]
|
||||
|
||||
cors_origins_env = os.environ.get("GATEWAY_CORS_ORIGINS", "").strip()
|
||||
cors_origins: list[str] = [o.strip() for o in cors_origins_env.split(",") if o.strip()] if cors_origins_env else []
|
||||
if cors_origins:
|
||||
cors_origins = list(dict.fromkeys([*cors_origins, *taskcop_vite_origins]))
|
||||
|
||||
# Headers the LangGraph SDK / browser clients need to read from cross-origin
|
||||
# responses. Without exposing them, the SDK's `response.headers.get(...)` returns
|
||||
@@ -1408,10 +1409,10 @@ This gateway provides custom endpoints for models, MCP configuration, skills, an
|
||||
"http://127.0.0.1:5173",
|
||||
"http://localhost:5174",
|
||||
"http://127.0.0.1:5174",
|
||||
"http://localhost:3000",
|
||||
"http://127.0.0.1:3000",
|
||||
*taskcop_vite_origins,
|
||||
]
|
||||
"http://localhost:3000",
|
||||
"http://127.0.0.1:3000",
|
||||
*taskcop_vite_origins,
|
||||
]
|
||||
logger.warning(
|
||||
"No CORS configuration found; enabling local dev origins only: %s. "
|
||||
"Set GATEWAY_CORS_ORIGINS or GATEWAY_CORS_ALLOW_ALL for deployment.",
|
||||
@@ -1471,25 +1472,25 @@ This gateway provides custom endpoints for models, MCP configuration, skills, an
|
||||
# Step3 流程图结构化抽取 + 校验 (SSE) at /api/flow-extract
|
||||
app.include_router(flow_extract.router)
|
||||
|
||||
# Roundtable-planning business chains at /api/roundtable-chains
|
||||
app.include_router(roundtable_chains.router)
|
||||
|
||||
# 岗位协同独立会话 / 节点状态(不使用原圆桌总控或后台作业)
|
||||
# Canonical position-workspace persistence API.
|
||||
app.include_router(position_roundtable.router, prefix="/api")
|
||||
# Compatibility route for intranet gateways whose allowlist only exposes
|
||||
# the established `/api/multi-agent/*` namespace.
|
||||
app.include_router(
|
||||
position_roundtable.router,
|
||||
prefix="/api/multi-agent",
|
||||
include_in_schema=False,
|
||||
)
|
||||
# Roundtable-planning business chains at /api/roundtable-chains
|
||||
app.include_router(roundtable_chains.router)
|
||||
|
||||
# 岗位协同独立会话 / 节点状态(不使用原圆桌总控或后台作业)
|
||||
# Canonical position-workspace persistence API.
|
||||
app.include_router(position_roundtable.router, prefix="/api")
|
||||
# Compatibility route for intranet gateways whose allowlist only exposes
|
||||
# the established `/api/multi-agent/*` namespace.
|
||||
app.include_router(
|
||||
position_roundtable.router,
|
||||
prefix="/api/multi-agent",
|
||||
include_in_schema=False,
|
||||
)
|
||||
|
||||
# Global business ? agent / chain mapping at /api/business-mapping
|
||||
app.include_router(business_mapping.router)
|
||||
|
||||
# Position-roundtable work-view role configuration at /api/position-roles.
|
||||
app.include_router(position_roles.router)
|
||||
app.include_router(business_mapping.router)
|
||||
|
||||
# Position-roundtable work-view role configuration at /api/position-roles.
|
||||
app.include_router(position_roles.router)
|
||||
|
||||
# Light-app registry (?????) at /api/light-apps
|
||||
app.include_router(light_apps.router)
|
||||
@@ -1508,6 +1509,7 @@ This gateway provides custom endpoints for models, MCP configuration, skills, an
|
||||
|
||||
# Task-workspace configurable jump buttons (按钮管理) at /api/task-buttons
|
||||
app.include_router(task_buttons.router)
|
||||
app.include_router(notification_templates.router)
|
||||
|
||||
# Temporary compatibility bridge for the TaskCOP situation-overview frontend.
|
||||
app.include_router(taskcop_tasks.router)
|
||||
|
||||
@@ -255,23 +255,23 @@ async def langgraph_runtime(app: FastAPI) -> AsyncGenerator[None, None]:
|
||||
|
||||
app.state.roundtable_draft_share_store = make_roundtable_draft_share_store(sf)
|
||||
|
||||
from deerflow.persistence.roundtable_chains import make_roundtable_chain_store
|
||||
|
||||
app.state.roundtable_chain_store = make_roundtable_chain_store(sf)
|
||||
|
||||
# 独立的岗位协同 Session / Node 存储。它只索引业务流程状态,真实消息和
|
||||
# 文件仍复用 LangGraph thread/checkpoint 与现有 artifact API。
|
||||
from deerflow.persistence.position_roundtable import make_position_roundtable_store
|
||||
|
||||
app.state.position_roundtable_store = make_position_roundtable_store(sf)
|
||||
|
||||
# 岗位会商工作视角(名称 / 顺序 / 特殊意图岗)是全局配置,和组织/RBAC
|
||||
# 岗位分开保存。启动只补齐缺失内置项,不覆盖管理员的既有修改。
|
||||
from app.gateway.position_role_defaults import POSITION_ROLE_SEED
|
||||
from deerflow.persistence.position_roles import make_position_role_store
|
||||
|
||||
app.state.position_role_store = make_position_role_store(sf)
|
||||
await app.state.position_role_store.ensure_seed(POSITION_ROLE_SEED)
|
||||
from deerflow.persistence.roundtable_chains import make_roundtable_chain_store
|
||||
|
||||
app.state.roundtable_chain_store = make_roundtable_chain_store(sf)
|
||||
|
||||
# 独立的岗位协同 Session / Node 存储。它只索引业务流程状态,真实消息和
|
||||
# 文件仍复用 LangGraph thread/checkpoint 与现有 artifact API。
|
||||
from deerflow.persistence.position_roundtable import make_position_roundtable_store
|
||||
|
||||
app.state.position_roundtable_store = make_position_roundtable_store(sf)
|
||||
|
||||
# 岗位会商工作视角(名称 / 顺序 / 特殊意图岗)是全局配置,和组织/RBAC
|
||||
# 岗位分开保存。启动只补齐缺失内置项,不覆盖管理员的既有修改。
|
||||
from app.gateway.position_role_defaults import POSITION_ROLE_SEED
|
||||
from deerflow.persistence.position_roles import make_position_role_store
|
||||
|
||||
app.state.position_role_store = make_position_role_store(sf)
|
||||
await app.state.position_role_store.ensure_seed(POSITION_ROLE_SEED)
|
||||
|
||||
from deerflow.persistence.business_mapping import make_business_mapping_store
|
||||
|
||||
@@ -295,17 +295,21 @@ async def langgraph_runtime(app: FastAPI) -> AsyncGenerator[None, None]:
|
||||
|
||||
from deerflow.persistence.task_buttons import make_task_button_store
|
||||
|
||||
app.state.task_button_store = make_task_button_store(sf)
|
||||
|
||||
from deerflow.persistence.taskcop_tasks import make_taskcop_task_store
|
||||
|
||||
app.state.taskcop_task_store = make_taskcop_task_store(sf)
|
||||
|
||||
from deerflow.persistence.task_reports import make_task_report_store
|
||||
|
||||
app.state.task_report_store = make_task_report_store(sf)
|
||||
|
||||
from deerflow.persistence.parallel_agent_tasks import make_parallel_agent_task_store
|
||||
app.state.task_button_store = make_task_button_store(sf)
|
||||
|
||||
from deerflow.persistence.notification_templates import make_notification_template_store
|
||||
|
||||
app.state.notification_template_store = make_notification_template_store(sf)
|
||||
|
||||
from deerflow.persistence.taskcop_tasks import make_taskcop_task_store
|
||||
|
||||
app.state.taskcop_task_store = make_taskcop_task_store(sf)
|
||||
|
||||
from deerflow.persistence.task_reports import make_task_report_store
|
||||
|
||||
app.state.task_report_store = make_task_report_store(sf)
|
||||
|
||||
from deerflow.persistence.parallel_agent_tasks import make_parallel_agent_task_store
|
||||
|
||||
app.state.parallel_agent_task_store = make_parallel_agent_task_store(sf)
|
||||
|
||||
@@ -389,11 +393,11 @@ async def langgraph_runtime(app: FastAPI) -> AsyncGenerator[None, None]:
|
||||
run_events_config = getattr(config, "run_events", None)
|
||||
app.state.run_event_store = make_run_event_store(run_events_config)
|
||||
|
||||
# RunManager with store backing for persistence
|
||||
app.state.run_manager = RunManager(store=app.state.run_store)
|
||||
from deerflow.runtime import make_redis_concurrency_gate
|
||||
|
||||
app.state.concurrency_gate = make_redis_concurrency_gate(config)
|
||||
# RunManager with store backing for persistence
|
||||
app.state.run_manager = RunManager(store=app.state.run_store)
|
||||
from deerflow.runtime import make_redis_concurrency_gate
|
||||
|
||||
app.state.concurrency_gate = make_redis_concurrency_gate(config)
|
||||
|
||||
try:
|
||||
yield
|
||||
@@ -407,10 +411,10 @@ async def langgraph_runtime(app: FastAPI) -> AsyncGenerator[None, None]:
|
||||
|
||||
await queue.stop()
|
||||
set_auto_ingest_queue(None)
|
||||
await close_engine()
|
||||
gate = getattr(app.state, "concurrency_gate", None)
|
||||
if gate is not None:
|
||||
await gate.aclose()
|
||||
await close_engine()
|
||||
gate = getattr(app.state, "concurrency_gate", None)
|
||||
if gate is not None:
|
||||
await gate.aclose()
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
@@ -436,12 +440,12 @@ get_run_manager: Callable[[Request], RunManager] = _require("run_manager", "Run
|
||||
get_checkpointer: Callable[[Request], Checkpointer] = _require("checkpointer", "Checkpointer")
|
||||
get_run_event_store: Callable[[Request], RunEventStore] = _require("run_event_store", "Run event store")
|
||||
get_feedback_repo: Callable[[Request], FeedbackRepository] = _require("feedback_repo", "Feedback")
|
||||
get_run_store: Callable[[Request], RunStore] = _require("run_store", "Run store")
|
||||
|
||||
|
||||
def get_concurrency_gate(request: Request):
|
||||
"""Return the optional cross-worker concurrency gate."""
|
||||
return getattr(request.app.state, "concurrency_gate", None)
|
||||
get_run_store: Callable[[Request], RunStore] = _require("run_store", "Run store")
|
||||
|
||||
|
||||
def get_concurrency_gate(request: Request):
|
||||
"""Return the optional cross-worker concurrency gate."""
|
||||
return getattr(request.app.state, "concurrency_gate", None)
|
||||
|
||||
|
||||
def get_store(request: Request):
|
||||
|
||||
@@ -0,0 +1,307 @@
|
||||
"""Notification template management API (通知模板管理).
|
||||
|
||||
Global / shared templates for admin-authored notification messages. Every
|
||||
endpoint (including reads) requires ``system_role == "admin"``.
|
||||
|
||||
Routes (prefix ``/api/notification-templates``):
|
||||
GET "" list (keyword / enabled / tag / page / page_size)
|
||||
POST "" create
|
||||
GET "/{id}" read one
|
||||
PUT "/{id}" update (optimistic lock via expected_version)
|
||||
DELETE "/{id}" delete
|
||||
POST "/{id}/duplicate" duplicate
|
||||
POST "/preview" render title/content with variables
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
|
||||
from fastapi import APIRouter, HTTPException, Query, Request, Response
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from app.gateway.deps import get_current_user, get_optional_user_from_request
|
||||
from deerflow.persistence.notification_templates import (
|
||||
DuplicateNotificationTemplateNameError,
|
||||
NotificationTemplateStore,
|
||||
TemplateVariableError,
|
||||
VersionConflictError,
|
||||
preview_templates,
|
||||
validate_templates,
|
||||
)
|
||||
|
||||
router = APIRouter(prefix="/api/notification-templates", tags=["notification-templates"])
|
||||
|
||||
|
||||
# ── schemas ──────────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
class NotificationTemplateResponse(BaseModel):
|
||||
id: str
|
||||
name: str
|
||||
title_template: str
|
||||
content_template: str
|
||||
tags: list[str] = Field(default_factory=list)
|
||||
enabled: bool = True
|
||||
version: int = 1
|
||||
created_by: str | None = None
|
||||
created_at: datetime | str | None = None
|
||||
updated_at: datetime | str | None = None
|
||||
|
||||
|
||||
class NotificationTemplateListResponse(BaseModel):
|
||||
items: list[NotificationTemplateResponse]
|
||||
total: int
|
||||
page: int
|
||||
page_size: int
|
||||
|
||||
|
||||
class NotificationTemplateCreateRequest(BaseModel):
|
||||
name: str = Field(..., min_length=1, max_length=80)
|
||||
title_template: str = Field(..., min_length=1, max_length=120)
|
||||
content_template: str = Field(..., min_length=1, max_length=5000)
|
||||
tags: list[str] = Field(default_factory=list)
|
||||
enabled: bool = True
|
||||
|
||||
|
||||
class NotificationTemplateUpdateRequest(BaseModel):
|
||||
name: str = Field(..., min_length=1, max_length=80)
|
||||
title_template: str = Field(..., min_length=1, max_length=120)
|
||||
content_template: str = Field(..., min_length=1, max_length=5000)
|
||||
tags: list[str] = Field(default_factory=list)
|
||||
enabled: bool = True
|
||||
expected_version: int = Field(..., ge=1)
|
||||
|
||||
|
||||
class PreviewRequest(BaseModel):
|
||||
title_template: str = Field(..., min_length=0, max_length=120)
|
||||
content_template: str = Field(..., min_length=0, max_length=5000)
|
||||
variables: dict[str, str] = Field(default_factory=dict)
|
||||
|
||||
|
||||
class PreviewResponse(BaseModel):
|
||||
title: str
|
||||
content: str
|
||||
missing_variables: list[str] = Field(default_factory=list)
|
||||
|
||||
|
||||
# ── helpers ──────────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
def _get_store(request: Request) -> NotificationTemplateStore:
|
||||
store = getattr(request.app.state, "notification_template_store", None)
|
||||
if store is None:
|
||||
raise HTTPException(status_code=503, detail="Notification template store not available")
|
||||
return store
|
||||
|
||||
|
||||
async def _require_admin(request: Request) -> None:
|
||||
"""Reject non-admins. Lets the call through when auth is disabled."""
|
||||
user = await get_optional_user_from_request(request)
|
||||
if user is None:
|
||||
return
|
||||
if getattr(user, "system_role", None) != "admin":
|
||||
raise HTTPException(status_code=403, detail="通知模板管理仅限管理员")
|
||||
|
||||
|
||||
def _normalize_name(name: str) -> str:
|
||||
cleaned = (name or "").strip()
|
||||
if not (2 <= len(cleaned) <= 50):
|
||||
raise HTTPException(status_code=422, detail="名称去除首尾空格后长度须为 2~50")
|
||||
return cleaned
|
||||
|
||||
|
||||
def _normalize_tags(tags: list[str] | None) -> list[str]:
|
||||
seen: set[str] = set()
|
||||
out: list[str] = []
|
||||
for raw in tags or []:
|
||||
tag = (raw or "").strip()
|
||||
if not tag:
|
||||
continue
|
||||
if not (1 <= len(tag) <= 20):
|
||||
raise HTTPException(status_code=422, detail="单个标签长度须为 1~20")
|
||||
if tag in seen:
|
||||
continue
|
||||
seen.add(tag)
|
||||
out.append(tag)
|
||||
if len(out) > 5:
|
||||
raise HTTPException(status_code=422, detail="标签最多 5 个")
|
||||
return out
|
||||
|
||||
|
||||
def _validate_lengths(title: str, content: str) -> None:
|
||||
if not (1 <= len(title) <= 120):
|
||||
raise HTTPException(status_code=422, detail="标题模板长度须为 1~120")
|
||||
if not (1 <= len(content) <= 5000):
|
||||
raise HTTPException(status_code=422, detail="正文模板长度须为 1~5000")
|
||||
|
||||
|
||||
def _validate_variables(title: str, content: str) -> None:
|
||||
try:
|
||||
validate_templates(title, content)
|
||||
except TemplateVariableError as exc:
|
||||
raise HTTPException(status_code=422, detail=exc.message) from exc
|
||||
|
||||
|
||||
def _to_response(row: dict) -> NotificationTemplateResponse:
|
||||
return NotificationTemplateResponse(**row)
|
||||
|
||||
|
||||
async def _unique_duplicate_name(store: NotificationTemplateStore, original: str) -> str:
|
||||
base = f"{original} - 副本"
|
||||
if not await store.name_exists(base):
|
||||
return base
|
||||
n = 2
|
||||
while True:
|
||||
candidate = f"{original} - 副本 {n}"
|
||||
if not await store.name_exists(candidate):
|
||||
return candidate
|
||||
n += 1
|
||||
|
||||
|
||||
# ── routes ───────────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
@router.get("", response_model=NotificationTemplateListResponse)
|
||||
async def list_notification_templates(
|
||||
request: Request,
|
||||
keyword: str | None = Query(default=None),
|
||||
enabled: bool | None = Query(default=None),
|
||||
tag: str | None = Query(default=None),
|
||||
page: int = Query(default=1, ge=1),
|
||||
page_size: int = Query(default=20, ge=1, le=100),
|
||||
) -> NotificationTemplateListResponse:
|
||||
await _require_admin(request)
|
||||
store = _get_store(request)
|
||||
items, total = await store.list_templates(
|
||||
keyword=keyword,
|
||||
enabled=enabled,
|
||||
tag=tag,
|
||||
page=page,
|
||||
page_size=page_size,
|
||||
)
|
||||
return NotificationTemplateListResponse(
|
||||
items=[_to_response(r) for r in items],
|
||||
total=total,
|
||||
page=page,
|
||||
page_size=page_size,
|
||||
)
|
||||
|
||||
|
||||
@router.post("/preview", response_model=PreviewResponse)
|
||||
async def preview_notification_template(request: Request, body: PreviewRequest) -> PreviewResponse:
|
||||
await _require_admin(request)
|
||||
result = preview_templates(body.title_template, body.content_template, body.variables)
|
||||
return PreviewResponse(**result) # type: ignore[arg-type]
|
||||
|
||||
|
||||
@router.post("", response_model=NotificationTemplateResponse, status_code=201)
|
||||
async def create_notification_template(
|
||||
request: Request,
|
||||
body: NotificationTemplateCreateRequest,
|
||||
) -> NotificationTemplateResponse:
|
||||
await _require_admin(request)
|
||||
name = _normalize_name(body.name)
|
||||
tags = _normalize_tags(body.tags)
|
||||
_validate_lengths(body.title_template, body.content_template)
|
||||
_validate_variables(body.title_template, body.content_template)
|
||||
store = _get_store(request)
|
||||
user_id = await get_current_user(request)
|
||||
try:
|
||||
row = await store.create_template(
|
||||
{
|
||||
"name": name,
|
||||
"title_template": body.title_template,
|
||||
"content_template": body.content_template,
|
||||
"tags": tags,
|
||||
"enabled": body.enabled,
|
||||
"created_by": user_id,
|
||||
}
|
||||
)
|
||||
except DuplicateNotificationTemplateNameError:
|
||||
raise HTTPException(status_code=409, detail="模板名称已存在")
|
||||
return _to_response(row)
|
||||
|
||||
|
||||
@router.get("/{template_id}", response_model=NotificationTemplateResponse)
|
||||
async def get_notification_template(request: Request, template_id: str) -> NotificationTemplateResponse:
|
||||
await _require_admin(request)
|
||||
store = _get_store(request)
|
||||
row = await store.get_template(template_id)
|
||||
if row is None:
|
||||
raise HTTPException(status_code=404, detail="模板不存在")
|
||||
return _to_response(row)
|
||||
|
||||
|
||||
@router.put("/{template_id}", response_model=NotificationTemplateResponse)
|
||||
async def update_notification_template(
|
||||
request: Request,
|
||||
template_id: str,
|
||||
body: NotificationTemplateUpdateRequest,
|
||||
) -> NotificationTemplateResponse:
|
||||
await _require_admin(request)
|
||||
name = _normalize_name(body.name)
|
||||
tags = _normalize_tags(body.tags)
|
||||
_validate_lengths(body.title_template, body.content_template)
|
||||
_validate_variables(body.title_template, body.content_template)
|
||||
store = _get_store(request)
|
||||
try:
|
||||
row = await store.update_template(
|
||||
template_id,
|
||||
{
|
||||
"name": name,
|
||||
"title_template": body.title_template,
|
||||
"content_template": body.content_template,
|
||||
"tags": tags,
|
||||
"enabled": body.enabled,
|
||||
},
|
||||
expected_version=body.expected_version,
|
||||
)
|
||||
except VersionConflictError as exc:
|
||||
raise HTTPException(
|
||||
status_code=409,
|
||||
detail={"message": "版本冲突,请重新加载或覆盖保存", "server": exc.server},
|
||||
) from exc
|
||||
except DuplicateNotificationTemplateNameError:
|
||||
raise HTTPException(status_code=409, detail="模板名称已存在")
|
||||
if row is None:
|
||||
raise HTTPException(status_code=404, detail="模板不存在")
|
||||
return _to_response(row)
|
||||
|
||||
|
||||
@router.delete("/{template_id}", status_code=204)
|
||||
async def delete_notification_template(request: Request, template_id: str) -> Response:
|
||||
await _require_admin(request)
|
||||
store = _get_store(request)
|
||||
deleted = await store.delete_template(template_id)
|
||||
if not deleted:
|
||||
raise HTTPException(status_code=404, detail="模板不存在")
|
||||
return Response(status_code=204)
|
||||
|
||||
|
||||
@router.post("/{template_id}/duplicate", response_model=NotificationTemplateResponse, status_code=201)
|
||||
async def duplicate_notification_template(
|
||||
request: Request,
|
||||
template_id: str,
|
||||
) -> NotificationTemplateResponse:
|
||||
await _require_admin(request)
|
||||
store = _get_store(request)
|
||||
source = await store.get_template(template_id)
|
||||
if source is None:
|
||||
raise HTTPException(status_code=404, detail="模板不存在")
|
||||
new_name = await _unique_duplicate_name(store, source["name"])
|
||||
user_id = await get_current_user(request)
|
||||
try:
|
||||
row = await store.create_template(
|
||||
{
|
||||
"name": new_name,
|
||||
"title_template": source["title_template"],
|
||||
"content_template": source["content_template"],
|
||||
"tags": list(source.get("tags") or []),
|
||||
"enabled": source.get("enabled", True),
|
||||
"created_by": user_id,
|
||||
}
|
||||
)
|
||||
except DuplicateNotificationTemplateNameError:
|
||||
raise HTTPException(status_code=409, detail="模板名称已存在")
|
||||
return _to_response(row)
|
||||
+2
@@ -45,6 +45,7 @@ from deerflow.persistence.llm_metrics.model import LlmCallMetricRow
|
||||
from deerflow.persistence.memory_config.model import UserMemoryConfigRow
|
||||
from deerflow.persistence.menu_overrides.model import MenuOverrideRow
|
||||
from deerflow.persistence.models.run_event import RunEventRow
|
||||
from deerflow.persistence.notification_templates.model import NotificationTemplateRow
|
||||
from deerflow.persistence.notifications.model import NotificationRow
|
||||
from deerflow.persistence.parallel_agent_tasks.model import ParallelAgentTaskRow
|
||||
from deerflow.persistence.position_roles.model import PositionRoleRow
|
||||
@@ -110,6 +111,7 @@ __all__ = [
|
||||
"LlmCallMetricRow",
|
||||
"MenuOverrideRow",
|
||||
"NotificationRow",
|
||||
"NotificationTemplateRow",
|
||||
"ParallelAgentTaskRow",
|
||||
"PositionRoundtableNodeRow",
|
||||
"PositionRoundtableSessionRow",
|
||||
|
||||
+38
@@ -0,0 +1,38 @@
|
||||
"""Notification template persistence (通知模板管理)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from deerflow.persistence.notification_templates.base import (
|
||||
DuplicateNotificationTemplateNameError,
|
||||
NotificationTemplateStore,
|
||||
VersionConflictError,
|
||||
)
|
||||
from deerflow.persistence.notification_templates.memory import MemoryNotificationTemplateStore
|
||||
from deerflow.persistence.notification_templates.model import NotificationTemplateRow
|
||||
from deerflow.persistence.notification_templates.sql import NotificationTemplateRepository
|
||||
from deerflow.persistence.notification_templates.variables import (
|
||||
ALLOWED_VARIABLES,
|
||||
TemplateVariableError,
|
||||
preview_templates,
|
||||
validate_templates,
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
"ALLOWED_VARIABLES",
|
||||
"DuplicateNotificationTemplateNameError",
|
||||
"MemoryNotificationTemplateStore",
|
||||
"NotificationTemplateRepository",
|
||||
"NotificationTemplateRow",
|
||||
"NotificationTemplateStore",
|
||||
"TemplateVariableError",
|
||||
"VersionConflictError",
|
||||
"make_notification_template_store",
|
||||
"preview_templates",
|
||||
"validate_templates",
|
||||
]
|
||||
|
||||
|
||||
def make_notification_template_store(session_factory):
|
||||
if session_factory is None:
|
||||
return MemoryNotificationTemplateStore()
|
||||
return NotificationTemplateRepository(session_factory)
|
||||
+69
@@ -0,0 +1,69 @@
|
||||
"""Abstract notification-template persistence API.
|
||||
|
||||
Global / shared store: no ``user_id`` scoping. The router gates every endpoint
|
||||
behind admin. ``created_by`` is audit-only.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from abc import ABC, abstractmethod
|
||||
from typing import Any
|
||||
|
||||
|
||||
class DuplicateNotificationTemplateNameError(ValueError):
|
||||
"""Raised when creating/updating would collide on the unique name."""
|
||||
|
||||
|
||||
class VersionConflictError(Exception):
|
||||
"""Raised when ``expected_version`` does not match the stored version."""
|
||||
|
||||
def __init__(self, server: dict[str, Any]) -> None:
|
||||
super().__init__("version conflict")
|
||||
self.server = server
|
||||
|
||||
|
||||
class NotificationTemplateStore(ABC):
|
||||
@abstractmethod
|
||||
async def list_templates(
|
||||
self,
|
||||
*,
|
||||
keyword: str | None = None,
|
||||
enabled: bool | None = None,
|
||||
tag: str | None = None,
|
||||
page: int = 1,
|
||||
page_size: int = 20,
|
||||
) -> tuple[list[dict[str, Any]], int]:
|
||||
"""Return ``(items, total)`` newest-first with optional filters."""
|
||||
raise NotImplementedError
|
||||
|
||||
@abstractmethod
|
||||
async def get_template(self, template_id: str) -> dict[str, Any] | None:
|
||||
raise NotImplementedError
|
||||
|
||||
@abstractmethod
|
||||
async def create_template(self, data: dict[str, Any]) -> dict[str, Any]:
|
||||
"""Create a template. Raises ``DuplicateNotificationTemplateNameError``."""
|
||||
raise NotImplementedError
|
||||
|
||||
@abstractmethod
|
||||
async def update_template(
|
||||
self,
|
||||
template_id: str,
|
||||
data: dict[str, Any],
|
||||
*,
|
||||
expected_version: int,
|
||||
) -> dict[str, Any] | None:
|
||||
"""Update with optimistic lock. Returns None if missing.
|
||||
|
||||
Raises ``VersionConflictError`` (with ``.server``) on mismatch, or
|
||||
``DuplicateNotificationTemplateNameError`` on a name clash.
|
||||
"""
|
||||
raise NotImplementedError
|
||||
|
||||
@abstractmethod
|
||||
async def delete_template(self, template_id: str) -> bool:
|
||||
raise NotImplementedError
|
||||
|
||||
@abstractmethod
|
||||
async def name_exists(self, name: str, *, exclude_id: str | None = None) -> bool:
|
||||
raise NotImplementedError
|
||||
+135
@@ -0,0 +1,135 @@
|
||||
"""In-memory notification-template store (tests / no-DB)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import uuid
|
||||
from datetime import UTC, datetime
|
||||
from typing import Any
|
||||
|
||||
from deerflow.persistence.notification_templates.base import (
|
||||
DuplicateNotificationTemplateNameError,
|
||||
NotificationTemplateStore,
|
||||
VersionConflictError,
|
||||
)
|
||||
|
||||
_WRITABLE = {
|
||||
"name",
|
||||
"title_template",
|
||||
"content_template",
|
||||
"tags",
|
||||
"enabled",
|
||||
}
|
||||
|
||||
|
||||
class MemoryNotificationTemplateStore(NotificationTemplateStore):
|
||||
def __init__(self) -> None:
|
||||
self._rows: dict[str, dict[str, Any]] = {}
|
||||
|
||||
@staticmethod
|
||||
def _public(row: dict[str, Any]) -> dict[str, Any]:
|
||||
out = dict(row)
|
||||
out["tags"] = list(out.get("tags") or [])
|
||||
return out
|
||||
|
||||
def _name_taken(self, name: str, *, exclude_id: str | None = None) -> bool:
|
||||
return any(r["name"] == name and r["id"] != exclude_id for r in self._rows.values())
|
||||
|
||||
async def name_exists(self, name: str, *, exclude_id: str | None = None) -> bool:
|
||||
return self._name_taken(name, exclude_id=exclude_id)
|
||||
|
||||
def _matches(
|
||||
self,
|
||||
row: dict[str, Any],
|
||||
*,
|
||||
keyword: str | None,
|
||||
enabled: bool | None,
|
||||
tag: str | None,
|
||||
) -> bool:
|
||||
if enabled is not None and bool(row.get("enabled")) is not enabled:
|
||||
return False
|
||||
if tag is not None and tag not in (row.get("tags") or []):
|
||||
return False
|
||||
if keyword:
|
||||
needle = keyword.strip().lower()
|
||||
if needle:
|
||||
hay = " ".join(
|
||||
[
|
||||
str(row.get("name") or ""),
|
||||
str(row.get("title_template") or ""),
|
||||
str(row.get("content_template") or ""),
|
||||
]
|
||||
).lower()
|
||||
if needle not in hay:
|
||||
return False
|
||||
return True
|
||||
|
||||
async def list_templates(
|
||||
self,
|
||||
*,
|
||||
keyword: str | None = None,
|
||||
enabled: bool | None = None,
|
||||
tag: str | None = None,
|
||||
page: int = 1,
|
||||
page_size: int = 20,
|
||||
) -> tuple[list[dict[str, Any]], int]:
|
||||
rows = [
|
||||
r
|
||||
for r in self._rows.values()
|
||||
if self._matches(r, keyword=keyword, enabled=enabled, tag=tag)
|
||||
]
|
||||
rows.sort(key=lambda r: r.get("created_at", ""), reverse=True)
|
||||
total = len(rows)
|
||||
page = max(1, page)
|
||||
page_size = max(1, page_size)
|
||||
start = (page - 1) * page_size
|
||||
items = [self._public(r) for r in rows[start : start + page_size]]
|
||||
return items, total
|
||||
|
||||
async def get_template(self, template_id: str) -> dict[str, Any] | None:
|
||||
row = self._rows.get(template_id)
|
||||
return self._public(row) if row is not None else None
|
||||
|
||||
async def create_template(self, data: dict[str, Any]) -> dict[str, Any]:
|
||||
if self._name_taken(data["name"]):
|
||||
raise DuplicateNotificationTemplateNameError(data["name"])
|
||||
now = datetime.now(UTC).isoformat()
|
||||
template_id = data.get("id") or uuid.uuid4().hex[:12]
|
||||
row = {
|
||||
"id": template_id,
|
||||
"name": data["name"],
|
||||
"title_template": data["title_template"],
|
||||
"content_template": data["content_template"],
|
||||
"tags": list(data.get("tags") or []),
|
||||
"enabled": data.get("enabled", True),
|
||||
"version": 1,
|
||||
"created_by": data.get("created_by"),
|
||||
"created_at": now,
|
||||
"updated_at": now,
|
||||
}
|
||||
self._rows[template_id] = row
|
||||
return self._public(row)
|
||||
|
||||
async def update_template(
|
||||
self,
|
||||
template_id: str,
|
||||
data: dict[str, Any],
|
||||
*,
|
||||
expected_version: int,
|
||||
) -> dict[str, Any] | None:
|
||||
row = self._rows.get(template_id)
|
||||
if row is None:
|
||||
return None
|
||||
if int(row["version"]) != int(expected_version):
|
||||
raise VersionConflictError(self._public(row))
|
||||
new_name = data.get("name")
|
||||
if new_name is not None and new_name != row["name"] and self._name_taken(new_name, exclude_id=template_id):
|
||||
raise DuplicateNotificationTemplateNameError(new_name)
|
||||
for key, value in data.items():
|
||||
if key in _WRITABLE:
|
||||
row[key] = value
|
||||
row["version"] = int(row["version"]) + 1
|
||||
row["updated_at"] = datetime.now(UTC).isoformat()
|
||||
return self._public(row)
|
||||
|
||||
async def delete_template(self, template_id: str) -> bool:
|
||||
return self._rows.pop(template_id, None) is not None
|
||||
+35
@@ -0,0 +1,35 @@
|
||||
"""ORM model for notification templates (通知模板管理).
|
||||
|
||||
Global / shared — no ``user_id`` scoping. ``created_by`` is audit-only.
|
||||
All reads/writes are admin-gated at the router layer.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import UTC, datetime
|
||||
|
||||
from sqlalchemy import Boolean, Integer, String, Text, UniqueConstraint
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
|
||||
from deerflow.persistence.base import Base
|
||||
from deerflow.persistence.types import BeijingDateTime, PortableJSON
|
||||
|
||||
|
||||
class NotificationTemplateRow(Base):
|
||||
__tablename__ = "notification_templates"
|
||||
__table_args__ = (UniqueConstraint("name", name="uq_notification_templates_name"),)
|
||||
|
||||
id: Mapped[str] = mapped_column(String(64), primary_key=True)
|
||||
name: Mapped[str] = mapped_column(String(50))
|
||||
title_template: Mapped[str] = mapped_column(String(120))
|
||||
content_template: Mapped[str] = mapped_column(Text)
|
||||
tags: Mapped[list] = mapped_column(PortableJSON(), default=list)
|
||||
enabled: Mapped[bool] = mapped_column(Boolean, default=True, index=True)
|
||||
version: Mapped[int] = mapped_column(Integer, default=1)
|
||||
created_by: Mapped[str | None] = mapped_column(String(64))
|
||||
created_at: Mapped[datetime] = mapped_column(BeijingDateTime(), default=lambda: datetime.now(UTC))
|
||||
updated_at: Mapped[datetime] = mapped_column(
|
||||
BeijingDateTime(),
|
||||
default=lambda: datetime.now(UTC),
|
||||
onupdate=lambda: datetime.now(UTC),
|
||||
)
|
||||
+163
@@ -0,0 +1,163 @@
|
||||
"""SQLAlchemy-backed notification-template store (global / shared)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import uuid
|
||||
from datetime import UTC, datetime
|
||||
from typing import Any
|
||||
|
||||
from sqlalchemy import or_, select
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
|
||||
|
||||
from deerflow.persistence.notification_templates.base import (
|
||||
DuplicateNotificationTemplateNameError,
|
||||
NotificationTemplateStore,
|
||||
VersionConflictError,
|
||||
)
|
||||
from deerflow.persistence.notification_templates.model import NotificationTemplateRow
|
||||
|
||||
_WRITABLE = {
|
||||
"name",
|
||||
"title_template",
|
||||
"content_template",
|
||||
"tags",
|
||||
"enabled",
|
||||
}
|
||||
|
||||
|
||||
def _to_dict(row: NotificationTemplateRow) -> dict[str, Any]:
|
||||
data = row.to_dict()
|
||||
for key in ("created_at", "updated_at"):
|
||||
value = data.get(key)
|
||||
if isinstance(value, datetime):
|
||||
data[key] = value.isoformat()
|
||||
data["tags"] = list(data.get("tags") or [])
|
||||
return data
|
||||
|
||||
|
||||
class NotificationTemplateRepository(NotificationTemplateStore):
|
||||
def __init__(self, session_factory: async_sessionmaker[AsyncSession]) -> None:
|
||||
self._sf = session_factory
|
||||
|
||||
async def name_exists(self, name: str, *, exclude_id: str | None = None) -> bool:
|
||||
async with self._sf() as session:
|
||||
return await self._name_taken(session, name, exclude_id=exclude_id)
|
||||
|
||||
async def _name_taken(self, session: AsyncSession, name: str, *, exclude_id: str | None = None) -> bool:
|
||||
stmt = select(NotificationTemplateRow.id).where(NotificationTemplateRow.name == name)
|
||||
if exclude_id is not None:
|
||||
stmt = stmt.where(NotificationTemplateRow.id != exclude_id)
|
||||
result = await session.execute(stmt.limit(1))
|
||||
return result.first() is not None
|
||||
|
||||
def _filter_stmt(
|
||||
self,
|
||||
*,
|
||||
keyword: str | None,
|
||||
enabled: bool | None,
|
||||
tag: str | None,
|
||||
):
|
||||
stmt = select(NotificationTemplateRow)
|
||||
if enabled is not None:
|
||||
stmt = stmt.where(NotificationTemplateRow.enabled.is_(enabled))
|
||||
if keyword:
|
||||
needle = f"%{keyword.strip()}%"
|
||||
if keyword.strip():
|
||||
stmt = stmt.where(
|
||||
or_(
|
||||
NotificationTemplateRow.name.ilike(needle),
|
||||
NotificationTemplateRow.title_template.ilike(needle),
|
||||
NotificationTemplateRow.content_template.ilike(needle),
|
||||
)
|
||||
)
|
||||
# Tag filter is applied in Python (PortableJSON differs across backends).
|
||||
return stmt
|
||||
|
||||
async def list_templates(
|
||||
self,
|
||||
*,
|
||||
keyword: str | None = None,
|
||||
enabled: bool | None = None,
|
||||
tag: str | None = None,
|
||||
page: int = 1,
|
||||
page_size: int = 20,
|
||||
) -> tuple[list[dict[str, Any]], int]:
|
||||
page = max(1, page)
|
||||
page_size = max(1, page_size)
|
||||
stmt = self._filter_stmt(keyword=keyword, enabled=enabled, tag=tag)
|
||||
stmt = stmt.order_by(NotificationTemplateRow.created_at.desc())
|
||||
async with self._sf() as session:
|
||||
result = await session.execute(stmt)
|
||||
rows = [_to_dict(r) for r in result.scalars()]
|
||||
if tag is not None:
|
||||
rows = [r for r in rows if tag in (r.get("tags") or [])]
|
||||
total = len(rows)
|
||||
start = (page - 1) * page_size
|
||||
return rows[start : start + page_size], total
|
||||
|
||||
async def get_template(self, template_id: str) -> dict[str, Any] | None:
|
||||
async with self._sf() as session:
|
||||
row = await session.get(NotificationTemplateRow, template_id)
|
||||
return _to_dict(row) if row is not None else None
|
||||
|
||||
async def create_template(self, data: dict[str, Any]) -> dict[str, Any]:
|
||||
row = NotificationTemplateRow(
|
||||
id=data.get("id") or uuid.uuid4().hex[:12],
|
||||
name=data["name"],
|
||||
title_template=data["title_template"],
|
||||
content_template=data["content_template"],
|
||||
tags=list(data.get("tags") or []),
|
||||
enabled=data.get("enabled", True),
|
||||
version=1,
|
||||
created_by=data.get("created_by"),
|
||||
)
|
||||
async with self._sf() as session:
|
||||
if await self._name_taken(session, row.name):
|
||||
raise DuplicateNotificationTemplateNameError(row.name)
|
||||
session.add(row)
|
||||
try:
|
||||
await session.commit()
|
||||
except IntegrityError as exc:
|
||||
await session.rollback()
|
||||
raise DuplicateNotificationTemplateNameError(row.name) from exc
|
||||
await session.refresh(row)
|
||||
return _to_dict(row)
|
||||
|
||||
async def update_template(
|
||||
self,
|
||||
template_id: str,
|
||||
data: dict[str, Any],
|
||||
*,
|
||||
expected_version: int,
|
||||
) -> dict[str, Any] | None:
|
||||
async with self._sf() as session:
|
||||
row = await session.get(NotificationTemplateRow, template_id)
|
||||
if row is None:
|
||||
return None
|
||||
if int(row.version) != int(expected_version):
|
||||
raise VersionConflictError(_to_dict(row))
|
||||
new_name = data.get("name")
|
||||
if new_name is not None and new_name != row.name and await self._name_taken(session, new_name, exclude_id=template_id):
|
||||
raise DuplicateNotificationTemplateNameError(new_name)
|
||||
for key, value in data.items():
|
||||
if key in _WRITABLE:
|
||||
setattr(row, key, value)
|
||||
row.version = int(row.version) + 1
|
||||
row.updated_at = datetime.now(UTC)
|
||||
try:
|
||||
await session.commit()
|
||||
except IntegrityError as exc:
|
||||
await session.rollback()
|
||||
raise DuplicateNotificationTemplateNameError(new_name or row.name) from exc
|
||||
await session.refresh(row)
|
||||
return _to_dict(row)
|
||||
|
||||
async def delete_template(self, template_id: str) -> bool:
|
||||
async with self._sf() as session:
|
||||
row = await session.get(NotificationTemplateRow, template_id)
|
||||
if row is None:
|
||||
return False
|
||||
await session.delete(row)
|
||||
await session.commit()
|
||||
return True
|
||||
+110
@@ -0,0 +1,110 @@
|
||||
"""Template variable validation and preview helpers for notification templates.
|
||||
|
||||
Supported placeholders (exact names, no spaces):
|
||||
{{userName}} {{taskName}} {{taskId}} {{dueDate}}
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
|
||||
ALLOWED_VARIABLES: frozenset[str] = frozenset({"userName", "taskName", "taskId", "dueDate"})
|
||||
|
||||
# Captures the inner of a well-formed {{...}} pair (no nested braces).
|
||||
_VAR_RE = re.compile(r"\{\{([^{}]*)\}\}")
|
||||
# Valid identifier: letters then letters/digits (no spaces / punctuation).
|
||||
_IDENT_RE = re.compile(r"^[A-Za-z][A-Za-z0-9]*$")
|
||||
|
||||
|
||||
class TemplateVariableError(ValueError):
|
||||
"""Raised when a template contains an invalid / unsupported / unclosed variable."""
|
||||
|
||||
def __init__(self, message: str) -> None:
|
||||
super().__init__(message)
|
||||
self.message = message
|
||||
|
||||
|
||||
def validate_template_text(text: str) -> None:
|
||||
"""Validate all ``{{var}}`` occurrences in *text*.
|
||||
|
||||
Raises ``TemplateVariableError`` with a Chinese message pointing at the
|
||||
offending variable or position.
|
||||
"""
|
||||
if not text:
|
||||
return
|
||||
|
||||
i = 0
|
||||
while True:
|
||||
start = text.find("{{", i)
|
||||
if start < 0:
|
||||
break
|
||||
end = text.find("}}", start + 2)
|
||||
if end < 0:
|
||||
raise TemplateVariableError(f"未闭合的变量(位置 {start})")
|
||||
inner = text[start + 2 : end]
|
||||
token = "{{" + inner + "}}"
|
||||
if not inner or not _IDENT_RE.fullmatch(inner):
|
||||
raise TemplateVariableError(f"变量格式错误:{token}")
|
||||
if inner not in ALLOWED_VARIABLES:
|
||||
raise TemplateVariableError(f"不支持的变量:{token}")
|
||||
i = end + 2
|
||||
|
||||
|
||||
def validate_templates(*texts: str) -> None:
|
||||
"""Validate every template string; first error wins."""
|
||||
for text in texts:
|
||||
validate_template_text(text or "")
|
||||
|
||||
|
||||
def extract_variables(text: str) -> list[str]:
|
||||
"""Return ordered unique allowed-looking variable names found in *text*."""
|
||||
seen: set[str] = set()
|
||||
out: list[str] = []
|
||||
for match in _VAR_RE.finditer(text or ""):
|
||||
name = match.group(1)
|
||||
if name in seen:
|
||||
continue
|
||||
seen.add(name)
|
||||
out.append(name)
|
||||
return out
|
||||
|
||||
|
||||
def render_template(text: str, variables: dict[str, str] | None) -> tuple[str, list[str]]:
|
||||
"""Replace known placeholders; keep missing ones and report their names.
|
||||
|
||||
Returns ``(rendered, missing_variables)``. Missing names are unique and
|
||||
appear in first-seen order.
|
||||
"""
|
||||
vars_map = variables or {}
|
||||
missing: list[str] = []
|
||||
seen_missing: set[str] = set()
|
||||
|
||||
def _repl(match: re.Match[str]) -> str:
|
||||
name = match.group(1)
|
||||
if name in vars_map and vars_map[name] is not None:
|
||||
return str(vars_map[name])
|
||||
if name not in seen_missing:
|
||||
seen_missing.add(name)
|
||||
missing.append(name)
|
||||
return match.group(0)
|
||||
|
||||
rendered = _VAR_RE.sub(_repl, text or "")
|
||||
return rendered, missing
|
||||
|
||||
|
||||
def preview_templates(
|
||||
title_template: str,
|
||||
content_template: str,
|
||||
variables: dict[str, str] | None = None,
|
||||
) -> dict[str, object]:
|
||||
"""Render title + content; merge missing variable lists (order-preserving)."""
|
||||
title, missing_title = render_template(title_template, variables)
|
||||
content, missing_content = render_template(content_template, variables)
|
||||
seen: set[str] = set()
|
||||
missing: list[str] = []
|
||||
for name in missing_title + missing_content:
|
||||
if name in seen:
|
||||
continue
|
||||
seen.add(name)
|
||||
missing.append(name)
|
||||
return {"title": title, "content": content, "missing_variables": missing}
|
||||
Reference in new issue
Block a user