feat(ai): W1-AI-CLOSURE 超级 Sprint — 9 APP 全链路收口 + chat 上下文真激活

Phase 2.3 chat 上下文捕获链路从未真正激活到完整工作:
- 14 处 ai-float-button 补 sourcePage,chat.ts 三分支同步设 pageFilters.contextId
- 后端 page_context 4 层 BUG 修(列名错位 + RLS site_id 未重设)
- xcx_chat filters.pop 破坏 body.page_context 引用 — dict() 浅拷贝隔离
- chat 流式 markdown 实时解析(表格/标题/列表/加粗 + KPI 富卡)
- reference_card KPI 富卡接入 SSE 路径,db 真写入
- 维客线索 source 显示规则:AI 来源用机器人 icon 替代长文字

数据库:
- public.member_retention_clue 加 emoji + runtime_mode + sandbox_instance_id
- biz.ai_run_logs 加 assistant_id + 复合索引
- chk_ai_cache_type CHECK 约束 8 类应用名
- cache_type / app_type 命名统一(app6_note / app7_customer / app8_consolidation)
- 历史 emoji 抽取脚本 44/44 成功

后端 silent failure 修:
- cleanup_service WHERE app_type → cache_type(90 天清理 + 20K 上限重新生效)
- _build_ai_insight 字段错位修复(app4 → app7 + 字段对齐 prompt schema)
- task_manager talkingPoints 改 app5_tactics + tactics 字段
- task_manager aiSuggestion 改取 one_line_summary
- cache_service.CACHE_EXPIRY_DAYS 加 app2a_finance_area
- WS /ws/ai-cache 加 token + JWT + site_id 校验(P0 信息泄露漏洞)
- internal_ai token 改 hmac.compare_digest

工具/文档:
- main.py 加 RotatingFileHandler logs/backend.log + uvicorn /health 过滤
- 新建 utils/clue_category.py(VI 6 类配色 + emoji fallback + source 显示规则)
- 新建 utils/markdown.ts(轻量 md 转 rich-text 解析 + streaming 容错)
- audit + 数据库变更说明 + backlog §七 #14 收口 + #15-#38 残余子任务
- backlog 追加 §十一 App1 参数/MCP/沙箱审计 + §十二 百炼/SQL MCP 主任务线

实地 MCP 走查:14 入口数据层 + 5 代表入口 sourcePage 注入 + customer-detail 全模块 + chat md 渲染 + reference_card 富卡 都已验证。9 项预先 BUG/UX 登记 §七 #29-#38 后续修复。

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
Neo
2026-05-06 16:39:07 +08:00
parent c9c2bce101
commit 2dfc926f96
56 changed files with 1983 additions and 278 deletions

View File

@@ -1,8 +1,11 @@
/**
* 回归测试admin-web 手动执行 App 类型必须与后端 /api/admin/ai/run/{app_type} 对齐。
* 回归测试:admin-web app_type / cache_type 命名必须与后端
* (CacheTypeEnum + dispatcher 写入 + chk_ai_cache_type CHECK 约束)对齐。
*
* 缓存类型仍使用 `*_analysis` / `*_consolidated`,但手动执行和 run log
* 应使用 dispatcher 支持的 app_type避免前端发出后端 400 的路径。
* W1-AI-CLOSURE 组 1+5 命名统一后:
* - cache_type 与 app_type 使用同一组应用名(与 prompt 文件名一致)
* - 旧描述性后缀 'app6_note_analysis' / 'app7_customer_analysis' /
* 'app8_clue_consolidated' / 'app8_consolidate' 已绝迹,前端不再保留。
*/
import { describe, expect, it } from "vitest";
@@ -10,34 +13,55 @@ import { RUN_APP_TYPES } from "../api/adminAI";
import { CACHE_TYPE_OPTIONS, RUN_APP_TYPE_OPTIONS } from "../pages/AIOperations";
import { RUN_LOG_APP_TYPE_OPTIONS } from "../pages/AIRunLogs";
describe("admin AI app_type 对齐", () => {
it("手动执行类型使用后端支持的 app_type而不是缓存类型", () => {
const apiTypes = [...RUN_APP_TYPES];
const runOptionValues = RUN_APP_TYPE_OPTIONS.map((item) => item.value);
const NEW_APP_TYPES = [
"app2_finance",
"app2a_finance_area",
"app3_clue",
"app4_analysis",
"app5_tactics",
"app6_note",
"app7_customer",
"app8_consolidation",
] as const;
for (const appType of ["app6_note", "app7_customer", "app8_consolidation"]) {
expect(apiTypes).toContain(appType);
const LEGACY_NAMES = [
"app6_note_analysis",
"app7_customer_analysis",
"app8_clue_consolidated",
"app8_consolidate",
];
describe("admin AI app_type / cache_type 命名对齐", () => {
it("RUN_APP_TYPES 与统一命名一致", () => {
expect([...RUN_APP_TYPES]).toEqual(NEW_APP_TYPES);
});
it("手动执行下拉只暴露统一命名(8 个),不含旧描述性后缀", () => {
const runOptionValues = RUN_APP_TYPE_OPTIONS.map((item) => item.value);
for (const appType of NEW_APP_TYPES) {
expect(runOptionValues).toContain(appType);
}
for (const cacheType of ["app6_note_analysis", "app7_customer_analysis", "app8_clue_consolidated"]) {
expect(runOptionValues).not.toContain(cacheType);
for (const legacy of LEGACY_NAMES) {
expect(runOptionValues).not.toContain(legacy);
}
});
it("缓存失效继续使用 cache_type避免破坏已有缓存管理", () => {
it("缓存失效下拉与统一命名对齐,不含旧描述性后缀", () => {
const cacheOptionValues = CACHE_TYPE_OPTIONS.map((item) => item.value);
expect(cacheOptionValues).toContain("app6_note_analysis");
expect(cacheOptionValues).toContain("app7_customer_analysis");
expect(cacheOptionValues).toContain("app8_clue_consolidated");
for (const cacheType of NEW_APP_TYPES) {
expect(cacheOptionValues).toContain(cacheType);
}
for (const legacy of LEGACY_NAMES) {
expect(cacheOptionValues).not.toContain(legacy);
}
});
it("调用记录筛选包含真实写入 ai_run_logs 的 app_type", () => {
it("调用记录筛选包含 chat + 8 个写缓存应用,不含旧 'app8_consolidate'", () => {
const runLogOptionValues = RUN_LOG_APP_TYPE_OPTIONS.map((item) => item.value);
expect(runLogOptionValues).toContain("app6_note");
expect(runLogOptionValues).toContain("app7_customer");
expect(runLogOptionValues).toContain("app8_consolidate");
expect(runLogOptionValues).toContain("app1_chat");
for (const appType of NEW_APP_TYPES) {
expect(runLogOptionValues).toContain(appType);
}
expect(runLogOptionValues).not.toContain("app8_consolidate");
});
});

View File

@@ -33,13 +33,17 @@ const EVENT_TYPE_OPTIONS = [
const { TextArea } = Input;
const { Title } = Typography;
// W1-AI-CLOSURE 组 1+5:cache_type 命名与 prompt 文件名 + 数据库 chk_ai_cache_type
// 约束完全对齐(旧描述性后缀 _analysis / _consolidated 已废弃)。
export const CACHE_TYPE_OPTIONS = [
{ label: "App2 财务洞察(全域)", value: "app2_finance" },
{ label: "App2a 财务洞察(区域)", value: "app2a_finance_area" },
{ label: "App3 维客线索", value: "app3_clue" },
{ label: "App4 关系分析", value: "app4_analysis" },
{ label: "App5 话术参考", value: "app5_tactics" },
{ label: "App6 备注分析", value: "app6_note_analysis" },
{ label: "App7 客户分析", value: "app7_customer_analysis" },
{ label: "App8 线索整理", value: "app8_clue_consolidated" },
{ label: "App6 备注分析", value: "app6_note" },
{ label: "App7 客户分析", value: "app7_customer" },
{ label: "App8 线索整理", value: "app8_consolidation" },
];
export const RUN_APP_TYPE_OPTIONS: { label: string; value: AppType }[] = [

View File

@@ -253,8 +253,10 @@ const AIRunLogs: React.FC = () => {
export default AIRunLogs;
// W1-AI-CLOSURE 组 1+5:ai_run_logs.app_type 命名统一(数据库已 UPDATE);
// 旧 'app8_consolidate' 已不再存在,从下拉移除。
export const RUN_LOG_APP_TYPE_OPTIONS = [
"app1_chat", "app2_finance", "app2a_finance_area", "app3_clue",
"app4_analysis", "app5_tactics", "app6_note", "app7_customer",
"app8_consolidate", "app8_consolidation",
"app8_consolidation",
].map((v) => ({ label: v, value: v }));

View File

@@ -27,15 +27,19 @@ from app.services.runtime_context import (
logger = logging.getLogger(__name__)
# 缓存过期策略cache_type → 过期天数0 表示当日 23:59:59
# 缓存过期策略:cache_type → 过期天数(0 表示当日 23:59:59)
# 命名与 prompt 文件名一致(W1-AI-CLOSURE 组 1 数据库迁移已统一)。
# P0-11 修正:补 app2a_finance_area,与 app2_finance 同当日过期策略,
# 之前漏配导致 64 个区域组合缓存 expires_at=NULL 永不过期。
CACHE_EXPIRY_DAYS: dict[str, int] = {
"app2_finance": 0, # 当日 23:59:59
"app2_finance": 0,
"app2a_finance_area": 0,
"app3_clue": 7,
"app4_analysis": 7,
"app5_tactics": 7,
"app6_note_analysis": 30,
"app7_customer_analysis": 7,
"app8_clue_consolidated": 7,
"app6_note": 30,
"app7_customer": 7,
"app8_consolidation": 7,
}
# 每 App 保留上限

View File

@@ -192,6 +192,13 @@ def _text_customer_detail(
try:
etl_conn = get_etl_readonly_connection(site_id)
with etl_conn.cursor() as cur:
# W1-AI-CLOSURE 复盘修正:get_etl_readonly_connection 在 SET LOCAL 后
# commit(LOCAL 失效),后续 cursor 进入新事务,RLS 视图 current_setting
# ('app.current_site_id') 拿到空串导致 bigint 转换失败。每次 cursor 必须
# 重新 SET 当前事务的 GUC(对齐 member_data.py / assistant_data.py 模式)。
cur.execute(
"SET LOCAL app.current_site_id = %s", (str(site_id),)
)
cur.execute(
"SET LOCAL statement_timeout = %s",
(f"{FDW_QUERY_TIMEOUT_SEC * 1000}",),
@@ -210,21 +217,34 @@ def _text_customer_detail(
nickname = m_row[0] if m_row else f"ID:{member_id}"
# 最近 5 条消费
# W1-AI-CLOSURE 复盘修正:列名错位 — v_dwd_settlement_head 实际列是
# pay_time / settle_name(无 settle_date / room_name);items_sum 按
# DWD-DOC 强制规则 #1 用合成表达式(consume_money 禁止直接计算)。
cur.execute(
"""
SELECT settle_date, items_sum, room_name
SELECT
pay_time,
(COALESCE(table_charge_money, 0)
+ COALESCE(goods_money, 0)
+ COALESCE(assistant_pd_money, 0)
+ COALESCE(assistant_cx_money, 0)
+ COALESCE(electricity_money, 0)) AS items_sum,
settle_name
FROM app.v_dwd_settlement_head
WHERE member_id = %s AND settle_type IN (1, 3)
ORDER BY settle_date DESC LIMIT 5
ORDER BY pay_time DESC LIMIT 5
""",
(member_id,),
)
recent = cur.fetchall()
# 余额
# W1-AI-CLOSURE 复盘修正:列名 balance_amount 不存在,实际列是
# cash_card_balance / gift_card_balance / total_card_balance;
# total_card_balance 是合计储值(对齐 customer_service.balance 字段)。
cur.execute(
"""
SELECT balance_amount
SELECT total_card_balance
FROM app.v_dws_member_consumption_summary
WHERE member_id = %s LIMIT 1
""",
@@ -233,14 +253,15 @@ def _text_customer_detail(
bal_row = cur.fetchone()
etl_conn.commit()
# 维客线索
# 维客线索(W1-AI-CLOSURE 复盘修正:列名 created_at 不存在,实际是 recorded_at;
# 表加 schema 前缀 public 防 search_path 漂移;补 is_hidden 过滤)
biz_conn = get_connection()
with biz_conn.cursor() as cur:
cur.execute(
"""
SELECT summary FROM member_retention_clue
WHERE member_id = %s AND site_id = %s
ORDER BY created_at DESC LIMIT 5
SELECT summary FROM public.member_retention_clue
WHERE member_id = %s AND site_id = %s AND is_hidden = false
ORDER BY recorded_at DESC LIMIT 5
""",
(member_id, site_id),
)
@@ -281,6 +302,11 @@ def _text_coach_detail(
try:
etl_conn = get_etl_readonly_connection(site_id)
with etl_conn.cursor() as cur:
# W1-AI-CLOSURE 复盘修正:get_etl_readonly_connection 在 SET LOCAL 后
# commit(LOCAL 失效),后续 cursor 在新事务中 RLS 视图查不到 site_id。
cur.execute(
"SET LOCAL app.current_site_id = %s", (str(site_id),)
)
cur.execute(
"SET LOCAL statement_timeout = %s",
(f"{FDW_QUERY_TIMEOUT_SEC * 1000}",),
@@ -348,6 +374,11 @@ def _text_board_finance(
try:
etl_conn = get_etl_readonly_connection(site_id)
with etl_conn.cursor() as cur:
# W1-AI-CLOSURE 复盘修正:get_etl_readonly_connection 在 SET LOCAL 后
# commit(LOCAL 失效),后续 cursor 在新事务中 RLS 视图查不到 site_id。
cur.execute(
"SET LOCAL app.current_site_id = %s", (str(site_id),)
)
cur.execute(
"SET LOCAL statement_timeout = %s",
(f"{FDW_QUERY_TIMEOUT_SEC * 1000}",),
@@ -399,6 +430,11 @@ def _text_board_customer(
try:
etl_conn = get_etl_readonly_connection(site_id)
with etl_conn.cursor() as cur:
# W1-AI-CLOSURE 复盘修正:get_etl_readonly_connection 在 SET LOCAL 后
# commit(LOCAL 失效),后续 cursor 在新事务中 RLS 视图查不到 site_id。
cur.execute(
"SET LOCAL app.current_site_id = %s", (str(site_id),)
)
cur.execute(
"SET LOCAL statement_timeout = %s",
(f"{FDW_QUERY_TIMEOUT_SEC * 1000}",),
@@ -456,6 +492,11 @@ def _text_board_coach(
try:
etl_conn = get_etl_readonly_connection(site_id)
with etl_conn.cursor() as cur:
# W1-AI-CLOSURE 复盘修正:get_etl_readonly_connection 在 SET LOCAL 后
# commit(LOCAL 失效),后续 cursor 在新事务中 RLS 视图查不到 site_id。
cur.execute(
"SET LOCAL app.current_site_id = %s", (str(site_id),)
)
cur.execute(
"SET LOCAL statement_timeout = %s",
(f"{FDW_QUERY_TIMEOUT_SEC * 1000}",),
@@ -515,6 +556,11 @@ def _text_performance(
try:
etl_conn = get_etl_readonly_connection(site_id)
with etl_conn.cursor() as cur:
# W1-AI-CLOSURE 复盘修正:get_etl_readonly_connection 在 SET LOCAL 后
# commit(LOCAL 失效),后续 cursor 在新事务中 RLS 视图查不到 site_id。
cur.execute(
"SET LOCAL app.current_site_id = %s", (str(site_id),)
)
cur.execute(
"SET LOCAL statement_timeout = %s",
(f"{FDW_QUERY_TIMEOUT_SEC * 1000}",),
@@ -599,6 +645,11 @@ def _text_customer_service_records(
try:
etl_conn = get_etl_readonly_connection(site_id)
with etl_conn.cursor() as cur:
# W1-AI-CLOSURE 复盘修正:get_etl_readonly_connection 在 SET LOCAL 后
# commit(LOCAL 失效),后续 cursor 在新事务中 RLS 视图查不到 site_id。
cur.execute(
"SET LOCAL app.current_site_id = %s", (str(site_id),)
)
cur.execute(
"SET LOCAL statement_timeout = %s",
(f"{FDW_QUERY_TIMEOUT_SEC * 1000}",),

View File

@@ -545,67 +545,86 @@ class AIDispatcher:
consolidate_result: dict,
source: str,
) -> None:
"""全量替换 member_retention_clueDELETE 同源旧记录 + INSERT 新记录事务
"""全量替换 member_retention_clue:DELETE 同源旧记录 + INSERT 新记录(事务)
同一 member 同一 site 同一 source 当天只保留最新一批。
人工线索source='manual')不受影响
同一 member + site + source + (runtime_mode, sandbox_instance_id) 全量替换:
live 模式只覆盖 live 数据,sandbox 实例只覆盖该实例数据;互不污染
人工线索(source='manual')不受影响。
事务失败自动回滚。
字段映射
字段映射(W1-AI-CLOSURE 组 3 修正:emoji 独立列,不再嵌 summary):
- category → category
- emoji + " " + summary → summary"📅 偏好周末下午时段消费"
- summary → summary(原文,不拼 emoji 前缀)
- emoji → emoji(独立列)
- detail → detail
- providers → recorded_by_name
- runtime_mode + sandbox_instance_id → 同列(沙箱隔离)
"""
from app.database import get_connection
from app.services.runtime_context import (
LIVE_INSTANCE_ID,
MODE_LIVE,
MODE_SANDBOX,
get_runtime_context,
)
clues = consolidate_result.get("clues", [])
if not clues:
logger.info(
"App8 无线索数据跳过写入: member_id=%d site_id=%d", member_id, site_id,
"App8 无线索数据,跳过写入: member_id=%d site_id=%d", member_id, site_id,
)
return
conn = get_connection()
try:
ctx = get_runtime_context(site_id, conn=conn)
if ctx.is_sandbox and ctx.sandbox_instance_id:
runtime_mode = MODE_SANDBOX
sandbox_instance_id = ctx.sandbox_instance_id
else:
runtime_mode = MODE_LIVE
sandbox_instance_id = LIVE_INSTANCE_ID
with conn.cursor() as cur:
cur.execute(
"""
DELETE FROM member_retention_clue
DELETE FROM public.member_retention_clue
WHERE member_id = %s AND site_id = %s AND source = %s
AND runtime_mode = %s AND sandbox_instance_id = %s
""",
(member_id, site_id, source),
(member_id, site_id, source, runtime_mode, sandbox_instance_id),
)
deleted = cur.rowcount
for clue in clues:
emoji = clue.get("emoji", "")
raw_summary = clue.get("summary", "")
summary = f"{emoji} {raw_summary}" if emoji else raw_summary
cur.execute(
"""
INSERT INTO member_retention_clue
(member_id, category, summary, detail, site_id,
source, recorded_by_name, recorded_by_assistant_id)
VALUES (%s, %s, %s, %s, %s, %s, %s, NULL)
INSERT INTO public.member_retention_clue
(member_id, category, summary, detail, emoji, site_id,
source, recorded_by_name, recorded_by_assistant_id,
runtime_mode, sandbox_instance_id)
VALUES (%s, %s, %s, %s, %s, %s, %s, %s, NULL, %s, %s)
""",
(
member_id,
clue.get("category", "客户基础"),
summary,
clue.get("summary", ""),
clue.get("detail", ""),
clue.get("emoji", ""),
site_id,
source,
clue.get("providers", ""),
runtime_mode,
sandbox_instance_id,
),
)
conn.commit()
logger.info(
"维客线索全量替换完成: member_id=%d site_id=%d source=%s "
"deleted=%d inserted=%d",
member_id, site_id, source, deleted, len(clues),
"runtime=%s/%s deleted=%d inserted=%d",
member_id, site_id, source,
runtime_mode, sandbox_instance_id, deleted, len(clues),
)
except Exception:
conn.rollback()
@@ -682,7 +701,7 @@ class AIDispatcher:
# ── Step 2: App8 线索整合 ──
app3_clues = (app3_result or {}).get("clues", []) if isinstance(app3_result, dict) else []
app6_clues, app6_generated_at = self._fetch_recent_clues(
CacheTypeEnum.APP6_NOTE_ANALYSIS.value, site_id, member_id,
CacheTypeEnum.APP6_NOTE.value, site_id, member_id,
)
try:
@@ -701,11 +720,11 @@ class AIDispatcher:
app8_result = None
if app8_prompt:
app8_result = await self._run_step(
"app8_consolidate", self.config.app_id_8_consolidate,
"app8_consolidation", self.config.app_id_8_consolidate,
app8_prompt, context,
)
self._write_cache(
CacheTypeEnum.APP8_CLUE_CONSOLIDATED.value, site_id, str(member_id),
CacheTypeEnum.APP8_CONSOLIDATION.value, site_id, str(member_id),
app8_result, "consumption",
)
if app8_result is not None:
@@ -738,7 +757,7 @@ class AIDispatcher:
app7_prompt, context,
)
self._write_cache(
CacheTypeEnum.APP7_CUSTOMER_ANALYSIS.value, site_id, str(member_id),
CacheTypeEnum.APP7_CUSTOMER.value, site_id, str(member_id),
app7_result, "consumption",
)
@@ -781,7 +800,7 @@ class AIDispatcher:
)
score = (app6_result or {}).get("score") if isinstance(app6_result, dict) else None
self._write_cache(
CacheTypeEnum.APP6_NOTE_ANALYSIS.value, site_id, str(member_id),
CacheTypeEnum.APP6_NOTE.value, site_id, str(member_id),
app6_result, "note_created", score=score,
)
@@ -805,11 +824,11 @@ class AIDispatcher:
return
app8_result = await self._run_step(
"app8_consolidate", self.config.app_id_8_consolidate,
"app8_consolidation", self.config.app_id_8_consolidate,
app8_prompt, context,
)
self._write_cache(
CacheTypeEnum.APP8_CLUE_CONSOLIDATED.value, site_id, str(member_id),
CacheTypeEnum.APP8_CONSOLIDATION.value, site_id, str(member_id),
app8_result, "note_created",
)
if app8_result is not None:
@@ -1070,7 +1089,7 @@ class AIDispatcher:
raise ValueError("app6_note 需要 member_id")
prompt = await build_app6_prompt(context, self.cache_svc)
app_id = self.config.app_id_6_note
cache_type = CacheTypeEnum.APP6_NOTE_ANALYSIS.value
cache_type = CacheTypeEnum.APP6_NOTE.value
target_id = str(context["member_id"])
elif app_type == "app7_customer":
@@ -1078,7 +1097,7 @@ class AIDispatcher:
raise ValueError("app7_customer 需要 member_id")
prompt = await build_app7_prompt(context, self.cache_svc)
app_id = self.config.app_id_7_customer
cache_type = CacheTypeEnum.APP7_CUSTOMER_ANALYSIS.value
cache_type = CacheTypeEnum.APP7_CUSTOMER.value
target_id = str(context["member_id"])
elif app_type == "app8_consolidation":
@@ -1090,7 +1109,7 @@ class AIDispatcher:
CacheTypeEnum.APP3_CLUE.value, site_id, member_id,
)
app6_clues, app6_at = self._fetch_recent_clues(
CacheTypeEnum.APP6_NOTE_ANALYSIS.value, site_id, member_id,
CacheTypeEnum.APP6_NOTE.value, site_id, member_id,
)
prompt = await build_app8_prompt({
"site_id": site_id,
@@ -1101,7 +1120,7 @@ class AIDispatcher:
"app6_generated_at": app6_at,
})
app_id = self.config.app_id_8_consolidate
cache_type = CacheTypeEnum.APP8_CLUE_CONSOLIDATED.value
cache_type = CacheTypeEnum.APP8_CONSOLIDATION.value
target_id = str(member_id)
else:
raise ValueError(f"不支持的 app_type: {app_type}")

View File

@@ -108,7 +108,7 @@ def _build_reference(
target_id = str(member_id)
app6_latest = cache_svc.get_latest(
CacheTypeEnum.APP6_NOTE_ANALYSIS.value, site_id, target_id,
CacheTypeEnum.APP6_NOTE.value, site_id, target_id,
)
if app6_latest:
ref["app6_note_clues"] = {
@@ -117,7 +117,7 @@ def _build_reference(
}
app8_history = cache_svc.get_history(
CacheTypeEnum.APP8_CLUE_CONSOLIDATED.value, site_id, target_id, limit=2,
CacheTypeEnum.APP8_CONSOLIDATION.value, site_id, target_id, limit=2,
)
if app8_history:
ref["app8_history"] = [

View File

@@ -131,7 +131,7 @@ def _build_reference(
target_id = str(member_id)
latest = cache_svc.get_latest(
CacheTypeEnum.APP8_CLUE_CONSOLIDATED.value, site_id, target_id,
CacheTypeEnum.APP8_CONSOLIDATION.value, site_id, target_id,
)
if latest:
ref["app8_latest"] = {
@@ -140,7 +140,7 @@ def _build_reference(
}
history = cache_svc.get_history(
CacheTypeEnum.APP8_CLUE_CONSOLIDATED.value, site_id, target_id, limit=2,
CacheTypeEnum.APP8_CONSOLIDATION.value, site_id, target_id, limit=2,
)
if history:
ref["app8_history"] = [

View File

@@ -130,7 +130,7 @@ def _build_reference(
ref: dict = {}
history = cache_svc.get_history(
CacheTypeEnum.APP8_CLUE_CONSOLIDATED.value,
CacheTypeEnum.APP8_CONSOLIDATION.value,
site_id,
str(member_id),
limit=2,

View File

@@ -128,7 +128,7 @@ def _build_reference(
}
app8_history = cache_svc.get_history(
CacheTypeEnum.APP8_CLUE_CONSOLIDATED.value, site_id, target_id, limit=2,
CacheTypeEnum.APP8_CONSOLIDATION.value, site_id, target_id, limit=2,
)
if app8_history:
ref["app8_history"] = [

View File

@@ -125,7 +125,7 @@ def _build_reference(
target_id = str(member_id)
latest = cache_svc.get_latest(
CacheTypeEnum.APP8_CLUE_CONSOLIDATED.value, site_id, target_id,
CacheTypeEnum.APP8_CONSOLIDATION.value, site_id, target_id,
)
if latest:
ref["app8_latest"] = {
@@ -134,7 +134,7 @@ def _build_reference(
}
history = cache_svc.get_history(
CacheTypeEnum.APP8_CLUE_CONSOLIDATED.value, site_id, target_id, limit=2,
CacheTypeEnum.APP8_CONSOLIDATION.value, site_id, target_id, limit=2,
)
if history:
ref["app8_history"] = [

View File

@@ -36,14 +36,21 @@ class SSEEvent(BaseModel):
class CacheTypeEnum(str, enum.Enum):
"""ai_cache.cache_type 允许的取值(8 类,与 prompt 文件名 + 数据库 chk_ai_cache_type
约束完全对齐;app1_chat 走 ai_messages 不进缓存)。
W1-AI-CLOSURE 组 1 命名统一:旧名字 app6_note_analysis / app7_customer_analysis /
app8_clue_consolidated / app8_consolidate 已在数据库迁移中清理,代码不再使用。
"""
APP2_FINANCE = "app2_finance"
APP2A_FINANCE_AREA = "app2a_finance_area" # 2026-04-23 新增区域财务洞察64 组合)
APP2A_FINANCE_AREA = "app2a_finance_area"
APP3_CLUE = "app3_clue"
APP4_ANALYSIS = "app4_analysis"
APP5_TACTICS = "app5_tactics"
APP6_NOTE_ANALYSIS = "app6_note_analysis"
APP7_CUSTOMER_ANALYSIS = "app7_customer_analysis"
APP8_CLUE_CONSOLIDATED = "app8_clue_consolidated"
APP6_NOTE = "app6_note"
APP7_CUSTOMER = "app7_customer"
APP8_CONSOLIDATION = "app8_consolidation"
# ── 线索相关 ──

View File

@@ -11,6 +11,47 @@ from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from starlette.exceptions import HTTPException as StarletteHTTPException
# ── 日志配置(W1-AI-CLOSURE 复盘加固):文件输出 + 过滤 /health 访问日志 ──
# 1. 所有 INFO+ 日志同时写到仓库根 logs/backend.log(滚动 5 个,每个 20MB 上限)
# 2. uvicorn.access 中含 "/health" 的访问日志被过滤(健康检查 noise 抑制)
def _configure_logging() -> None:
import logging
from logging.handlers import RotatingFileHandler
from pathlib import Path
log_dir = Path(__file__).resolve().parents[3] / "logs"
log_dir.mkdir(exist_ok=True)
log_file = log_dir / "backend.log"
file_handler = RotatingFileHandler(
log_file, maxBytes=20 * 1024 * 1024, backupCount=5, encoding="utf-8"
)
file_handler.setFormatter(
logging.Formatter("%(asctime)s [%(levelname)s] %(name)s: %(message)s")
)
root = logging.getLogger()
# 防止重复挂载(uvicorn --reload 可能重入)
if not any(
isinstance(h, RotatingFileHandler) and getattr(h, "baseFilename", None) == str(log_file)
for h in root.handlers
):
root.addHandler(file_handler)
if root.level > logging.INFO or root.level == logging.NOTSET:
root.setLevel(logging.INFO)
class _SuppressHealthAccess(logging.Filter):
def filter(self, record: logging.LogRecord) -> bool:
return "/health" not in record.getMessage()
access_logger = logging.getLogger("uvicorn.access")
if not any(isinstance(f, _SuppressHealthAccess) for f in access_logger.filters):
access_logger.addFilter(_SuppressHealthAccess())
_configure_logging()
from app.middleware.response_wrapper import (
ResponseWrapperMiddleware,
http_exception_handler,

View File

@@ -76,7 +76,9 @@ def verify_internal_token(authorization: str = Header(...)) -> str:
detail="AI 配置异常",
)
if token != config.internal_api_token:
# P1-7 修正:用 hmac.compare_digest 防时序攻击,而不是 Python `==` 字符串比较
import hmac
if not hmac.compare_digest(token, config.internal_api_token or ""):
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Token 不匹配",

View File

@@ -218,9 +218,10 @@ async def chat_stream(
try:
from app.ai.data_fetchers import build_page_text
filters = {}
if body.page_context:
filters = body.page_context
# W1-AI-CLOSURE 复盘修正:必须 dict() 浅拷贝,否则 filters.pop("contextId")
# 会破坏 body.page_context(同引用),导致后续 reference_card 块
# 拿不到 contextId(返回 None,跳过 KPI 富卡构建)。
filters = dict(body.page_context) if body.page_context else {}
context_id = filters.pop("contextId", None)
page_text = await build_page_text(
source_page=body.source_page,
@@ -266,14 +267,34 @@ async def chat_stream(
full_reply = "".join(full_reply_parts)
estimated_tokens = len(full_reply)
# Phase 1.3assistant 消息挂 reference_card(若用户从特定详情页入口发起对话)
# Phase 1.3 + W1-AI-CLOSURE 组 4(P0-15):assistant 消息挂 reference_card
# customer-detail / customer-service-records 入口走 KPI 富卡(余额/30 天消费/到店),
# 其他入口走简单跳转链接卡(保持现状)。
try:
from app.ai.references import build_app1_reference_card
_ref_card = None
_pc = body.page_context or {}
_ctx_id = _pc.get("contextId") or _pc.get("taskId") or _pc.get("customerId") or _pc.get("coachId")
_ctx_id = (
_pc.get("contextId")
or _pc.get("taskId")
or _pc.get("customerId")
or _pc.get("coachId")
)
if body.source_page and _ctx_id:
_ref_card = build_app1_reference_card(body.source_page, _ctx_id)
if body.source_page in ("customer-detail", "customer-service-records"):
try:
_customer_id = int(_ctx_id)
_ref_card = svc.build_reference_card(_customer_id, user.site_id)
if _ref_card:
_ref_card.setdefault(
"link",
f"/pages/customer-detail/customer-detail?customerId={_ctx_id}",
)
_ref_card.setdefault("source_page", body.source_page)
except (ValueError, TypeError):
_ref_card = None
if _ref_card is None:
_ref_card = build_app1_reference_card(body.source_page, _ctx_id)
except Exception:
logger.warning("构建 reference_card 失败", exc_info=True)
_ref_card = None

View File

@@ -1,7 +1,9 @@
"""
维客线索相关 Pydantic 模型。
大类枚举:客户基础信息、消费习惯、玩法偏好、促销偏好、社交关系、重要反馈
大类枚举(6 类,与数据库 chk_retention_clue_category 约束 + ai/schemas
App3CategoryEnum / App6CategoryEnum 完全对齐):
客户基础、消费习惯、玩法偏好、促销偏好、社交关系、重要反馈
"""
from datetime import datetime
@@ -12,8 +14,10 @@ from pydantic import BaseModel, Field
class ClueCategory(str, Enum):
"""维客线索大类枚举"""
BASIC_INFO = "客户基础信息"
"""维客线索大类枚举(W1-AI-CLOSURE 组 5:'客户基础信息' 字面量纠正为 '客户基础',
旧值与数据库 CHECK 约束不一致,POST /api/retention-clue 写库会失败)。"""
BASIC_INFO = "客户基础"
CONSUMPTION = "消费习惯"
PLAY_PREF = "玩法偏好"
PROMO_PREF = "促销偏好"

View File

@@ -40,12 +40,19 @@ class ChatHistoryResponse(CamelModel):
class ReferenceCard(CamelModel):
"""引用卡片附加在 AI 回复消息中的结构化上下文数据。"""
"""引用卡片,附加在消息中的结构化上下文数据。
type: str # 'customer' | 'record'
W1-AI-CLOSURE 组 4 修正(P0-13):补全 link / source_page 字段,与
references.py:91 build_app1_reference_card 的实际输出对齐。之前 schema
缺这两字段导致 Pydantic 序列化时丢失,前端 wxml 的 link 跳转按钮永远拿不到 link。
"""
type: str # 'customer' | 'record' | 'member' | 'task' 等
title: str
summary: str
data: dict[str, str] # 键值对详情
summary: str = ""
data: dict[str, str] | None = None
link: str | None = None # 跳转链接(如 /pages/customer-detail/...)
source_page: str | None = None # 起源页面(用于回链定位)
class ChatMessageItem(CamelModel):

View File

@@ -8,7 +8,12 @@ from app.schemas.base import CamelModel
class AiStrategy(CamelModel):
color: str
"""App7 客户分析策略单条(对齐 demo 标杆 wxml `{{item.text}}` 单字段)。
W1-AI-CLOSURE 组 3 + 复盘修正:服务层把 prompt schema 的 {title, content}
拼接成 demo 标杆的 text 单字段;color 由前端按 index 轮换 6 色。
"""
text: str
class AiInsight(CamelModel):
@@ -71,8 +76,23 @@ class ConsumptionRecord(CamelModel):
recharge_amount: float | None = None
class RetentionClue(CamelModel):
type: str
"""维客线索单条(对齐 clue-card 组件契约 + task-detail.ts 字段命名)。
W1-AI-CLOSURE 组 3 修正:从 {type, text} 2 字段扩展为 6 字段。
- tag: 中文分类(如 "客户基础"),前端 wxml 显示用,可由 css 强制两行
- tag_color: 6 类配色 alias(VI-DESIGN-SYSTEM §2.1:primary/success/orange/gold/purple/error)
- emoji: 独立 emoji 字符,App8 prompt 输出独立字段(W1-AI-CLOSURE 组 1 加列)
- text: summary 主文案(20 字内)
- source: 显示用来源("AI" / "系统" / 录入人姓名),前端拼 "By:" 前缀
- desc: detail 详情(120 字内,可空,前端可折叠展示)
"""
tag: str
tag_color: str
emoji: str = ""
text: str
source: str = ""
desc: str = ""
class CustomerNote(CamelModel):
id: int

View File

@@ -123,8 +123,20 @@ class ServiceRecord(CamelModel):
date: str
class TacticItem(CamelModel):
"""App5 话术单条(场景 + 话术)。
W1-AI-CLOSURE 组 3 修正:talking_points 从 list[str] 改为 list[TacticItem],
对齐 App5Result.tactics(prompt schema 权威 — 之前查的 cache_type
'app5_talking_points' 与字段 'talking_points' 全是不存在的幽灵命名,P0-6)。
"""
scenario: str
script: str
class AiAnalysis(CamelModel):
"""AI 分析结果。"""
"""AI 分析结果(对齐 App4Result one_line_summary + action_suggestions)"""
summary: str
suggestions: list[str]
@@ -169,7 +181,7 @@ class TaskDetailResponse(CamelModel):
balance: float | None = None
# 扩展模块
retention_clues: list[RetentionClue]
talking_points: list[str]
talking_points: list[TacticItem]
service_summary: ServiceSummary
service_records: list[ServiceRecord]
ai_analysis: AiAnalysis

View File

@@ -26,15 +26,18 @@ class AICleanupService:
RETENTION_DAYS = 90
CACHE_LIMIT_PER_APP = 20_000
CACHE_APP_TYPES = [
# 8 类需要走 ai_cache 的应用(app1_chat 走 ai_messages,不进 ai_cache)
# 命名与 prompt 文件名一致(W1-AI-CLOSURE 组 1 数据库迁移已统一)。
CACHE_TYPES: tuple[str, ...] = (
"app2_finance",
"app2a_finance_area", # P0-11 修正:之前漏掉,导致 64 区域组合永不清理
"app3_clue",
"app4_analysis",
"app5_tactics",
"app6_note_analysis",
"app7_customer_analysis",
"app8_clue_consolidated",
]
"app6_note",
"app7_customer",
"app8_consolidation",
)
async def run_cleanup(self) -> dict:
"""执行全部清理,返回各步骤删除记录数。
@@ -119,7 +122,12 @@ class AICleanupService:
conn.close()
async def _cleanup_cache(self) -> dict[str, int]:
"""每个 App 类型保留最新 20,000 条,删除超出部分。"""
"""每个 cache_type 保留最新 20,000 条,删除超出部分。
P0-8 修正:ai_cache 表列名是 cache_type 不是 app_type;之前 SQL `WHERE
app_type=%s` 一直抛 UndefinedColumn 错误被 except 静默吞,导致 90 天清理
与 20K 上限完全失效,生产 ai_cache 表无限膨胀。
"""
from app.database import get_connection
result: dict[str, int] = {}
@@ -127,35 +135,35 @@ class AICleanupService:
try:
with conn.cursor() as cur:
cur.execute("SET statement_timeout = 300000")
for app_type in self.CACHE_APP_TYPES:
for cache_type in self.CACHE_TYPES:
try:
# 子查询找到该 app_type 第 20001 条的 created_at 作为截断点
# 子查询:找到该 cache_type 第 20001 条的 created_at 作为截断点
cur.execute(
"""
DELETE FROM biz.ai_cache
WHERE app_type = %s
WHERE cache_type = %s
AND id NOT IN (
SELECT id FROM biz.ai_cache
WHERE app_type = %s
WHERE cache_type = %s
ORDER BY created_at DESC
LIMIT %s
)
""",
(app_type, app_type, self.CACHE_LIMIT_PER_APP),
(cache_type, cache_type, self.CACHE_LIMIT_PER_APP),
)
deleted = cur.rowcount
result[app_type] = deleted
result[cache_type] = deleted
if deleted > 0:
logger.info(
"清理 ai_cache [%s]: 删除 %d",
app_type,
cache_type,
deleted,
)
except Exception:
logger.exception("清理 ai_cache [%s] 失败", app_type)
result[app_type] = -1
logger.exception("清理 ai_cache [%s] 失败", cache_type)
result[cache_type] = -1
conn.rollback()
# 重新开始事务以继续后续 app_type
# 重新开始事务以继续后续 cache_type
continue
conn.commit()
return result

View File

@@ -316,8 +316,13 @@ class ChatService:
conn = get_connection()
try:
with conn.cursor() as cur:
# W1-AI-CLOSURE 组 4 修正(P0-12):排除 role='system' 消息;
# 历史 35 条 system 行被前端误渲染成内容暴露 prompt 拼装细节。
cur.execute(
"SELECT COUNT(*) FROM biz.ai_messages WHERE conversation_id = %s",
"""
SELECT COUNT(*) FROM biz.ai_messages
WHERE conversation_id = %s AND role IN ('user', 'assistant')
""",
(chat_id,),
)
total = cur.fetchone()[0]
@@ -326,7 +331,7 @@ class ChatService:
"""
SELECT id, role, content, created_at, reference_card
FROM biz.ai_messages
WHERE conversation_id = %s
WHERE conversation_id = %s AND role IN ('user', 'assistant')
ORDER BY created_at ASC
LIMIT %s OFFSET %s
""",

View File

@@ -143,13 +143,13 @@ async def get_customer_detail(customer_id: int, site_id: int) -> dict:
# ── 扩展模块(独立 try/except 优雅降级)──
try:
ai_insight = _build_ai_insight(customer_id, conn)
ai_insight = _build_ai_insight(customer_id, site_id, conn)
except Exception:
logger.warning("构建 aiInsight 失败,降级为空", exc_info=True)
ai_insight = {"summary": "", "strategies": []}
try:
retention_clues = _build_retention_clues(customer_id, conn)
retention_clues = _build_retention_clues(customer_id, site_id, conn)
except Exception:
logger.warning("构建 retentionClues 失败,降级为空列表", exc_info=True)
retention_clues = []
@@ -223,24 +223,29 @@ async def get_customer_detail(customer_id: int, site_id: int) -> dict:
# ── 3.2 AI 洞察 / 维客线索 / 备注 ──────────────────────────
def _build_ai_insight(customer_id: int, conn) -> dict:
def _build_ai_insight(customer_id: int, site_id: int, conn) -> dict:
"""
构建 aiInsight 模块。
构建 aiInsight 模块(来自 App7 客户分析缓存)
查询 biz.ai_cache WHERE cache_type='app4_analysis' AND target_id=customerId
解析 result_json JSON。无缓存时返回空默认值。
查询 biz.ai_cache WHERE cache_type='app7_customer' AND target_id=customerId
AND site_id=site_id。无缓存时返回空默认值。
App7Result schema: {strategies: [{title, content}], summary: str}
"""
with conn.cursor() as cur:
cur.execute(
"""
SELECT result_json
FROM biz.ai_cache
WHERE cache_type = 'app4_analysis'
WHERE cache_type = 'app7_customer'
AND site_id = %s
AND target_id = %s
AND COALESCE(status, 'valid') = 'valid'
AND (expires_at IS NULL OR expires_at > now())
ORDER BY created_at DESC
LIMIT 1
""",
(str(customer_id),),
(site_id, str(customer_id)),
)
row = cur.fetchone()
@@ -255,37 +260,69 @@ def _build_ai_insight(customer_id: int, conn) -> dict:
summary = data.get("summary", "")
strategies_raw = data.get("strategies", [])
strategies = []
# App7Result schema: strategies = [{title, content}],但前端 demo 标杆 wxml 用单
# 字段 text(`{{item.text}}`)。在 service 层拼接成 demo 形态,前端保持 demo 一致。
for s in strategies_raw:
if isinstance(s, dict):
strategies.append({
"color": s.get("color", ""),
"text": s.get("text", ""),
})
t = (s.get("title") or "").strip()
c = (s.get("content") or "").strip()
text = f"{t}{c}" if t and c else (c or t)
strategies.append({"text": text})
return {"summary": summary, "strategies": strategies}
def _build_retention_clues(customer_id: int, conn) -> list[dict]:
def _build_retention_clues(customer_id: int, site_id: int, conn) -> list[dict]:
"""
构建 retentionClues 模块。
查询 public.member_retention_clue,按 recorded_at 倒序。
查询 public.member_retention_clue(含 emoji 独立列、source、detail
按 recorded_at 倒序,跨 source(manual / ai_consumption / ai_note)合并。
返回字段对齐 clue-card 组件契约 + xcx_customers.RetentionClue schema:
{tag, tag_color, emoji, text, source, desc}
"""
# CHANGE 2026-03-23 | BUG: clue_type/clue_text 列不存在,应为 category/summarycreated_at → recorded_at
from app.utils.clue_category import (
CATEGORY_TAG_COLOR,
SOURCE_DISPLAY_NAME,
format_category_tag,
)
with conn.cursor() as cur:
cur.execute(
"""
SELECT category, summary
SELECT category, summary, detail, emoji, source, recorded_by_name
FROM public.member_retention_clue
WHERE member_id = %s
AND site_id = %s
AND is_hidden = false
ORDER BY recorded_at DESC
""",
(customer_id,),
(customer_id, site_id),
)
rows = cur.fetchall()
return [{"type": r[0] or "", "text": r[1] or ""} for r in rows]
result: list[dict] = []
for category, summary, detail, emoji, source, recorded_by_name in rows:
category_str = category or ""
# source 显示规则(用户拍板:AI 来源用统一短标识 "AI",前端渲染 AI icon):
# - ai_consumption / ai_note → "AI"(舍弃 providers 详细文字,前端用 icon)
# - manual + recorded_by_name 非空 → 姓名(如"小燕")
# - manual + 空 → "系统"
src = source or "manual"
if src in ("ai_consumption", "ai_note"):
display_source = "AI"
else:
display_source = recorded_by_name or SOURCE_DISPLAY_NAME.get(src, "系统")
result.append({
"tag": format_category_tag(category_str),
"tag_color": CATEGORY_TAG_COLOR.get(category_str, "primary"),
"emoji": emoji or "",
"text": summary or "",
"source": display_source,
"desc": detail or "",
})
return result
NOTE_TYPE_LABELS = {"normal": "备注", "follow_up": "回访", "system": "系统", "ai": "AI"}

View File

@@ -468,19 +468,10 @@ _COURSE_TYPE_CLASS_MAP: dict[str, str] = {
"激励": "incentive",
}
# 维客线索 category → tag_color 映射
# CHANGE 2026-03-24 | 值改为前端 clue-card 组件 CSS 类名后缀primary/success/...
# 不再用十六进制颜色——WXSS 类名 `clue-tag-#0052d9` 无效。
_CATEGORY_COLOR_MAP: dict[str, str] = {
"客户基础": "primary",
"客户基础信息": "primary",
"消费习惯": "error",
"玩法偏好": "success",
"促销偏好": "orange",
"促销接受": "orange",
"社交关系": "purple",
"重要反馈": "error",
}
# W1-AI-CLOSURE 组 5:维客线索 category → tag_color 映射已迁移至
# app.utils.clue_category.CATEGORY_TAG_COLOR(VI-DESIGN-SYSTEM v1.1 权威映射,
# 与 customer_service 共享)。原本地 _CATEGORY_COLOR_MAP 与 VI 规范不一致
# (消费习惯=error 应是 success;玩法偏好=success 应是 orange),已删除。
@trace_service(description_zh="map_course_type_class", description_en="Map Course Type Class")
@@ -514,20 +505,10 @@ def sanitize_tag(raw_tag: str | None) -> str:
return raw_tag.replace("\n", " ").strip()
def _extract_emoji_and_text(summary: str | None) -> tuple[str, str]:
"""
从 summary 中提取 emoji 前缀和正文。
AI 写入格式: "📅 偏好周末下午时段消费" → ("📅", "偏好周末下午时段消费")
手动写入无 emoji: "喜欢打中式" → ("", "喜欢打中式")
"""
if not summary:
return "", ""
# 检查第一个字符是否为 emoji非 ASCII 且非中文常用范围)
first_char = summary[0]
if ord(first_char) > 0x2600 and summary[1:2] == " ":
return first_char, summary[2:].strip()
return "", summary.strip()
# W1-AI-CLOSURE 组 5:_extract_emoji_and_text 已删除。
# 维客线索 emoji 在数据库已独立列(public.member_retention_clue.emoji),
# 不再需要从 summary 字符串解析。dispatcher._write_retention_clue 直接写
# emoji 列,task_manager / customer_service 直接读 emoji 列。
def _format_time(dt: datetime | None) -> str | None:
@@ -693,6 +674,8 @@ async def get_task_list_v2(
logger.warning("ETL 批量查询失败,降级为空数据", exc_info=True)
# ── 6. 查询 ai_cache 获取 aiSuggestion优雅降级 ──
# App4Result schema: {task_description, action_suggestions[], one_line_summary}
# aiSuggestion 用于任务列表一行简短提示,取 one_line_summary 最贴合。
ai_suggestion_map: dict[int, str] = {}
try:
runtime_ctx = get_runtime_context(site_id, conn=conn)
@@ -708,6 +691,8 @@ async def get_task_list_v2(
WHERE site_id = %s
AND target_id = ANY(%s)
AND cache_type = 'app4_analysis'
AND COALESCE(status, 'valid') = 'valid'
AND (expires_at IS NULL OR expires_at > now())
ORDER BY created_at DESC
""",
(site_id, member_id_strs),
@@ -718,10 +703,11 @@ async def get_task_list_v2(
if target_id_str not in seen:
seen.add(target_id_str)
result = row[1] if isinstance(row[1], dict) else {}
summary = result.get("summary", "")
if summary:
# P0-7: App4 schema 是 one_line_summary,不是 summary
suggestion = result.get("one_line_summary", "")
if suggestion:
raw_target = target_id_str.split(":", 1)[-1]
ai_suggestion_map[int(raw_target)] = summary
ai_suggestion_map[int(raw_target)] = suggestion
conn.commit()
except Exception:
logger.warning("查询 ai_cache aiSuggestion 失败", exc_info=True)
@@ -1110,6 +1096,13 @@ async def get_task_detail(
logger.warning("ETL 查询 RS 指数失败", exc_info=True)
# ── 3. 查询维客线索 ──
# 字段对齐 xcx_customers.RetentionClue schema(W1-AI-CLOSURE 组 3):
# 直接读 emoji 独立列(不再从 summary 字符串抽取),tag_color 走 utils 共用映射。
from app.utils.clue_category import (
CATEGORY_TAG_COLOR,
SOURCE_DISPLAY_NAME,
format_category_tag,
)
retention_clues = []
try:
runtime_ctx = get_runtime_context(site_id, conn=conn)
@@ -1121,7 +1114,7 @@ async def get_task_detail(
with conn.cursor() as cur:
cur.execute(
"""
SELECT id, category, summary, detail, source
SELECT category, summary, detail, source, emoji, recorded_by_name
FROM public.member_retention_clue
WHERE member_id = %s AND site_id = %s
AND is_hidden = false
@@ -1130,29 +1123,38 @@ async def get_task_detail(
(member_id, site_id),
)
for clue_row in cur.fetchall():
category = clue_row[1] or ""
summary_raw = clue_row[2] or ""
detail = clue_row[3]
source = clue_row[4] or "manual"
category = clue_row[0] or ""
summary = clue_row[1] or ""
detail = clue_row[2]
source = clue_row[3] or "manual"
emoji = clue_row[4] or ""
recorded_by_name = clue_row[5] or ""
emoji, text = _extract_emoji_and_text(summary_raw)
tag = sanitize_tag(category)
tag_color = _CATEGORY_COLOR_MAP.get(tag, "primary")
# source 显示规则(用户拍板):AI 类用 "AI" 短标识(前端渲染 icon)
if source in ("ai_consumption", "ai_note"):
display_src = "AI"
else:
display_src = recorded_by_name or SOURCE_DISPLAY_NAME.get(source, "系统")
retention_clues.append({
"tag": tag,
"tag_color": tag_color,
"tag": format_category_tag(tag),
"tag_color": CATEGORY_TAG_COLOR.get(tag, "primary"),
"emoji": emoji,
"text": text,
"source": source,
"desc": detail,
"text": summary,
"source": display_src,
"desc": detail or "",
})
conn.commit()
except Exception:
logger.warning("查询维客线索失败", exc_info=True)
# ── 4. 查询 AI 缓存talkingPoints + aiAnalysis ──
talking_points: list[str] = []
# ── 4. 查询 AI 缓存(talkingPoints + aiAnalysis) ──
# P0-6 修正:cache_type 从不存在的 'app5_talking_points' 改为正确的 'app5_tactics';
# 字段从不存在的 'talking_points' 改为正确的 tactics[{scenario, script}]。
# P0-7 修正:App4 schema 字段不存在 summary/suggestions,实际为
# one_line_summary / action_suggestions / task_description。
# tactics 直接以对象列表透出,前端 task-detail 渲染 scenario 与 script 两栏。
talking_points: list[dict] = []
ai_analysis = {"summary": "", "suggestions": []}
try:
with conn.cursor() as cur:
@@ -1161,7 +1163,9 @@ async def get_task_detail(
SELECT cache_type, result_json
FROM biz.ai_cache
WHERE target_id = %s AND site_id = %s
AND cache_type IN ('app4_analysis', 'app5_talking_points')
AND cache_type IN ('app4_analysis', 'app5_tactics')
AND COALESCE(status, 'valid') = 'valid'
AND (expires_at IS NULL OR expires_at > now())
ORDER BY created_at DESC
""",
(member_target_id, site_id),
@@ -1175,16 +1179,21 @@ async def get_task_detail(
result = cache_row[1] if isinstance(cache_row[1], dict) else {}
if cache_type == "app5_talking_points":
# talkingPoints: 话术列表
points = result.get("talking_points", [])
if isinstance(points, list):
talking_points = [str(p) for p in points]
if cache_type == "app5_tactics":
tactics = result.get("tactics", [])
if isinstance(tactics, list):
talking_points = [
{
"scenario": t.get("scenario", ""),
"script": t.get("script", ""),
}
for t in tactics
if isinstance(t, dict)
]
elif cache_type == "app4_analysis":
# aiAnalysis: summary + suggestions
ai_analysis = {
"summary": result.get("summary", ""),
"suggestions": result.get("suggestions", []),
"summary": result.get("one_line_summary", ""),
"suggestions": result.get("action_suggestions", []),
}
conn.commit()
except Exception:

View File

@@ -0,0 +1,64 @@
# -*- coding: utf-8 -*-
"""维客线索分类映射工具(W1-AI-CLOSURE 组 5)。
集中管理维客线索的"中文分类 → 视觉/显示属性"映射,供 customer_service 和
task_manager 共用,避免重复定义。
来源权威:
- 6 类 categoryColor: docs/miniprogram-dev/design-system/VI-DESIGN-SYSTEM.md §2.1
- source 三态: docs/ai/system-prompts/app8_consolidation.md §五
- 用户拍板(2026-05-06): AI 来源统一显示为 "AI"(前端拼 "By:AI")
"""
from __future__ import annotations
from types import MappingProxyType
# 6 类客户线索分类 → tag_color(英文别名,前端 clue-card 接收)
# VI-DESIGN-SYSTEM §2.1 权威映射(玩法偏好=orange,与 demo 早期 purple 不一致以本规范为准)
CATEGORY_TAG_COLOR: MappingProxyType[str, str] = MappingProxyType({
"客户基础": "primary",
"消费习惯": "success",
"玩法偏好": "orange",
"促销偏好": "gold",
"促销接受": "gold", # App8 prompt 里的别名
"社交关系": "purple",
"重要反馈": "error",
})
# 6 类客户线索分类 → 默认 emoji(用于手工录入/AI 输出 emoji 为空时的兜底)
CATEGORY_EMOJI_FALLBACK: MappingProxyType[str, str] = MappingProxyType({
"客户基础": "👤",
"消费习惯": "💰",
"玩法偏好": "🎮",
"促销偏好": "🎁",
"促销接受": "🎁",
"社交关系": "👥",
"重要反馈": "⚠️",
})
# 数据库 source 字段 → 显示用名称(用户拍板:AI 类全显示 "AI",手工 fallback "系统")
# 实际 source 优先级:recorded_by_name > SOURCE_DISPLAY_NAME[source]
SOURCE_DISPLAY_NAME: MappingProxyType[str, str] = MappingProxyType({
"manual": "系统",
"ai_consumption": "AI",
"ai_note": "AI",
})
def format_category_tag(category: str) -> str:
"""把 category 中文字面量格式化为 clue-card tag(强制 2+2 两行)。
db 存的是 4 字字面量(如 "消费习惯"),demo 标杆 wxml `white-space: pre-line`
依赖 `\n` 强制 2+2 布局("消费\n习惯")。如果不强制,4 字在 72rpx 容器内可能被
css 自动换成 3+1 / 1+3 而非 2+2,视觉错位。
输入空 / 长度 != 4 / 含 \n 的字符串原样返回。
"""
if not category or "\n" in category:
return category or ""
if len(category) == 4:
return f"{category[:2]}\n{category[2:]}"
return category

View File

@@ -1,55 +1,113 @@
"""AI 事件 WebSocket 推送端点。
提供
- /ws/ai-cache/{site_id} — 缓存更新 / 失效事件
- /ws/ai-alerts/{site_id} — AI 告警事件Phase 3.1
提供:
- /ws/ai-cache/{site_id}?token=xxx — 缓存更新 / 失效事件
- /ws/ai-alerts/{site_id}?token=xxx — AI 告警事件(Phase 3.1)
协议
- 客户端连接 → 服务端 accept → 订阅 EventBus → 持续 send_json 事件
- 事件格式:{"type": "cache_updated|cache_invalidated|alert_created|...", "site_id": int, "payload": {...}}
协议:
- 客户端连接(必须带 token query)→ 服务端校验 JWT → accept →
订阅 EventBus → 持续 send_json 事件
- 事件格式:{"type": "cache_updated|alert_created|...", "site_id": int, "payload": {...}}
- 服务端关闭或客户端断开时清理订阅
用 site_id=-1 表示全局订阅收所有门店事件admin-web 全局监控用)。
W1-AI-CLOSURE 组 7 安全加固(P0-9):
- 新增 token query 参数,JWT 解码失败 → 关闭(4401)
- site_id 必须与 token 中的 site_id 一致;site_id=-1 全局订阅要求
token 角色含 super_admin
- 不再允许任何用户监听任意门店的 AI 事件流
"""
from __future__ import annotations
import logging
from fastapi import APIRouter, WebSocket, WebSocketDisconnect
from fastapi import APIRouter, Query, WebSocket, WebSocketDisconnect, status
from jose import JWTError
from ..ai.event_bus import AIEvent, get_event_bus
from ..auth.jwt import decode_access_token
logger = logging.getLogger(__name__)
ws_router = APIRouter()
_WS_CLOSE_AUTH_FAILED = 4401 # 自定义 close code(WebSocket close codes 4000-4999 给应用使用)
def _authorize_ws(token: str | None, site_id: int) -> bool:
"""校验 WS 连接的 JWT token 与 site_id。
返回 True 表示通过,False 表示拒绝。
site_id == -1 时要求 token roles 含 super_admin。
"""
if not token:
return False
try:
payload = decode_access_token(token)
except JWTError:
return False
token_site_id = payload.get("site_id")
roles = payload.get("roles") or []
if not isinstance(roles, list):
roles = []
if site_id == -1:
# 全局订阅(admin-web 全局监控):仅 super_admin
return "super_admin" in roles
# 站点订阅:token 的 site_id 必须等于 URL 中的 site_id
# super_admin 跨站点放行
return token_site_id == site_id or "super_admin" in roles
@ws_router.websocket("/ws/ai-cache/{site_id}")
async def ws_ai_cache(websocket: WebSocket, site_id: int) -> None:
async def ws_ai_cache(
websocket: WebSocket,
site_id: int,
token: str | None = Query(default=None),
) -> None:
"""AI 缓存事件推送。
site_id=-1 表示订阅全局收所有门店的 cache_updated / cache_invalidated)。
site_id=-1 表示订阅全局(收所有门店的 cache_updated / cache_invalidated),
需 super_admin token。
"""
await _serve_event_stream(websocket, site_id, endpoint="ai-cache")
await _serve_event_stream(websocket, site_id, token=token, endpoint="ai-cache")
@ws_router.websocket("/ws/ai-alerts/{site_id}")
async def ws_ai_alerts(websocket: WebSocket, site_id: int) -> None:
"""AI 告警事件推送Phase 3.1)。
async def ws_ai_alerts(
websocket: WebSocket,
site_id: int,
token: str | None = Query(default=None),
) -> None:
"""AI 告警事件推送(Phase 3.1)。
site_id=-1 表示订阅全局告警。
site_id=-1 表示订阅全局告警,需 super_admin token
事件 type: alert_created / alert_updated / budget_exceeded / circuit_opened。
"""
await _serve_event_stream(websocket, site_id, endpoint="ai-alerts")
await _serve_event_stream(websocket, site_id, token=token, endpoint="ai-alerts")
async def _serve_event_stream(
websocket: WebSocket, site_id: int, endpoint: str,
websocket: WebSocket,
site_id: int,
*,
token: str | None,
endpoint: str,
) -> None:
"""共享事件流处理逻辑。"""
"""共享事件流处理逻辑(含 token 鉴权)"""
if not _authorize_ws(token, site_id):
await websocket.close(code=_WS_CLOSE_AUTH_FAILED, reason="auth required")
logger.warning(
"WS %s 鉴权失败: site_id=%s token_present=%s",
endpoint, site_id, bool(token),
)
return
await websocket.accept()
# -1 映射为全局订阅None
# -1 映射为全局订阅(None)
subscribe_key: int | None = None if site_id == -1 else site_id
logger.info(
"WS %s 连接建立: site_id=%s", endpoint, subscribe_key if subscribe_key else "ALL",

View File

@@ -274,7 +274,7 @@ class MemberConsumptionTask(BaseDwsTask):
生日来源dim_member.birthdayAPI 来源)
CHANGE 2026-02-26 | 维客线索重构:移除 FDW member_birthday_manual 读取,
生日不再单独补录,归入维客线索"客户基础信息"大类
生日不再单独补录,归入维客线索"客户基础"大类
"""
cutoff = self.config.get("app.business_day_start_hour", 8)
biz_expr_create = biz_date_sql_expr("m.create_time", cutoff)

View File

@@ -367,7 +367,7 @@ class MemberVisitTask(BaseDwsTask):
生日来源dim_member.birthdayAPI 来源)
CHANGE 2026-02-26 | 维客线索重构:移除 FDW member_birthday_manual 读取,
生日不再单独补录,归入维客线索"客户基础信息"大类
生日不再单独补录,归入维客线索"客户基础"大类
"""
sql = """
SELECT

View File

@@ -5,7 +5,17 @@
<view class="clue-content">
<view class="clue-text-container">
<text class="clue-text"><text class="clue-emoji">{{emoji}}</text> {{title}}</text>
<text class="clue-source">{{source}}</text>
<!-- source = "AI" 时用 icon 替代文字(W1-AI-CLOSURE 复盘:节字符 + 直观);其他显示文字 -->
<view class="clue-source">
<text class="clue-source-prefix">By:</text>
<image
wx:if="{{source === 'AI' || source === 'By:AI'}}"
class="clue-source-ai-icon"
src="/assets/icons/ai-robot.svg"
mode="aspectFit"
/>
<text wx:else class="clue-source-text">{{source}}</text>
</view>
</view>
</view>
<view class="clue-desc" wx:if="{{content}}">

View File

@@ -103,6 +103,8 @@
position: absolute;
bottom: 0;
right: 0;
display: flex;
align-items: center;
font-size: 24rpx;
line-height: 36rpx;
color: var(--color-gray-7);
@@ -111,6 +113,17 @@
padding-left: 50rpx;
z-index: 1;
}
.clue-source-prefix,
.clue-source-text {
font-size: 24rpx;
color: var(--color-gray-7);
}
.clue-source-ai-icon {
width: 32rpx;
height: 32rpx;
margin-left: 2rpx;
vertical-align: middle;
}
.clue-desc {
line-height: 30rpx;

View File

@@ -133,7 +133,7 @@
<!-- 自定义底部导航栏 -->
<board-tab-bar active="board" />
<!-- AI 悬浮按钮 — 在导航栏上方 -->
<ai-float-button />
<!-- AI 悬浮按钮 — 在导航栏上方(W1-AI-CLOSURE 组 6:补 sourcePage) -->
<ai-float-button sourcePage="board-coach" />
<dev-fab wx:if="{{false}}" />

View File

@@ -312,7 +312,7 @@
<!-- 自定义底部导航栏 -->
<board-tab-bar active="board" />
<!-- AI 悬浮按钮 -->
<ai-float-button />
<!-- AI 悬浮按钮(W1-AI-CLOSURE 组 6:补 sourcePage) -->
<ai-float-button sourcePage="board-customer" />
<dev-fab wx:if="{{false}}" />

View File

@@ -876,7 +876,8 @@
</view>
</block>
<!-- AI 悬浮按钮 -->
<ai-float-button bottom="{{200}}" />
<!-- AI 悬浮按钮(W1-AI-CLOSURE 组 6:补 sourcePage,具体 timeDimension/areaFilter
ai-float-button 组件按 page data 自动收集,这里不重复传 pageFilters) -->
<ai-float-button bottom="{{200}}" sourcePage="board-finance" />
<dev-fab wx:if="{{false}}" />

View File

@@ -54,8 +54,8 @@
<text class="footer-text">— 已加载全部记录 —</text>
</view>
<!-- AI 悬浮按钮 -->
<ai-float-button />
<!-- AI 悬浮按钮(W1-AI-CLOSURE 组 6:对话列表入口仍可启动新对话) -->
<ai-float-button sourcePage="chat-history" />
</view>
<dev-fab />

View File

@@ -10,6 +10,7 @@ import { checkPageAccess } from '../../utils/auth-guard'
import { fetchChatMessages, fetchChatMessagesByContext } from '../../services/api'
import { formatRelativeTime, formatIMTime, shouldShowTimeDivider } from '../../utils/time'
import { API_BASE } from '../../utils/config'
import { mdToRichHtml } from '../../utils/markdown'
/** API 返回的消息项类型 */
interface ApiMessageItem {
@@ -31,12 +32,15 @@ function toDataList(data?: Record<string, string>): Array<{ key: string; value:
return Object.keys(data).map((k) => ({ key: k, value: data[k] }))
}
/** 为消息列表补充展示字段时间分割线、IM时间、引用卡片*/
/** 为消息列表补充展示字段时间分割线、IM时间、引用卡片、md 渲染*/
function enrichMessages(msgs: ApiMessageItem[]) {
return msgs.map((m, i) => ({
id: String(m.id),
role: m.role,
content: m.content,
// W1-AI-CLOSURE 任务 1:AI 消息预解析 markdown 为 rich-text html
// (用户消息保持纯文本)
contentHtml: m.role === 'assistant' ? mdToRichHtml(m.content) : '',
timestamp: m.createdAt,
timeLabel: formatRelativeTime(m.createdAt),
imTimeLabel: formatIMTime(m.createdAt),
@@ -146,6 +150,8 @@ type DisplayMessage = {
id: string
role: 'user' | 'assistant'
content: string
/** AI 消息预解析的 markdown → rich-text html(用户消息为空字符串)*/
contentHtml?: string
timestamp: string
timeLabel?: string
imTimeLabel?: string
@@ -223,13 +229,27 @@ Page({
this.loadMessages(options.historyId)
} else if (options?.taskId) {
// 从 task-detail 跳转:同一 taskId 始终复用同一对话(无时限)
// W1-AI-CLOSURE 组 6:同步 sourcePage + pageContext.contextId 让后端 SSE
// 阶段能注入页面上下文(build_page_text)+ build_app1_reference_card 跳转卡。
this.setData({
sourcePage: 'task-detail',
pageFilters: { contextId: options.taskId },
})
this.loadMessagesByContext('task', options.taskId)
} else if (options?.customerId) {
// 从 customer-detail 跳转:≤ 3 天复用、> 3 天新建
this.setData({ customerId: options.customerId })
this.setData({
customerId: options.customerId,
sourcePage: 'customer-detail',
pageFilters: { contextId: options.customerId },
})
this.loadMessagesByContext('customer', options.customerId)
} else if (options?.coachId) {
// 从 coach-detail 跳转:≤ 3 天复用、> 3 天新建
this.setData({
sourcePage: 'coach-detail',
pageFilters: { contextId: options.coachId },
})
this.loadMessagesByContext('coach', options.coachId)
} else if (options?.sourcePage) {
// 看板类入口:保存来源页面和筛选参数
@@ -411,6 +431,7 @@ Page({
id: aiMsgId,
role: 'assistant',
content: '',
contentHtml: '',
timestamp: aiNow,
timeLabel: '刚刚',
imTimeLabel: formatIMTime(aiNow),
@@ -429,12 +450,12 @@ Page({
let fullContent = ''
const parser = new SSEParser(
// onMessage: 逐 token 追加
// onMessage: 逐 token 追加 + 实时 markdown 解析
(token: string) => {
fullContent += token
const key = `messages[${aiIndex}].content`
this.setData({
[key]: fullContent,
[`messages[${aiIndex}].content`]: fullContent,
[`messages[${aiIndex}].contentHtml`]: mdToRichHtml(fullContent),
streamingContent: fullContent,
})
this.scrollToBottom()

View File

@@ -82,14 +82,15 @@
</view>
</view>
<!-- AI 消息:左对齐白色 -->
<!-- AI 消息:左对齐白色W1-AI-CLOSURE 任务 1流式 markdown 实时渲染)-->
<view class="message-row message-assistant" wx:else id="msg-{{item.id}}">
<view class="ai-avatar">
<image src="/assets/icons/ai-robot.svg" class="ai-avatar-img" mode="aspectFit" />
</view>
<view class="bubble-col">
<view class="bubble bubble-assistant">
<text class="bubble-text">{{item.content}}</text>
<rich-text wx:if="{{item.contentHtml}}" class="bubble-md" nodes="{{item.contentHtml}}" />
<text wx:else class="bubble-text">{{item.content}}</text>
</view>
<!-- AI 侧引用卡片(后端 referenceCard 附加在 assistant 回复中)-->
<view

View File

@@ -376,3 +376,86 @@ page {
width: 44rpx;
height: 44rpx;
}
/* W1-AI-CLOSURE 任务 1: AI 消息 markdown 渲染样式 ===================== */
/* rich-text 不允许内联 style,样式通过 class 控制 */
.bubble-md {
font-size: 30rpx;
line-height: 1.65;
color: var(--color-gray-13, #242424);
word-break: break-word;
}
/* 段落 */
.md-p {
margin: 0 0 16rpx;
}
.md-p:last-child {
margin-bottom: 0;
}
/* 标题 */
.md-h1 { font-size: 38rpx; font-weight: 700; margin: 24rpx 0 14rpx; color: #1a1a1a; }
.md-h2 { font-size: 34rpx; font-weight: 700; margin: 22rpx 0 12rpx; color: #1a1a1a; }
.md-h3 { font-size: 30rpx; font-weight: 600; margin: 18rpx 0 10rpx; color: #2c2c2c; }
.md-h4 { font-size: 28rpx; font-weight: 600; margin: 14rpx 0 8rpx; color: #2c2c2c; }
/* 列表 */
.md-ul, .md-ol {
margin: 8rpx 0 16rpx;
padding-left: 36rpx;
}
.md-li {
margin-bottom: 6rpx;
line-height: 1.6;
}
/* 表格 */
.md-table {
border-collapse: collapse;
margin: 12rpx 0 18rpx;
width: 100%;
font-size: 26rpx;
background: #fafafa;
border-radius: 12rpx;
overflow: hidden;
}
.md-th, .md-td {
border: 1rpx solid #e0e0e0;
padding: 10rpx 14rpx;
text-align: left;
vertical-align: top;
}
.md-th {
background: rgba(0, 82, 217, 0.06);
font-weight: 600;
color: #2c2c2c;
}
/* 行内代码 */
.md-code {
font-family: SFMono-Regular, Menlo, Consolas, monospace;
font-size: 26rpx;
background: rgba(0, 0, 0, 0.05);
padding: 2rpx 10rpx;
border-radius: 6rpx;
color: #c7254e;
}
/* 代码块 */
.md-pre {
margin: 12rpx 0 16rpx;
padding: 16rpx 20rpx;
background: #2d2d2d;
border-radius: 12rpx;
overflow-x: auto;
}
.md-code-block {
font-family: SFMono-Regular, Menlo, Consolas, monospace;
font-size: 24rpx;
line-height: 1.55;
color: #e0e0e0;
white-space: pre;
background: transparent;
}

View File

@@ -319,6 +319,9 @@
</view>
</view>
</view>
<!-- AI 悬浮按钮(W1-AI-CLOSURE 组 6:补 coach-detail 此前死注册的组件 + sourcePage) -->
<ai-float-button coachId="{{detail.id}}" sourcePage="coach-detail" />
</block>
<dev-fab />

View File

@@ -117,7 +117,7 @@
</view>
</block>
<!-- AI 悬浮按钮 -->
<ai-float-button />
<!-- AI 悬浮按钮(W1-AI-CLOSURE 组 6:补 sourcePage) -->
<ai-float-button sourcePage="coach-service-records" />
<dev-fab />

View File

@@ -55,17 +55,21 @@ Page({
},
phoneVisible: false,
aiColor: "indigo" as "red" | "orange" | "yellow" | "blue" | "indigo" | "purple",
// 对齐 demo 标杆 wxml(`{{item.text}}` 单字段);color 由前端按 index 轮换。
aiInsight: {
summary: '',
strategies: [
{ color: '', text: '' },
{ color: '', text: '' },
],
strategies: [] as Array<{ color: string; text: string }>,
},
clues: [
{ category: '', categoryColor: '', text: '', source: '' },
{ category: '', categoryColor: '', text: '', source: '', detail: '' },
],
// W1-AI-CLOSURE 组 6:clues 字段对齐 RetentionClue schema
// {tag, tag_color, emoji, text, source, desc} → camelCase {tag, tagColor, emoji, text, source, desc}
clues: [] as Array<{
tag: string
tagColor: string
emoji: string
text: string
source: string
desc: string
}>,
coachTasks: [
{ name: '', level: '', levelColor: '', taskType: '', taskColor: '', bgClass: '', status: '', lastService: '', metrics: [{ label: '', value: '' }] },
{ name: '', level: '', levelColor: '', taskType: '', taskColor: '', bgClass: '', status: '', lastService: '', metrics: [{ label: '', value: '' }] },
@@ -142,15 +146,19 @@ Page({
},
async _loadAIInsight(memberId: string) {
const cache = await fetchAICache('app7_customer_analysis', memberId)
// cache_type 统一为 'app7_customer'(W1-AI-CLOSURE 组 1 数据库迁移已对齐)。
// App7Result.strategies = [{title, content}],前端拼成 demo 标杆 {color, text} 单字段。
const cache = await fetchAICache('app7_customer', memberId)
if (!cache?.result_json) return
const rj = cache.result_json as any
const rj = cache.result_json as { summary?: string; strategies?: Array<{ title?: string; content?: string; text?: string }> }
const COLORS = ['blue', 'indigo', 'purple', 'red', 'orange', 'yellow'] as const
const strategies = Array.isArray(rj.strategies)
? rj.strategies.map((s: any, i: number) => ({
color: COLORS[i % COLORS.length],
text: s.title || s.text || '',
}))
? rj.strategies.map((s, i) => {
const t = (s?.title || '').trim()
const c = (s?.content || '').trim()
const text = s?.text || (t && c ? `${t}${c}` : (c || t))
return { color: COLORS[i % COLORS.length], text }
})
: []
this.setData({
'aiInsight.summary': rj.summary || '',

View File

@@ -59,8 +59,8 @@
<!-- 主体内容 -->
<view class="main-content" >
<!-- AI 智能洞察 -->
<view class="ai-insight-card">
<!-- AI 智能洞察(W1-AI-CLOSURE 复盘:cache miss 时整段不渲染,避免空白卡) -->
<view class="ai-insight-card" wx:if="{{aiInsight.summary || aiInsight.strategies.length > 0}}">
<view class="ai-insight-header">
<view class="ai-icon-box">
<image class="ai-icon-img" src="/assets/icons/ai-robot.svg" mode="aspectFit" />
@@ -84,7 +84,7 @@
</view>
<!-- 维客线索 -->
<view class="card">
<view class="card" wx:if="{{clues.length > 0}}">
<view class="card-header">
<text class="section-title title-green">维客线索</text>
<ai-title-badge color="{{aiColor}}" />
@@ -93,12 +93,12 @@
<clue-card
wx:for="{{clues}}"
wx:key="index"
tag="{{item.category}}"
category="{{item.categoryColor}}"
emoji=""
tag="{{item.tag}}"
category="{{item.tagColor}}"
emoji="{{item.emoji}}"
title="{{item.text}}"
source="By:{{item.source}}"
content="{{item.detail}}"
source="{{item.source}}"
content="{{item.desc}}"
/>
</view>
</view>
@@ -325,8 +325,8 @@
<!-- 备注弹窗 -->
<note-modal visible="{{noteModalVisible}}" customerName="{{detail.name}}" showExpandBtn="{{false}}" showRating="{{false}}" bind:confirm="onNoteConfirm" bind:cancel="onNoteCancel" />
<!-- AI 悬浮按钮 -->
<ai-float-button customerId="{{detail.id}}" />
<!-- AI 悬浮按钮(W1-AI-CLOSURE 组 6:补 sourcePage 让 chat 上下文捕获生效) -->
<ai-float-button customerId="{{detail.id}}" sourcePage="customer-detail" />
</block>
<dev-fab />

View File

@@ -121,8 +121,8 @@
</view>
<!-- AI 悬浮按钮 -->
<ai-float-button customerId="{{customerId}}" />
<!-- AI 悬浮按钮(W1-AI-CLOSURE 组 6:补 sourcePage) -->
<ai-float-button customerId="{{customerId}}" sourcePage="customer-service-records" />
</block>

View File

@@ -62,7 +62,7 @@
</view>
</view>
<!-- AI 悬浮按钮 — TabBar 页面 bottom 200rpx -->
<ai-float-button visible="{{true}}" />
<!-- AI 悬浮按钮 — TabBar 页面 bottom 200rpx(W1-AI-CLOSURE 组 6:补 sourcePage) -->
<ai-float-button visible="{{true}}" sourcePage="my-profile" />
<dev-fab wx:if="{{false}}" />

View File

@@ -50,8 +50,8 @@
<text class="footer-text">— 没有更多了 —</text>
</view>
<!-- AI 悬浮按钮 -->
<ai-float-button />
<!-- AI 悬浮按钮(W1-AI-CLOSURE 组 6:补 sourcePage) -->
<ai-float-button sourcePage="notes" />
</view>
<dev-fab />

View File

@@ -117,7 +117,7 @@
</view>
</block>
<!-- AI 悬浮按钮 -->
<ai-float-button />
<!-- AI 悬浮按钮(W1-AI-CLOSURE 组 6:补 sourcePage) -->
<ai-float-button sourcePage="performance-records" />
<dev-fab />

View File

@@ -296,7 +296,7 @@
</view>
</block>
<!-- AI 悬浮按钮 -->
<ai-float-button />
<!-- AI 悬浮按钮(W1-AI-CLOSURE 组 6:补 sourcePage) -->
<ai-float-button sourcePage="performance" />
<dev-fab />

View File

@@ -13,6 +13,7 @@
"t-loading": "tdesign-miniprogram/loading/loading",
"clue-card": "/components/clue-card/clue-card",
"service-record-card": "/components/service-record-card/service-record-card",
"dev-fab": "/components/dev-fab/dev-fab"
"dev-fab": "/components/dev-fab/dev-fab",
"ai-float-button": "/components/ai-float-button/ai-float-button"
}
}

View File

@@ -10,10 +10,10 @@ import { sortByTimestamp } from '../../utils/sort'
import { formatRelativeTime } from '../../utils/time'
import { formatStorageLevel } from '../../utils/storage-level'
/** 维客线索项 */
/** 维客线索项(W1-AI-CLOSURE 组 6:tagColor 6 类对齐 VI-DESIGN-SYSTEM v1.1) */
interface RetentionClue {
tag: string
tagColor: 'primary' | 'success' | 'purple' | 'error'
tagColor: 'primary' | 'success' | 'orange' | 'gold' | 'purple' | 'error'
emoji: string
text: string
source: string
@@ -21,6 +21,12 @@ interface RetentionClue {
expanded?: boolean
}
/** 话术参考项(W1-AI-CLOSURE 组 6:对齐 App5Result.tactics) */
interface TacticItem {
scenario: string
script: string
}
/** 服务记录项 */
interface ServiceRecord {
table: string
@@ -58,12 +64,8 @@ Page({
{ tag: '', tagColor: 'error', emoji: '', text: '', source: '', desc: '', expanded: false },
] as RetentionClue[],
// --- 话术参考 ---
talkingPoints: [
'',
'',
'',
] as string[],
// --- 话术参考(对齐 App5Result.tactics 字段) ---
talkingPoints: [] as TacticItem[],
copiedIndex: -1,
// --- 近期服务记录 ---
@@ -264,13 +266,13 @@ Page({
this.setData({ [key]: !current })
},
/** 复制话术 */
/** 复制话术(W1-AI-CLOSURE 组 6:tactics 含 scenario+script 双字段,复制 script 部分) */
onCopySpeech(e: WechatMiniprogram.BaseEvent) {
const idx = e.currentTarget.dataset.index as number
const text = this.data.talkingPoints[idx]
if (!text) return
const item = this.data.talkingPoints[idx]
if (!item || !item.script) return
wx.setClipboardData({
data: text,
data: item.script,
success: () => {
this.setData({ copiedIndex: idx })
setTimeout(() => this.setData({ copiedIndex: -1 }), 2000)

View File

@@ -95,7 +95,7 @@
<view class="speech-bubble" wx:for="{{talkingPoints}}" wx:key="index">
<view class="speech-text-wrap">
<ai-inline-icon color="{{aiColor}}" />
<text class="speech-text">{{item}}</text>
<text class="speech-text">{{item.scenario ? item.scenario + '' + item.script : item.script}}</text>
</view>
<view class="speech-copy-row">
<view class="copy-btn" bindtap="onCopySpeech" data-index="{{index}}" hover-class="copy-btn--hover">
@@ -277,4 +277,7 @@
<text>🔧</text>
</view>
<!-- AI 悬浮按钮(W1-AI-CLOSURE 组 6:补 task-detail 整页缺失的入口 + sourcePage) -->
<ai-float-button taskId="{{detail.id}}" sourcePage="task-detail" />
</block>

View File

@@ -329,8 +329,8 @@
bind:cancel="onNoteCancel"
/>
<!-- AI 悬浮按钮 -->
<ai-float-button />
<!-- AI 悬浮按钮(W1-AI-CLOSURE 组 6:补 sourcePage) -->
<ai-float-button sourcePage="task-list" />
<!-- 开发调试 FAB -->
<dev-fab />

View File

@@ -0,0 +1,205 @@
/**
* 轻量 Markdown 转 rich-text 兼容 HTML 字符串(W1-AI-CLOSURE 任务 1)。
*
* 用途:chat 页 AI 回复流式渲染。每次 token 拼接后调用,输出供小程序
* <rich-text nodes="{{html}}"> 渲染。
*
* 支持(80% AI 输出场景覆盖):
* 段落 / 换行 / 标题 H1-H4 / 粗体 / 斜体 / 行内代码 / 代码块
* 无序列表 / 有序列表 / GFM 表格 / 行内 emoji 不变
*
* Streaming 容错:partial 标记(未闭合 双星 / 未结尾 三引号 / 未完整 竖线)
* 不渲染对应节点,降级为纯文本。每次 token 来重新解析整段。
*
* rich-text 限制:
* 不允许 inline style 属性
* 仅支持有限 tag(p / div / h1-h6 / strong / em / code / ul / ol / li /
* table / tr / th / td / pre / br / a)
* class 由 wxss 全局样式控制
*/
const HTML_ESCAPE_MAP: Record<string, string> = {
"&": "&amp;",
"<": "&lt;",
">": "&gt;",
'"': "&quot;",
"'": "&#39;",
}
function escapeHtml(s: string): string {
return s.replace(/[&<>"']/g, (c) => HTML_ESCAPE_MAP[c])
}
/**
* 解析行内 markdown(粗体 / 斜体 / 行内代码),返回带 tag 的 html。
* 优先级:行内代码 > 粗体 > 斜体。已转义 html 特殊字符。
*/
function parseInline(text: string): string {
if (!text) return ""
// 步骤 1:抽出 `code` 占位(纯 ASCII 标记防与原文冲突)
const codeStash: string[] = []
let s = text.replace(/`([^`\n]+)`/g, (_m, c) => {
const idx = codeStash.length
codeStash.push(c)
return `[[MDCODE${idx}MDCODE]]`
})
// 步骤 2:转义 html(占位标记 [[MDCODE0MDCODE]] 中的 [ ] 不会转义)
s = escapeHtml(s)
// 步骤 3:还原 code 为 <code> 标签
s = s.replace(/\[\[MDCODE(\d+)MDCODE\]\]/g, (_m, i) => {
const c = codeStash[Number(i)] || ""
return `<code class="md-code">${escapeHtml(c)}</code>`
})
// 步骤 4:粗体 **xx**(确保有闭合)
s = s.replace(/\*\*([^\n*][^\n*]*?)\*\*/g, "<strong>$1</strong>")
// 步骤 5:斜体 *xx*(避免 **)
s = s.replace(/(^|[^*])\*([^\n*][^\n*]*?)\*(?!\*)/g, "$1<em>$2</em>")
return s
}
/**
* 主入口:Markdown 转 rich-text 兼容 HTML 字符串。
*/
export function mdToRichHtml(md: string): string {
if (!md) return ""
const lines = md.split("\n")
const out: string[] = []
let i = 0
let inCodeBlock = false
let codeBuf: string[] = []
while (i < lines.length) {
const line = lines[i]
// 代码块 ```xx```
if (line.trim().startsWith("```")) {
if (!inCodeBlock) {
inCodeBlock = true
codeBuf = []
} else {
out.push(
`<pre class="md-pre"><code class="md-code-block">${escapeHtml(
codeBuf.join("\n"),
)}</code></pre>`,
)
inCodeBlock = false
}
i++
continue
}
if (inCodeBlock) {
codeBuf.push(line)
i++
continue
}
// 标题 #
const h = line.match(/^(#{1,4})\s+(.+)$/)
if (h) {
const level = h[1].length
out.push(`<h${level} class="md-h${level}">${parseInline(h[2])}</h${level}>`)
i++
continue
}
// GFM 表格(连续 2 行,第二行为分隔)
if (
line.trim().startsWith("|") &&
i + 1 < lines.length &&
/^\s*\|[\s\-:|]+\|\s*$/.test(lines[i + 1])
) {
const headers = line.split("|").slice(1, -1).map((c) => c.trim())
i += 2
const rows: string[][] = []
while (
i < lines.length &&
lines[i].trim().startsWith("|") &&
lines[i].trim().endsWith("|")
) {
rows.push(lines[i].split("|").slice(1, -1).map((c) => c.trim()))
i++
}
let html = '<table class="md-table"><thead><tr>'
for (const h0 of headers) html += `<th class="md-th">${parseInline(h0)}</th>`
html += "</tr></thead><tbody>"
for (const r of rows) {
html += "<tr>"
for (const c of r) html += `<td class="md-td">${parseInline(c)}</td>`
html += "</tr>"
}
html += "</tbody></table>"
out.push(html)
continue
}
// 无序列表
if (/^\s*[-*]\s+/.test(line)) {
const items: string[] = []
while (i < lines.length && /^\s*[-*]\s+/.test(lines[i])) {
items.push(lines[i].replace(/^\s*[-*]\s+/, ""))
i++
}
out.push(
`<ul class="md-ul">${items
.map((it) => `<li class="md-li">${parseInline(it)}</li>`)
.join("")}</ul>`,
)
continue
}
// 有序列表
if (/^\s*\d+\.\s+/.test(line)) {
const items: string[] = []
while (i < lines.length && /^\s*\d+\.\s+/.test(lines[i])) {
items.push(lines[i].replace(/^\s*\d+\.\s+/, ""))
i++
}
out.push(
`<ol class="md-ol">${items
.map((it) => `<li class="md-li">${parseInline(it)}</li>`)
.join("")}</ol>`,
)
continue
}
// 空行 → 段落分隔
if (line.trim() === "") {
i++
continue
}
// 普通段落(连续非空行合并,内部用 <br/> 保留软换行)
const para: string[] = [line]
i++
while (
i < lines.length &&
lines[i].trim() !== "" &&
!lines[i].trim().startsWith("#") &&
!lines[i].trim().startsWith("|") &&
!/^\s*[-*]\s+/.test(lines[i]) &&
!/^\s*\d+\.\s+/.test(lines[i]) &&
!lines[i].trim().startsWith("```")
) {
para.push(lines[i])
i++
}
out.push(`<p class="md-p">${parseInline(para.join("<br/>"))}</p>`)
}
// 流未闭合的代码块降级为纯文本 pre
if (inCodeBlock && codeBuf.length > 0) {
out.push(
`<pre class="md-pre"><code class="md-code-block">${escapeHtml(
codeBuf.join("\n"),
)}</code></pre>`,
)
}
return out.join("")
}