Compare commits

..

40 Commits

Author SHA1 Message Date
zhanxi 83e7e6edb2 merge(chat): 同步生产看板发布到测试分支 2026-10-28 14:35:30 +00:00
zhanxi d3bc75e232 merge(chat): 发布增长可视化运营工作台 2026-10-28 14:34:22 +00:00
zhanxi 00a3f7e817 merge(chat): 修复图表图例与日期标签布局 2026-10-28 14:34:19 +00:00
湛兮 81e6dff270 fix(growth): 避免图例与日期标签重叠 2026-10-28 22:33:32 +08:00
zhanxi 454b0f4643 merge(chat): 增长工作台可视化数据看板 2026-10-28 14:31:36 +00:00
湛兮 e09db9b280 feat(growth): 将增长工作台升级为可视化数据看板
- growth-charts.vue: 增加指标卡、转化、留存、实验与预算图表,处理空样本和生命周期
- growth.vue: 优化布局与响应式层级,保留数据明细
- README.md: 说明图表口径及字符成本边界
2026-10-28 22:31:03 +08:00
zhanxi 5b90178e48 merge(chat): 提测C端增长运营工作台 2026-10-28 13:18:44 +00:00
湛兮 30a92025a0 feat(growth): 新增C端增长运营工作台
- 增长工作台:展示漏斗、留存、推荐实验和质量成本
- 权益与活动:支持幂等赠送、站内分群活动和策略版本校验
- 路由及文档:增加超级管理员入口,说明指标和支付边界
2026-10-28 21:17:47 +08:00
zhanxi c2f1e5492d merge(chat): 同步会话恢复生产版本到测试分支 2026-10-28 11:23:40 +00:00
zhanxi ad13b76475 merge(chat): 支持恢复用户已删除会话 2026-10-28 11:21:28 +00:00
湛兮 8dba72591a feat(users): 支持恢复用户已删除会话
- 用户会话:展示删除时间并提供居中确认恢复
- 异步状态:避免切换用户后迟到结果覆盖详情
- README:说明历史会话恢复能力
2026-10-28 19:19:58 +08:00
zhanxi 54a1e537c3 merge(master): 同步移动键盘优化与会话软删除到测试分支 2026-10-28 08:12:15 +00:00
zhanxi 60bef7436b merge(chat): 标记前台已删除的历史会话 2026-10-28 08:10:13 +00:00
湛兮 6d3f6a0a8e fix(users): 标记前台已删除的历史会话
- 会话摘要增加软删除时间字段
- 后台聊天列表显示前台已删除状态并保留消息查看入口
2026-10-28 16:08:40 +08:00
zhanxi 51c6600904 merge(master): 同步通知教程与通用 Skill 2026-10-28 04:07:06 +00:00
zhanxi 26123e6911 merge(guides): 发布通知教程与通用 Webhook Skill 2026-10-28 04:05:38 +00:00
湛兮 9512204226 feat(guides): 新增通知图文教程与通用 Webhook Skill
- guides: 新增消息推送教程入口、固定目录、截图放大与技能下载
- docs/notifications: 补齐企微接入、业务适配、预览测试与发布验收图文
- skill: 固化跨平台配置体验,增加注册日报和充值通知示例及界面参考图
- scripts: 统一生成教程、原图标注和可重复验证的技能包
- README: 同步目录、入口和维护命令
2026-10-28 12:03:35 +08:00
zhanxi 34737e4acd merge(master): 同步对白与叙述排版发布到测试分支 2026-10-27 14:27:10 +00:00
zhanxi d5677b5109 merge(chat): 增加对白与叙述排版预览 2026-10-27 14:21:15 +00:00
湛兮 5dc709865a feat(content): 增加对白与叙述排版预览
- DigitalMessageText.vue: 为角色预览与聊天记录提供统一的受限文本展示
- content.vue: 增加首次问候、备用开场、示例对白的实时预览与格式说明
- users.vue: 按相同规则展示角色聊天记录,保留用户纯文本
- digital-message-format.ts、tests、README.md: 同步前台格式实现、兼容用例与目录说明
2026-10-27 22:19:16 +08:00
zhanxi 9b10b6b4c2 merge(nsfw): 发布登录账号成人内容偏好
合入已验证的 NSFW 账号偏好改动,游客登录限制保持不变。
2026-10-27 12:39:18 +00:00
湛兮 98ddd137e0 feat(nsfw): 支持管理 C 端账号成人内容偏好
- src/api/access.ts: 补充 C 端账号 NSFW 偏好字段与中文注释
- src/views/digital/users.vue: 展示开关状态,创建默认开启,编辑可保存账号选择
- README.md: 说明前后台共用偏好及配套发布要求
2026-10-27 20:18:16 +08:00
zhanxi 418783069b Merge pull request 'chore: 同步独立用户与聊天管理到测试分支' (#19) from master into develop 2026-10-27 11:02:56 +00:00
zhanxi 48aac171dd Merge pull request 'feat(users): 独立 C 端账号并提供聊天记录管理' (#18) from feature/env-pipeline-split into master 2026-10-27 10:56:50 +00:00
湛兮 0b7c1cba24 feat(users): 新增独立用户与聊天记录管理
- users.vue: 支持开户、停用、重置密码和按会话查看原始消息
- digital 路由与接口: 区分用户管理和实验用户分组,同步教程与文档
2026-10-27 18:56:11 +08:00
zhanxi 098ecee594 Merge pull request 'chore: 同步继续功能与阅读体验发布到测试分支' (#17) from master into develop 2026-10-27 10:16:50 +00:00
zhanxi 643f1b76b8 Merge pull request 'fix(guide): 固定目录并同步阅读章节高亮' (#16) from feature/env-pipeline-split into master 2026-10-27 10:15:52 +00:00
湛兮 4c35e50270 fix(guide): 固定目录并同步阅读章节高亮
- 目录与正文独立滚动,滚轮和目录定位均同步当前章节高亮

- 按截图真实比例预留空间,避免懒加载后定位偏移,补充使用说明
2026-10-27 18:15:31 +08:00
zhanxi 6a8407da48 Merge pull request 'chore: 同步用户分组管理发布到测试分支' (#15) from master into develop 2026-10-27 09:15:37 +00:00
zhanxi 3e78e79971 Merge pull request 'feat(experiments): 优化用户分组管理与指定说明' (#14) from feature/env-pipeline-split into master 2026-10-27 09:15:22 +00:00
湛兮 41bf7d8bae feat(experiments): 优化用户分组管理与指定说明
- experiment-users.vue: 分离预计分组与实际入组,新增查找指定入口并明确人群限制及有效期状态

- docs/experiments 与 public/guides: 同步用户分组教程、原始截图和编号标注

- README.md: 更新用户分组入口与真实接入边界说明
2026-10-27 17:14:51 +08:00
zhanxi b87b2cad73 Merge pull request 'chore: 同步完整实验教程发布到测试分支' (#13) from master into develop 2026-10-27 08:15:23 +00:00
zhanxi c93acad3d9 Merge pull request 'feat(experiments): 发布完整截图教程与分组规则说明' (#12) from feature/env-pipeline-split into master 2026-10-27 08:14:35 +00:00
湛兮 c406f8c127 feat(experiments): 发布完整截图教程与分组规则说明
- 操作指南改为带目录和图片放大的二级教程页面,完整覆盖实验生命周期
- 用隔离演示数据拍摄14张实际组件截图,生成编号箭头标注与共享内容README
- 标明稳定分组算法与比例区间,修正比例输入提交时的回显同步
- 同步路由、项目目录和教程资源一致性校验脚本
2026-10-27 16:13:49 +08:00
zhanxi 6a420983f7 Merge pull request 'chore: 同步多组实验发布到测试分支' (#11) from master into develop 2026-10-27 07:16:30 +00:00
zhanxi 0cd7ed078e Merge pull request 'feat(experiments): 发布多组方案配置界面' (#10) from feature/env-pipeline-split into master 2026-10-27 07:15:53 +00:00
湛兮 df7b9a0cb3 feat(experiments): 重设计多组比例与返回值配置
- 方案使用动态分组表,支持添加删除、互补比例、平均分配与合计校验
- 移除默认方案,用户管理与结束实验按实际分组展示
- 固定弹窗标题和操作区并同步多组说明
2026-10-27 15:15:21 +08:00
zhanxi 30b52b5d73 Merge pull request 'chore: 同步空白实验配置发布到测试分支' (#9) from master into develop 2026-10-27 06:44:16 +00:00
zhanxi c9dcfa1975 Merge pull request 'fix(experiments): 移除预置实验提示和 UI 默认选择' (#8) from feature/env-pipeline-split into master 2026-10-27 06:43:16 +00:00
湛兮 afad5507a6 fix(experiments): 移除预置类型提示与默认选择
- 实验类型统一展示真实接入状态
- 创建方案不预选 UI 类型,操作指南改为通用手动验收流程
2026-10-27 14:42:07 +08:00
78 changed files with 6547 additions and 403 deletions
+68 -4
View File
@@ -46,7 +46,14 @@ http://localhost:8848/
## 目录说明 ## 目录说明
```text ```text
. .
├── docs/experiments/ # 教程README、共享内容、原始截图与标注坐标
├── docs/notifications/ # 企微消息推送教程、截图来源与可复用 skill 源码
├── public/guides/experiments/ # 可放大的编号箭头SVG截图
├── public/guides/notifications/ # 消息推送标注截图与可下载的 Codex skill 包
├── scripts/build-experiment-guide.mjs # 生成与核对图文教程
├── scripts/build-notification-guide.py # 生成通知教程、原图标注、技能包及一致性检查
├── .agents/ # 当前项目 Agent skill 索引与中文提交、注释同步规则 ├── .agents/ # 当前项目 Agent skill 索引与中文提交、注释同步规则
├── .codex/skills/ # 旧版仓库内协作 skill,保留 README 同步规则 ├── .codex/skills/ # 旧版仓库内协作 skill,保留 README 同步规则
├── .husky/ # Git hooks,提交前执行 lint-staged,提交信息走 commitlint ├── .husky/ # Git hooks,提交前执行 lint-staged,提交信息走 commitlint
@@ -58,7 +65,7 @@ http://localhost:8848/
├── src/ # 前端源码 ├── src/ # 前端源码
│ ├── api/ # HTTP API 封装,业务接口集中在 access.ts │ ├── api/ # HTTP API 封装,业务接口集中在 access.ts
│ ├── assets/ # 图片、SVG、iconfont 等静态资源 │ ├── assets/ # 图片、SVG、iconfont 等静态资源
│ ├── components/ # 模板沉淀的通用组件 │ ├── components/ # 通用组件,DigitalMessageText.vue 提供对白/叙述预览与聊天记录展示
│ ├── config/ # 读取 public/platform-config.json 的运行时配置 │ ├── config/ # 读取 public/platform-config.json 的运行时配置
│ ├── directives/ # 自定义指令,如权限、复制、长按、波纹 │ ├── directives/ # 自定义指令,如权限、复制、长按、波纹
│ ├── layout/ # 后台布局、菜单、标签页、导航栏与布局 hooks │ ├── layout/ # 后台布局、菜单、标签页、导航栏与布局 hooks
@@ -66,11 +73,13 @@ http://localhost:8848/
│ ├── router/ # 静态路由、剩余路由、路由实例与守卫 │ ├── router/ # 静态路由、剩余路由、路由实例与守卫
│ ├── store/ # Pinia store,含用户、权限、标签页、主题等模块 │ ├── store/ # Pinia store,含用户、权限、标签页、主题等模块
│ ├── style/ # 全局样式、主题、暗色模式、侧边栏和过渡样式 │ ├── style/ # 全局样式、主题、暗色模式、侧边栏和过渡样式
│ ├── utils/ # 鉴权、HTTP、缓存、消息、进度条、树处理等工具 │ ├── utils/ # 鉴权、HTTP、缓存及 digital-message-format.ts 受限文本解析
│ └── views/ │ └── views/
│ ├── digital/ # 内容库、实验类型、测试方案和用户分组 │ ├── digital/ # 内容库、实验类型、测试方案和用户分组
│ ├── guides/ # 接入文档;消息推送图文页与技能下载
│ └── ... # 原门店与员工业务兼容页面 │ └── ... # 原门店与员工业务兼容页面
├── types/ # 全局类型声明、组件声明、路由声明和 Vue shim ├── types/ # 全局类型声明、组件声明、路由声明和 Vue shim
├── tests/ # 数字人对白/叙述格式回归,与 role-user 使用相同用例
├── AGENTS.md # Codex/Agent 入口规则,转到 RTK.md 并登记本地 skill ├── AGENTS.md # Codex/Agent 入口规则,转到 RTK.md 并登记本地 skill
├── RTK.md # 本仓库协作规则与 README 同步要求 ├── RTK.md # 本仓库协作规则与 README 同步要求
├── Dockerfile # 容器构建入口 ├── Dockerfile # 容器构建入口
@@ -210,10 +219,14 @@ pnpm build
## 数字人运营 ## 数字人运营
角色「人格与开场」提供对白/叙述格式说明和首次问候、示例对白、其他开场的实时预览,预览替换角色/用户占位符但不修改原文。生成预设始终遵守系统统一排版:`*叙述*` 与 `“对白”`,切换时空一行。用户管理的聊天记录也使用 `DigitalMessageText.vue`,用户原文保持纯文本,角色消息兼容旧括号与引号。
`src/utils/digital-message-format.ts` 与 `role-user/src/lib/digital-message-format.ts` 保持同一实现和用例,两仓独立构建。所有内容通过文本节点展示,不使用 HTML 注入。执行 `node --experimental-strip-types --test tests/*.test.mjs` 验证协议兼容。
- `src/views/digital/content.vue`:角色卡、世界书、预设,草稿/发布/下架,JSON 导入导出。 - `src/views/digital/content.vue`:角色卡、世界书、预设,草稿/发布/下架,JSON 导入导出。
- `src/views/digital/experiments.vue`:测试方案的类型选择、A/B 返回值、百分比、人群、生命周期、效果和审计。 - `src/views/digital/experiments.vue`:测试方案的类型选择、A/B 返回值、百分比、人群、生命周期、效果和审计。
- `src/views/digital/experiment-types.vue`:类型创建、默认值契约、来源、调用示例与接入验收。 - `src/views/digital/experiment-types.vue`:类型创建、默认值契约、来源、调用示例与接入验收。
- `src/views/digital/experiment-users.vue`:按方案分页搜索真实账号、分组预览、人工指定和恢复自动。 - `src/views/digital/experiment-users.vue`:按方案搜索真实账号,区分预计分组、实际入组和手动指定,保留有效期并解释目标人群限制。
- `src/views/digital/experiment-value.vue`:开关/数字/字符串/JSON 类型编辑器。 - `src/views/digital/experiment-value.vue`:开关/数字/字符串/JSON 类型编辑器。
- `src/router/modules/digital.ts`:数字人菜单,只有超级管理员可见;接口仍集中在 `src/api/access.ts`,后端独立验证权限。 - `src/router/modules/digital.ts`:数字人菜单,只有超级管理员可见;接口仍集中在 `src/api/access.ts`,后端独立验证权限。
- 保留既有员工管理模块和数据。沿用原 Vite 构建、域名与 Jenkins 发布。 - 保留既有员工管理模块和数据。沿用原 Vite 构建、域名与 Jenkins 发布。
@@ -222,8 +235,59 @@ pnpm build
标签页图标采用 `public/stellar-icon-v2.svg`,同时提供多尺寸 `favicon.ico`、180/192/512 PNG,覆盖浏览器、Apple 主屏幕和 PWA。版本化资源路径用于刷新旧图标缓存。 标签页图标采用 `public/stellar-icon-v2.svg`,同时提供多尺寸 `favicon.ico`、180/192/512 PNG,覆盖浏览器、Apple 主屏幕和 PWA。版本化资源路径用于刷新旧图标缓存。
「实验类型」「测试方案」「用户管理」是独立菜单。新类型填写自己的稳定标识与数据契约,先接入应用、收到实际调用并人工确认验收,再启动方案;未接入类型可存草稿。UI/对话是标注来源的已接入类型;不再使用固定业务功能的场景下拉框。方案行可直接跳转该方案的用户管理,用户预览不写分组、不记曝光,人工指定有原因、时效和审计。前台只消费决策。 「实验类型」「测试方案」「实验用户分组」是独立菜单。新类型填写自己的稳定标识与数据契约,先接入应用、收到实际调用并人工确认验收,再启动方案;未接入类型可存草稿。系统不预置 UI/对话类型;自建类型需要真实前台接入,不再使用固定业务功能的场景下拉框。方案行可直接跳转该方案的用户管理,用户预览不写分组、不记曝光,人工指定有原因、时效和审计。前台只消费决策。
比例统一按百分比输入,50代表50%,保留0.01%精度;既有用户分组保持不变。 比例统一按百分比输入,50代表50%,保留0.01%精度;既有用户分组保持不变。
后台统一隐藏原生及 Element Plus 自绘内部滚动条;表格、弹窗、抽屉和下拉选项仍支持触摸、鼠标和键盘滚动。叙事预设编辑与后端预算、下架回退及方案快照行为保持一致。 后台统一隐藏原生及 Element Plus 自绘内部滚动条;表格、弹窗、抽屉和下拉选项仍支持触摸、鼠标和键盘滚动。叙事预设编辑与后端预算、下架回退及方案快照行为保持一致。
实验方案分组支持 A~Z(最多26组),每组自行设置返回值和比例,合计必须100%。两组比例自动互补,多组显示总和并支持平均分配、补足剩余;0%组保留配置供人工验收。不再提供默认方案选择,未入组及暂停时使用类型默认返回值。用户管理按当前方案动态展示可指定的组,结束实验也可选择任意已配置组。
## 实验图文操作指南
测试方案页的「操作指南」进入二级页面 `/digital/experiments/guide`(`src/views/digital/experiment-guide.vue`),不再弹出简短说明。页面有章节目录、14张可放大的编号箭头截图和返回业务入口,覆盖类型创建、应用接入验收、仅自己验收、分组算法、启动、人工指定、正式分流、效果审计、暂停恢复及结束保留组。
项目内教程见 [完整实验教程](docs/experiments/README.md)。内容源为 `docs/experiments/guide.json`,网页直接读取同一文件;`screenshots.json` 保存标注坐标,原图只含隔离演示账号与状态。图中演示调用和统计不代表真实生产验收。
- 更新图文内容或截图后:`node scripts/build-experiment-guide.mjs`。
- 发布前验证文档、标注与源码一致:`node scripts/build-experiment-guide.mjs --check`。
- 原始截图及标注后的SVG都纳入版本管理,维护时保留“隔离演示”说明,不能用伪造回执替代真实接入。
用户分组管理提供独立的方案概况、用户查找和指定入口。列表覆盖全部真实账号,不把只读预计结果称为实际入组;手动指定明确显示草稿待生效、人群不符、已过期等状态。不符合目标人群的账号须明确选择“作为测试账号加入”,不修改其他用户的人群范围。取消指定或到期后沿用原自动分组,否则按当前方案规则计算。
教程目录固定在阅读区左侧,右侧正文独立滚动并自动高亮当前章节;点击目录平滑定位,目录过长时会自动滚动到当前项。窄屏将目录置于正文上方,保留正文滚动与章节同步。
## 消息推送机器人图文指南与 Skill
「接入文档 → 消息推送机器人」对应 `/guides/notifications`(`src/views/guides/notifications.vue`),沿用当前超级管理员权限。页面仅承载静态教程和技能下载,不在 Admin 中保存 Webhook 或调用 DevOps 写接口。实际配置入口仍为运维平台 `/settings?tab=notifications`。
内容源为 `docs/notifications/guide.json`,项目内教程见 [企微消息推送全流程](docs/notifications/README.md)。13 个章节覆盖创建权限、企微消息推送、服务端协议、通知时机、字段顺序、三种样式、变量、预览/测试、实收、迁移发布与排障。8 张可放大截图分别标注用户提供、隔离演示与先前测试实收来源,标注使用独立 SVG 图层,不改变原图内容。
- `python3 scripts/build-notification-guide.py`:生成 README、SVG 和可下载技能包。
- `python3 scripts/build-notification-guide.py --check`:检查内容、来源、尺寸、标注与派生文件一致。
- `python3 scripts/build-notification-guide.py --install-skill`:显式安装或更新本地 `wecom-notification-integration` 技能;再加 `--check` 检查安装版一致性。
- 技能源码:`docs/notifications/skill/wecom-notification-integration/`;下载包:`public/guides/notifications/wecom-notification-integration.zip`,可从教程页下载。
技能复用同一套配置能力与界面体验,业务数据和触发器按目标项目适配,覆盖注册日报、充值成功、统计和告警等消息;包内包含两张界面参考原图。通用实现契约、业务适配、企微通道、发布排障和 DevOps 历史案例分别读取,不绑定原项目的发布枚举、框架、权限或 CI 平台;调用技能本身不授权创建分支/worktree、提交推送、部署或发送真实群消息。公开静态资源不包含完整 Webhook 或私密群内容。
### C 端用户管理
`src/views/digital/users.vue` 对应 `/digital/users`,用于创建独立 C 端账号、搜索用户、修改昵称/状态、重置密码,以及按用户查看数字人会话和原始消息。账号由后台开通,无公开注册;与管理员/员工账号分别鉴权,重置 C 端密码不影响后台。停用保留聊天记录。
`src/api/access.ts` 定义 C 端用户、会话和消息响应类型。消息记录第1页为最新内容,每页按发送顺序展示,支持刷新、分页和生成状态查看。原实验账号页面 `/digital/experiment-users` 更名为「实验用户分组」,只针对 C 端用户配置实验。
用户列表展示账号的 NSFW 开关;创建用户默认开启,编辑用户可单独开启或关闭。与前台「我的」读取和修改同一份服务端账号偏好,不覆盖收藏、称呼或身份背景。已有账号未保存该字段时默认开启,游客的登录限制不变;需与 `access-manage` 配套发布。
聊天历史中的“前台已删除”显示删除时间,管理员可在会话详情通过“恢复给用户”恢复可见性。接口校验用户归属并记录审计,原消息不重写。
## C端增长与体验
新增 `src/views/digital/growth.vue`,菜单 `/digital/growth` 仅超级管理员可用,后端再次鉴权。需先执行配套后端 `020_digital_growth.sql`,再发布前后台。
页面集中展示严格顺序漏斗、成熟队列次日活跃、推荐曝光与有效开聊、分配比例诊断、首字时延和反馈原因、字符预算及最近100笔额度流水。无样本显示暂无样本;超过事件边界会显示截断提示,不注入演示数据,不自动宣称实验显著性。
运营可配置免费/游客/会员限额、全站字符预算、生成开关、独立推荐实验及探索比例;变更实验参数必须增加版本。会员赠送/撤销需要理由、确认与绑定参数的幂等请求号,是运营权益操作,不创建支付订单或收款。站内活动支持新用户/活跃/沉默分群、时间窗、对照组和频控,仅站内展示,不发送短信、邮件或企微。保存策略和活动均校验版本,失败时保留输入供处理。
### 增长数据可视化
`src/views/digital/growth-charts.vue` 为增长工作台提供指标卡、严格顺序转化、成熟队列次留、推荐实验转化与最近14个记账日字符预算图表。数据来自真实聚合接口,空样本单独展示;有输出结算包括中止后已产生输出的请求,不等同完整回复。保留对应数据明细,图表随容器尺寸变化并在卸载时释放。
+230
View File
@@ -0,0 +1,230 @@
# 实验完整操作教程
从创建类型到结束实验,按顺序走一遍。建议第一次先只选自己的测试账号,验证真实应用效果后再扩大流量。
更新时间:2026-10-27
> 截图由仓库实际页面组件在隔离演示环境拍摄。红色箭头和编号为操作标注;演示调用、账号和统计不是生产验收证据。
## 目录
- 先分清三个概念
- 1. 创建自己的实验类型
- 2. 接入应用并完成业务验收
- 3. 先建“仅自己验收”的测试方案
- 4. 用户究竟如何被分组
- 5. 启动验收方案
- 6. 查看账号分组,指定 A/B 做对照
- 7. 验收完成后,另建正式分流方案
- 8. 查看效果与审计
- 9. 暂停与恢复
- 10. 结束并保留最终结果
- 完成前再核对一次
## 先分清三个概念
类型定义测什么,测试方案定义怎么测,分组定义每种返回结果。
- 实验类型:例如“新老 UI(教程)”,稳定标识 tutorial_ui,返回格式为开关,默认值 false。名称不会自动接入任何功能。
- 测试方案:一次有明确目标、人群、流量和生命周期的实验。相同类型可以先做仅自己验收,再结束验收方案、另建正式实验。
- 分组:方案内的 A~Z 组。每组有比例和返回值,合计100%;false / true 只是教程示例,实际含义由应用代码决定。
- 本文使用隔离演示数据拍摄实际页面组件,标注编号对应下方操作;演示调用与统计不代表你的类型已经接入或线上实验已验收。
## 1. 创建自己的实验类型
进入“实验类型”,点击“创建实验类型”。
![1. 创建自己的实验类型:编号操作截图](../../public/guides/experiments/01-create-type.svg)
1. 填写稳定标识;名称用于辨认,标识才是应用读取决策的依据。
2. 选择返回值格式,本例为开关;下面的默认值使用 false。
3. 启用类型后保存;保存成功仍须完成真实应用接入。
- 填写名称与稳定标识。本例 tutorial_ui 只是演示,不要照抄成已有业务的标识;标识创建后不可改。
- 选择“开关(是/否)”,默认返回值设为关闭 false;在应用中约定 false 为旧 UI、true 为新 UI。
- 保持“启用类型”开启并保存。启用只表示允许这一类型参与决策,不会直接开启新 UI。
- 保存后应看到“待应用调用”。这是正常状态;此时可以保存草稿,不能启动实验。
## 2. 接入应用并完成业务验收
在类型所在行点击“接入与验收”,先让真实功能读取并使用返回值。
![2. 接入应用并完成业务验收:编号操作截图](../../public/guides/experiments/02-integration.svg)
1. 核对要接入的稳定标识,避免读错类型。
2. 按调用说明接入,让真实功能使用接口返回的 value。
3. 收到调用并验证实际功能后,勾选确认、填写记录,再确认接入验收。
- 将类型标识、数据格式、默认值和目标功能交给负责应用接入的人。后台只能配置,不能替客户端实现界面切换。
- 应用以当前用户的已登录身份调用决策接口,读取 value,并将 false / true 实际用于切换旧 / 新 UI。只请求接口并不等于功能已经消费返回值。
- 在实际页面检查结果,返回后台点击“刷新调用状态”;收到当前契约的调用后,勾选真实验证并填写至少8字的验收记录,再点“确认接入验收”。
- 应看到“已确认接入”。没有调用时按钮不可用,不应伪造回执。截图中的状态来自隔离演示,不是对线上接入的证明。
```text
GET /api/digital/decisions/tutorial_ui
Authorization: Bearer <当前用户的访问令牌>
// 应用接入示意:使用自己的请求封装和实际界面切换方法。
const decision = await readDecision("tutorial_ui");
applyUiVersion(decision.value === true ? "new" : "old");
```
## 3. 先建“仅自己验收”的测试方案
回到“测试方案”,创建草稿,先用自己的真实测试账号验证。
![3. 先建“仅自己验收”的测试方案:编号操作截图](../../public/guides/experiments/03-trial.svg)
1. 命名本次“仅自己验收”的方案,并选择正确类型。
2. 入组范围选指定名单,只选择自己的测试账号。
3. 分组配置完成后保存草稿;保存不会启动实验。
![3. 先建“仅自己验收”的测试方案:编号操作截图](../../public/guides/experiments/03b-trial-groups.svg)
1. A设0%,保留 false;没有自动流量进入A。
2. B设100%,返回 true;自动入组的验收账号读取B值。
3. 核对目标、人群和返回值后保存草稿。
- 填方案名称、选择刚才的类型,写清目标与验收指标。方案名称用于辨认本次实验,不负责绑定功能。
- 入组范围选“指定名单”,只选自己的测试账号;进入实验的流量设为100%。请确认页面选择的是你自己的账号。
- A 组设0%、返回 false;B 组设100%、返回 true。A仍保留另一种返回值,可通过人工指定进行对照;没有自动流量进入A。
- 点击“保存草稿”。保存不会改变应用行为;比例必须合计100%,0%组也必须填写合法返回值。
## 4. 用户究竟如何被分组
分组规则会直接标注在配置页,并随着比例显示当前区间。
![4. 用户究竟如何被分组:编号操作截图](../../public/guides/experiments/04-allocation.svg)
1. 分组方式固定标注在页面:按账号稳定随机分配。
2. 当前区间随比例联动,A/B各50%时按0~4999与5000~9999划分。
3. 展开查看具体算法,以及人工指定、稳定分组、流量筛选的优先顺序。
- “所有用户”只表示所有账号有资格参加,不按性别、年龄或账号尾号区分。首次自动分配先判断人群及实验流量。
- 系统用账号标识、本次测试方案ID及用途做SHA-256,取摘要前4字节的无符号大端整数,对10000取余,得到0~9999。流量和组别使用两个独立的用途值。
- A/B各50%时,按配置顺序A为0~4999,B为5000~9999。A为100%时,A覆盖0~9999,B为0%不自动分配。
- 首次实际入组后保存稳定分组,刷新和重新登录不重抽;有效人工指定优先。新建方案的ID不同,同一账号可能分到不同组。
- 比例是分配概率,不保证小样本恰好一半。未入组、草稿或暂停时使用类型默认返回值,不属于任何组。
## 5. 启动验收方案
接入已确认、草稿配置无误后,点击方案行中的“启动”。
![5. 启动验收方案:编号操作截图](../../public/guides/experiments/05-start.svg)
1. 确认目标方案,并注意启动后配置冻结。
2. 核对无误再确认;之后到应用中验收实际效果。
- 核对方案名称、人群与比例,再确认启动。启动后应显示“运行中”。
- 启动后组别、比例、人群和返回值冻结;需要新规则时创建下一条方案,不能直接改正在运行的配置。
- 在应用中重新读取决策并检查新 UI。人工指定用户也需要刷新或等待应用读取新决策;决策请求、实际展示和曝光记录是不同的事情。
- 如果仍看旧 UI,先检查类型标识与接入代码、账号是否在名单、返回值是否被使用,而不是仅看后台状态。
## 6. 查看账号分组,指定 A/B 做对照
从方案行进入“实验用户分组”,确认当前方案,再搜索测试账号。
![6. 查看账号分组,指定 A/B 做对照:编号操作截图](../../public/guides/experiments/06-users.svg)
1. 先选择本次测试方案,并在方案详情中核对目标人群与比例。
2. 当前分组和值与分配方式分列展示,明确区分预计自动分组和手动指定。
3. 查找用户或指定用户分组;已有指定可修改,也可取消,原有效期限单独展示。
![6. 查看账号分组,指定 A/B 做对照:编号操作截图](../../public/guides/experiments/06b-override.svg)
1. 指定分组直接展示返回值与自动分流比例;A 为 0% 也可手动指定。
2. 账号不在目标人群时,须明确作为测试账号加入;设置未来30天内的有效期。
3. 填写原因后确认指定;方案运行且前台已接入时,应用下次读取才会使用指定值。
- 先选择本次方案,再按账号、姓名或用户名查询;用户列表包含未参与实验的账号。“预计自动分组”只读,首次实际调用后才保存入组,查询不会计曝光。
- 点击“指定用户分组”查找账号,或在用户行点击“指定分组/修改指定”。每组直接展示返回值和自动分流比例,0% 组也可手动指定。有效期须在未来30天内,操作原因至少2字。
- 账号不符合目标人群时,页面会说明具体原因。例如仅新用户的实验中指定老账号,须勾选“将此账号作为测试账号加入,仍使用上面指定的组”;仅对此账号放开限制,不修改其他用户。符合人群时无需此选项。
- 有效期内不一定正在生效:草稿/暂停要等方案运行,人群不符且未允许测试账号加入时不生效。前台仍须真实接入并读取返回值,才能验证功能变化。
- 点击“取消手动指定”,或等待到期后恢复方案规则:符合目标人群时沿用原自动分组,否则重新判断。取消指定不保证会换到另一组;修改指定会保留原有效期限,不自动延长。
## 7. 验收完成后,另建正式分流方案
先结束验收方案并保留需要的组,再为同一类型创建新的正式方案。
![7. 验收完成后,另建正式分流方案:编号操作截图](../../public/guides/experiments/07-formal.svg)
1. 正式分流示例A/B各50%,C为0%;合计须为100%。
2. 返回值与比例独立配置,不要根据组名猜业务含义。
3. 添加更多组或平均分配,最多A到Z共26组。
- 同一类型消费标识只允许一个运行中或暂停中的方案,可以先保存多份草稿;请先结束验收方案,再启动正式方案。
- 本例选择“所有用户”,进入实验流量100%,A/B各50%,分别返回 false / true。也可选择新用户、老用户,并设置明确的注册时间分界。
- 可添加到Z组。新增组初始0%,各组返回值独立配置;三组及以上需要自行调整合计100%,或点击“平均分配”“补足剩余”。
- 如要扩大实验流量,已启动方案不能直接调规则,需要结束后另建方案。组内比例与实验流量不同:实验流量20%、A/B各50%时,目标人群约10%进入A、10%进入B,其余使用类型默认值。
- 截图为另一份演示草稿,比例与返回值请按实际目标设置;不要把教程示例直接当作上线决策。
## 8. 查看效果与审计
在方案行点击“效果与审计”,同时核对配置、效果和操作记录。
![8. 查看效果与审计:编号操作截图](../../public/guides/experiments/08-metrics.svg)
1. 先核对当前组配置,确认所分析的值与比例。
2. 区分决策和曝光;曝光须由实际展示后的回报产生。
3. 切换“操作审计”,追溯创建、状态流转和人工指定。
![8. 查看效果与审计:编号操作截图](../../public/guides/experiments/08b-audit.svg)
1. 进入操作审计页签。
2. 查看动作、操作人、详情与时间;图中为隔离演示记录。
- 上方显示实际组别、比例与返回值,下方按组展示决策、曝光和漏斗;人工指定与规则分组分开统计。
- 决策次数是读取结果的次数,曝光是应用实际展示后的回报;不能将请求接口的数量当成用户已看到界面的数量。
- 根据事先写好的指标比较体验、留存等业务结果;当前页面的漏斗统计不等于完整留存报表,也不会自动给出显著性结论。
- “操作审计”保留创建、状态变更和人工指定等操作。没有数据时先检查是否有真实入组、是否完成曝光接入;后台预览不会制造统计。
- 截图统计为演示样例,用于解释字段,不能作为生产结果或发布验收凭据。
## 9. 暂停与恢复
运行中可以暂停;暂停用于停止实验效果,并不释放同类型的未结束方案。
![9. 暂停与恢复:编号操作截图](../../public/guides/experiments/09-pause.svg)
1. 已暂停表示使用类型默认返回值,不属于某个默认组。
2. 需要继续时点击恢复;已有稳定分组保持不变。
- 点击“暂停”并确认后,用户使用实验类型的默认返回值,而不是某个默认组。
- 已保存分组保留;点击“恢复”后沿用分组。暂停期间的人工指定也不会让方案重新生效。
- 需要彻底换一套人群或分组比例时,结束当前方案,再创建下一条方案。
## 10. 结束并保留最终结果
点击“结束实验”,从当前方案已有组中选择最终保留哪一组。
![10. 结束并保留最终结果:编号操作截图](../../public/guides/experiments/10a-choose-winner.svg)
1. 打开结束实验菜单。
2. 明确选定最终保留的组,本例是返回 true 的B组。
![10. 结束并保留最终结果:编号操作截图](../../public/guides/experiments/10-finish.svg)
1. 确认影响范围:结束后所有用户采用所选组返回值,且不能重新启动。
2. 确认无误后提交;若希望回旧版,请先核对所选组是否真的返回旧版值。
- 本例选择“保留 B 组”,确认文案会明确说明:结束后所有用户采用该组的返回值。
- 结束是最终状态,不能恢复运行;它不是“停止并自动回旧版”。如果希望回旧版,应选择实际返回旧版值的组。
- 结束后该组返回值会持续生效,直到有新的有效方案接管,或类型被停用;停用类型后回类型默认返回值。
- 结束后核对应用效果和审计,再规划下一次实验。不要仅因B叫“B”就认为它一定是新版;含义取决于该组配置的值和消费代码。
## 完成前再核对一次
每次实验都按这份清单自查。
- 类型标识、格式、默认值与应用实现一致,真实功能已经使用返回值,并完成当前契约的接入验收。
- 先用自己的账号验收,再正式分流;所有组比例合计100%,零比例组的值同样正确。
- 确认人工指定是否仍有效,区分规则分组与人工指定的统计。
- 真实调用、真实展示、曝光回报和业务指标分别核实;截图教程与构建成功都不是业务效果验收。
- 暂停使用类型默认值;结束保留所选组。按需要的结果操作,不凭组名猜测功能。
## 维护教程
- 内容源:`guide.json`;二级教程页直接读取同一内容源。
- 原始截图:`screenshots/*.jpg`;标注坐标:`screenshots.json`。截图必须使用隔离演示数据。
- 执行 `node scripts/build-experiment-guide.mjs` 重新生成本README和带箭头、编号的SVG。
- 执行 `node scripts/build-experiment-guide.mjs --check` 检查派生文件与内容源一致。
- 二级页面:`/digital/experiments/guide`;点击“操作指南”进入。
+221
View File
@@ -0,0 +1,221 @@
{
"title": "实验完整操作教程",
"updated": "2026-10-27",
"intro": "从创建类型到结束实验,按顺序走一遍。建议第一次先只选自己的测试账号,验证真实应用效果后再扩大流量。",
"steps": [
{
"id": "concepts",
"title": "先分清三个概念",
"lead": "类型定义测什么,测试方案定义怎么测,分组定义每种返回结果。",
"bullets": [
"实验类型:例如“新老 UI(教程)”,稳定标识 tutorial_ui,返回格式为开关,默认值 false。名称不会自动接入任何功能。",
"测试方案:一次有明确目标、人群、流量和生命周期的实验。相同类型可以先做仅自己验收,再结束验收方案、另建正式实验。",
"分组:方案内的 A~Z 组。每组有比例和返回值,合计100%;false / true 只是教程示例,实际含义由应用代码决定。",
"本文使用隔离演示数据拍摄实际页面组件,标注编号对应下方操作;演示调用与统计不代表你的类型已经接入或线上实验已验收。"
]
},
{
"id": "create-type",
"title": "1. 创建自己的实验类型",
"lead": "进入“实验类型”,点击“创建实验类型”。",
"bullets": [
"填写名称与稳定标识。本例 tutorial_ui 只是演示,不要照抄成已有业务的标识;标识创建后不可改。",
"选择“开关(是/否)”,默认返回值设为关闭 false;在应用中约定 false 为旧 UI、true 为新 UI。",
"保持“启用类型”开启并保存。启用只表示允许这一类型参与决策,不会直接开启新 UI。",
"保存后应看到“待应用调用”。这是正常状态;此时可以保存草稿,不能启动实验。"
],
"images": ["01-create-type"]
},
{
"id": "integrate",
"title": "2. 接入应用并完成业务验收",
"lead": "在类型所在行点击“接入与验收”,先让真实功能读取并使用返回值。",
"bullets": [
"将类型标识、数据格式、默认值和目标功能交给负责应用接入的人。后台只能配置,不能替客户端实现界面切换。",
"应用以当前用户的已登录身份调用决策接口,读取 value,并将 false / true 实际用于切换旧 / 新 UI。只请求接口并不等于功能已经消费返回值。",
"在实际页面检查结果,返回后台点击“刷新调用状态”;收到当前契约的调用后,勾选真实验证并填写至少8字的验收记录,再点“确认接入验收”。",
"应看到“已确认接入”。没有调用时按钮不可用,不应伪造回执。截图中的状态来自隔离演示,不是对线上接入的证明。"
],
"code": "GET /api/digital/decisions/tutorial_ui\nAuthorization: Bearer <当前用户的访问令牌>\n\n// 应用接入示意:使用自己的请求封装和实际界面切换方法。\nconst decision = await readDecision(\"tutorial_ui\");\napplyUiVersion(decision.value === true ? \"new\" : \"old\");",
"images": ["02-integration"]
},
{
"id": "trial",
"title": "3. 先建“仅自己验收”的测试方案",
"lead": "回到“测试方案”,创建草稿,先用自己的真实测试账号验证。",
"bullets": [
"填方案名称、选择刚才的类型,写清目标与验收指标。方案名称用于辨认本次实验,不负责绑定功能。",
"入组范围选“指定名单”,只选自己的测试账号;进入实验的流量设为100%。请确认页面选择的是你自己的账号。",
"A 组设0%、返回 false;B 组设100%、返回 true。A仍保留另一种返回值,可通过人工指定进行对照;没有自动流量进入A。",
"点击“保存草稿”。保存不会改变应用行为;比例必须合计100%,0%组也必须填写合法返回值。"
],
"images": ["03-trial", "03b-trial-groups"]
},
{
"id": "allocation",
"title": "4. 用户究竟如何被分组",
"lead": "分组规则会直接标注在配置页,并随着比例显示当前区间。",
"bullets": [
"“所有用户”只表示所有账号有资格参加,不按性别、年龄或账号尾号区分。首次自动分配先判断人群及实验流量。",
"系统用账号标识、本次测试方案ID及用途做SHA-256,取摘要前4字节的无符号大端整数,对10000取余,得到0~9999。流量和组别使用两个独立的用途值。",
"A/B各50%时,按配置顺序A为0~4999,B为5000~9999。A为100%时,A覆盖0~9999,B为0%不自动分配。",
"首次实际入组后保存稳定分组,刷新和重新登录不重抽;有效人工指定优先。新建方案的ID不同,同一账号可能分到不同组。",
"比例是分配概率,不保证小样本恰好一半。未入组、草稿或暂停时使用类型默认返回值,不属于任何组。"
],
"images": ["04-allocation"]
},
{
"id": "start",
"title": "5. 启动验收方案",
"lead": "接入已确认、草稿配置无误后,点击方案行中的“启动”。",
"bullets": [
"核对方案名称、人群与比例,再确认启动。启动后应显示“运行中”。",
"启动后组别、比例、人群和返回值冻结;需要新规则时创建下一条方案,不能直接改正在运行的配置。",
"在应用中重新读取决策并检查新 UI。人工指定用户也需要刷新或等待应用读取新决策;决策请求、实际展示和曝光记录是不同的事情。",
"如果仍看旧 UI,先检查类型标识与接入代码、账号是否在名单、返回值是否被使用,而不是仅看后台状态。"
],
"images": ["05-start"]
},
{
"id": "users",
"title": "6. 查看账号分组,指定 A/B 做对照",
"lead": "从方案行进入“实验用户分组”,确认当前方案,再搜索测试账号。",
"bullets": [
"先选择本次方案,再按账号、姓名或用户名查询;用户列表包含未参与实验的账号。“预计自动分组”只读,首次实际调用后才保存入组,查询不会计曝光。",
"点击“指定用户分组”查找账号,或在用户行点击“指定分组/修改指定”。每组直接展示返回值和自动分流比例,0% 组也可手动指定。有效期须在未来30天内,操作原因至少2字。",
"账号不符合目标人群时,页面会说明具体原因。例如仅新用户的实验中指定老账号,须勾选“将此账号作为测试账号加入,仍使用上面指定的组”;仅对此账号放开限制,不修改其他用户。符合人群时无需此选项。",
"有效期内不一定正在生效:草稿/暂停要等方案运行,人群不符且未允许测试账号加入时不生效。前台仍须真实接入并读取返回值,才能验证功能变化。",
"点击“取消手动指定”,或等待到期后恢复方案规则:符合目标人群时沿用原自动分组,否则重新判断。取消指定不保证会换到另一组;修改指定会保留原有效期限,不自动延长。"
],
"images": ["06-users", "06b-override"]
},
{
"id": "formal",
"title": "7. 验收完成后,另建正式分流方案",
"lead": "先结束验收方案并保留需要的组,再为同一类型创建新的正式方案。",
"bullets": [
"同一类型消费标识只允许一个运行中或暂停中的方案,可以先保存多份草稿;请先结束验收方案,再启动正式方案。",
"本例选择“所有用户”,进入实验流量100%,A/B各50%,分别返回 false / true。也可选择新用户、老用户,并设置明确的注册时间分界。",
"可添加到Z组。新增组初始0%,各组返回值独立配置;三组及以上需要自行调整合计100%,或点击“平均分配”“补足剩余”。",
"如要扩大实验流量,已启动方案不能直接调规则,需要结束后另建方案。组内比例与实验流量不同:实验流量20%、A/B各50%时,目标人群约10%进入A、10%进入B,其余使用类型默认值。",
"截图为另一份演示草稿,比例与返回值请按实际目标设置;不要把教程示例直接当作上线决策。"
],
"images": ["07-formal"]
},
{
"id": "metrics",
"title": "8. 查看效果与审计",
"lead": "在方案行点击“效果与审计”,同时核对配置、效果和操作记录。",
"bullets": [
"上方显示实际组别、比例与返回值,下方按组展示决策、曝光和漏斗;人工指定与规则分组分开统计。",
"决策次数是读取结果的次数,曝光是应用实际展示后的回报;不能将请求接口的数量当成用户已看到界面的数量。",
"根据事先写好的指标比较体验、留存等业务结果;当前页面的漏斗统计不等于完整留存报表,也不会自动给出显著性结论。",
"“操作审计”保留创建、状态变更和人工指定等操作。没有数据时先检查是否有真实入组、是否完成曝光接入;后台预览不会制造统计。",
"截图统计为演示样例,用于解释字段,不能作为生产结果或发布验收凭据。"
],
"images": ["08-metrics", "08b-audit"]
},
{
"id": "pause",
"title": "9. 暂停与恢复",
"lead": "运行中可以暂停;暂停用于停止实验效果,并不释放同类型的未结束方案。",
"bullets": [
"点击“暂停”并确认后,用户使用实验类型的默认返回值,而不是某个默认组。",
"已保存分组保留;点击“恢复”后沿用分组。暂停期间的人工指定也不会让方案重新生效。",
"需要彻底换一套人群或分组比例时,结束当前方案,再创建下一条方案。"
],
"images": ["09-pause"]
},
{
"id": "finish",
"title": "10. 结束并保留最终结果",
"lead": "点击“结束实验”,从当前方案已有组中选择最终保留哪一组。",
"bullets": [
"本例选择“保留 B 组”,确认文案会明确说明:结束后所有用户采用该组的返回值。",
"结束是最终状态,不能恢复运行;它不是“停止并自动回旧版”。如果希望回旧版,应选择实际返回旧版值的组。",
"结束后该组返回值会持续生效,直到有新的有效方案接管,或类型被停用;停用类型后回类型默认返回值。",
"结束后核对应用效果和审计,再规划下一次实验。不要仅因B叫“B”就认为它一定是新版;含义取决于该组配置的值和消费代码。"
],
"images": ["10a-choose-winner", "10-finish"]
},
{
"id": "checklist",
"title": "完成前再核对一次",
"lead": "每次实验都按这份清单自查。",
"bullets": [
"类型标识、格式、默认值与应用实现一致,真实功能已经使用返回值,并完成当前契约的接入验收。",
"先用自己的账号验收,再正式分流;所有组比例合计100%,零比例组的值同样正确。",
"确认人工指定是否仍有效,区分规则分组与人工指定的统计。",
"真实调用、真实展示、曝光回报和业务指标分别核实;截图教程与构建成功都不是业务效果验收。",
"暂停使用类型默认值;结束保留所选组。按需要的结果操作,不凭组名猜测功能。"
]
}
],
"captions": {
"01-create-type": [
"填写稳定标识;名称用于辨认,标识才是应用读取决策的依据。",
"选择返回值格式,本例为开关;下面的默认值使用 false。",
"启用类型后保存;保存成功仍须完成真实应用接入。"
],
"02-integration": [
"核对要接入的稳定标识,避免读错类型。",
"按调用说明接入,让真实功能使用接口返回的 value。",
"收到调用并验证实际功能后,勾选确认、填写记录,再确认接入验收。"
],
"03-trial": [
"命名本次“仅自己验收”的方案,并选择正确类型。",
"入组范围选指定名单,只选择自己的测试账号。",
"分组配置完成后保存草稿;保存不会启动实验。"
],
"03b-trial-groups": [
"A设0%,保留 false;没有自动流量进入A。",
"B设100%,返回 true;自动入组的验收账号读取B值。",
"核对目标、人群和返回值后保存草稿。"
],
"04-allocation": [
"分组方式固定标注在页面:按账号稳定随机分配。",
"当前区间随比例联动,A/B各50%时按0~4999与5000~9999划分。",
"展开查看具体算法,以及人工指定、稳定分组、流量筛选的优先顺序。"
],
"05-start": [
"确认目标方案,并注意启动后配置冻结。",
"核对无误再确认;之后到应用中验收实际效果。"
],
"06-users": [
"先选择本次测试方案,并在方案详情中核对目标人群与比例。",
"当前分组和值与分配方式分列展示,明确区分预计自动分组和手动指定。",
"查找用户或指定用户分组;已有指定可修改,也可取消,原有效期限单独展示。"
],
"06b-override": [
"指定分组直接展示返回值与自动分流比例;A 为 0% 也可手动指定。",
"账号不在目标人群时,须明确作为测试账号加入;设置未来30天内的有效期。",
"填写原因后确认指定;方案运行且前台已接入时,应用下次读取才会使用指定值。"
],
"07-formal": [
"正式分流示例A/B各50%,C为0%;合计须为100%。",
"返回值与比例独立配置,不要根据组名猜业务含义。",
"添加更多组或平均分配,最多A到Z共26组。"
],
"08-metrics": [
"先核对当前组配置,确认所分析的值与比例。",
"区分决策和曝光;曝光须由实际展示后的回报产生。",
"切换“操作审计”,追溯创建、状态流转和人工指定。"
],
"08b-audit": [
"进入操作审计页签。",
"查看动作、操作人、详情与时间;图中为隔离演示记录。"
],
"09-pause": [
"已暂停表示使用类型默认返回值,不属于某个默认组。",
"需要继续时点击恢复;已有稳定分组保持不变。"
],
"10a-choose-winner": [
"打开结束实验菜单。",
"明确选定最终保留的组,本例是返回 true 的B组。"
],
"10-finish": [
"确认影响范围:结束后所有用户采用所选组返回值,且不能重新启动。",
"确认无误后提交;若希望回旧版,请先核对所选组是否真的返回旧版值。"
]
}
}
+567
View File
@@ -0,0 +1,567 @@
{
"01-create-type": {
"width": 1920,
"height": 902,
"annotations": [
{
"number": 1,
"rect": {
"x": 649.5,
"y": 273.796875,
"width": 606,
"height": 30
},
"badge": {
"x": 573.5,
"y": 288.796875
}
},
{
"number": 2,
"rect": {
"x": 650.5,
"y": 396.796875,
"width": 156,
"height": 24
},
"badge": {
"x": 574.5,
"y": 408.796875
}
},
{
"number": 3,
"rect": {
"x": 1178.5,
"y": 803.796875,
"width": 88,
"height": 32
},
"badge": {
"x": 1336.5,
"y": 819.796875
}
}
]
},
"02-integration": {
"width": 1920,
"height": 902,
"annotations": [
{
"number": 1,
"rect": {
"x": 1455.3515625,
"y": 95,
"width": 429.1484375,
"height": 40
},
"badge": {
"x": 1379.3515625,
"y": 115
}
},
{
"number": 2,
"rect": {
"x": 1160,
"y": 319.5,
"width": 725,
"height": 26.5
},
"badge": {
"x": 1084,
"y": 332.75
}
},
{
"number": 3,
"rect": {
"x": 1160,
"y": 868.875,
"width": 116,
"height": 32
},
"badge": {
"x": 1346,
"y": 872
}
}
]
},
"03-trial": {
"width": 1920,
"height": 902,
"annotations": [
{
"number": 1,
"rect": {
"x": 547,
"y": 132.09375,
"width": 384.5,
"height": 30
},
"badge": {
"x": 471,
"y": 147.09375
}
},
{
"number": 2,
"rect": {
"x": 823.578125,
"y": 427.09375,
"width": 513.421875,
"height": 24
},
"badge": {
"x": 747.578125,
"y": 439.09375
}
},
{
"number": 3,
"rect": {
"x": 1296,
"y": 808.890625,
"width": 88,
"height": 32
},
"badge": {
"x": 1454,
"y": 824.890625
}
}
]
},
"05-start": {
"width": 1920,
"height": 902,
"annotations": [
{
"number": 1,
"rect": {
"x": 798,
"y": 423,
"width": 360,
"height": 48
},
"badge": {
"x": 722,
"y": 447
}
},
{
"number": 2,
"rect": {
"x": 1098,
"y": 483,
"width": 60,
"height": 32
},
"badge": {
"x": 1228,
"y": 499.0
}
}
]
},
"06-users": {
"width": 1920,
"height": 958,
"annotations": [
{
"number": 1,
"rect": {
"x": 470,
"y": 225,
"width": 305,
"height": 38
},
"badge": {
"x": 520,
"y": 170
}
},
{
"number": 2,
"rect": {
"x": 625,
"y": 425,
"width": 560,
"height": 187
},
"badge": {
"x": 580,
"y": 447
}
},
{
"number": 3,
"rect": {
"x": 1200,
"y": 355,
"width": 675,
"height": 255
},
"badge": {
"x": 1795,
"y": 708
}
}
]
},
"06b-override": {
"width": 1920,
"height": 958,
"annotations": [
{
"number": 1,
"rect": {
"x": 655,
"y": 225,
"width": 595,
"height": 135
},
"badge": {
"x": 1390,
"y": 270
}
},
{
"number": 2,
"rect": {
"x": 655,
"y": 418,
"width": 595,
"height": 223
},
"badge": {
"x": 520,
"y": 470
}
},
{
"number": 3,
"rect": {
"x": 655,
"y": 665,
"width": 595,
"height": 157
},
"badge": {
"x": 1390,
"y": 720
}
}
]
},
"03b-trial-groups": {
"width": 1920,
"height": 902,
"annotations": [
{
"number": 1,
"rect": {
"x": 660,
"y": 575.46875,
"width": 66,
"height": 30
},
"badge": {
"x": 480,
"y": 543.46875
}
},
{
"number": 2,
"rect": {
"x": 660,
"y": 624.46875,
"width": 66,
"height": 30
},
"badge": {
"x": 480,
"y": 592.46875
}
},
{
"number": 3,
"rect": {
"x": 1296,
"y": 808.890625,
"width": 88,
"height": 32
},
"badge": {
"x": 1454,
"y": 824.890625
}
}
]
},
"04-allocation": {
"width": 1920,
"height": 902,
"annotations": [
{
"number": 1,
"rect": {
"x": 551,
"y": 342.09375,
"width": 182,
"height": 16
},
"badge": {
"x": 475,
"y": 350.09375
}
},
{
"number": 2,
"rect": {
"x": 551,
"y": 395.28125,
"width": 803,
"height": 22.09375
},
"badge": {
"x": 475,
"y": 406.328125
}
},
{
"number": 3,
"rect": {
"x": 551,
"y": 452.46875,
"width": 811,
"height": 49
},
"badge": {
"x": 475,
"y": 476.46875
}
}
]
},
"07-formal": {
"width": 1920,
"height": 902,
"annotations": [
{
"number": 1,
"rect": {
"x": 660,
"y": 575.46875,
"width": 66,
"height": 30
},
"badge": {
"x": 480,
"y": 543.46875
}
},
{
"number": 2,
"rect": {
"x": 818,
"y": 623.46875,
"width": 116,
"height": 32
},
"badge": {
"x": 999,
"y": 639.46875
}
},
{
"number": 3,
"rect": {
"x": 536,
"y": 729.46875,
"width": 88,
"height": 32
},
"badge": {
"x": 460,
"y": 745.46875
}
}
]
},
"08-metrics": {
"width": 1920,
"height": 902,
"annotations": [
{
"number": 1,
"rect": {
"x": 1180,
"y": 260.28125,
"width": 720,
"height": 40
},
"badge": {
"x": 1104,
"y": 280.28125
}
},
{
"number": 2,
"rect": {
"x": 1594,
"y": 537.28125,
"width": 153,
"height": 40
},
"badge": {
"x": 1518,
"y": 557.28125
}
},
{
"number": 3,
"rect": {
"x": 1056,
"y": 443.28125,
"width": 76,
"height": 40
},
"badge": {
"x": 980,
"y": 463.28125
}
}
]
},
"08b-audit": {
"width": 1920,
"height": 902,
"annotations": [
{
"number": 1,
"rect": {
"x": 1056,
"y": 443.28125,
"width": 76,
"height": 40
},
"badge": {
"x": 980,
"y": 463.28125
}
},
{
"number": 2,
"rect": {
"x": 1048,
"y": 494.28125,
"width": 149.40625,
"height": 17
},
"badge": {
"x": 972,
"y": 502.78125
}
}
]
},
"09-pause": {
"width": 1920,
"height": 902,
"annotations": [
{
"number": 1,
"rect": {
"x": 983,
"y": 659.65625,
"width": 36,
"height": 12
},
"badge": {
"x": 907,
"y": 665.65625
}
},
{
"number": 2,
"rect": {
"x": 1404,
"y": 656.65625,
"width": 34,
"height": 20
},
"badge": {
"x": 1328,
"y": 666.65625
}
}
]
},
"10a-choose-winner": {
"width": 1920,
"height": 902,
"annotations": [
{
"number": 1,
"rect": {
"x": 1448,
"y": 656.65625,
"width": 62,
"height": 20
},
"badge": {
"x": 1372,
"y": 666.65625
}
},
{
"number": 2,
"rect": {
"x": 1433,
"y": 727,
"width": 91.453125,
"height": 32
},
"badge": {
"x": 1357,
"y": 743
}
}
]
},
"10-finish": {
"width": 1920,
"height": 902,
"annotations": [
{
"number": 1,
"rect": {
"x": 798,
"y": 435,
"width": 338.625,
"height": 24
},
"badge": {
"x": 722,
"y": 447
}
},
{
"number": 2,
"rect": {
"x": 1098,
"y": 471,
"width": 60,
"height": 32
},
"badge": {
"x": 1228,
"y": 487.0
}
}
]
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 68 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 94 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 106 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 110 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 103 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 71 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 81 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 89 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 106 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 105 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 83 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 96 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 79 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 97 KiB

+284
View File
@@ -0,0 +1,284 @@
# 企微消息推送 · 从创建到上线
让业务消息按你喜欢的样子抵达 💌 图文以 DevOps 通知为示例;配套 Skill 将相同的配置体验复用到任意业务平台,适配注册、充值、统计和告警。
更新时间:2026-10-28
> 企微截图由用户提供;运维平台截图来自真实组件的隔离演示环境。标注只辅助定位,示例配置和截图不代表当前生产配置或验收结果。所有 Webhook 示例均为占位值。
## 目录
- [开始前:账号、群聊与职责](#prepare)
- [1. 在企微群中添加消息推送](#wecom-entry)
- [2. 填名称,复制完整 Webhook](#wecom-create)
- [3. 接通服务端通知通道](#server)
- [4. 选择什么时候通知](#events)
- [5. 挑选字段,调整显示顺序](#fields)
- [6. 选信封,加一点 emoji](#styles)
- [7. 编辑标题、正文与信尾](#templates)
- [8. 预览,再发送一封测试信](#preview-test)
- [9. 保存配置,核对群内实收](#save-receive)
- [10. 实现、迁移与上线验收](#implementation-release)
- [11. 没收到消息时怎么查](#troubleshooting)
- [12. 把流程交给 Codex Skill](#reuse-skill)
<a id="prepare"></a>
## 开始前:账号、群聊与职责
这套方案通过企业内部群的 Webhook 主动推送消息。先准备接收通知的群,再配置负责发送的服务端。
- 复用的是配置能力与交互,业务字段、数据来源和触发规则按项目适配;本文图片仍展示 DevOps 案例,不代表注册或充值功能已在当前平台上线。
- 没有企业管理员身份也可能创建:企业需要允许你创建消息推送,目标群也需要允许添加。若看不到入口,先核对内部群与群设置,再请管理员开通创建权限。
- 企微负责接收和呈现;DevOps 平台负责真实业务事件、通知时机、字段、模板、投递和重试。机器人名称不会自动连接 Jenkins。
- 本 Admin 页面只提供图文教程和 skill 下载。实际通知偏好在运维平台的「设置 → 通知」维护;完整 Webhook 只保存在服务端。
- 本教程使用群消息推送,不涉及监听群聊、智能机器人对话或代发个人消息。
<a id="wecom-entry"></a>
## 1. 在企微群中添加消息推送
电脑企微进入目标内部群,打开群详情 → 消息推送。旧版入口可能显示为「群机器人」。
![1. 在企微群中添加消息推送](../../public/guides/notifications/01-wecom-entry.svg)
*用户提供的企微客户端截图 · 点击图片可放大*
1. 点击「添加」,开始创建群消息推送。
- 点击「添加」,选择自定义消息推送。截图里已有的 devops 构建日志只是示例名称,你可以使用便于辨认的名字。
- 如果入口不存在或提示无权限,联系群主确认群管理设置,或请企业管理员为你开放创建消息推送权限;不需要索取企业管理员账号。
<a id="wecom-create"></a>
## 2. 填名称,复制完整 Webhook
名称、简介和图标方便群成员辨认。配置完成后复制完整 Webhook,并在企微保存。
![2. 填名称,复制完整 Webhook](../../public/guides/notifications/02-wecom-create.svg)
*用户提供的企微客户端截图,Webhook 已截断 · 点击图片可放大*
1. 填写方便辨认的推送名称与简介。
2. 复制完整 Webhook,只放到服务端密钥配置。
3. 核对信息后在企微保存。
- 名称可用「DevOps 发布通知」,简介说明推送哪些项目和结果。它们不负责决定发送内容,后续以平台配置为准。
- 将完整地址存入服务端 secret 或环境文件。截图中的地址已截断,不能从图片复制后直接使用。
- 截图、文档、Git、前端配置和日志都不保存完整 Webhook。若发现地址泄漏,按企微实际能力重置并同步服务端。
<a id="server"></a>
## 3. 接通服务端通知通道
由负责部署的人配置发送服务。企微使用 wecom 专用协议,随后重启或重新加载对应服务。
- NOTIFICATION_PROVIDER 设为 wecom;企微地址放 WECOM_WEBHOOK_URL。NOTIFICATION_WEBHOOK_URL 用于通用 JSON 网关,不能用它替代企微专用配置。
- DEVOPS_PUBLIC_URL 填运维平台公开地址,用于通知中的发布详情链接。
- 核对密钥源文件、部署副本和进程环境,避免只改当前进程导致下次发布丢配置。先备份,只修改需要的键。
- 「已接入」表示服务端变量存在;供应商是否接受、群里是否实收要在测试和真实业务环节分别确认。
```text
NOTIFICATION_PROVIDER=wecom
WECOM_WEBHOOK_URL=https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=replace-with-secret
DEVOPS_PUBLIC_URL=https://devops.example.com
```
<a id="events"></a>
## 4. 选择什么时候通知
打开运维平台「设置 → 通知」。开启发布通知,再选择关心的业务时机。
![4. 选择什么时候通知](../../public/guides/notifications/03-events.svg)
*真实 DevOps 组件的本地隔离演示截图 · 点击图片可放大*
1. 开启或暂停业务发布通知。
2. 按需选择通知时机,或只看成功/失败结果。
3. 右侧显示示例预览,与订阅时机相互独立。
- 可选创建发布、进入队列、发布成功、发布失败、发布取消和重新发布。系统默认六种全选。
- 只关心最终结果时,点击「只看发布结果」,会选择发布成功和发布失败;这一步要保存后才生效。
- 关闭发布通知后,仍能编辑和测试草稿;正式业务通知在保存后暂停。预览选择某种时机不会自动启用它。
- 保存需要平台超级管理员权限,和企微企业管理员身份是两套权限。
<a id="fields"></a>
## 5. 挑选字段,调整显示顺序
勾选消息要展示的信息,再用上移 / 下移调整顺序。缺少真实数据时自动略过。
![5. 挑选字段,调整显示顺序](../../public/guides/notifications/04-fields.svg)
*真实 DevOps 组件的本地隔离演示截图 · 点击图片可放大*
1. 勾选需要的字段,缺少真实数据时会略过。
2. 上移 / 下移调整正文顺序。
3. 发布详情与构建日志链接可以分别开关。
- 共有 11 种字段:项目、环境、分支/标签、状态、操作者、构建编号、耗时、提交 SHA、创建时间、发布单 ID、失败摘要。
- 字段顺序直接影响正文顺序。取消勾选后,预设正文和对应字段变量都不再显示它;你自己写下的固定文字不会被自动删除。
- 「附上发布详情链接」和「附上构建日志链接」独立控制自动链接。真实记录没有构建链接时会略过,预览中的示例链接不可当成真实构建。
- 失败摘要只在有错误数据时出现,耗时需要有效开始/结束时间。
<a id="styles"></a>
## 6. 选信封,加一点 emoji
三种样式共用同一份业务数据,选择适合群聊的信息密度。
![6. 选信封,加一点 emoji](../../public/guides/notifications/05-styles.svg)
*真实 DevOps 组件的本地隔离演示截图 · 点击图片可放大*
1. 选择软萌信笺、清爽简报或极简速报。
2. 控制自动 emoji 点缀。
3. 标题与信尾可继续编辑,右侧实时预览。
- 💌 软萌信笺:轻量问候、字段 emoji 和分行引用;🫧 清爽简报:清晰分行、减少点缀;⚡ 极简速报:把字段收进一则短消息。
- 「点缀 emoji」影响自动标题、问候与字段点缀,不删除你在标题、正文或信尾手写的 emoji。
- 当前采用 Markdown,可控制标题、加粗、引用与链接。消息气泡、背景和字体由企微客户端统一呈现。
- 正文为空时使用选定的预设;填写自定义正文后,以自定义内容优先,预设仍会影响 {{fields}} 和 {{greeting}} 的展开。
<a id="templates"></a>
## 7. 编辑标题、正文与信尾
从预设开始,按需展开「自定义正文」。变量会在预览和真实业务中由同一渲染器展开。
![7. 编辑标题、正文与信尾](../../public/guides/notifications/06-custom-template.svg)
*真实 DevOps 组件的本地隔离演示草稿,未保存到生产 · 点击图片可放大*
1. 展开自定义正文,留空时恢复预设。
2. 插入变量并编写 Markdown。
3. 预览展示当前草稿,仍需保存后用于真实业务。
- 标题保持单行,可用 {{emoji}}、{{eventTitle}} 和已勾选的字段,例如 {{projectKey}}。
- 正文可插入 {{greeting}}、{{fields}}、{{links}} 和具体字段名。点击变量按钮会插入正文;字段变量仍受勾选约束。
- 留空正文即可恢复预设排版。信尾可以写一句简短的话;不要把密钥或敏感错误原文写进模板。
- 未知变量、空标题、重复字段和超长内容会被拒绝。当前实现按 UTF-8 限制为 3900 字节,给测试标记留出余量。
```text
标题:{{emoji}} {{eventTitle}} · {{projectKey}}
正文示例:
{{greeting}}
{{fields}}
{{links}}
信尾:今天也在认真把事情做好 🌷
```
<a id="preview-test"></a>
## 8. 预览,再发送一封测试信
右侧可切换预览成功、失败等时机。先看当前草稿,再决定是否实际发送。
![8. 预览,再发送一封测试信](../../public/guides/notifications/07-test-confirmation.svg)
*本地隔离演示的确认框,拍摄后取消发送 · 点击图片可放大*
1. 核对当前通道和测试标记,确认后才实际发送;本截图未点击发送。
- 预览使用明确标注的示例数据,不创建发布单、不触发构建、不发送消息。切换预览时机会改变示例,不改变已保存的订阅。
- 点击「发送一条测试消息」,核对确认框中的目标通道,再点击「发送测试消息」。会向当前配置的群发送,使用当前草稿,并带「通知测试」标记。
- 测试不会自动保存偏好,暂停正式通知也能单独测试。后端有 10 秒限流,重复点击时等待窗口结束即可。
- 截图只展示隔离演示中的确认框,拍摄过程没有向真实企微群发送消息。
<a id="save-receive"></a>
## 9. 保存配置,核对群内实收
确认草稿后点击「保存配置」。后续业务通知使用已保存的版本。
![9. 保存配置,核对群内实收](../../public/guides/notifications/08-wecom-received.svg)
*用户提供的先前企微测试消息实收截图 · 点击图片可放大*
- 保存成功后重新读取,确认字段、时机和样式仍一致。离开页面会提示未保存修改;保存返回 409 时说明配置已被他人更新,应重读再比较。
- 企微接口 HTTP 200 还不够,业务响应 errcode=0 才表示接口接受。群里实际看到消息,才完成目标群实收确认。
- 实收截图由用户提供,展示先前测试消息的样式;它不代替你的新模板、当前目标群或真实发布事件验收。
- 最后触发一次已授权的真实业务事件,核对时机、真实字段、详情链接和投递记录。测试消息成功不等于所有业务链路都已完成验收。
<a id="implementation-release"></a>
## 10. 实现、迁移与上线验收
如果要在其他项目复用,先核对已有架构。开发、提交、推送和部署按本次授权分别执行。
- 前端只调用本方后端;后端提供读取/保存/预览/测试接口,统一渲染器处理预览、测试、真实事件和重试,HTTP 客户端检查企微 errcode。
- 本例偏好保存在 notification_configs,version 防止覆盖他人更新;Outbox 保存事件、状态、次数与重试时间。记录去重不是跨进程恰好一次投递的保证。
- 发布前执行相关测试、lint、类型检查与构建,备份数据库。先发后端并执行 20261028030000_notification_config 迁移,检查迁移记录、新表和健康,再发前端。
- 核对 Jenkins checkout SHA、公网资源、已授权接口的读取/预览/保存和落库。用实际结果区分代码测试、供应商接受、群内实收和真实业务验收。
- 切换机器人前查看历史待重试记录,避免旧通知集中补发。关闭的通知时机会停止相应自动重试,再开启不会自动恢复 dead。
```text
相对于 API 根地址:
GET /notifications/config
PUT /notifications/config { preferences, version }
POST /notifications/config/preview { preferences, event }
POST /notifications/config/test { preferences, event, confirmed: true }
本例数据库迁移:20261028030000_notification_config
```
<a id="troubleshooting"></a>
## 11. 没收到消息时怎么查
沿着「权限 → 配置 → 订阅 → 响应 → 记录 → 实收」逐项定位,不用反复触发真实发布。
- 没有添加入口:看内部群、群管理设置和企业的创建成员范围。
- 提示缺少 NOTIFICATION_WEBHOOK_URL:检查是否误选 generic,直连企微应使用 wecom 和 WECOM_WEBHOOK_URL。
- 显示已接入但没收到:核对进程环境、机器人是否仍在群、通知是否开启、时机是否勾选、企微业务码和 Outbox 错误。
- 预览与实收不同:看草稿是否保存、真实字段是否缺失、自定义正文是否覆盖预设,以及客户端排版差异。
- 409 需要重读版本;429 需要等待;dead 不再自动重试。只有明确了目标、范围和授权,才手动补发历史通知。
- 通知失败独立记录,不改变真实部署结果。成功构建也不等于服务实时健康。
<a id="reuse-skill"></a>
## 12. 把流程交给 Codex Skill
给 Codex Webhook 和目标业务需求,它会在目标项目复用相同的配置界面与交互,再接入真实数据和触发规则。支持业务事件、定时统计和按需的阈值提醒。
- 压缩包根目录是 wecom-notification-integration,解压到 ~/.codex/skills/,最终路径应为 ~/.codex/skills/wecom-notification-integration/SKILL.md,避免多套一层目录。
- 刷新技能列表后可用 $wecom-notification-integration 调用,也可由匹配任务自动选择。
- 告诉 Codex 目标项目、消息内容、触发需求和已授权范围。它会优先从现有代码识别数据口径、权限和技术栈,缺少关键业务定义时再询问;Webhook 本身不能推导注册人数或充值金额。
- 固定复用开关、字段勾选/排序、三种样式、emoji、模板/变量/信尾、链接、实时预览、草稿测试、保存与持久化。注册/充值主题使用自己的字段与时机,多个主题分别保存。
- 技能包自带两张界面参考原图,离开本仓库也可对照复现。目标系统沿用自己的前后端、数据库、权限和调度设施;接收端按实际 Webhook 协议适配,不强制采用原 DevOps 技术栈。
- 项目中保留技能源与图文内容源;下载包可重复生成,避免网页、README 和安装版各说一套。
```text
示例一:
请使用 $wecom-notification-integration,在当前平台复用这套通知配置。
每天北京时间 09:00 向我给的 Webhook 推送昨天注册人数,口径沿用现有注册统计。
示例二:
在当前订单平台复用同样的通知配置,充值成功后推送金额和币种,
支持勾选字段、调整顺序、编辑模板、预览和测试。
Webhook 只放服务端;真实发送、提交推送和部署按本次授权范围执行。
```
## 官方参考
- [腾讯官方:企微消息推送创建入口](https://cloud.tencent.com/document/product/1759/128391)
- [腾讯官方:内部群通知接入与限制](https://cloud.tencent.com/document/product/248/50413)
- [企微消息推送协议](https://developer.work.weixin.qq.com/document/path/99110)
## 维护教程
- 内容源:`guide.json`;网页读取相同内容。原图与来源/坐标:`screenshots/`、`screenshots.json`。
- `python3 scripts/build-notification-guide.py` 生成 README、SVG 标注和 skill ZIP;`--check` 只检查一致性。
- skill 源码:`skill/wecom-notification-integration/`;显式添加 `--install-skill` 安装或更新本地技能。
- 网页入口:`/guides/notifications`;skill 下载:`/guides/notifications/wecom-notification-integration.zip`。
- public 中的静态资源可能独立访问,不能依赖页面路由鉴权保密;发布前检查原图与文字中没有真实密钥、联系人和私密群内容。
+230
View File
@@ -0,0 +1,230 @@
{
"title": "企微消息推送 · 从创建到上线",
"intro": "让业务消息按你喜欢的样子抵达 💌 图文以 DevOps 通知为示例;配套 Skill 将相同的配置体验复用到任意业务平台,适配注册、充值、统计和告警。",
"updated": "2026-10-28",
"notice": "企微截图由用户提供;运维平台截图来自真实组件的隔离演示环境。标注只辅助定位,示例配置和截图不代表当前生产配置或验收结果。所有 Webhook 示例均为占位值。",
"steps": [
{
"id": "prepare",
"title": "开始前:账号、群聊与职责",
"lead": "这套方案通过企业内部群的 Webhook 主动推送消息。先准备接收通知的群,再配置负责发送的服务端。",
"bullets": [
"复用的是配置能力与交互,业务字段、数据来源和触发规则按项目适配;本文图片仍展示 DevOps 案例,不代表注册或充值功能已在当前平台上线。",
"没有企业管理员身份也可能创建:企业需要允许你创建消息推送,目标群也需要允许添加。若看不到入口,先核对内部群与群设置,再请管理员开通创建权限。",
"企微负责接收和呈现;DevOps 平台负责真实业务事件、通知时机、字段、模板、投递和重试。机器人名称不会自动连接 Jenkins。",
"本 Admin 页面只提供图文教程和 skill 下载。实际通知偏好在运维平台的「设置 → 通知」维护;完整 Webhook 只保存在服务端。",
"本教程使用群消息推送,不涉及监听群聊、智能机器人对话或代发个人消息。"
]
},
{
"id": "wecom-entry",
"title": "1. 在企微群中添加消息推送",
"lead": "电脑企微进入目标内部群,打开群详情 → 消息推送。旧版入口可能显示为「群机器人」。",
"images": [
"01-wecom-entry"
],
"bullets": [
"点击「添加」,选择自定义消息推送。截图里已有的 devops 构建日志只是示例名称,你可以使用便于辨认的名字。",
"如果入口不存在或提示无权限,联系群主确认群管理设置,或请企业管理员为你开放创建消息推送权限;不需要索取企业管理员账号。"
]
},
{
"id": "wecom-create",
"title": "2. 填名称,复制完整 Webhook",
"lead": "名称、简介和图标方便群成员辨认。配置完成后复制完整 Webhook,并在企微保存。",
"images": [
"02-wecom-create"
],
"bullets": [
"名称可用「DevOps 发布通知」,简介说明推送哪些项目和结果。它们不负责决定发送内容,后续以平台配置为准。",
"将完整地址存入服务端 secret 或环境文件。截图中的地址已截断,不能从图片复制后直接使用。",
"截图、文档、Git、前端配置和日志都不保存完整 Webhook。若发现地址泄漏,按企微实际能力重置并同步服务端。"
]
},
{
"id": "server",
"title": "3. 接通服务端通知通道",
"lead": "由负责部署的人配置发送服务。企微使用 wecom 专用协议,随后重启或重新加载对应服务。",
"bullets": [
"NOTIFICATION_PROVIDER 设为 wecom;企微地址放 WECOM_WEBHOOK_URL。NOTIFICATION_WEBHOOK_URL 用于通用 JSON 网关,不能用它替代企微专用配置。",
"DEVOPS_PUBLIC_URL 填运维平台公开地址,用于通知中的发布详情链接。",
"核对密钥源文件、部署副本和进程环境,避免只改当前进程导致下次发布丢配置。先备份,只修改需要的键。",
"「已接入」表示服务端变量存在;供应商是否接受、群里是否实收要在测试和真实业务环节分别确认。"
],
"code": "NOTIFICATION_PROVIDER=wecom\nWECOM_WEBHOOK_URL=https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=replace-with-secret\nDEVOPS_PUBLIC_URL=https://devops.example.com"
},
{
"id": "events",
"title": "4. 选择什么时候通知",
"lead": "打开运维平台「设置 → 通知」。开启发布通知,再选择关心的业务时机。",
"images": [
"03-events"
],
"bullets": [
"可选创建发布、进入队列、发布成功、发布失败、发布取消和重新发布。系统默认六种全选。",
"只关心最终结果时,点击「只看发布结果」,会选择发布成功和发布失败;这一步要保存后才生效。",
"关闭发布通知后,仍能编辑和测试草稿;正式业务通知在保存后暂停。预览选择某种时机不会自动启用它。",
"保存需要平台超级管理员权限,和企微企业管理员身份是两套权限。"
]
},
{
"id": "fields",
"title": "5. 挑选字段,调整显示顺序",
"lead": "勾选消息要展示的信息,再用上移 / 下移调整顺序。缺少真实数据时自动略过。",
"images": [
"04-fields"
],
"bullets": [
"共有 11 种字段:项目、环境、分支/标签、状态、操作者、构建编号、耗时、提交 SHA、创建时间、发布单 ID、失败摘要。",
"字段顺序直接影响正文顺序。取消勾选后,预设正文和对应字段变量都不再显示它;你自己写下的固定文字不会被自动删除。",
"「附上发布详情链接」和「附上构建日志链接」独立控制自动链接。真实记录没有构建链接时会略过,预览中的示例链接不可当成真实构建。",
"失败摘要只在有错误数据时出现,耗时需要有效开始/结束时间。"
]
},
{
"id": "styles",
"title": "6. 选信封,加一点 emoji",
"lead": "三种样式共用同一份业务数据,选择适合群聊的信息密度。",
"images": [
"05-styles"
],
"bullets": [
"💌 软萌信笺:轻量问候、字段 emoji 和分行引用;🫧 清爽简报:清晰分行、减少点缀;⚡ 极简速报:把字段收进一则短消息。",
"「点缀 emoji」影响自动标题、问候与字段点缀,不删除你在标题、正文或信尾手写的 emoji。",
"当前采用 Markdown,可控制标题、加粗、引用与链接。消息气泡、背景和字体由企微客户端统一呈现。",
"正文为空时使用选定的预设;填写自定义正文后,以自定义内容优先,预设仍会影响 {{fields}} 和 {{greeting}} 的展开。"
]
},
{
"id": "templates",
"title": "7. 编辑标题、正文与信尾",
"lead": "从预设开始,按需展开「自定义正文」。变量会在预览和真实业务中由同一渲染器展开。",
"images": [
"06-custom-template"
],
"bullets": [
"标题保持单行,可用 {{emoji}}、{{eventTitle}} 和已勾选的字段,例如 {{projectKey}}。",
"正文可插入 {{greeting}}、{{fields}}、{{links}} 和具体字段名。点击变量按钮会插入正文;字段变量仍受勾选约束。",
"留空正文即可恢复预设排版。信尾可以写一句简短的话;不要把密钥或敏感错误原文写进模板。",
"未知变量、空标题、重复字段和超长内容会被拒绝。当前实现按 UTF-8 限制为 3900 字节,给测试标记留出余量。"
],
"code": "标题:{{emoji}} {{eventTitle}} · {{projectKey}}\n\n正文示例:\n{{greeting}}\n\n{{fields}}\n\n{{links}}\n\n信尾:今天也在认真把事情做好 🌷"
},
{
"id": "preview-test",
"title": "8. 预览,再发送一封测试信",
"lead": "右侧可切换预览成功、失败等时机。先看当前草稿,再决定是否实际发送。",
"images": [
"07-test-confirmation"
],
"bullets": [
"预览使用明确标注的示例数据,不创建发布单、不触发构建、不发送消息。切换预览时机会改变示例,不改变已保存的订阅。",
"点击「发送一条测试消息」,核对确认框中的目标通道,再点击「发送测试消息」。会向当前配置的群发送,使用当前草稿,并带「通知测试」标记。",
"测试不会自动保存偏好,暂停正式通知也能单独测试。后端有 10 秒限流,重复点击时等待窗口结束即可。",
"截图只展示隔离演示中的确认框,拍摄过程没有向真实企微群发送消息。"
]
},
{
"id": "save-receive",
"title": "9. 保存配置,核对群内实收",
"lead": "确认草稿后点击「保存配置」。后续业务通知使用已保存的版本。",
"images": [
"08-wecom-received"
],
"bullets": [
"保存成功后重新读取,确认字段、时机和样式仍一致。离开页面会提示未保存修改;保存返回 409 时说明配置已被他人更新,应重读再比较。",
"企微接口 HTTP 200 还不够,业务响应 errcode=0 才表示接口接受。群里实际看到消息,才完成目标群实收确认。",
"实收截图由用户提供,展示先前测试消息的样式;它不代替你的新模板、当前目标群或真实发布事件验收。",
"最后触发一次已授权的真实业务事件,核对时机、真实字段、详情链接和投递记录。测试消息成功不等于所有业务链路都已完成验收。"
]
},
{
"id": "implementation-release",
"title": "10. 实现、迁移与上线验收",
"lead": "如果要在其他项目复用,先核对已有架构。开发、提交、推送和部署按本次授权分别执行。",
"bullets": [
"前端只调用本方后端;后端提供读取/保存/预览/测试接口,统一渲染器处理预览、测试、真实事件和重试,HTTP 客户端检查企微 errcode。",
"本例偏好保存在 notification_configs,version 防止覆盖他人更新;Outbox 保存事件、状态、次数与重试时间。记录去重不是跨进程恰好一次投递的保证。",
"发布前执行相关测试、lint、类型检查与构建,备份数据库。先发后端并执行 20261028030000_notification_config 迁移,检查迁移记录、新表和健康,再发前端。",
"核对 Jenkins checkout SHA、公网资源、已授权接口的读取/预览/保存和落库。用实际结果区分代码测试、供应商接受、群内实收和真实业务验收。",
"切换机器人前查看历史待重试记录,避免旧通知集中补发。关闭的通知时机会停止相应自动重试,再开启不会自动恢复 dead。"
],
"code": "相对于 API 根地址:\nGET /notifications/config\nPUT /notifications/config { preferences, version }\nPOST /notifications/config/preview { preferences, event }\nPOST /notifications/config/test { preferences, event, confirmed: true }\n\n本例数据库迁移:20261028030000_notification_config"
},
{
"id": "troubleshooting",
"title": "11. 没收到消息时怎么查",
"lead": "沿着「权限 → 配置 → 订阅 → 响应 → 记录 → 实收」逐项定位,不用反复触发真实发布。",
"bullets": [
"没有添加入口:看内部群、群管理设置和企业的创建成员范围。",
"提示缺少 NOTIFICATION_WEBHOOK_URL:检查是否误选 generic,直连企微应使用 wecom 和 WECOM_WEBHOOK_URL。",
"显示已接入但没收到:核对进程环境、机器人是否仍在群、通知是否开启、时机是否勾选、企微业务码和 Outbox 错误。",
"预览与实收不同:看草稿是否保存、真实字段是否缺失、自定义正文是否覆盖预设,以及客户端排版差异。",
"409 需要重读版本;429 需要等待;dead 不再自动重试。只有明确了目标、范围和授权,才手动补发历史通知。",
"通知失败独立记录,不改变真实部署结果。成功构建也不等于服务实时健康。"
]
},
{
"id": "reuse-skill",
"title": "12. 把流程交给 Codex Skill",
"lead": "给 Codex Webhook 和目标业务需求,它会在目标项目复用相同的配置界面与交互,再接入真实数据和触发规则。支持业务事件、定时统计和按需的阈值提醒。",
"bullets": [
"压缩包根目录是 wecom-notification-integration,解压到 ~/.codex/skills/,最终路径应为 ~/.codex/skills/wecom-notification-integration/SKILL.md,避免多套一层目录。",
"刷新技能列表后可用 $wecom-notification-integration 调用,也可由匹配任务自动选择。",
"告诉 Codex 目标项目、消息内容、触发需求和已授权范围。它会优先从现有代码识别数据口径、权限和技术栈,缺少关键业务定义时再询问;Webhook 本身不能推导注册人数或充值金额。",
"固定复用开关、字段勾选/排序、三种样式、emoji、模板/变量/信尾、链接、实时预览、草稿测试、保存与持久化。注册/充值主题使用自己的字段与时机,多个主题分别保存。",
"技能包自带两张界面参考原图,离开本仓库也可对照复现。目标系统沿用自己的前后端、数据库、权限和调度设施;接收端按实际 Webhook 协议适配,不强制采用原 DevOps 技术栈。",
"项目中保留技能源与图文内容源;下载包可重复生成,避免网页、README 和安装版各说一套。"
],
"code": "示例一:\n请使用 $wecom-notification-integration,在当前平台复用这套通知配置。\n每天北京时间 09:00 向我给的 Webhook 推送昨天注册人数,口径沿用现有注册统计。\n\n示例二:\n在当前订单平台复用同样的通知配置,充值成功后推送金额和币种,\n支持勾选字段、调整顺序、编辑模板、预览和测试。\n\nWebhook 只放服务端;真实发送、提交推送和部署按本次授权范围执行。"
}
],
"captions": {
"01-wecom-entry": [
"点击「添加」,开始创建群消息推送。"
],
"02-wecom-create": [
"填写方便辨认的推送名称与简介。",
"复制完整 Webhook,只放到服务端密钥配置。",
"核对信息后在企微保存。"
],
"03-events": [
"开启或暂停业务发布通知。",
"按需选择通知时机,或只看成功/失败结果。",
"右侧显示示例预览,与订阅时机相互独立。"
],
"04-fields": [
"勾选需要的字段,缺少真实数据时会略过。",
"上移 / 下移调整正文顺序。",
"发布详情与构建日志链接可以分别开关。"
],
"05-styles": [
"选择软萌信笺、清爽简报或极简速报。",
"控制自动 emoji 点缀。",
"标题与信尾可继续编辑,右侧实时预览。"
],
"06-custom-template": [
"展开自定义正文,留空时恢复预设。",
"插入变量并编写 Markdown。",
"预览展示当前草稿,仍需保存后用于真实业务。"
],
"07-test-confirmation": [
"核对当前通道和测试标记,确认后才实际发送;本截图未点击发送。"
],
"08-wecom-received": []
},
"references": [
{
"label": "腾讯官方:企微消息推送创建入口",
"url": "https://cloud.tencent.com/document/product/1759/128391"
},
{
"label": "腾讯官方:内部群通知接入与限制",
"url": "https://cloud.tencent.com/document/product/248/50413"
},
{
"label": "企微消息推送协议",
"url": "https://developer.work.weixin.qq.com/document/path/99110"
}
]
}
+286
View File
@@ -0,0 +1,286 @@
{
"01-wecom-entry": {
"width": 480,
"height": 510,
"source": "用户提供的企微客户端截图",
"annotations": [
{
"number": 1,
"rect": {
"x": 26,
"y": 118,
"width": 429,
"height": 49
},
"badge": {
"x": 435,
"y": 98
}
}
],
"format": "png"
},
"02-wecom-create": {
"width": 480,
"height": 530,
"source": "用户提供的企微客户端截图,Webhook 已截断",
"annotations": [
{
"number": 1,
"rect": {
"x": 85,
"y": 158,
"width": 331,
"height": 125
},
"badge": {
"x": 440,
"y": 139
}
},
{
"number": 2,
"rect": {
"x": 154,
"y": 402,
"width": 292,
"height": 31
},
"badge": {
"x": 112,
"y": 454
}
},
{
"number": 3,
"rect": {
"x": 247,
"y": 475,
"width": 215,
"height": 31
},
"badge": {
"x": 440,
"y": 455
}
}
],
"format": "png"
},
"03-events": {
"width": 1265,
"height": 712,
"source": "真实 DevOps 组件的本地隔离演示截图",
"annotations": [
{
"number": 1,
"rect": {
"x": 764.435546875,
"y": 357.18203125,
"width": 39.53125,
"height": 31.644444444444446
},
"badge": {
"x": 828.1796875,
"y": 372.81111111111113
}
},
{
"number": 2,
"rect": {
"x": 76.591796875,
"y": 445.98116319444443,
"width": 727.375,
"height": 84.05555555555556
},
"badge": {
"x": 35.578125,
"y": 488.00894097222226
}
},
{
"number": 3,
"rect": {
"x": 875.123046875,
"y": 413.2551215277778,
"width": 300.4375,
"height": 31.644444444444446
},
"badge": {
"x": 832.1328125,
"y": 429.1777777777778
}
}
],
"format": "jpeg"
},
"04-fields": {
"width": 1265,
"height": 712,
"source": "真实 DevOps 组件的本地隔离演示截图",
"annotations": [
{
"number": 1,
"rect": {
"height": 129.54444444444445,
"width": 727.375,
"x": 76.591796875,
"y": 123.20164930555556
},
"badge": {
"x": 35.578125,
"y": 187.9738715277778
}
},
{
"number": 2,
"rect": {
"height": 52.41111111111111,
"width": 727.375,
"x": 76.591796875,
"y": 264.6127604166667
},
"badge": {
"x": 35.578125,
"y": 290.81831597222225
}
},
{
"number": 3,
"rect": {
"height": 41.53333333333333,
"width": 727.375,
"x": 76.591796875,
"y": 317.02387152777777
},
"badge": {
"x": 35.578125,
"y": 337.7905381944445
}
}
],
"format": "jpeg"
},
"05-styles": {
"width": 1265,
"height": 712,
"source": "真实 DevOps 组件的本地隔离演示截图",
"annotations": [
{
"number": 1,
"rect": {
"height": 109.76666666666667,
"width": 727.375,
"x": 76.591796875,
"y": 200.92213541666666
},
"badge": {
"x": 35.578125,
"y": 255.80546875000002
}
},
{
"number": 2,
"rect": {
"height": 23.733333333333334,
"width": 91.18438720703125,
"x": 712.7824096679688,
"y": 147.72300347222222
},
"badge": {
"x": 828.1796875,
"y": 159.2111111111111
}
},
{
"number": 3,
"rect": {
"height": 234.86111111111111,
"width": 727.375,
"x": 76.591796875,
"y": 332.4443576388889
},
"badge": {
"x": 35.578125,
"y": 449.87491319444445
}
}
],
"format": "jpeg"
},
"06-custom-template": {
"width": 1265,
"height": 712,
"source": "真实 DevOps 组件的本地隔离演示草稿,未保存到生产",
"annotations": [
{
"number": 1,
"rect": {
"height": 16.316666666666666,
"width": 727.375,
"x": 76.591796875,
"y": 205.86657986111112
},
"badge": {
"x": 35.578125,
"y": 214.02491319444445
}
},
{
"number": 2,
"rect": {
"height": 188.8777777777778,
"width": 727.375,
"x": 76.591796875,
"y": 247.8943576388889
},
"badge": {
"x": 35.578125,
"y": 342.3332465277778
}
},
{
"number": 3,
"rect": {
"height": 348.4674479166667,
"width": 300.4375,
"x": 875.123046875,
"y": 95.72135416666667
},
"badge": {
"x": 832.1328125,
"y": 158.22222222222223
}
}
],
"format": "jpeg"
},
"07-test-confirmation": {
"width": 1280,
"height": 720,
"source": "本地隔离演示的确认框,拍摄后取消发送",
"annotations": [
{
"number": 1,
"rect": {
"height": 152.0,
"width": 420.0,
"x": 430.0,
"y": 284.0
},
"badge": {
"x": 390.0,
"y": 360.0
}
}
],
"format": "jpeg"
},
"08-wecom-received": {
"width": 302,
"height": 212,
"source": "用户提供的先前企微测试消息实收截图",
"annotations": [],
"format": "png"
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 42 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 74 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 46 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 54 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 53 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 57 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 48 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 36 KiB

@@ -0,0 +1,38 @@
---
name: wecom-notification-integration
description: 在任意业务平台按给定 Webhook 复用同一套通知配置体验,支持注册统计、充值、告警、发布等消息的字段、触发时机、模板、预览和测试。识别接收端协议,确认是企微才使用企微协议;不用于读取群聊或智能对话机器人。
---
# 可复用的 Webhook 通知配置
用户给出 Webhook 和目标项目后,在该项目实现与原通知面板相同的配置能力和视觉体验,再接入目标业务的真实数据。适用于任意业务平台和技术栈:注册日报、充值成功、统计金额、告警和发布通知都可以复用。保留现有技能名供兼容,DevOps 只是首个案例。
“一样”指配置能力和交互一致:开关、时机选择、字段勾选与排序、三种样式、emoji、标题/正文/信尾、变量插入、链接开关、实时预览、草稿测试、保存与持久化。业务事件、字段、统计口径、权限、数据源和触发器按目标项目替换;不能把注册或充值套进发布成功枚举。
目标业务平台与接收端协议分别识别。企微、飞书或其他 Webhook 的请求体和成功条件可能不同;配置体验共用,发送适配器遵循实际协议,不根据“都是 Webhook”认定兼容。
## 工作入口
- 实现配置模块:先读 [references/implementation.md](references/implementation.md),其中定义共同验收基线,并链接包内界面参考图。以目标项目的 UI、后端、数据库和调度设施实现,不要求 Vue、NestJS、Prisma 或 Jenkins。
- 接入业务数据与触发:读 [references/business-adaptation.md](references/business-adaptation.md),明确事件通知、定时汇总或用户要求的阈值提醒;包含注册日报和充值成功两个完整适配示例。
- 创建企微消息推送或接通通道:读 [references/wecom-setup.md](references/wecom-setup.md)。已有完整地址时跳过创建步骤;其他协议查其当前官方文档及项目适配器。
- 发布、验收、排障:读 [references/release-and-verification.md](references/release-and-verification.md)。图文教程只在任务要求时补充,不扩展每次接入的交付范围。
- 维护原发布通知或追溯旧实现时才读 [references/devops-example.md](references/devops-example.md),不把它的字段、路径、迁移或部署平台当成通用要求。
## 先确定什么
检查目标仓库、已有配置/权限/业务接口,优先从源码和现有指标定义找到消息主题、数据来源、字段、统计范围、时区和触发规则。Webhook 只说明发送目的地,不能推导用户数或充值额。仅在缺失信息影响正确性时询问,例如“每日汇总还是每笔通知”“统计哪个租户、什么币种”;同时继续可独立完成的配置模块。不编造数据、不默认套用 DevOps 指标,不要求用户重复提供已给出的地址。
## 必须保持
1. 核对真实仓库、分支和未提交修改,遵循当前 AGENTS.md 并保留无关工作。调用技能本身不授权创建分支/worktree、提交、推送、部署、真实发送或历史补发;已有明确授权不重复询问。
2. Webhook 是密钥,只留在服务端 secret / 环境配置中。前端、Git、教程截图、日志、审计和错误响应不包含完整地址或 key;示例使用占位值。
3. 环境变量、路由、表名、权限和依赖沿用目标项目约定。NOTIFICATION_PROVIDER、WECOM_WEBHOOK_URL、notification_configs 等仅是原案例命名;多个消息主题的字段、触发和模板配置应独立保存,不能互相覆盖。
4. 预览、测试、真实事件与重试共用渲染器。字段缺失时略过,动态数据脱敏;预览不发消息,测试带清晰标记并单独确认。用户已明确要求实际测试时,不重复索要同一授权。
5. 按供应商协议检查接受结果;企微必须同时检查 HTTP 与 errcode === 0,其他通道不套用企微业务码。通知失败独立记录,不回滚已确认业务结果,不阻塞注册、入账或支付回调。
## 完成标准
按共同基线核对功能与视觉,验证配置重读、真实数据/触发接线及失败处理。仅成功发送一条手工消息,或做出预览页,都不算完整接入。区分自动测试、供应商接受、群内实收与真实业务链路;按实际授权报告完成情况和缺口。发布时验证实际版本、适用的迁移和存储、服务健康及触发设施,不限定某个 CI 平台。
本例图文教程位于 Admin 项目的 docs/notifications/README.md,网页入口 /guides/notifications;这些是参考位置,不是其他项目的固定路径。
@@ -0,0 +1,4 @@
interface:
display_name: "可复用消息通知配置"
short_description: "给定 Webhook,在任意业务平台复用字段、时机、模板、预览与测试,适配注册和充值等消息"
default_prompt: "请使用 $wecom-notification-integration,根据我提供的 Webhook 和业务需求,在当前项目复用同样的通知配置界面与交互,接上真实数据和触发规则,并按本次授权范围验证。"
Binary file not shown.

After

Width:  |  Height:  |  Size: 57 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 46 KiB

@@ -0,0 +1,45 @@
# 业务数据与触发规则
Webhook 决定发到哪里;本文件决定何时发送、统计什么,以及怎样接到真实业务。优先使用项目已有指标/订单口径和调度设施,避免再造一套不一致的统计。
## 适配前确认
从源码和产品配置确定主题、权威数据源、状态/过滤条件、租户或项目范围、字段格式、业务时区和触发规则。用户没有明确的数据口径不能从 Webhook 猜出;只询问会改变结果的缺口。其余配置、渲染和预览工作继续完成。
| 触发方式 | 接入位置 | 防止重复的逻辑身份 |
| --- | --- | --- |
| 业务事件 | 已验证且提交成功的业务状态转换,或已有领域事件/事务 outbox | 作用域 + 主题 + 业务事件/支付流水 ID |
| 定时汇总 | 服务端现有调度/任务系统,支持配置时间、时区和统计窗口 | 作用域 + 主题 + 窗口起止 + 触发规则修订(仅当窗口语义改变) |
| 阈值提醒(用户需要时) | 基于真实指标的调度/事件评估 | 作用域 + 规则 + 越阈周期;约定冷却与恢复,避免每次采样刷屏 |
统计失败/数据源不可用是“暂不可得”,不能显示成 0;查得确实没有记录才显示 0。幂等身份不随纯模板修改或投递重试改变,除非用户明确发起一次补发。
## 示例 A:每天北京时间 09:00 推送昨天注册人数
适用于用户明确提出这个规则的场景,不能将其当所有项目的默认时机。
1. 检查注册成功事实的定义:用户记录、注册完成事件还是已有运营指标;是否排除测试/已注销账号、是否去重、统计哪个租户/应用,均沿用业务口径。区分新增注册与累计用户/DAU。
2. 主题如 `registration.daily`,触发配置为每天 09:00、`Asia/Shanghai`。使用该时区前一自然日 `[00:00, 次日 00:00)` 的半开区间,再转换为数据库时间;不以“现在减 24 小时”代替自然日。
3. 字段目录提供 `reportDate`、`registrationCount`、`timezone` 和真实存在的应用/范围信息;按需提供报表链接。示例值只用于预览;真实任务从权威数据源取数,查询受租户/项目范围约束。
4. 配置页的 01 区显示定时模式、发送时间与时区,02 区显示上述字段,03 区保留三种样式与正文编辑。标题例如 `{{emoji}} 注册日报 · {{reportDate}}`,正文可用 `{{fields}}`;不出现构建编号或发布成功。
5. 按“范围 + 主题 + 统计窗口”创建持久化逻辑任务,多实例重复调度不产生多条逻辑通知。重试保持窗口与上下文稳定,不因跨午夜改算另一天。
6. 核对项目已有漏跑策略。无既定策略时默认恢复后按未来计划执行并报告漏跑,历史补发需明确日期范围;不悄悄补发旧日报。调度时间变化不隐式重复发送同一窗口。
7. 使用固定时钟/隔离数据验证跨日与月末窗口、真实零注册、数据源失败、重复调度、租户隔离、关闭后不发和重启后按保存配置继续。只有预览或手工测试成功还不算日报任务接通。
若用户只说“推送注册人数”,先核对既有需求;缺失时询问要逐次注册通知、定时汇总还是阈值提醒,以及必要的统计范围。
## 示例 B:充值成功后推送金额
适用于成功支付/入账事件;“充值总额日报”应改走汇总模式,不将每笔金额与汇总金额混用。
1. 找到现有支付回调的验签、订单/支付流水状态校验、入账事务与成功事件。复用其校验结果,在可信业务事实提交后创建通知;不根据浏览器支付成功页或未验证回调发送。
2. 以项目权威定义决定是支付完成还是到账完成。复用事务 outbox、领域事件或等价提交后机制;不能先向群里报成功再提交业务事务,也不能在请求线程等待群消息重试。
3. 主题如 `payment.succeeded`。用支付流水/已发生的成功事件作幂等键,结合业务范围与主题;重复回调、队列重复消费或 worker 重试不能变成新业务通知。
4. 字段目录可提供 `orderNo`、`amount`、`currency`、`paidAt`、`maskedUser` 和现有订单详情链接。金额保持原有最小单位整数/Decimal 精度,格式化带币种,不经二进制浮点运算;多个币种不能不加区分地相加。展示经现有权限允许和脱敏的数据。
5. 01 区提供“充值成功”等真实业务时机;02 区选择/排序金额、币种等;03 区保留相同模板能力。标题例如 `{{emoji}} 充值到账提醒`,正文用 `{{fields}}`。模拟订单只用于隔离预览,测试不能创建真实充值、发货或记账。
6. 通知失败单独入队、限次重试并记录结果,不改变已确认的支付/入账状态,不影响支付回调正常应答;退款、更正是否单独通知按本次需求处理。
7. 用隔离数据覆盖成功提交、失败/未验证回调不发、事务回滚不发、重复回调与并发消费、金额精度/币种、字段脱敏及 provider 超时不影响业务结果。真实支付/充值操作需在实际授权范围内,不能为验证通知自行制造交易。
## 跨平台验收
从不同业务栈挑一个实际入口验证:事件/调度 → 权威数据 → 主题字段目录 → 已保存偏好 → 统一渲染 → provider → 投递记录。配置界面和测试消息只是其中一部分。不能因为宿主不是原 Vue/NestJS 项目就要求换框架;沿用现有代码与设施完成等价模块。
@@ -0,0 +1,72 @@
# DevOps 参考案例:发布通知
仅当目标就是原 DevOps 项目,或需要追溯原实现时读取。以下路径、枚举、权限、变量和迁移均属于这个案例,不是其他业务平台的要求。
# 配置页面与服务端契约
这是本次 DevOps 的可追溯示例,其他项目先核对当前源码,不照搬历史分支或版本。
## 拥有方
| 职责 | 源码入口 |
| --- | --- |
| 偏好、校验、目录、模板 | `devops-platform-api/src/notifications/config/` |
| 发布事件、重试 | `devops-platform-api/src/notifications/wecom/deploy-notification.service.ts` |
| 企微 HTTP 客户端 | `devops-platform-api/src/notifications/wecom/wecom.client.ts` |
| Outbox | `devops-platform-api/src/notifications/outbox/` |
| 数据表与迁移 | `NotificationConfig` / `notification_configs`,`prisma/migrations/20261028030000_notification_config/` |
| 界面 | `devops-platform-web/src/components/NotificationSettingsPanel.vue` |
| 安全预览 | `NotificationMarkdownPreview.vue`、`src/utils/notificationMarkdown.ts` |
| 前端 API | `devops-platform-web/src/services/notificationApi.ts` |
操作入口是 DevOps 的 `/settings?tab=notifications`;Admin 的 `/guides/notifications` 只承载教程,不存密钥,也不代理 DevOps 配置。
## 接口
沿用登录、首次改密检查和超级管理员权限。路径相对于 API 根地址,生产反代通常加 `/api`。
| 接口 | 入参与行为 |
| --- | --- |
| `GET /notifications/config` | 返回 preferences、version、updatedAt、channel、catalog;不返回 webhook |
| `PUT /notifications/config` | `{preferences, version}`,旧版本返回 409 |
| `POST /notifications/config/preview` | `{preferences, event}`,明确标注示例,不发送消息 |
| `POST /notifications/config/test` | 同预览并要求 `confirmed: true`;使用当前草稿,带「通知测试」标记,不保存偏好 |
`channel.status=ok` 仅表示配置存在,不证明最近请求已被接受。
## 偏好示例(不是系统默认值)
```json
{
"enabled": true,
"events": ["succeeded", "failed"],
"fields": ["projectKey", "environment", "ref", "operator", "duration", "failureSummary"],
"style": "cozy",
"emojiEnabled": true,
"titleTemplate": "{{emoji}} {{eventTitle}}",
"bodyTemplate": "",
"footer": "今天也在认真把事情做好 🌷",
"includeDetailLink": true,
"includeBuildLink": true
}
```
- 时机:created、queued、succeeded、failed、canceled、retried。当前默认全选;「只看发布结果」选择成功和失败。
- 字段:projectKey、environment、ref、status、operator、buildNumber、duration、commit、createdAt、runId、failureSummary。数组顺序就是显示顺序,未选择或无数据时略过。
- 样式:cozy 软萌信笺、simple 清爽简报、compact 极简速报。正文为空使用预设,自定义正文优先。
- 变量:emoji、eventTitle、greeting、fields、links 和字段名。字段变量受勾选约束,用户直接写下的固定文字不受字段开关控制。
- Emoji 开关影响自动标题、问候和字段点缀,不删除手写 emoji。链接开关控制自动链接或 `{{links}}`,不改写手写链接。
## 实现约束
1. 预览、测试、真实事件、重试共用渲染器。浏览器只安全展示,不执行模板 HTML。
2. 校验枚举、重复字段、空标题、未知变量、开启状态下空时机和 UTF-8 长度。本例限制 3900 字节,为测试标记留余量;变更前核对当前企微协议。
3. 动态错误、操作者、ref 等脱敏并转义,不让动态值注入 @all。只生成不带用户名密码的 HTTP(S) 链接。
4. 版本校验防覆盖,生产偏好经 Prisma Repository 持久化,审计记录字段/时机/样式与操作者摘要。前端与进程内状态不等于持久化。
5. Outbox 保留事件、状态、次数、下次重试。记录键去重不能称为跨进程「恰好一次投递」;重复事件与 worker 并发要独立验证。
6. 关闭时机不创建新通知,对应重试终止。再开启不自动恢复 dead;手动重发仍检查当前开关。切换目标群前先看历史待重试,避免旧消息集中涌入。
7. 测试检查供应商业务码、限制重复点击、记录审计。本例 10 秒限流在单进程内,多实例要使用共享限流或队列。
## 有效验证
覆盖事件过滤、字段隐藏/顺序、缺失值、变量、超长正文、危险链接/HTML、版本冲突、未确认测试拒绝、限流和 HTTP 200 业务失败。本地接收器只能证明请求格式,不能证明真实企微群实收。
@@ -0,0 +1,67 @@
# 共同配置体验与实现契约
这是每个业务平台都要复用的交付基线。字段和时机来自目标业务;路径、语言、框架、数据库、权限系统按项目适配。不要把复用缩减为一段发送脚本。
## 界面与交互基线
先查看包内真实界面参考:[整体布局](../assets/settings-overview.jpg)、[自定义正文与预览](../assets/settings-custom-template.jpg)。它们来自原 DevOps 组件的本地隔离演示,只参考布局和交互,不代表注册/充值已接入。即使原仓库不可访问,下载包也包含这两张原图。
截图底部的 outbox 列表属于原设置页已有的发送记录区。新项目需要能查询投递状态与失败摘要,可复用已有记录入口或提供简明列表;无需复制整张设置页或额外建设日志管理平台。
| 区域 | 在新项目中保留的行为 |
| --- | --- |
| 顶部 | 信封图标、简短说明、通道已接入/待接入状态;多个主题时先选通知主题 |
| 01 什么时候告诉我 | 主题总开关、业务时机勾选、全选;按需求显示定时频率/发送时间/时区或阈值配置,保存后生效;暂停后可编辑和测试 |
| 02 信里放些什么 | 字段勾选和数量、上移/下移排序、首尾禁用;缺失字段略过,0 是有效数据;按业务提供详情/报表/订单等自动链接开关 |
| 03 选一件喜欢的信封 | 💌 软萌信笺 cozy、🫧 清爽简报 simple、⚡ 极简速报 compact;emoji 开关、标题、可折叠自定义正文、变量按钮、信尾 |
| 右侧看看送达的样子 | 聊天气泡、示例数据标记、场景选择、实时草稿预览、测试按钮与反馈;预览不启用业务时机、不发消息 |
| 底部 | 已保存/有未保存修改、重新加载、保存;离开时保护草稿;版本冲突保留草稿,重读比较后保存 |
桌面左侧编辑、右侧约 350px 预览,24px 栏间距、16px 卡片间距、圆角白卡、淡紫选中态,聊天气泡用白底和浅绿灰描边;窄屏改单列。沿用宿主字体、基础控件与主题变量,保持上述密度、层次、交互和温柔文案。将“发布时机/构建日志/每次发布”等文字全部替换为目标业务用语,避免只换页面标题。
预设的视觉和功能保持一致:cozy 使用问候、字段点缀与分行引用;simple 清晰分行、减少点缀;compact 压缩为短消息。默认从 cozy 和 emoji 点缀开始,订阅与字段默认值按目标业务确定。自定义正文为空恢复预设;填写后正文优先,预设仍影响 fields/greeting。emoji/链接开关控制自动内容,不改写用户手写文字。
## 业务目录与配置
由服务端维护每个主题的 catalog,页面按目录渲染,避免固定六种发布时机或十一种构建字段。
- `topic`:稳定业务 key、名称、配置作用域。多个主题可以使用同一个服务端通道,配置按实际租户/项目/主题隔离,不额外建设多通道管理平台。
- `events`:真实业务时机 key、名称、预览场景;如 payment.succeeded,不能把它映射为 deployment.succeeded。仅提供本次业务需要的事件/定时/阈值模式,阈值不是必做扩展。
- `fields`:key、显示名、类型、单位、格式化规则、emoji、示例值与可见性;金额带币种,时间带时区,0 与无数据区分。客户端不能提交任意 SQL、函数或数据源地址。
- `variables`:emoji、eventTitle、greeting、fields、links,加本主题允许的字段名。插入按钮与后端白名单来自同一目录。
- `preferences`:enabled、events/trigger、有序 fields、style、emojiEnabled、titleTemplate、bodyTemplate、footer、自动链接选择。保留共同语义,命名和存储结构可按项目适配。
- `version/updatedAt`:保存并发控制;通道只返回状态/名称/必要脱敏标识,不返回 Webhook。多租户页面的编辑、预览、测试和发送均执行对应权限与作用域检查。
例如注册日报的字段可为 reportDate、registrationCount、timezone;充值成功可为 orderNo、amount、currency、paidAt、maskedUser。两者有各自配置,不能在切换主题时覆盖另一套模板。
## 服务端能力
复用目标项目接口与认证约定,提供读取、保存、预览、测试四种等价能力;不强制固定 `/notifications/config` 路径或超级管理员角色。
| 能力 | 必须满足 |
| --- | --- |
| 读取 | 已保存偏好、版本、主题目录、通道状态、适用触发参数;无密钥 |
| 保存 | 校验主题/字段/事件/变量/触发参数与权限,持久化;乐观锁等并发保护,不静默覆盖他人更新 |
| 预览 | 使用当前草稿与所选主题的明确示例;返回渲染结果,不创建订单、用户、统计任务或业务通知 |
| 测试 | 使用当前草稿的同一预览上下文,带“通知测试”标记,明确确认且限流;不保存、不把示例写入业务库、不改变正式订阅 |
预览请求应防抖、忽略旧请求结果;保存和测试有独立的 loading/错误状态,取消确认没有副作用。正式发送也走同一渲染器。共享渲染的是同一业务上下文下的转换规则,不承诺示例值与真实数据相同。
业务适配器先输出已确认的业务事实与允许字段,渲染器负责选择、排序、格式化与模板展开,provider 适配器负责协议和成功判断。按目标项目组织代码即可,不要求新建相同目录或引入同一套框架。
## 真实触发与可靠性
先按 [业务适配](business-adaptation.md) 接上真实事件或服务端调度,再复用现有 outbox/任务队列或等价可靠机制。记录业务幂等键、上下文/统计窗口、状态、次数、错误摘要与重试时间。重试保持同一业务事实和幂等键,不按重试时刻重新计算“昨天”;明确采用的模板版本策略。
同一支付事件或同一统计窗口重复进入时应合并为同一逻辑通知,验证重复触发与多实例 worker;不宣称网络投递恰好一次。关闭主题/时机后停止新发送与相应待重试,重新开启不自动补发历史;人工补发按授权范围执行。通知错误与真实业务结果分开记录。
## 渲染与安全边界
- 标题单行非空,正文只支持受控模板变量,模板不能执行脚本、SQL 或任意表达式。字段未勾选/不可见/缺失时略过,允许的数字 0 正常显示。
- 动态数据脱敏、转义;浏览器安全呈现 Markdown 子集,不执行 HTML;预览中的示例链接不可操作,真实链接仅生成经过校验的 HTTP(S) 地址。
- 按当前 provider 的实际格式和 UTF-8 字节上限校验最终内容并预留测试标记空间。原企微案例 3900 字节、10 秒进程内测试限流只是参考;多实例采用共享限流/队列,不能把进程内变量称为全局限流。
- 服务端密钥仅用于 provider 请求,不进入页面响应、源码、下载包、截图、审计或错误日志。定时/队列 worker 采用同一服务端密钥来源。
## 完成交付时检查
使用包内图片比较布局,再逐项验证开关、订阅/触发参数、字段顺序、三种样式、emoji、模板/信尾、变量、链接、预览、测试、保存重读和草稿保护。补充目标业务的零值/缺失值、业务口径、作用域、重复触发、版本冲突、模板字节限制、供应商业务失败和通知失败隔离。没有真实数据源或触发器时明确报告未完成,不能以一条手工测试代替业务闭环。
@@ -0,0 +1,52 @@
# 发布、验收与排障
## 按目标项目发布
核对当前仓库、分支、remote、未提交修改和自动部署钩子,使用项目已有流程。开发不代表授权提交/推送/部署;调用本 Skill 也不授权创建分支/worktree。已明确授权的操作继续执行,不重复询问。适用时使用已安装的 Git 流程和提交审查技能。
在用户授权上线后,完成以下适用项;不存在数据库变更时无需为了照搬案例新增迁移,不存在 Jenkins 时不用接入 Jenkins:
1. 审查本次差异、检查命令、密钥与截图,仅提交任务范围内内容,保留无关修改。
2. 执行目标技术栈声明的相关测试、类型检查、构建;核对通知配置的共同交互基线。
3. 有存储变更时备份与检查恢复方案,按项目迁移工具验证结构、作用域、版本和存储兼容性。凭据不进入命令参数或输出。
4. 按依赖顺序发布;新后端能力与兼容迁移准备好后再启用界面和触发器。核对实际提交与产物、服务健康、调度/队列 worker 的版本和密钥来源。
5. 用已授权会话/测试账号检查读取、预览、保存、持久化及作用域隔离;重启或新实例重读后仍一致。缺少会话时先做其他检查,不重置真实密码或冒充用户签发令牌。
6. 接业务事件或实际调度,验证幂等、失败重试、暂停和恢复策略。没有发送授权时仅做隔离验证并报告实收待验,不能自行触发真实充值或注册。
原 DevOps 的源码、枚举、Prisma 迁移和仓库路径只在 [案例](devops-example.md) 追溯;不作为其他项目固定发布目标。
## 分层证据
| 层次 | 可以证明 |
| --- | --- |
| 自动测试 / 编译 / 界面对照 | 约束、共同配置能力和可构建性 |
| 本地 HTTP 接收器 | 请求体和测试链路,不能证明真实供应商接受 |
| 通道状态已接入 | 必要配置存在,不能证明目标群实收 |
| HTTP 与协议业务码成功 | 供应商接受该条消息;企微为 errcode=0,其他 provider 按其协议 |
| 群内可见 | 目标群实收及排版可辨认 |
| 真实业务事实/调度、数据与投递记录 | 数据来源、口径、真实触发和消息共同工作 |
| 存储与重启后重读 | 配置持久化及执行实例使用已保存参数 |
注册日报应核对指定时区/窗口、权威人数、零值、重复调度与漏跑;充值应核对可信成功事实、币种/精度、重复回调与事务回滚不发。接口测试成功不代替这些验收。
实际测试与历史补发在用户授权范围内进行;正常业务事件按已保存订阅投递。通知失败独立记录,不更改已确认注册、支付、入账或部署结果。
## 排障入口
- 通道已配置却无消息:检查实际进程/worker 的密钥来源、接收机器人或 endpoint、provider 协议/业务码、主题开关、投递记录和重试状态。
- 预览正常但正式消息没有:检查真实事件是否产生并提交,调度器是否执行,是否保存当前草稿,业务去重键是否误冲突。
- 报表数值不符:检查业务口径、租户/应用范围、时区和半开统计窗口;数据源错误不能当作零值。
- 充值重复:检查可信状态转换、支付流水逻辑身份、重复回调与 worker 领用,不通过改回失败状态来重发通知。
- 预览与实收不同:检查草稿/保存版本、同一渲染器、实际缺失字段与客户端排版;自动 emoji/链接开关不改写手写文字。
- 版本冲突:保留草稿,重读比较;限流:等待,不通过并发重试绕过;永久失败:查明目标与授权范围后再补发。
## 本例图文维护
role-admin/docs/notifications/guide.json 是内容源;screenshots/ 存原图,screenshots.json 存来源/坐标。网页 /guides/notifications 读取同一内容。截图体现 DevOps 演示,通用 Skill 和新业务的验收不能混称为已上线功能。
```bash
python3 scripts/build-notification-guide.py
python3 scripts/build-notification-guide.py --check
```
保留截图来源,不含密钥、联系人或私密群内容。下载包包括共同规范、业务适配示例和两张界面原图;安装版、项目源与下载版应同步。图文维护是当前文档项目的流程,不要求每个接入项目都生成同样教程。
@@ -0,0 +1,72 @@
# 企微群消息推送:创建与通道接入
## 类型与权限
使用群聊的「消息推送 / 自定义消息推送」(旧版称群机器人),通过 Webhook 主动发送通知。它不监听群消息,也不提供智能对话或个人聊天收发。
普通成员可以在企业允许的范围内创建;企业可限制创建成员,群设置也可能限制添加。先在企业内部群检查入口。若无权限,申请「创建消息推送」权限或请有权限的人创建,不需要索取整个企业的管理员账号,也不能承诺自己建群就能绕过限制。
## 创建与服务端配置
已有完整 Webhook 时直接接入,跳过创建。以下变量名来自原 DevOps 案例;在其他平台沿用其服务端密钥管理和命名约定,不强制新增同名环境变量。
1. 电脑企微进入目标内部群,打开群详情 → 消息推送。
2. 点击添加 → 自定义消息推送,填写名称、简介和图标。
3. 复制生成的完整 Webhook,保存在目标服务端 secret / 环境文件。名称和简介只帮助辨认,不会自动连接业务系统。
4. 截图里的省略号、前缀或打码的 key 不能用于实际配置;不要为判断完整性而打印地址原文。
```dotenv
NOTIFICATION_PROVIDER=wecom
WECOM_WEBHOOK_URL=https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=replace-with-secret
DEVOPS_PUBLIC_URL=https://devops.example.com
```
这里的 `DEVOPS_PUBLIC_URL` 只为原发布详情生成链接;其他业务按需使用已有的订单/报表基址,没有构建链接时不提供构建日志开关。
`wecom` 发送企微 Markdown;`feishu` 和 `generic` 是不同协议。先看 provider 分支和请求体再选择变量,避免把企微地址当成任意 JSON 网关。
Webhook 是通知目的地,不是用户/订单数据接口,也不是支付平台发给本系统的入站回调地址。业务数据与触发见 [business-adaptation.md](business-adaptation.md)。
若既有密钥源文件又有部署副本,核对部署脚本、运行进程和下次构建使用哪个文件,避免本次重启可用、下次发布又丢失。只修改必要键,备份原文件并保留访问权限,日志只输出布尔状态。
## 实际测试
用户明确授权向该群发送测试时,准备带测试标记的具体内容。使用环境变量,不把真实密钥写进示例、命令参数或日志。
```python
# 在已获授权的终端执行;密钥仅从服务端环境读取,不放到命令参数中。
import json
import os
from urllib.error import HTTPError, URLError
from urllib.request import Request, urlopen
payload = {"msgtype": "markdown", "markdown": {"content": "# 通知接入测试\n\n这是一条测试消息。"}}
request = Request(os.environ["WECOM_WEBHOOK_URL"],
data=json.dumps(payload).encode("utf-8"),
headers={"Content-Type": "application/json"}, method="POST")
try:
with urlopen(request, timeout=10) as response:
result = json.load(response)
code = result.get("errcode") if isinstance(result, dict) else None
accepted = 200 <= response.status < 300 and type(code) is int and code == 0
print({"http_status": response.status,
"errcode": code if type(code) is int else "invalid_response",
"accepted": accepted})
raise SystemExit(0 if accepted else 1)
except HTTPError as error:
print({"http_status": error.code, "accepted": False})
raise SystemExit(1)
except (URLError, TimeoutError, ValueError):
print("网络或响应解析失败;地址和响应原文已隐藏。")
raise SystemExit(1)
```
检查 HTTP 状态和 JSON 中的 `errcode`;只有 `errcode=0` 才能报告接口已接受。群里实际可见才是实收确认。真实业务事件仍要单独验证,手工消息不能代替业务联调。
## 当前官方参考
- 创建入口:https://cloud.tencent.com/document/product/1759/128391
- 内部群与接入说明:https://cloud.tencent.com/document/product/248/50413
- 消息推送协议:https://developer.work.weixin.qq.com/document/path/99110
客户端入口可能变化;出现差异时核对当前官方说明与企业策略。
File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 93 KiB

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 127 KiB

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 143 KiB

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 148 KiB

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 140 KiB

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 96 KiB

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 110 KiB

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 121 KiB

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 144 KiB

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 141 KiB

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 112 KiB

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 130 KiB

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 107 KiB

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 131 KiB

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 57 KiB

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 100 KiB

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 64 KiB

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 75 KiB

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 73 KiB

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 78 KiB

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 65 KiB

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 48 KiB

+98
View File
@@ -0,0 +1,98 @@
/** 从同一教程内容源生成仓库README和带编号箭头的SVG截图;--check只验证,不修改文件。 */
import { readFile, writeFile } from "node:fs/promises";
import path from "node:path";
import { fileURLToPath } from "node:url";
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
const docRoot = path.join(root, "docs/experiments");
const guide = JSON.parse(
await readFile(path.join(docRoot, "guide.json"), "utf8")
);
const shots = JSON.parse(
await readFile(path.join(docRoot, "screenshots.json"), "utf8")
);
const check = process.argv.includes("--check");
const escape = value =>
String(value).replace(
/[&<>"']/g,
c =>
({
"&": "&amp;",
"<": "&lt;",
">": "&gt;",
'"': "&quot;",
"'": "&apos;"
})[c]
);
/** 派生文件必须与共享源一致,防止网页教程、标注和README各自漂移。 */
async function output(file, content) {
if (check) {
if ((await readFile(file, "utf8")) !== content)
throw new Error(`派生文档需要重新生成:${path.relative(root, file)}`);
} else await writeFile(file, content);
}
let readme = `# ${guide.title}\n\n${guide.intro}\n\n更新时间:${guide.updated}\n\n> 截图由仓库实际页面组件在隔离演示环境拍摄。红色箭头和编号为操作标注;演示调用、账号和统计不是生产验收证据。\n\n## 目录\n\n`;
for (const step of guide.steps) readme += `- ${step.title}\n`;
for (const step of guide.steps) {
readme += `\n## ${step.title}\n\n${step.lead}\n`;
for (const image of step.images ?? []) {
const shot = shots[image];
if (!shot || shot.annotations.length < 1)
throw new Error(`缺少截图标注:${image}`);
if (guide.captions[image]?.length !== shot.annotations.length)
throw new Error(`标注编号与说明不匹配:${image}`);
const raw = await readFile(
path.join(docRoot, "screenshots", `${image}.jpg`)
);
if (raw[0] !== 255 || raw[1] !== 216)
throw new Error(`截图不是JPEG:${image}`);
const { width, height } = shot;
if (
!Number.isInteger(width) ||
!Number.isInteger(height) ||
width < 1 ||
height < 1
)
throw new Error("截图尺寸无效");
const annotations = shot.annotations
.map(a => {
const { x, y, width: w, height: h } = a.rect,
{ x: bx, y: by } = a.badge;
for (const n of [x, y, w, h, bx, by])
if (!Number.isFinite(n)) throw new Error("标注坐标无效");
if (
w <= 0 ||
h <= 0 ||
x < 0 ||
y < 0 ||
x + w > width + 1 ||
y + h > height + 1 ||
bx < 20 ||
bx > width - 20 ||
by < 20 ||
by > height - 20
)
throw new Error(`标注超出截图:${image}`);
const targetX = Math.max(x, Math.min(x + w, bx)),
targetY = Math.max(y, Math.min(y + h, by));
return `<g><rect x="${x - 4}" y="${y - 4}" width="${w + 8}" height="${h + 8}" rx="7" fill="none" stroke="#ff3b30" stroke-width="4"/><path d="M ${bx} ${by} L ${targetX} ${targetY}" fill="none" stroke="#ff3b30" stroke-width="5" marker-end="url(#arrow)"/><circle cx="${bx}" cy="${by}" r="22" fill="#ff3b30" stroke="white" stroke-width="3"/><text x="${bx}" y="${by + 8}" text-anchor="middle" fill="white" font-family="Arial,sans-serif" font-size="24" font-weight="700">${a.number}</text></g>`;
})
.join("");
const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${height}" viewBox="0 0 ${width} ${height}" role="img" aria-labelledby="title desc"><title id="title">${escape(step.title)}</title><desc id="desc">隔离演示界面截图,红色箭头和编号对应教程操作步骤。</desc><defs><marker id="arrow" markerWidth="10" markerHeight="10" refX="9" refY="5" orient="auto" markerUnits="userSpaceOnUse"><path d="M0,0 L10,5 L0,10Z" fill="#ff3b30"/></marker></defs><image width="${width}" height="${height}" href="data:image/jpeg;base64,${raw.toString("base64")}"/>${annotations}</svg>\n`;
await output(
path.join(root, "public/guides/experiments", `${image}.svg`),
svg
);
readme +=
`\n![${step.title}:编号操作截图](../../public/guides/experiments/${image}.svg)\n\n` +
guide.captions[image].map((note, i) => `${i + 1}. ${note}`).join("\n") +
"\n";
}
readme += "\n" + step.bullets.map(line => `- ${line}`).join("\n") + "\n";
if (step.code) readme += `\n\`\`\`text\n${step.code}\n\`\`\`\n`;
}
readme +=
"\n## 维护教程\n\n- 内容源:`guide.json`;二级教程页直接读取同一内容源。\n- 原始截图:`screenshots/*.jpg`;标注坐标:`screenshots.json`。截图必须使用隔离演示数据。\n- 执行 `node scripts/build-experiment-guide.mjs` 重新生成本README和带箭头、编号的SVG。\n- 执行 `node scripts/build-experiment-guide.mjs --check` 检查派生文件与内容源一致。\n- 二级页面:`/digital/experiments/guide`;点击“操作指南”进入。\n";
await output(path.join(docRoot, "README.md"), readme);
console.log(
check ? "图文教程与标注一致性检查通过" : "已生成图文README与标注截图"
);
+169
View File
@@ -0,0 +1,169 @@
#!/usr/bin/env python3
"""由同一内容源生成通知教程、保留原图的 SVG 标注和可下载技能包。"""
import argparse
import base64
import html
import io
import json
import math
import os
from pathlib import Path
import re
import shutil
import struct
import zipfile
ROOT = Path(__file__).resolve().parents[1]
DOCS = ROOT / "docs/notifications"
PUBLIC = ROOT / "public/guides/notifications"
SLUG = "wecom-notification-integration"
SKILL = DOCS / "skill" / SLUG
def image_size(raw, image_format):
"""读取 PNG/JPEG 文件头尺寸,不重新编码截图。"""
if image_format == "png" and raw[:8] == b"\x89PNG\r\n\x1a\n":
return struct.unpack(">II", raw[16:24])
if image_format == "jpeg" and raw[:2] == b"\xff\xd8":
offset = 2
while offset + 8 < len(raw):
if raw[offset] != 255:
break
while raw[offset] == 255:
offset += 1
marker = raw[offset]
offset += 1
if marker in (0xD8, 0xD9) or 0xD0 <= marker <= 0xD7:
continue
length = int.from_bytes(raw[offset:offset + 2], "big")
if marker in (0xC0, 0xC1, 0xC2, 0xC3, 0xC5, 0xC6, 0xC7, 0xC9, 0xCA, 0xCB, 0xCD, 0xCE, 0xCF):
height, width = struct.unpack(">HH", raw[offset + 3:offset + 7])
return width, height
if length < 2:
break
offset += length
raise ValueError("截图不是有效的 PNG/JPEG")
def render_svg(key, raw, shot, title):
"""保留原始图片字节,仅以独立矢量图层增加操作指引。"""
width, height = shot["width"], shot["height"]
image_format = shot["format"]
if image_size(raw, image_format) != (width, height):
raise ValueError(f"截图格式或尺寸不匹配:{key}")
radius = 15 if width < 600 else 20
stroke = 2 if width < 600 else 3
annotations = []
for number, annotation in enumerate(shot["annotations"], 1):
rect, badge = annotation["rect"], annotation["badge"]
x, y, w, h = (rect[k] for k in ("x", "y", "width", "height"))
bx, by = badge["x"], badge["y"]
if annotation["number"] != number or not all(math.isfinite(v) for v in (x, y, w, h, bx, by)):
raise ValueError(f"标注编号或坐标无效:{key}")
if not (w > 0 and h > 0 and x >= 0 and y >= 0 and x + w <= width and y + h <= height):
raise ValueError(f"标注框超出截图:{key}")
if not (radius <= bx <= width - radius and radius <= by <= height - radius):
raise ValueError(f"标注编号超出截图:{key}")
tx, ty = max(x, min(x + w, bx)), max(y, min(y + h, by))
annotations.append(
f'<g><rect x="{x - 3}" y="{y - 3}" width="{w + 6}" height="{h + 6}" rx="6" '
f'fill="none" stroke="#ef4444" stroke-width="{stroke}"/>'
f'<path d="M {bx} {by} L {tx} {ty}" fill="none" stroke="#ef4444" '
f'stroke-width="{stroke}" marker-end="url(#arrow)"/>'
f'<circle cx="{bx}" cy="{by}" r="{radius}" fill="#ef4444" stroke="white" stroke-width="2"/>'
f'<text x="{bx}" y="{by + 6}" text-anchor="middle" fill="white" '
f'font-family="Arial,sans-serif" font-size="{radius + 3}" font-weight="700">{number}</text></g>'
)
encoded = base64.b64encode(raw).decode("ascii")
return (
f'<svg xmlns="http://www.w3.org/2000/svg" width="{width}" height="{height}" '
f'viewBox="0 0 {width} {height}" role="img" aria-labelledby="title desc">'
f'<title id="title">{html.escape(title)}</title><desc id="desc">{html.escape(shot["source"])}</desc>'
'<defs><marker id="arrow" markerWidth="9" markerHeight="9" refX="8" refY="4.5" '
'orient="auto" markerUnits="userSpaceOnUse"><path d="M0,0 L9,4.5 L0,9Z" fill="#ef4444"/></marker></defs>'
f'<image width="{width}" height="{height}" href="data:image/{image_format};base64,{encoded}"/>'
+ "".join(annotations) + "</svg>\n"
).encode("utf8")
def skill_archive():
"""固定文件顺序、权限和时间戳,下载包在不同机器也可重复核对。"""
output = io.BytesIO()
files = sorted(path for path in SKILL.rglob("*") if path.is_file())
if not (SKILL / "SKILL.md").is_file():
raise ValueError("缺少技能入口")
with zipfile.ZipFile(output, "w", compression=zipfile.ZIP_STORED) as archive:
for path in files:
if path.is_symlink():
raise ValueError("技能包不能包含外部文件链接")
item = zipfile.ZipInfo(f"{SLUG}/{path.relative_to(SKILL).as_posix()}", (1980, 1, 1, 0, 0, 0))
item.create_system = 3
item.external_attr = 0o100644 << 16
archive.writestr(item, path.read_bytes())
return output.getvalue()
def generate(check=False, install=False):
"""核对内容、来源、标注与派生文件;安装仅在显式参数下写入个人技能目录。"""
guide = json.loads((DOCS / "guide.json").read_text())
shots = json.loads((DOCS / "screenshots.json").read_text())
outputs = {}
used, ids = set(), set()
readme = [f'# {guide["title"]}', guide["intro"], f'更新时间:{guide["updated"]}', f'> {guide["notice"]}', "## 目录"]
readme.append("\n".join(f'- [{step["title"]}](#{step["id"]})' for step in guide["steps"]))
for step in guide["steps"]:
if not re.fullmatch(r"[a-z][a-z0-9-]*", step["id"]) or step["id"] in ids:
raise ValueError("章节 ID 不合法或重复")
ids.add(step["id"])
readme.extend([f'<a id="{step["id"]}"></a>', f'## {step["title"]}', step["lead"]])
for key in step.get("images", []):
shot = shots[key]
if not shot.get("source") or len(guide["captions"][key]) != len(shot["annotations"]):
raise ValueError(f"缺少截图来源或标注与说明不一致:{key}")
extension = "jpg" if shot["format"] == "jpeg" else "png"
raw = (DOCS / "screenshots" / f"{key}.{extension}").read_bytes()
outputs[PUBLIC / f"{key}.svg"] = render_svg(key, raw, shot, step["title"])
used.add(key)
readme.extend([f'![{step["title"]}](../../public/guides/notifications/{key}.svg)', f'*{shot["source"]} · 点击图片可放大*'])
if guide["captions"][key]:
readme.append("\n".join(f"{i}. {text}" for i, text in enumerate(guide["captions"][key], 1)))
readme.append("\n".join(f"- {text}" for text in step["bullets"]))
if step.get("code"):
readme.append(f'```text\n{step["code"]}\n```')
if used != set(shots):
raise ValueError("存在未引用或遗漏的截图")
readme.extend(["## 官方参考", "\n".join(f'- [{ref["label"]}]({ref["url"]})' for ref in guide["references"]), "## 维护教程",
"- 内容源:`guide.json`;网页读取相同内容。原图与来源/坐标:`screenshots/`、`screenshots.json`。",
"- `python3 scripts/build-notification-guide.py` 生成 README、SVG 标注和 skill ZIP;`--check` 只检查一致性。",
"- skill 源码:`skill/wecom-notification-integration/`;显式添加 `--install-skill` 安装或更新本地技能。",
"- 网页入口:`/guides/notifications`;skill 下载:`/guides/notifications/wecom-notification-integration.zip`。",
"- public 中的静态资源可能独立访问,不能依赖页面路由鉴权保密;发布前检查原图与文字中没有真实密钥、联系人和私密群内容。"])
outputs[DOCS / "README.md"] = ("\n\n".join(readme) + "\n").encode("utf8")
outputs[PUBLIC / f"{SLUG}.zip"] = skill_archive()
for path, content in outputs.items():
if check:
if not path.is_file() or path.read_bytes() != content:
raise ValueError(f"派生文件需要重新生成:{path.relative_to(ROOT)}")
else:
path.parent.mkdir(parents=True, exist_ok=True)
path.write_bytes(content)
if install:
target = Path(os.environ.get("CODEX_HOME", str(Path.home() / ".codex"))) / "skills" / SLUG
if check:
for path in SKILL.rglob("*"):
if path.is_file() and (not (target / path.relative_to(SKILL)).is_file() or path.read_bytes() != (target / path.relative_to(SKILL)).read_bytes()):
raise ValueError("本地安装技能与项目源不一致")
else:
shutil.copytree(SKILL, target, dirs_exist_ok=True)
print(f'本地技能{"检查通过" if check else "已安装"}:{target}')
print(f'{"检查通过" if check else "已生成"}:{len(guide["steps"])} 个章节、{len(shots)} 张截图和技能包')
if __name__ == "__main__":
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--check", action="store_true", help="只检查派生文件一致性")
parser.add_argument("--install-skill", action="store_true", help="安装或检查本地技能")
args = parser.parse_args()
generate(args.check, args.install_skill)
+45 -11
View File
@@ -1091,7 +1091,7 @@ export type Result<T> = { success: boolean; data: T };
/** 数字人后台 API,复用已有 JWT 拦截器。 */ /** 数字人后台 API,复用已有 JWT 拦截器。 */
export async function digital<T>( export async function digital<T>(
path: string, path: string,
method: "get" | "post" | "put" | "delete" = "get", method: "get" | "post" | "put" | "patch" | "delete" = "get",
data?: unknown data?: unknown
): Promise<T> { ): Promise<T> {
try { try {
@@ -1154,7 +1154,9 @@ export type Entry = {
caseSensitive: boolean; caseSensitive: boolean;
scanDepth: number; scanDepth: number;
}; };
/** 测试方案:A/B 的返回值遵循已注册类型的数据契约。 */ /** 组比例以万分比保存,key使用A至Z,0%组仍可用于人工指定。 */
export type ExperimentGroup = { key: string; weight: number; value: unknown };
/** 测试方案:动态分组的返回值遵循已注册类型的数据契约。 */
export type Experiment = { export type Experiment = {
id: string; id: string;
name: string; name: string;
@@ -1168,13 +1170,9 @@ export type Experiment = {
cutoff?: string; cutoff?: string;
accounts: string[]; accounts: string[];
traffic: number; traffic: number;
weightB: number; groups: ExperimentGroup[];
baseline: "A" | "B"; winner?: string;
winner?: "A" | "B";
presetA?: string;
presetB?: string;
description: string; description: string;
values?: { A: unknown; B: unknown };
typeRevision?: number; typeRevision?: number;
}; };
}; };
@@ -1213,16 +1211,52 @@ export type ExperimentUser = {
status: string; status: string;
createdAt: string; createdAt: string;
decision: null | { decision: null | {
variant: "A" | "B"; variant: string | null;
reason: string; reason: string;
value: unknown; value: unknown;
revision: number; revision: number;
}; };
override: null | { override: null | {
variant: "A" | "B"; variant: string;
reason: string; reason: string;
expiresAt: string; expiresAt: string;
bypassAudience: number; bypassAudience: number;
}; };
assignment: null | { variant: "A" | "B"; createdAt: string }; assignment: null | { variant: string; createdAt: string };
};
/** 独立 C 端用户的后台公开资料,不含密码/令牌或员工权限。 */
export type DigitalUser = {
id: number;
account: string;
username: string;
displayName: string;
status: "ACTIVE" | "INACTIVE";
/** 账号未保存内容偏好时默认开启,后端在生成时读取实际值。 */
nsfwEnabled?: boolean;
createdAt: string;
lastLoginAt: string | null;
conversations: number;
messages: number;
};
/** 用户所属会话的只读摘要,包含前台已删除但后台保留的记录。 */
export type UserConversation = {
id: string;
deletedAt: string | null;
title: string;
characterId: string;
characterName: string;
messages: number;
createdAt: string;
updatedAt: string;
};
/** 持久化聊天消息;包括已停止、失败和被替换的历史版本。 */
export type UserChatMessage = {
id: string;
role: "user" | "assistant";
content: string;
status: string;
pinned: number;
sequenceId: number;
createdAt: string;
}; };
+79
View File
@@ -0,0 +1,79 @@
<script setup lang="ts">
/** 角色编辑预览与聊天记录共用的受限文本展示,用户消息和 HTML 字面量均不作为标签解释。 */
import { computed } from "vue";
import { parseDigitalMessage } from "@/utils/digital-message-format";
const props = withDefaults(
defineProps<{
text: string;
role?: "assistant" | "user";
incomplete?: boolean;
}>(),
{ role: "assistant", incomplete: false }
);
const blocks = computed(() =>
parseDigitalMessage(props.text, props.incomplete)
);
</script>
<template>
<div
class="digital-message-text"
:class="{ 'is-prose': role === 'assistant' }"
>
<template v-if="role === 'assistant' && blocks.length">
<p
v-for="(block, index) in blocks"
:key="index"
:class="[
block.kind,
{
'is-latin':
/[A-Za-z]/.test(block.text) && !/[\u3400-\u9fff]/.test(block.text)
}
]"
>
<strong v-if="block.kind === 'dialogue'">{{ block.text }}</strong>
<template v-else>{{ block.text }}</template>
</p>
</template>
<template v-else>{{ text || "(未生成正文)" }}</template>
</div>
</template>
<style scoped>
.digital-message-text {
line-height: 1.9;
overflow-wrap: anywhere;
white-space: pre-wrap;
}
.is-prose {
white-space: normal;
}
.is-prose > p {
margin: 0;
white-space: pre-wrap;
}
.is-prose > p + p {
margin-top: 12px;
}
.dialogue {
color: var(--digital-dialogue-ink, var(--el-text-color-primary));
}
.dialogue strong {
font-weight: 600;
}
.narration {
color: var(--digital-narration-ink, var(--el-text-color-regular));
}
.narration.is-latin {
font-style: italic;
}
</style>
+24 -1
View File
@@ -8,6 +8,18 @@ export default {
redirect: "/digital/content", redirect: "/digital/content",
meta: { title: "数字人运营", icon: "ep/chat-dot-round", rank: 0 }, meta: { title: "数字人运营", icon: "ep/chat-dot-round", rank: 0 },
children: [ children: [
{
path: "/digital/growth",
name: "DigitalGrowth",
component: () => import("@/views/digital/growth.vue"),
meta: { title: "C端增长与体验", permission: "*" }
},
{
path: "/digital/users",
name: "DigitalUsers",
component: () => import("@/views/digital/users.vue"),
meta: { title: "用户管理", permission: "*" }
},
{ {
path: "/digital/content", path: "/digital/content",
name: "DigitalContent", name: "DigitalContent",
@@ -26,11 +38,22 @@ export default {
component: () => import("@/views/digital/experiments.vue"), component: () => import("@/views/digital/experiments.vue"),
meta: { title: "测试方案", permission: "*" } meta: { title: "测试方案", permission: "*" }
}, },
{
path: "/digital/experiments/guide",
name: "DigitalExperimentGuide",
component: () => import("@/views/digital/experiment-guide.vue"),
meta: {
title: "实验操作指南",
permission: "*",
showLink: false,
activePath: "/digital/experiments"
}
},
{ {
path: "/digital/experiment-users", path: "/digital/experiment-users",
name: "DigitalExperimentUsers", name: "DigitalExperimentUsers",
component: () => import("@/views/digital/experiment-users.vue"), component: () => import("@/views/digital/experiment-users.vue"),
meta: { title: "用户管理", permission: "*" } meta: { title: "实验用户分组", permission: "*" }
} }
] ]
} satisfies RouteConfigsTable; } satisfies RouteConfigsTable;
+19
View File
@@ -0,0 +1,19 @@
/** 接入教程沿用现有后台壳和超级管理员权限,只提供静态说明与安全的技能下载。 */
const Layout = () => import("@/layout/index.vue");
/** 消息推送教程与数字人运营配置分开导航,不在 Admin 中保存运维平台凭据。 */
export default {
path: "/guides",
name: "IntegrationGuides",
component: Layout,
redirect: "/guides/notifications",
meta: { title: "接入文档", icon: "ep/reading", rank: 3 },
children: [
{
path: "/guides/notifications",
name: "NotificationIntegrationGuide",
component: () => import("@/views/guides/notifications.vue"),
meta: { title: "消息推送机器人", permission: "*" }
}
]
} satisfies RouteConfigsTable;
+151
View File
@@ -0,0 +1,151 @@
/** 数字人消息的受限文本格式:对白、故事叙述与旧版括号;始终返回文本,不解释 HTML。 */
/** 有序展示片段;原始 content 继续用于存储、复制、记忆和上下文。 */
export type DigitalMessageBlock = {
kind: "dialogue" | "narration" | "plain";
text: string;
};
const quotePairs: Record<string, string> = {
'"': '"',
"“": "”",
"「": "」",
"『": "』",
"«": "»",
""": """
};
/** 跳过转义字符;引号不跨行,括号按同类型嵌套匹配,避免误吞后续内容。 */
function closingIndex(
text: string,
from: number,
open: string,
close: string,
nested = false
) {
let depth = 1;
for (let i = from; i < text.length; i++) {
if (text[i] === "\\") {
i++;
continue;
}
if (!nested && quotePairs[open] && text[i] === "\n") return -1;
if (nested && text.startsWith(open, i)) depth++;
if (text.startsWith(close, i)) {
depth--;
if (depth === 0) return i;
}
}
return -1;
}
/** 星号需要处于词边界,避免把乘法、文件名或普通单词里的星号视为排版。 */
function markerBoundary(text: string, index: number) {
return (
index === 0 || /[\s。!?!?,,;;::))\]”"」』»]/u.test(text[index - 1])
);
}
/**
* 解析累计正文而非单个 SSE delta。未闭合标记仅在流式/中断展示时延续当前样式;
* 旧版括号外文本按对白处理,有引号的旧开场白将引号外文字作为叙述,其他纯文本保留。
* 与 role-user/src/lib/digital-message-format.ts 保持同一实现和用例,独立构建时无需跨仓引用。
*/
export function parseDigitalMessage(
source: string,
streaming = false
): DigitalMessageBlock[] {
const blocks: DigitalMessageBlock[] = [];
for (const paragraph of source.replace(/\r\n?/g, "\n").split(/\n\s*\n/)) {
const parts: DigitalMessageBlock[] = [];
let legacyNarration = false;
const push = (kind: DigitalMessageBlock["kind"], text: string) => {
if (!text) return;
const last = parts[parts.length - 1];
if (last?.kind === kind) last.text += text;
else parts.push({ kind, text });
};
for (let i = 0; i < paragraph.length; ) {
const char = paragraph[i];
if (
char === "\\" &&
/[*"\\()()“”「」『』]/u.test(paragraph[i + 1] ?? "")
) {
push("plain", paragraph[i + 1]);
i += 2;
continue;
}
const quoteEnd = quotePairs[char];
if (quoteEnd) {
const close = closingIndex(paragraph, i + 1, char, quoteEnd);
const lineEnd = paragraph.indexOf("\n", i + 1);
const end =
close >= 0 ? close + 1 : lineEnd >= 0 ? lineEnd : paragraph.length;
push("dialogue", paragraph.slice(i, end));
i = end;
continue;
}
if (
char === "*" &&
markerBoundary(paragraph, i) &&
!/\s/u.test(paragraph[i + 1] ?? "")
) {
const marker = paragraph.startsWith("**", i) ? "**" : "*";
const close = closingIndex(
paragraph,
i + marker.length,
marker,
marker
);
if (close >= 0 || streaming) {
push(
marker === "**" ? "dialogue" : "narration",
paragraph.slice(i + marker.length, close >= 0 ? close : undefined)
);
i = close >= 0 ? close + marker.length : paragraph.length;
continue;
}
// 格式不完整的历史正文原样保留,不猜测后面的哪些字符属于标记。
push("plain", paragraph.slice(i));
break;
}
if ((char === "(" || char === "(") && markerBoundary(paragraph, i)) {
const close = closingIndex(
paragraph,
i + 1,
char,
char === "(" ? ")" : ")",
true
);
if (close >= 0 || streaming) {
legacyNarration = true;
push(
"narration",
paragraph.slice(i + 1, close >= 0 ? close : undefined)
);
i = close >= 0 ? close + 1 : paragraph.length;
continue;
}
push("plain", paragraph.slice(i));
break;
}
push("plain", char);
i++;
}
const hasDialogue = parts.some(part => part.kind === "dialogue");
for (const part of parts) {
const kind =
part.kind !== "plain"
? part.kind
: legacyNarration
? "dialogue"
: hasDialogue
? "narration"
: "plain";
for (const line of part.text.split(/\n+/)) {
if (line.trim()) blocks.push({ kind, text: line.trim() });
}
}
}
return blocks;
}
+89 -9
View File
@@ -1,8 +1,9 @@
<script setup lang="ts"> <script setup lang="ts">
/** 数字人内容库:角色、世界书、叙事预设分别编辑,发布状态显式可见。 */ /** 数字人内容库:角色、世界书、预设分别编辑,开场与示例使用聊天格式实时预览。 */
import { computed, onMounted, ref } from "vue"; import { computed, onMounted, ref } from "vue";
import { ElMessage } from "element-plus"; import { ElMessage } from "element-plus";
import { digital, type Content, type Entry } from "@/api/access"; import { digital, type Content, type Entry } from "@/api/access";
import DigitalMessageText from "@/components/DigitalMessageText.vue";
const contents = ref<Content[]>([]), const contents = ref<Content[]>([]),
kind = ref("character"), kind = ref("character"),
query = ref(""), query = ref(""),
@@ -29,6 +30,12 @@ const statusNames: Record<string, string> = {
published: "已发布", published: "已发布",
archived: "已下架" archived: "已下架"
}; };
/** 占位符仅用于当前预览,不改写编辑内容或数据库中的角色模板。 */
function previewText(value: string) {
return value
.replaceAll("{{char}}", edit.value?.name || "角色")
.replaceAll("{{user}}", "旅人");
}
const books = computed(() => const books = computed(() =>
contents.value.filter(c => c.kind === "worldbook" && c.status === "published") contents.value.filter(c => c.kind === "worldbook" && c.status === "published")
); );
@@ -323,7 +330,12 @@ onMounted(load);
v-if="edit.kind === 'character'" v-if="edit.kind === 'character'"
label="人格与开场" label="人格与开场"
name="persona" name="persona"
><el-form-item label="性格、背景和关系" ><el-alert
class="format-guide"
title="对白与叙述分段书写"
description="对白使用成对引号,如:“你来了。”;动作、神态、心理和环境用单星号包裹,如:*她合上书,抬头微笑。*。切换时空一行,下方预览与聊天使用相同的格式规则。"
:closable="false"
/><el-form-item label="性格、背景和关系"
><el-input ><el-input
v-model="edit.body.personality" v-model="edit.body.personality"
type="textarea" type="textarea"
@@ -334,15 +346,36 @@ onMounted(load);
type="textarea" type="textarea"
:rows="3" /></el-form-item :rows="3" /></el-form-item
><el-form-item label="首次问候(支持 {{char}} / {{user}} 占位符)" ><el-form-item label="首次问候(支持 {{char}} / {{user}} 占位符)"
><el-input ><div class="format-editor">
<el-input
v-model="edit.body.greeting" v-model="edit.body.greeting"
type="textarea" type="textarea"
:rows="4" /></el-form-item :rows="4"
placeholder="*她合上书,抬头看向你。*&#10;&#10;“你来了。”"
/>
<div
v-if="edit.body.greeting.trim()"
class="format-preview"
aria-label="首次问候展示预览"
>
<small>首次问候 · 展示效果</small>
<DigitalMessageText :text="previewText(edit.body.greeting)" />
</div></div></el-form-item
><el-form-item label="示例对白" ><el-form-item label="示例对白"
><el-input ><div class="format-editor">
<el-input
v-model="edit.body.examples" v-model="edit.body.examples"
type="textarea" type="textarea"
:rows="4" /></el-form-item :rows="4"
/>
<div
v-if="edit.body.examples.trim()"
class="format-preview"
aria-label="示例对白展示预览"
>
<small>示例对白 · 展示效果</small>
<DigitalMessageText :text="previewText(edit.body.examples)" />
</div></div></el-form-item
><el-form-item label="角色系统指令" ><el-form-item label="角色系统指令"
><el-input ><el-input
v-model="edit.body.systemPrompt" v-model="edit.body.systemPrompt"
@@ -355,12 +388,24 @@ onMounted(load);
:key="i" :key="i"
class="entry-row" class="entry-row"
> >
<div class="format-editor">
<el-input <el-input
v-model="edit.body.alternateGreetings[i]" v-model="edit.body.alternateGreetings[i]"
type="textarea" type="textarea"
:rows="2" :rows="2"
/><el-button />
@click="edit.body.alternateGreetings.splice(i, 1)" <div
v-if="edit.body.alternateGreetings[i].trim()"
class="format-preview"
:aria-label="`其他开场 ${i + 1} 展示预览`"
>
<small>其他开场 {{ i + 1 }} · 展示效果</small>
<DigitalMessageText
:text="previewText(edit.body.alternateGreetings[i])"
/>
</div>
</div>
<el-button @click="edit.body.alternateGreetings.splice(i, 1)"
>移除</el-button >移除</el-button
> >
</div> </div>
@@ -465,7 +510,11 @@ onMounted(load);
v-if="edit.kind === 'preset'" v-if="edit.kind === 'preset'"
label="生成编排" label="生成编排"
name="generation" name="generation"
><el-form-item label="系统指令" ><el-alert
class="format-guide"
title="系统统一区分对白和叙述"
description="本页设置叙事风格;对白使用引号、叙述使用单星号并分段的排版规则始终生效,发送、继续与重新生成共用。"
:closable="false" /><el-form-item label="系统指令"
><el-input ><el-input
v-model="edit.body.systemPrompt" v-model="edit.body.systemPrompt"
type="textarea" type="textarea"
@@ -512,6 +561,37 @@ onMounted(load);
</div> </div>
</template> </template>
<style scoped> <style scoped>
.format-guide {
margin-bottom: 18px;
}
.format-editor {
width: 100%;
min-width: 0;
}
.format-preview {
--digital-dialogue-ink: #fff5fc;
--digital-narration-ink: #c2b6c4;
max-height: 300px;
padding: 14px 18px;
margin-top: 10px;
overflow: auto;
font-size: 14px;
color: #e6dfe7;
background: #211c23;
border: 1px solid #ffffff12;
border-radius: 10px;
}
.format-preview > small {
display: block;
margin-bottom: 10px;
font-size: 11px;
color: #b5a6b8;
}
.heading { .heading {
display: flex; display: flex;
gap: 16px; gap: 16px;
+414
View File
@@ -0,0 +1,414 @@
<script setup lang="ts">
/** 实验图文教程二级页:固定目录与独立正文滚动,按实际阅读位置同步当前章节。 */
import {
nextTick,
onActivated,
onBeforeUnmount,
onMounted,
ref,
watch
} from "vue";
import { useRouter } from "vue-router";
import guide from "../../../docs/experiments/guide.json";
import screenshotSizes from "../../../docs/experiments/screenshots.json";
// 为懒加载截图预留真实比例,避免图片出现后章节位置发生跳动。
const sizes = screenshotSizes as Record<
string,
{ width: number; height: number }
>;
const router = useRouter();
const page = ref<HTMLElement>(),
body = ref<HTMLElement>(),
toc = ref<HTMLElement>();
const activeId = ref(guide.steps[0].id);
let frame = 0,
observer: ResizeObserver | undefined;
/** 正文是唯一阅读滚动容器,懒加载图片改变章节高度后也重新判定位置。 */
function updateReadingPosition() {
frame = 0;
if (!page.value?.offsetWidth || !body.value) return;
const available =
window.innerHeight - page.value.getBoundingClientRect().top - 24;
page.value.style.setProperty(
"--guide-height",
`${Math.max(360, available)}px`
);
const sections = Array.from(
body.value.querySelectorAll<HTMLElement>(".guide-section")
);
const top = body.value.getBoundingClientRect().top + 24;
let current = sections[0]?.id;
for (const section of sections) {
if (section.getBoundingClientRect().top <= top) current = section.id;
else break;
}
// 最后一章可能不足一屏;滚到底部时仍须选中它。
if (
body.value.scrollTop + body.value.clientHeight >=
body.value.scrollHeight - 2
)
current = sections.at(-1)?.id;
if (current) activeId.value = current.replace(/^guide-/, "");
}
function scheduleUpdate() {
if (!frame) frame = requestAnimationFrame(updateReadingPosition);
}
onMounted(() => {
window.addEventListener("resize", scheduleUpdate);
observer = new ResizeObserver(scheduleUpdate);
if (page.value) observer.observe(page.value);
if (body.value) {
observer.observe(body.value);
body.value
.querySelectorAll(".guide-section")
.forEach(section => observer!.observe(section));
}
scheduleUpdate();
});
onActivated(scheduleUpdate);
onBeforeUnmount(() => {
window.removeEventListener("resize", scheduleUpdate);
observer?.disconnect();
cancelAnimationFrame(frame);
});
watch(activeId, async id => {
await nextTick();
const button = toc.value?.querySelector<HTMLElement>(
`[data-section="${id}"]`
);
if (!button || !toc.value) return;
const item = button.getBoundingClientRect(),
menu = toc.value.getBoundingClientRect();
// 仅移动目录内部,避免 scrollIntoView 带动后台外层容器。
if (item.top < menu.top || item.bottom > menu.bottom)
toc.value.scrollTop +=
item.top - menu.top - toc.value.clientHeight / 2 + item.height / 2;
});
const images = guide.steps.flatMap(step =>
(step.images ?? []).map(image => `/guides/experiments/${image}.svg`)
);
/** 在当前二级页内滚动,不修改hash路由,也不触发任何实验写操作。 */
function jump(id: string) {
const section = body.value?.querySelector<HTMLElement>(`#guide-${id}`);
if (!section || !body.value) return;
body.value.scrollTo({
top:
body.value.scrollTop +
section.getBoundingClientRect().top -
body.value.getBoundingClientRect().top,
behavior: window.matchMedia("(prefers-reduced-motion: reduce)").matches
? "instant"
: "smooth"
});
}
</script>
<template>
<div ref="page" class="experiment-guide">
<header class="guide-heading">
<div>
<el-tag type="info">从零开始 · 图文教程</el-tag>
<h1>{{ guide.title }}</h1>
<p>{{ guide.intro }}</p>
</div>
<el-button @click="router.push('/digital/experiments')"
>返回测试方案</el-button
>
</header>
<el-alert
title="截图使用实际页面组件与隔离演示数据。红色编号对应下方操作;演示接入与统计状态不代表你的线上类型已经验收。点击图片可放大查看。"
type="info"
:closable="false"
/>
<div class="guide-layout">
<nav class="guide-toc" aria-label="教程目录">
<strong>本页目录</strong>
<div ref="toc" class="guide-links">
<button
v-for="step in guide.steps"
:key="step.id"
type="button"
:data-section="step.id"
:class="{ active: activeId === step.id }"
:aria-current="activeId === step.id ? 'location' : undefined"
@click="jump(step.id)"
>
{{ step.title }}
</button>
</div>
</nav>
<article
ref="body"
class="guide-body"
tabindex="0"
aria-label="教程正文"
@scroll="scheduleUpdate"
>
<section
v-for="step in guide.steps"
:id="`guide-${step.id}`"
:key="step.id"
class="guide-section"
>
<h2>{{ step.title }}</h2>
<p class="guide-lead">{{ step.lead }}</p>
<figure v-for="image in step.images ?? []" :key="image">
<el-image
:src="`/guides/experiments/${image}.svg`"
:style="{
aspectRatio: `${sizes[image].width} / ${sizes[image].height}`
}"
:alt="`${step.title},带红色箭头与编号的演示截图`"
:preview-src-list="images"
:initial-index="
images.indexOf(`/guides/experiments/${image}.svg`)
"
preview-teleported
lazy
fit="contain"
><template #error
><div class="image-error">
教程图片加载失败,请刷新重试。
</div></template
></el-image
>
<figcaption>隔离演示截图 · 点击放大 · 编号对应下方操作</figcaption>
<ol class="guide-callouts">
<li v-for="note in guide.captions[image]" :key="note">
{{ note }}
</li>
</ol>
</figure>
<ul>
<li v-for="line in step.bullets" :key="line">{{ line }}</li>
</ul>
<pre v-if="'code' in step"><code>{{ step.code }}</code></pre>
</section>
<footer class="guide-footer">
<p>
教程更新:{{
guide.updated
}}。开始操作前,请确认当前环境与目标账号。
</p>
<el-button @click="router.push('/digital/experiment-types')"
>去实验类型</el-button
><el-button
type="primary"
@click="router.push('/digital/experiments')"
>去测试方案</el-button
><el-button @click="router.push('/digital/experiment-users')"
>去实验用户分组</el-button
>
</footer>
</article>
</div>
</div>
</template>
<style scoped>
.experiment-guide {
display: flex;
flex-direction: column;
max-width: 1440px;
height: var(--guide-height, calc(100dvh - 134px));
min-height: 360px;
margin: 0 auto;
overflow: hidden;
}
.guide-heading {
display: flex;
gap: 24px;
align-items: flex-start;
justify-content: space-between;
margin-bottom: 24px;
}
.guide-heading h1 {
margin: 12px 0;
font-size: 28px;
}
.guide-heading p {
max-width: 800px;
line-height: 1.8;
color: var(--el-text-color-secondary);
}
.guide-layout {
display: grid;
flex: 1;
grid-template-columns: 220px minmax(0, 1fr);
gap: 32px;
min-height: 0;
margin-top: 24px;
}
.guide-toc {
display: flex;
flex-direction: column;
gap: 6px;
min-height: 0;
max-height: 100%;
padding: 16px;
overflow: hidden;
background: var(--el-bg-color);
border: 1px solid var(--el-border-color-lighter);
border-radius: 8px;
}
.guide-links {
display: flex;
flex-direction: column;
gap: 6px;
min-height: 0;
overflow-y: auto;
}
.guide-toc strong {
flex-shrink: 0;
padding: 4px 8px 12px;
}
.guide-toc button {
padding: 8px;
font: inherit;
font-size: 13px;
color: var(--el-text-color-regular);
text-align: left;
cursor: pointer;
background: transparent;
border: 0;
border-radius: 4px;
}
.guide-toc button.active {
font-weight: 600;
color: var(--el-color-primary);
background: var(--el-color-primary-light-9);
box-shadow: inset 3px 0 var(--el-color-primary);
}
.guide-body {
min-width: 0;
min-height: 0;
overflow-y: auto;
overscroll-behavior: contain;
}
.guide-body:focus-visible {
outline: 2px solid var(--el-color-primary);
outline-offset: -2px;
}
.guide-toc button:hover {
color: var(--el-color-primary);
background: var(--el-fill-color-light);
}
.guide-toc button:focus-visible {
outline: 2px solid var(--el-color-primary);
outline-offset: 2px;
}
.guide-section {
padding: 24px;
margin-bottom: 24px;
scroll-margin-top: 0;
background: var(--el-bg-color);
border: 1px solid var(--el-border-color-lighter);
border-radius: 8px;
}
.guide-section h2 {
margin: 0 0 12px;
font-size: 21px;
}
.guide-lead {
line-height: 1.8;
}
.guide-section figure {
margin: 20px 0;
}
.guide-section .el-image {
display: block;
width: 100%;
min-height: 100px;
border: 1px solid var(--el-border-color-lighter);
border-radius: 6px;
}
.guide-section figcaption {
margin-top: 8px;
font-size: 12px;
color: var(--el-text-color-secondary);
text-align: center;
}
.guide-section ul {
padding-left: 22px;
line-height: 1.9;
}
.guide-section li {
margin-bottom: 12px;
overflow-wrap: anywhere;
}
.guide-section pre {
padding: 16px;
overflow-x: auto;
font-size: 12px;
line-height: 1.8;
white-space: pre-wrap;
background: var(--el-fill-color-light);
border-radius: 6px;
}
.image-error {
padding: 24px;
color: var(--el-text-color-secondary);
text-align: center;
}
.guide-footer {
padding: 20px 0 32px;
line-height: 1.8;
}
.guide-footer p {
color: var(--el-text-color-secondary);
}
@media (width <= 900px) {
.guide-layout {
grid-template-rows: auto minmax(0, 1fr);
grid-template-columns: 1fr;
gap: 16px;
}
.guide-toc {
max-height: 140px;
}
.guide-heading {
flex-direction: column;
gap: 8px;
margin-bottom: 12px;
}
.guide-heading h1 {
font-size: 22px;
}
.guide-heading p {
margin: 0;
font-size: 12px;
}
.guide-section {
padding: 16px;
}
}
</style>
+3 -13
View File
@@ -99,8 +99,7 @@ async function save() {
} }
} }
function status(t: ExperimentType) { function status(t: ExperimentType) {
if (t.integrationState === "confirmed") if (t.integrationState === "confirmed") return "已确认接入";
return t.builtin || t.runtime ? "系统已接入" : "已确认接入";
return t.lastSeenAt && t.lastSeenRevision === t.contractRevision return t.lastSeenAt && t.lastSeenRevision === t.contractRevision
? "待业务验收" ? "待业务验收"
: "待应用调用"; : "待应用调用";
@@ -150,7 +149,7 @@ onMounted(load);
<div> <div>
<h2>实验类型</h2> <h2>实验类型</h2>
<p> <p>
先定义要测试的业务与返回值,再配置测试方案;这里不选择隐藏的固定功能列表。 先定义要测试的业务与返回值,再配置测试方案;所有类型由你创建,系统不预置实验类型。
</p> </p>
</div> </div>
<el-button type="primary" @click="open()">创建实验类型</el-button> <el-button type="primary" @click="open()">创建实验类型</el-button>
@@ -191,16 +190,7 @@ onMounted(load);
" "
>{{ status(row) }}</el-tag >{{ status(row) }}</el-tag
> >
<p class="secondary"> </template></el-table-column
{{
row.builtin
? "系统预置"
: row.runtime
? "历史接入保留"
: "后台创建"
}}
</p></template
></el-table-column
><el-table-column label="启用" width="80" ><el-table-column label="启用" width="80"
><template #default="{ row }">{{ ><template #default="{ row }">{{
row.enabled ? "是" : "否" row.enabled ? "是" : "否"
+555 -148
View File
@@ -1,5 +1,5 @@
<script setup lang="ts"> <script setup lang="ts">
/** 用户分组独立管理:分页查真实账号,预览不分配,人工指定与恢复自动均留审计。 */ /** 用户分组管理:区分实际入组与只读预估,按目标人群解释人工指定的生效条件。 */
import { computed, onMounted, ref, watch } from "vue"; import { computed, onMounted, ref, watch } from "vue";
import { useRoute, useRouter } from "vue-router"; import { useRoute, useRouter } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus"; import { ElMessage, ElMessageBox } from "element-plus";
@@ -26,7 +26,10 @@ const plans = ref<Experiment[]>([]),
saving = ref(false), saving = ref(false),
editor = ref(false), editor = ref(false),
detail = ref<ExperimentUser | null>(null), detail = ref<ExperimentUser | null>(null),
explanation = ref(false); explanation = ref(false),
planDetail = ref(false),
candidates = ref<ExperimentUser[]>([]),
finding = ref(false);
const selected = computed(() => const selected = computed(() =>
plans.value.find(p => p.id === selectedId.value) plans.value.find(p => p.id === selectedId.value)
); );
@@ -35,13 +38,12 @@ const availablePlans = computed(() =>
); );
const form = ref({ const form = ref({
account: "", account: "",
variant: "B" as "A" | "B", variant: "",
reason: "", reason: "",
bypassAudience: false, bypassAudience: false,
expiresAt: new Date(Date.now() + 86400000).toISOString() expiresAt: new Date(Date.now() + 86400000).toISOString()
}); });
const reasons: Record<string, string> = { const reasons: Record<string, string> = {
baseline: "默认组",
default: "无运行方案", default: "无运行方案",
finished: "最终方案", finished: "最终方案",
override: "人工指定", override: "人工指定",
@@ -49,8 +51,8 @@ const reasons: Record<string, string> = {
sticky: "已保存的稳定分组", sticky: "已保存的稳定分组",
outside_traffic: "未进入实验流量", outside_traffic: "未进入实验流量",
allocated: "按规则预计分组(未写入)", allocated: "按规则预计分组(未写入)",
paused: "方案暂停,使用默认组", paused: "方案暂停,使用类型默认值",
draft: "草稿,使用默认组" draft: "草稿,使用类型默认值"
}; };
const states: Record<string, string> = { const states: Record<string, string> = {
draft: "草稿", draft: "草稿",
@@ -63,6 +65,7 @@ let requestVersion = 0;
async function load() { async function load() {
const version = ++requestVersion; const version = ++requestVersion;
loading.value = true; loading.value = true;
items.value = [];
try { try {
const params = new URLSearchParams({ const params = new URLSearchParams({
q: q.value, q: q.value,
@@ -97,29 +100,163 @@ function summary(value: unknown) {
function overrideActive(row: ExperimentUser) { function overrideActive(row: ExperimentUser) {
return !!row.override && Date.parse(row.override.expiresAt) > Date.now(); return !!row.override && Date.parse(row.override.expiresAt) > Date.now();
} }
function formatTime(value?: string) {
return value ? new Date(value).toLocaleString() : "—";
}
const audienceName = computed(() => {
const cfg = selected.value?.config;
if (!cfg) return "";
return {
all: "所有用户",
new: "新用户",
existing: "老用户",
specified: "指定名单"
}[cfg.audience];
});
/** 与服务端人群边界一致:新用户包含分界时刻,人工指定不自动改变名单。 */
function inAudience(row: ExperimentUser) {
const cfg = selected.value?.config;
if (!cfg) return false;
if (cfg.audience === "all") return true;
if (cfg.audience === "specified") return cfg.accounts.includes(row.account);
const date = Date.parse(row.createdAt),
cutoff = Date.parse(cfg.cutoff ?? "");
if (!Number.isFinite(date) || !Number.isFinite(cutoff)) return false;
return cfg.audience === "new" ? date >= cutoff : date < cutoff;
}
const outsideSelectedAudience = computed(
() => !!detail.value && !inAudience(detail.value)
);
const audienceExplanation = computed(() => {
if (!selected.value || !detail.value) return "请先选择用户";
const cfg = selected.value.config;
if (inAudience(detail.value))
return `此账号符合“${audienceName.value}”范围。`;
if (cfg.audience === "specified") return "此账号不在方案的指定名单中。";
return `此账号注册于 ${formatTime(detail.value.createdAt)},方案仅面向${audienceName.value}(以 ${formatTime(cfg.cutoff)} 为界)。`;
});
function overrideStatus(row: ExperimentUser) {
if (!overrideActive(row)) return "已过期";
if (selected.value?.state === "finished") return "方案已结束,不再生效";
if (selected.value?.state !== "running") return "待方案运行后生效";
if (!selected.value.config.groups.some(g => g.key === row.override?.variant))
return "原分组已移除";
if (!inAudience(row) && !row.override?.bypassAudience)
return "不符合目标人群,未生效";
return "生效中";
}
function allocationLabel(row: ExperimentUser) {
if (!row.decision) return "未选择方案";
return (
{
override: "手动指定",
sticky: "自动分组",
allocated: "预计自动分组",
finished: "最终统一分组"
}[row.decision.reason] ?? "未参与实验"
);
}
let candidateVersion = 0;
/** 独立查找账号,避免将指定用户限定为当前表格页;过期响应不能覆盖新的搜索。 */
async function findCandidates(query: string) {
const version = ++candidateVersion;
finding.value = true;
try {
const params = new URLSearchParams({ q: query, page: "1", size: "20" });
if (selectedId.value) params.set("experiment", selectedId.value);
const result = await digital<{ items: ExperimentUser[] }>(
`experiment-users?${params}`
);
if (version === candidateVersion)
candidates.value = result.items.filter(row => row.status === "ACTIVE");
} catch (e) {
if (version === candidateVersion)
ElMessage.error(e instanceof Error ? e.message : "查找账号失败");
} finally {
if (version === candidateVersion) finding.value = false;
}
}
function chooseAccount(account: string) {
const row = candidates.value.find(item => item.account === account);
if (row) {
detail.value = row;
form.value.variant =
row.override?.variant ??
row.decision?.variant ??
selected.value?.config.groups[0]?.key ??
"";
form.value.bypassAudience = !!row.override?.bypassAudience;
form.value.expiresAt = overrideActive(row)
? row.override!.expiresAt
: new Date(Date.now() + 86400000).toISOString();
}
}
function startAssign() {
detail.value = null;
form.value = {
account: "",
variant: selected.value?.config.groups[0]?.key ?? "",
reason: "",
bypassAudience: false,
expiresAt: new Date(Date.now() + 86400000).toISOString()
};
candidates.value = [];
editor.value = true;
findCandidates("");
}
function open(row: ExperimentUser) { function open(row: ExperimentUser) {
if (!selected.value) return; if (!selected.value) return;
detail.value = row; detail.value = row;
form.value = { form.value = {
account: row.account, account: row.account,
variant: row.override?.variant ?? "B", variant:
row.override?.variant ??
row.decision?.variant ??
selected.value.config.groups[0]?.key ??
"",
reason: "", reason: "",
bypassAudience: !!row.override?.bypassAudience, bypassAudience: !!row.override?.bypassAudience,
expiresAt: new Date(Date.now() + 86400000).toISOString() expiresAt: overrideActive(row)
? row.override!.expiresAt
: new Date(Date.now() + 86400000).toISOString()
}; };
candidates.value = [row];
editor.value = true; editor.value = true;
} }
async function save() { async function save() {
const id = selectedId.value; const id = selectedId.value;
if (!id) return; if (!id || !selected.value || selected.value.state === "finished") return;
if (!detail.value || !form.value.account)
return ElMessage.warning("请先查找并选择用户");
if (!selected.value.config.groups.some(g => g.key === form.value.variant))
return ElMessage.warning("请选择方案中有效的分组");
const expiry = Date.parse(form.value.expiresAt);
if (
!Number.isFinite(expiry) ||
expiry <= Date.now() ||
expiry > Date.now() + 30 * 86400000
)
return ElMessage.warning("有效期须在未来 30 天内");
if (outsideSelectedAudience.value && !form.value.bypassAudience)
return ElMessage.warning(
"此账号不符合目标人群,请确认是否作为测试账号加入"
);
if (form.value.reason.trim().length < 2) if (form.value.reason.trim().length < 2)
return ElMessage.warning("请填写至少两个字的操作原因"); return ElMessage.warning("请填写至少两个字的操作原因");
const wasRunning = selected.value.state === "running";
saving.value = true; saving.value = true;
try { try {
await digital(`experiments/${id}/override`, "put", form.value); await digital(`experiments/${id}/override`, "put", {
...form.value,
bypassAudience: outsideSelectedAudience.value && form.value.bypassAudience
});
editor.value = false; editor.value = false;
await load(); await load();
ElMessage.success("人工分组已保存,用户刷新前台后读取结果"); ElMessage.success(
wasRunning
? "手动指定已保存,应用下次读取方案时生效"
: "手动指定已保存,方案运行后才会生效"
);
} catch (e) { } catch (e) {
ElMessage.error(e instanceof Error ? e.message : "指定失败"); ElMessage.error(e instanceof Error ? e.message : "指定失败");
} finally { } finally {
@@ -132,9 +269,9 @@ async function restore(row: ExperimentUser) {
try { try {
await ElMessageBox.confirm( await ElMessageBox.confirm(
`取消 ${row.name} 的人工指定?已有稳定分组保留,没有稳定分组时按方案规则判定。`, `取消 ${row.name} 的人工指定?已有稳定分组保留,没有稳定分组时按方案规则判定。`,
"恢复自动分组", "取消手动指定",
{ {
confirmButtonText: "恢复自动", confirmButtonText: "确认取消指定",
cancelButtonText: "取消", cancelButtonText: "取消",
type: "warning" type: "warning"
} }
@@ -153,6 +290,8 @@ async function restore(row: ExperimentUser) {
watch(selectedId, () => { watch(selectedId, () => {
editor.value = false; editor.value = false;
explanation.value = false; explanation.value = false;
planDetail.value = false;
++candidateVersion;
router.replace({ router.replace({
query: { ...route.query, experiment: selectedId.value || undefined } query: { ...route.query, experiment: selectedId.value || undefined }
}); });
@@ -192,94 +331,157 @@ onMounted(async () => {
<div class="users-page"> <div class="users-page">
<div class="heading"> <div class="heading">
<div> <div>
<h2>用户管理</h2> <h2>实验用户分组</h2>
<p> <p>选择测试方案,查看独立 C 端用户的分组,或为测试账号指定分组。</p>
账号来自现有登录体系。这里查看实验分组与管理人工指定,测试方案在独立页面配置。
</p>
</div> </div>
<el-button @click="router.push('/digital/experiments')" <el-button :loading="loading" @click="load">刷新</el-button>
>查看测试方案</el-button
>
</div> </div>
<el-alert <el-card shadow="never">
title="分组预览只读,不会给用户入组或记录曝光。先选择测试方案,再查人、指定 A/B 或恢复自动;草稿和暂停时使用方案默认组。" <div class="plan-filters">
:closable="false" <el-form-item label="实验类型"
type="info" ><el-select v-model="typeFilter" clearable placeholder="全部类型"
/>
<el-card shadow="never" class="content"
><div class="filters">
<el-select v-model="typeFilter" clearable placeholder="筛选实验类型"
><el-option ><el-option
v-for="t in types" v-for="t in types"
:key="t.id" :key="t.id"
:value="t.id" :value="t.id"
:label="t.name" /></el-select :label="t.name" /></el-select
></el-form-item>
<el-form-item label="当前测试方案"
><el-select ><el-select
v-model="selectedId" v-model="selectedId"
clearable clearable
filterable filterable
placeholder="选择测试方案(指定分组前必选)" placeholder="请选择测试方案"
><el-option ><el-option
v-for="p in availablePlans" v-for="p in availablePlans"
:key="p.id" :key="p.id"
:value="p.id" :value="p.id"
:label="`${p.name} · ${states[p.state]}`" /></el-select :label="p.name + ' · ' + states[p.state]" /></el-select
><el-input ></el-form-item>
<el-tag
v-if="selected"
:type="selected.state === 'running' ? 'success' : 'info'"
>{{ states[selected.state] }}</el-tag
>
<el-button
v-if="selected"
link
type="primary"
@click="planDetail = true"
>方案详情</el-button
>
<el-button
link
type="primary"
@click="router.push('/digital/experiments')"
>查看测试方案</el-button
>
</div>
<div v-if="selected" class="plan-summary">
{{ typeName(selected.scope) }} · 目标人群:{{ audienceName }} ·
参与流量:{{ selected.config.traffic / 100 }}% ·
{{
selected.config.groups
.map(g => `${g.key} 组 ${g.weight / 100}%`)
.join(" / ")
}}
</div>
</el-card>
<el-alert
v-if="selected && selected.state !== 'running'"
class="content"
:title="
selected.state === 'finished'
? '方案已结束:所有用户使用最终分组,原手动指定不再生效。'
: `方案${states[selected.state]}:用户当前使用类型默认值。手动指定可提前保存,方案运行后才会生效。`
"
:closable="false"
type="warning"
/>
<el-card shadow="never" class="content">
<div class="table-toolbar">
<div>
<strong>用户列表</strong
><span class="secondary"> 共 {{ total }} 个账号</span>
<p class="secondary">
包含尚未参与实验的账号;“预计分组”仅供查看,实际调用后才会入组。
</p>
</div>
<div class="search-actions">
<el-input
v-model="q" v-model="q"
clearable clearable
placeholder="搜索用户名、姓名或账号 ID" placeholder="用户名、姓名或账号 ID"
@keyup.enter="search" @keyup.enter="search"
@clear="search" @clear="search"
/><el-button type="primary" @click="search">查询</el-button> /><el-button :loading="loading" @click="search">查找用户</el-button
</div> ><el-button
<p v-if="selected" class="context"> type="primary"
{{ typeName(selected.scope) }} / {{ selected.name }} :disabled="!selected || selected.state === 'finished' || loading"
<el-tag>{{ states[selected.state] }}</el-tag @click="startAssign"
><span> >指定用户分组</el-button
流量 {{ selected.config.traffic / 100 }}% · B 组
{{ selected.config.weightB / 100 }}%</span
> >
</p> </div>
<el-table v-loading="loading" :data="items" </div>
><el-table-column label="用户" min-width="210" <el-table v-loading="loading" :data="items" empty-text="没有匹配的账号">
<el-table-column label="用户" min-width="230"
><template #default="{ row }" ><template #default="{ row }"
><strong>{{ row.name }}</strong> ><div class="user-cell">
<el-avatar :size="36">{{
(row.name || row.username).slice(0, 1)
}}</el-avatar>
<div>
<strong>{{ row.name }}</strong>
<p class="secondary">{{ row.username }} · {{ row.account }}</p> <p class="secondary">{{ row.username }} · {{ row.account }}</p>
<small class="secondary">{{ <el-tag v-if="row.status !== 'ACTIVE'" type="info" size="small"
new Date(row.createdAt).toLocaleString() >账号已停用</el-tag
}}</small></template >
</div>
</div></template
></el-table-column ></el-table-column
><el-table-column label="账号状态" width="95" >
><template #default="{ row }" <el-table-column label="当前分组 / 返回值" min-width="210"
><el-tag :type="row.status === 'ACTIVE' ? 'success' : 'info'">{{
row.status === "ACTIVE" ? "正常" : "已停用"
}}</el-tag></template
></el-table-column
><el-table-column label="分组预览 / 返回值" min-width="200"
><template #default="{ row }" ><template #default="{ row }"
><template v-if="row.decision" ><template v-if="row.decision"
><strong>{{ row.decision.variant }} 组</strong> ><div class="group-value">
<el-tag v-if="row.decision.variant"
>{{ row.decision.variant }} 组</el-tag
><strong v-else>未参与实验</strong
><code>{{ summary(row.decision.value) }}</code>
</div>
<p class="secondary"> <p class="secondary">
{{ reasons[row.decision.reason] ?? row.decision.reason }} {{ reasons[row.decision.reason] ?? row.decision.reason }}
</p> </p></template
<code>{{ summary(row.decision.value) }}</code></template ><span v-else class="secondary">选择方案后查看</span></template
><span v-else class="secondary">先选择测试方案</span></template
></el-table-column ></el-table-column
><el-table-column label="人工指定记录" min-width="190" >
<el-table-column label="分配方式" min-width="160"
><template #default="{ row }"
><el-tag
:type="row.decision?.reason === 'override' ? 'success' : 'info'"
>{{ allocationLabel(row) }}</el-tag
>
<p
v-if="row.override && row.decision?.reason !== 'override'"
class="secondary"
>
有手动指定 · {{ overrideStatus(row) }}
</p></template
></el-table-column
>
<el-table-column label="手动指定有效期" min-width="190"
><template #default="{ row }" ><template #default="{ row }"
><template v-if="row.override" ><template v-if="row.override"
><el-tag :type="overrideActive(row) ? 'warning' : 'info'" ><div>
>{{ row.override.variant }} 组 · {{ row.override.variant }} 组 · {{ overrideStatus(row) }}
{{ overrideActive(row) ? "有效期内" : "已过期" }}</el-tag </div>
> <p class="secondary">
<p class="secondary">{{ row.override.reason }}</p> 至 {{ formatTime(row.override.expiresAt) }}
<small class="secondary" </p></template
>到 ><span v-else class="secondary">—</span></template
{{ new Date(row.override.expiresAt).toLocaleString() }}</small
></template
><span v-else class="secondary">无</span></template
></el-table-column ></el-table-column
><el-table-column label="操作" min-width="240" fixed="right" >
<el-table-column label="操作" min-width="240" fixed="right"
><template #default="{ row }" ><template #default="{ row }"
><el-button ><el-button
link link
@@ -289,7 +491,7 @@ onMounted(async () => {
detail = row; detail = row;
explanation = true; explanation = true;
" "
>分组详情</el-button >详情</el-button
><el-button ><el-button
link link
type="primary" type="primary"
@@ -300,22 +502,19 @@ onMounted(async () => {
loading loading
" "
@click="open(row)" @click="open(row)"
>指定分组</el-button >{{ row.override ? "修改指定" : "指定分组" }}</el-button
><el-button ><el-button
v-if="row.override" v-if="row.override"
link link
type="warning" type="warning"
:disabled="loading" :disabled="loading || selected?.state === 'finished'"
@click="restore(row)" @click="restore(row)"
>恢复自动</el-button >取消手动指定</el-button
></template ></template
></el-table-column ></el-table-column
></el-table
> >
<el-empty </el-table>
v-if="!items.length && !loading" <el-pagination
description="没有匹配的账号"
/><el-pagination
v-model:current-page="page" v-model:current-page="page"
:page-size="size" :page-size="size"
:total="total" :total="total"
@@ -326,91 +525,209 @@ onMounted(async () => {
</el-card> </el-card>
<el-dialog <el-dialog
v-model="editor" v-model="editor"
title="指定用户分组" :title="detail?.override ? '修改用户指定分组' : '指定用户分组'"
width="min(560px,95vw)" width="min(640px,95vw)"
class="assignment-dialog"
:close-on-click-modal="false" :close-on-click-modal="false"
destroy-on-close destroy-on-close
><el-form label-position="top" >
><el-form-item label="当前测试方案" <el-form label-position="top">
><span>{{ selected?.name }}</span></el-form-item <el-form-item label="当前测试方案"
><el-form-item label="账号" ><strong>{{ selected?.name }}</strong
><strong ><el-tag class="state-tag">{{
>{{ detail?.name }} · {{ form.account }}</strong selected ? states[selected.state] : ""
></el-form-item }}</el-tag></el-form-item
><el-form-item label="指定分组" >
><el-radio-group v-model="form.variant" <el-form-item label="用户" required
><el-radio value="A">A 组</el-radio ><el-select
><el-radio value="B">B 组</el-radio></el-radio-group v-model="form.account"
></el-form-item filterable
><el-form-item label="有效期(最多 30 天)" remote
:remote-method="findCandidates"
:loading="finding"
placeholder="输入用户名、姓名或账号 ID 查找"
@change="chooseAccount"
><el-option
v-for="row in candidates"
:key="row.account"
:value="row.account"
:label="`${row.name} · ${row.username} · ${row.account}`" /></el-select
></el-form-item>
<el-form-item label="指定分组" required
><el-radio-group v-model="form.variant" class="group-options"
><el-radio
v-for="group in selected?.config.groups ?? []"
:key="group.key"
:value="group.key"
border
><span>{{ group.key }} 组 · 返回 {{ summary(group.value) }}</span
><span class="secondary">
自动分流 {{ group.weight / 100 }}%</span
></el-radio
></el-radio-group
>
<p class="secondary">
手动指定不受分流比例限制,0% 的组也可以选择。
</p></el-form-item
>
<div v-if="detail" class="audience-note">
<strong>目标人群:{{ audienceName }}</strong>
<p>{{ audienceExplanation }}</p>
<template v-if="outsideSelectedAudience"
><el-checkbox v-model="form.bypassAudience"
>将此账号作为测试账号加入,仍使用上面指定的组</el-checkbox
>
<p class="secondary">
只对这个账号放开人群限制,不修改方案人群和其他用户的分组。
</p></template
>
</div>
<el-form-item label="有效期(最多 30 天)" required
><el-date-picker ><el-date-picker
:model-value="new Date(form.expiresAt)" :model-value="new Date(form.expiresAt)"
type="datetime" type="datetime"
:clearable="false"
@update:model-value=" @update:model-value="
v => { v => {
if (v) form.expiresAt = new Date(v).toISOString(); if (v) form.expiresAt = new Date(v).toISOString();
} }
" /></el-form-item "
><el-form-item label="操作原因" required />
<p class="secondary">
到期后按方案规则恢复:符合目标人群时沿用原自动分组,否则重新判断。
</p></el-form-item
>
<el-form-item label="指定原因" required
><el-input ><el-input
v-model="form.reason" v-model="form.reason"
type="textarea" type="textarea"
:rows="3" :rows="2"
maxlength="500" /></el-form-item maxlength="500"
><el-checkbox v-model="form.bypassAudience" show-word-limit
>明确允许此账号越过人群限制</el-checkbox placeholder="例如:测试账号验证新版界面(至少 2 个字)"
><el-alert /></el-form-item>
title="人工指定优先于流量和稳定分组。方案未运行时仍使用默认组;恢复自动后保留原稳定分组,所有操作记录审计。" <el-alert
:title="
selected?.state === 'running'
? '保存后,应用下次读取此方案时使用指定组的返回值。请在已接入该实验类型的前台验证效果。'
: '当前方案未运行,保存只记录指定关系,不会切换前台。方案运行且指定未过期后才会生效。'
"
:closable="false" :closable="false"
class="content" /></el-form type="info"
><template #footer />
</el-form>
<template #footer
><el-button @click="editor = false">取消</el-button ><el-button @click="editor = false">取消</el-button
><el-button type="primary" :loading="saving" @click="save" ><el-button
>保存指定</el-button type="primary"
:loading="saving"
:disabled="
!detail || (outsideSelectedAudience && !form.bypassAudience)
"
@click="save"
>确认指定</el-button
></template ></template
></el-dialog
> >
</el-dialog>
<el-dialog <el-dialog
v-model="explanation" v-model="explanation"
title="用户分组详情(只读)" title="用户分组详情"
width="min(600px,95vw)" width="min(640px,95vw)"
><el-descriptions v-if="detail" :column="1" border >
><el-descriptions-item label="账号" <el-descriptions v-if="detail" :column="1" border>
<el-descriptions-item label="用户"
>{{ detail.name }} · {{ detail.account }}</el-descriptions-item >{{ detail.name }} · {{ detail.account }}</el-descriptions-item
><el-descriptions-item label="注册时间">{{ >
new Date(detail.createdAt).toLocaleString() <el-descriptions-item label="注册时间">{{
}}</el-descriptions-item formatTime(detail.createdAt)
><el-descriptions-item label="当前预览" }}</el-descriptions-item>
>{{ detail.decision?.variant }} 组 · <el-descriptions-item label="当前结果"
{{ reasons[detail.decision?.reason ?? ""] }}</el-descriptions-item >{{
><el-descriptions-item label="返回值"> detail.decision?.variant
<pre>{{ ? detail.decision.variant + " 组"
JSON.stringify(detail.decision?.value, null, 2) : "未参与实验"
}}</pre></el-descriptions-item }}
><el-descriptions-item label="已保存的稳定分组">{{ · {{ reasons[detail.decision?.reason ?? ""] }}
detail.assignment ? detail.assignment.variant + " 组" : "尚未实际入组" <pre>{{ JSON.stringify(detail.decision?.value, null, 2) }}</pre>
}}</el-descriptions-item </el-descriptions-item>
><el-descriptions-item label="人工指定">{{ <el-descriptions-item label="实际入组记录"
detail.override >{{
? detail.override.variant + " 组;" + detail.override.reason detail.assignment
: "无" ? detail.assignment.variant +
}}</el-descriptions-item " 组 · " +
><el-descriptions-item label="越过人群限制">{{ formatTime(detail.assignment.createdAt)
detail.override?.bypassAudience ? "是" : "否" : "尚无自动入组记录"
}}</el-descriptions-item></el-descriptions }}
<p class="secondary">
手动指定单独记录,不覆盖原自动分组。
</p></el-descriptions-item
>
<el-descriptions-item label="手动指定"
><template v-if="detail.override"
>{{ detail.override.variant }} 组 · {{ overrideStatus(detail) }}
<p>有效期至 {{ formatTime(detail.override.expiresAt) }}</p>
<p>原因:{{ detail.override.reason }}</p>
<p>
{{
detail.override.bypassAudience
? "已允许此测试账号不受目标人群限制"
: "仅在此账号符合目标人群时生效"
}}
</p></template
><span v-else>无</span></el-descriptions-item
>
<el-descriptions-item label="目标人群">{{
audienceExplanation
}}</el-descriptions-item> </el-descriptions
><el-alert ><el-alert
title="预览按当前规则和账号注册时间计算。首次实际调用才保存分组,实际展示后才计曝光。" title="页面查询不会让用户入组或记录曝光;前台需实际接入并读取实验结果,才能验证功能变化。"
type="info" type="info"
:closable="false" :closable="false"
class="content" class="content"
/></el-dialog> />
</el-dialog>
<el-dialog v-model="planDetail" title="当前方案详情" width="min(640px,95vw)"
><el-descriptions v-if="selected" :column="1" border
><el-descriptions-item label="测试方案"
>{{ selected.name }} ·
{{ states[selected.state] }}</el-descriptions-item
><el-descriptions-item label="实验类型">{{
typeName(selected.scope)
}}</el-descriptions-item
><el-descriptions-item label="目标人群"
>{{ audienceName
}}<span v-if="selected.config.cutoff"
>(注册时间分界:{{ formatTime(selected.config.cutoff) }})</span
><span v-if="selected.config.audience === 'specified'">
· {{ selected.config.accounts.length }} 个账号</span
></el-descriptions-item
><el-descriptions-item label="参与流量"
>{{ selected.config.traffic / 100 }}%</el-descriptions-item
><el-descriptions-item
v-for="group in selected.config.groups"
:key="group.key"
:label="group.key + ' 组'"
>{{ group.weight / 100 }}% · 返回
{{ summary(group.value) }}</el-descriptions-item
></el-descriptions
></el-dialog
>
</div> </div>
</template> </template>
<style scoped> <style scoped>
.heading { .heading,
.table-toolbar,
.plan-filters,
.search-actions,
.user-cell,
.group-value {
display: flex; display: flex;
gap: 16px; gap: 12px;
align-items: center; align-items: center;
}
.heading,
.table-toolbar {
justify-content: space-between; justify-content: space-between;
margin-bottom: 20px; margin-bottom: 20px;
} }
@@ -431,16 +748,39 @@ onMounted(async () => {
margin-top: 18px; margin-top: 18px;
} }
.filters { .plan-filters {
display: grid; flex-wrap: wrap;
grid-template-columns: 1fr 1.5fr 1.5fr auto;
gap: 12px;
margin-bottom: 20px;
} }
.context { .plan-filters :deep(.el-form-item) {
margin-bottom: 18px; display: block;
margin-bottom: 0;
}
.plan-filters :deep(.el-select) {
width: 300px;
}
.plan-filters :deep(.el-form-item:first-child .el-select) {
width: 200px;
}
.plan-summary {
margin-top: 18px;
font-size: 13px; font-size: 13px;
color: var(--el-text-color-secondary);
}
.search-actions {
flex-wrap: wrap;
}
.search-actions :deep(.el-input) {
width: 260px;
}
.search-actions :deep(.el-button + .el-button) {
margin-left: 0;
} }
.pagination { .pagination {
@@ -448,9 +788,56 @@ onMounted(async () => {
margin-top: 20px; margin-top: 20px;
} }
.group-options {
display: flex;
gap: 10px;
width: 100%;
}
.group-options :deep(.el-radio) {
width: 100%;
height: auto;
min-height: 42px;
padding: 12px;
margin: 0;
}
.group-options :deep(.el-radio__label) {
overflow-wrap: anywhere;
white-space: normal;
}
.audience-note {
padding: 14px;
margin-bottom: 18px;
background: var(--el-fill-color-light);
border-radius: 6px;
}
.audience-note p {
margin: 8px 0;
}
.audience-note :deep(.el-checkbox) {
height: auto;
white-space: normal;
}
.audience-note :deep(.el-checkbox__label) {
white-space: normal;
}
.assignment-dialog :deep(.el-form-item__content > p) {
flex-basis: 100%;
}
.state-tag {
margin-left: 12px;
}
code, code,
pre { pre {
word-break: break-word; overflow-wrap: anywhere;
white-space: pre-wrap; white-space: pre-wrap;
} }
@@ -458,16 +845,36 @@ code {
font-size: 12px; font-size: 12px;
} }
@media (width<=760px) { .users-page :deep(.assignment-dialog .el-dialog__body) {
.filters { max-height: 65vh;
grid-template-columns: 1fr; overflow-y: auto;
} }
@media (width <= 1000px) {
.table-toolbar {
flex-direction: column;
align-items: flex-start;
}
}
@media (width <= 760px) {
.heading { .heading {
flex-direction: column; flex-direction: column;
align-items: flex-start; align-items: flex-start;
} }
.plan-filters {
flex-direction: column;
align-items: flex-start;
}
.plan-filters :deep(.el-form-item),
.plan-filters :deep(.el-select),
.search-actions,
.search-actions :deep(.el-input) {
width: 100%;
}
.pagination { .pagination {
justify-content: flex-start; justify-content: flex-start;
} }
+333 -171
View File
@@ -8,6 +8,7 @@ import {
digital, digital,
type Content, type Content,
type Experiment, type Experiment,
type ExperimentGroup,
type ExperimentType type ExperimentType
} from "@/api/access"; } from "@/api/access";
type Account = { account: string; name: string; createdAt: string }; type Account = { account: string; name: string; createdAt: string };
@@ -47,12 +48,10 @@ type Details = {
createdAt: string; createdAt: string;
}>; }>;
}; };
const guideVisible = ref(false);
const router = useRouter(); const router = useRouter();
const scenes = ref<ExperimentType[]>([]); const scenes = ref<ExperimentType[]>([]);
const validA = ref(true), const groupValid = ref<Record<string, boolean>>({});
validB = ref(true), const filterType = ref("");
filterType = ref("");
const filtered = computed(() => const filtered = computed(() =>
list.value.filter(e => !filterType.value || e.scope === filterType.value) list.value.filter(e => !filterType.value || e.scope === filterType.value)
); );
@@ -98,12 +97,70 @@ const trafficPercent = computed({
if (edit.value) edit.value.config.traffic = Math.round((value ?? 0) * 100); if (edit.value) edit.value.config.traffic = Math.round((value ?? 0) * 100);
} }
}); });
const weightBPercent = computed({ const groupTotal = computed(
get: () => (edit.value?.config.weightB ?? 0) / 100, () => edit.value?.config.groups.reduce((sum, g) => sum + g.weight, 0) ?? 0
set: (value: number | undefined) => { );
if (edit.value) edit.value.config.weightB = Math.round((value ?? 0) * 100); const groupKeys = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".split("");
/** 展示服务端按配置顺序累计的半开区间;仅解释首次自动分组,不覆盖稳定分组或人工指定。 */
function groupRanges(groups: ExperimentGroup[]) {
if (groups.reduce((sum, group) => sum + group.weight, 0) !== 10000)
return "分组比例合计达到 100% 后显示区间";
let start = 0;
return groups
.map(group => {
const text =
group.weight === 0
? `${group.key}:0%,不参与自动分流`
: `${group.key}:${start}~${start + group.weight - 1}`;
start += group.weight;
return text;
})
.join(";");
}
/** 数字提交后更新万分比并联动两组,避免输入中间值导致控件回显与区间不同步。 */
function setWeight(group: ExperimentGroup, percentage: number | undefined) {
if (!edit.value) return;
group.weight = Math.round((percentage ?? 0) * 100);
if (edit.value.config.groups.length === 2) {
const other = edit.value.config.groups.find(g => g.key !== group.key)!;
other.weight = 10000 - group.weight;
} }
}); }
function addGroup() {
if (!edit.value || !editingType.value) return;
const key = groupKeys.find(
k => !edit.value!.config.groups.some(g => g.key === k)
);
if (key)
edit.value.config.groups.push({
key,
weight: 0,
value: JSON.parse(JSON.stringify(editingType.value.defaultValue))
});
}
function removeGroup(key: string) {
if (!edit.value || edit.value.config.groups.length <= 1) return;
edit.value.config.groups = edit.value.config.groups.filter(
g => g.key !== key
);
delete groupValid.value[key];
}
function distributeEvenly() {
if (!edit.value) return;
const groups = edit.value.config.groups;
const each = Math.floor(10000 / groups.length),
extra = 10000 % groups.length;
groups.forEach((g, i) => {
g.weight = each + (i < extra ? 1 : 0);
});
}
function fillRemaining(group: ExperimentGroup) {
group.weight = Math.max(0, 10000 - (groupTotal.value - group.weight));
}
function groupSummary(item: Experiment) {
return item.config.groups.map(g => `${g.key} ${g.weight / 100}%`).join(" · ");
}
const editingType = computed(() => const editingType = computed(() =>
scenes.value.find(s => s.id === edit.value?.scope) scenes.value.find(s => s.id === edit.value?.scope)
); );
@@ -112,23 +169,21 @@ const presetOptions = computed(() =>
? presets.value.map(p => ({ label: p.name, value: p.id })) ? presets.value.map(p => ({ label: p.name, value: p.id }))
: undefined : undefined
); );
/** 类型切换时重新初始化值,编辑历史方案时兼容旧预设字段。 */ /** 类型切换只重置返回值,不改变用户已经配置的组别和比例。 */
function initializeValues(reset = false) { function initializeValues(reset = false) {
if (!edit.value || !editingType.value) return; if (!edit.value || !editingType.value) return;
const t = editingType.value, const type = editingType.value;
c = edit.value.config; for (const group of edit.value.config.groups) {
c.values = JSON.parse( if (reset || group.value === undefined)
group.value = JSON.parse(
JSON.stringify( JSON.stringify(
t.contract.fixedValues ?? type.valueType === "boolean" && group.key === "B"
(!reset && c.values ? !type.defaultValue
? c.values : type.defaultValue
: t.contract.optionsSource === "presets"
? { A: c.presetA ?? "", B: c.presetB ?? "" }
: { A: t.defaultValue, B: t.defaultValue })
) )
); );
validA.value = true; }
validB.value = true; groupValid.value = {};
} }
function users(item: Experiment) { function users(item: Experiment) {
router.push({ router.push({
@@ -167,42 +222,23 @@ function open(item?: Experiment) {
: { : {
id: crypto.randomUUID(), id: crypto.randomUUID(),
name: "", name: "",
scope: scope: "",
(
scenes.value.find(s => s.enabled && s.runtime === "ui") ??
scenes.value.find(s => s.enabled)
)?.id ?? "",
state: "draft", state: "draft",
config: { config: {
audience: "all", audience: "all",
accounts: [], accounts: [],
traffic: 10000, traffic: 10000,
weightB: 5000, groups: [
baseline: "A", { key: "A", weight: 5000, value: undefined },
{ key: "B", weight: 5000, value: undefined }
],
description: "" description: ""
} }
}; };
edit.value.config.groups.sort((a, b) => a.key.localeCompare(b.key));
initializeValues(); initializeValues();
editor.value = true; editor.value = true;
} }
function createTrial() {
open();
if (!edit.value) return;
edit.value.name = "新老 UI 验收";
edit.value.scope =
(
scenes.value.find(s => s.id === "ui" && s.enabled) ??
scenes.value.find(s => s.runtime === "ui" && s.enabled)
)?.id ?? "";
edit.value.config.audience = "specified";
edit.value.config.accounts = [];
edit.value.config.traffic = 10000;
edit.value.config.weightB = 10000;
edit.value.config.description =
"只选择自己的账号,启动后先验证新版;在指定用户中切换A/B对照。结束时保留A可维持原界面,再另建正式实验。";
initializeValues(true);
guideVisible.value = false;
}
async function save() { async function save() {
if (!edit.value?.scope) return ElMessage.warning("请先创建或选择实验类型"); if (!edit.value?.scope) return ElMessage.warning("请先创建或选择实验类型");
if (!edit.value?.name.trim()) return ElMessage.warning("请输入方案名称"); if (!edit.value?.name.trim()) return ElMessage.warning("请输入方案名称");
@@ -216,8 +252,10 @@ async function save() {
!edit.value.config.accounts.length !edit.value.config.accounts.length
) )
return ElMessage.warning("请选择至少一个入组账号,验收时先选择自己"); return ElMessage.warning("请选择至少一个入组账号,验收时先选择自己");
if (!validA.value || !validB.value) if (groupTotal.value !== 10000)
return ElMessage.warning("请修正 A/B 返回值的 JSON 格式"); return ElMessage.warning("所有分组比例合计必须为 100%");
if (Object.values(groupValid.value).some(valid => !valid))
return ElMessage.warning("请修正分组返回值的 JSON 格式");
saving.value = true; saving.value = true;
try { try {
await digital(`experiments/${edit.value.id}`, "put", edit.value); await digital(`experiments/${edit.value.id}`, "put", edit.value);
@@ -233,15 +271,15 @@ async function save() {
async function move( async function move(
item: Experiment, item: Experiment,
state: "running" | "paused" | "finished", state: "running" | "paused" | "finished",
winner?: "A" | "B" winner?: string
) { ) {
try { try {
await ElMessageBox.confirm( await ElMessageBox.confirm(
state === "running" state === "running"
? `启动「${item.name}」?启动后人群、比例和方案将冻结。` ? `启动「${item.name}」?启动后人群、比例和方案将冻结。`
: state === "paused" : state === "paused"
? "暂停后用户回到默认方案,已有分组保留。" ? "暂停后用户使用类型默认返回值,已有分组保留。"
: `结束后所有用户采用 ${winner} 方案,实验不能重新启动。`, : `结束后所有用户采用 ${winner} 组返回值,实验不能重新启动。`,
state === "finished" ? "结束实验" : "确认状态变更", state === "finished" ? "结束实验" : "确认状态变更",
{ type: "warning", confirmButtonText: "确认", cancelButtonText: "取消" } { type: "warning", confirmButtonText: "确认", cancelButtonText: "取消" }
); );
@@ -290,20 +328,21 @@ onMounted(load);
<div> <div>
<h2>测试方案</h2> <h2>测试方案</h2>
<p> <p>
配置测什么、给谁看、分配多少流量;账号查询与人工分组在「用户管理」。 配置测什么、给谁看、分配多少流量;账号查询与人工分组在「实验用户分组」。
</p> </p>
</div> </div>
<div> <div>
<el-button @click="guideVisible = true">操作指南</el-button <el-button @click="router.push('/digital/experiments/guide')"
>操作指南</el-button
><el-button @click="router.push('/digital/experiment-types')" ><el-button @click="router.push('/digital/experiment-types')"
>实验类型</el-button >实验类型</el-button
><el-button @click="router.push('/digital/experiment-users')" ><el-button @click="router.push('/digital/experiment-users')"
>用户管理</el-button >实验用户分组</el-button
><el-button type="primary" @click="open()">创建测试方案</el-button> ><el-button type="primary" @click="open()">创建测试方案</el-button>
</div> </div>
</div> </div>
<el-alert <el-alert
title="第一次使用:先点「操作指南」,按“仅自己验收 → 正式实验 → 保留最终方案”走一遍。保存草稿不会改变前台,启动后才生效。" title="第一次使用:点击「操作指南」查看完整图文教程,按“仅自己验收 → 正式实验 → 保留最终结果”走一遍。保存草稿不会改变前台,启动后才生效。"
type="info" type="info"
:closable="false" :closable="false"
style="margin-bottom: 16px" style="margin-bottom: 16px"
@@ -321,7 +360,7 @@ onMounted(load);
> >
</div> </div>
<el-alert <el-alert
title="同一类型消费标识只允许一个未结束方案。新老用户以账号创建时间与显式分界判定;暂停回默认方案,结束后固化最终方案。" title="同一类型消费标识只允许一个未结束方案。新老用户以账号创建时间与显式分界判定;暂停使用类型默认返回值,结束后保留所选组的返回值。"
type="info" type="info"
:closable="false" :closable="false"
style="margin-bottom: 20px" style="margin-bottom: 20px"
@@ -377,8 +416,9 @@ onMounted(load);
><template #default="{ row }" ><template #default="{ row }"
><div>{{ audienceNames[row.config.audience] }}</div> ><div>{{ audienceNames[row.config.audience] }}</div>
<small class="secondary" <small class="secondary"
>流量 {{ row.config.traffic / 100 }}% · B组 >实验流量 {{ row.config.traffic / 100 }}%<br />{{
{{ row.config.weightB / 100 }}%</small groupSummary(row)
}}</small
></template ></template
></el-table-column ></el-table-column
><el-table-column label="操作" min-width="260" fixed="right" ><el-table-column label="操作" min-width="260" fixed="right"
@@ -411,16 +451,18 @@ onMounted(load);
><el-button link type="danger">结束实验</el-button ><el-button link type="danger">结束实验</el-button
><template #dropdown ><template #dropdown
><el-dropdown-menu ><el-dropdown-menu
><el-dropdown-item command="A">保留 A 方案</el-dropdown-item ><el-dropdown-item
><el-dropdown-item command="B" v-for="group in row.config.groups"
>保留 B 方案</el-dropdown-item :key="group.key"
:command="group.key"
>保留 {{ group.key }} 组</el-dropdown-item
></el-dropdown-menu ></el-dropdown-menu
></template ></template
></el-dropdown ></el-dropdown
><el-button link type="primary" @click="inspect(row)" ><el-button link type="primary" @click="inspect(row)"
>效果与审计</el-button >效果与审计</el-button
><el-button link type="primary" @click="users(row)" ><el-button link type="primary" @click="users(row)"
>用户管理</el-button >实验用户分组</el-button
></template ></template
></el-table-column ></el-table-column
></el-table ></el-table
@@ -431,14 +473,16 @@ onMounted(load);
<el-dialog <el-dialog
v-model="editor" v-model="editor"
title="测试方案草稿" title="测试方案草稿"
width="min(720px,95vw)" class="experiment-dialog"
top="5vh"
width="min(880px,95vw)"
:close-on-click-modal="false" :close-on-click-modal="false"
destroy-on-close destroy-on-close
><el-form v-if="edit" label-position="top" ><el-form v-if="edit" label-position="top">
><el-form-item label="名称" required <div class="form-grid">
<el-form-item label="名称" required
><el-input v-model="edit.name" maxlength="120" ><el-input v-model="edit.name" maxlength="120"
/></el-form-item> /></el-form-item>
<div class="form-grid">
<el-form-item label="实验类型" <el-form-item label="实验类型"
><el-select ><el-select
v-model="edit.scope" v-model="edit.scope"
@@ -449,19 +493,14 @@ onMounted(load);
:key="s.id" :key="s.id"
:value="s.id" :value="s.id"
:label="s.name" :label="s.name"
:disabled="!s.enabled" /></el-select></el-form-item :disabled="!s.enabled" /></el-select
><el-form-item label="默认方案"
><el-select v-model="edit.config.baseline"
><el-option label="A 方案" value="A" /><el-option
label="B 方案"
value="B" /></el-select
></el-form-item> ></el-form-item>
</div> </div>
<el-form-item label="实验目标与验收指标" <el-form-item label="实验目标与验收指标"
><el-input ><el-input
v-model="edit.config.description" v-model="edit.config.description"
type="textarea" type="textarea"
:rows="3" :rows="2"
placeholder="例如:观察首次聊天转化和用户反馈,确认新版交互是否改善体验。" /></el-form-item placeholder="例如:观察首次聊天转化和用户反馈,确认新版交互是否改善体验。" /></el-form-item
><el-divider content-position="left">实验人群</el-divider ><el-divider content-position="left">实验人群</el-divider
><el-form-item label="入组范围" ><el-form-item label="入组范围"
@@ -505,60 +544,166 @@ onMounted(load);
:label="`${a.name} (${a.account})`" :label="`${a.name} (${a.account})`"
:value="a.account" /></el-select :value="a.account" /></el-select
></el-form-item> ></el-form-item>
<div class="form-grid"> <el-form-item label="进入实验的流量(%)">
<el-form-item label="进入实验的流量(%)" <el-input-number
><el-input-number
v-model="trafficPercent" v-model="trafficPercent"
:min="0" :min="0"
:max="100" :max="100"
:precision="2" :precision="2"
:step="1" :step="1"
/><small>{{ edit.config.traffic / 100 }}%</small></el-form-item />
><el-form-item label="入组后 B 组比例(%)" <p class="secondary">
><el-input-number 目标人群中有多少人参与实验;未参与的用户使用类型默认返回值。
v-model="weightBPercent" </p>
</el-form-item>
<section class="group-config" aria-label="分组配置">
<div class="group-heading">
<strong>分组配置</strong>
<el-tag
:type="groupTotal === 10000 ? 'success' : 'danger'"
role="status"
>合计 {{ (groupTotal / 100).toFixed(2) }}% / 100%</el-tag
>
</div>
<p class="secondary">
默认 A、B 两组,可添加到 Z。0%
组不会自动分流,仍可人工指定;返回值不因比例改变。
</p>
<div class="allocation-rule">
<strong>分组方式:按账号稳定随机分配</strong>
<p>
账号标识与本次测试方案 ID 共同算出固定的 0~9999
数字,落在哪个区间就进入哪组。
</p>
<p class="allocation-ranges">
当前自动分组区间:{{ groupRanges(edit.config.groups) }}
</p>
<p>
首次实际入组后保存分组,刷新、重新登录仍保持同组;有效的人工指定优先。比例是分配概率,不保证小样本人数恰好相等。
</p>
<el-collapse>
<el-collapse-item
title="查看具体计算步骤与优先顺序"
name="algorithm"
>
<ol class="allocation-steps">
<li>
先检查入组范围。“所有用户”表示所有账号都有资格参与,不按性别、年龄或账号尾号分组。
</li>
<li>
符合人群或获准越过人群限制的有效人工指定,直接使用指定组;否则已保存的稳定分组优先。
</li>
<li>
首次自动分配先计算流量桶,数字小于“进入实验的流量 ×
100”才入组;未入组使用类型默认返回值。
</li>
<li>
入组后另算分组桶,按上方各组比例的累计区间分配。流量桶和分组桶独立,0%组不接收自动流量。
</li>
</ol>
<p>
技术算法:SHA-256
处理下方字符串,取摘要前4字节的无符号大端整数,再对10000取余。
</p>
<code>dh-v1\0{用途}\0{测试方案ID}\0{账号标识}</code>
<p>
用途分别为 traffic(流量)和 variant(分组);\0
为分隔符。账号标识包含账号类型与ID。新建方案的ID不同,同一账号可能分到不同组。
</p>
</el-collapse-item>
</el-collapse>
</div>
<el-table :data="edit.config.groups" row-key="key">
<el-table-column label="组别" width="70"
><template #default="{ row }"
><el-tag type="info">{{ row.key }}</el-tag></template
></el-table-column
>
<el-table-column label="分流比例(%)" width="200"
><template #default="{ row }">
<el-input-number
:model-value="row.weight / 100"
:aria-label="`${row.key}组分流比例`"
:min="0" :min="0"
:max="100" :max="100"
:precision="2" :precision="2"
:step="1" :step="1"
/><small @change="v => setWeight(row, v)"
>A {{ (10000 - edit.config.weightB) / 100 }}% / B />
{{ edit.config.weightB / 100 }}%</small <el-button
></el-form-item v-if="groupTotal < 10000"
link
type="primary"
@click="fillRemaining(row)"
>补足剩余</el-button
> >
</div> </template></el-table-column
<template v-if="editingType && edit.config.values">
<el-divider content-position="left">A/B 返回值</el-divider>
<div class="form-grid">
<el-form-item
v-for="group in ['A', 'B'] as const"
:key="group"
:label="`${group} 组${editingType.contract.labels?.[group] ? ' · ' + editingType.contract.labels[group] : ''}`"
required
> >
<el-table-column label="返回值" min-width="220"
><template #default="{ row }">
<ExperimentValue <ExperimentValue
:key="editingType.id + group" v-if="editingType"
v-model="edit.config.values[group]" :key="editingType.id + row.key"
v-model="row.value"
:kind="editingType.valueType" :kind="editingType.valueType"
:options="presetOptions" :options="presetOptions"
:disabled="!!editingType.contract.fixedValues" @valid="v => (groupValid[row.key] = v)"
@valid="v => (group === 'A' ? (validA = v) : (validB = v))"
/> />
</el-form-item> <span v-else class="secondary">请先选择实验类型</span>
</template></el-table-column
>
<el-table-column label="操作" width="85"
><template #default="{ row }"
><el-button
link
type="danger"
:disabled="edit.config.groups.length <= 1"
:aria-label="`删除${row.key}组`"
@click="removeGroup(row.key)"
>删除</el-button
></template
></el-table-column
>
</el-table>
<div class="group-actions">
<el-button
:disabled="!editingType || edit.config.groups.length >= 26"
@click="addGroup"
>添加分组</el-button
><el-button @click="distributeEvenly">平均分配</el-button
><span class="secondary"
>{{ edit.config.groups.length }} / 26 组</span
>
</div> </div>
<el-alert <el-alert
v-if="editingType.integrationState !== 'confirmed'" v-if="groupTotal !== 10000"
type="warning" type="error"
title="该类型还未完成应用接入验收,可以保存草稿;请到「实验类型 → 接入与验收」完成后再启动。"
:closable="false" :closable="false"
title="请调整各组比例,合计达到 100% 后才能保存。"
/> />
</template> </section>
<el-alert
v-if="editingType && editingType.integrationState !== 'confirmed'"
type="warning"
title="该类型尚未完成应用接入验收,可以保存草稿;完成接入与验收后才能启动。"
:closable="false" />
<p v-if="editingType" class="secondary">
未参与实验或实验暂停时,返回类型默认值:{{
JSON.stringify(editingType.defaultValue)
}},不属于任何实验组。
</p>
<el-alert <el-alert
title="启动前请核对人群和比例。启动后规则冻结,需要新规则时创建下一条实验。" title="启动前请核对人群和比例。启动后规则冻结,需要新规则时创建下一条实验。"
:closable="false" /></el-form :closable="false" /></el-form
><template #footer ><template #footer
><el-button @click="editor = false">取消</el-button ><el-button @click="editor = false">取消</el-button
><el-button type="primary" :loading="saving" @click="save" ><el-button
type="primary"
:loading="saving"
:disabled="
groupTotal !== 10000 || Object.values(groupValid).some(v => !v)
"
@click="save"
>保存草稿</el-button >保存草稿</el-button
></template ></template
></el-dialog ></el-dialog
@@ -574,13 +719,36 @@ onMounted(load);
><span>{{ sceneName(selected.scope) }}</span ><span>{{ sceneName(selected.scope) }}</span
><small>版本 {{ selected.revision }}</small> ><small>版本 {{ selected.revision }}</small>
</div> </div>
<div class="allocation-rule">
<strong>分组方式:按账号稳定随机分配</strong>
<p>
账号标识与本次方案 ID 计算固定的 0~9999
数字,按累计比例区间首次分组;已保存的稳定分组保留,有效人工指定优先。
</p>
<p class="allocation-ranges">
当前自动分组区间:{{ groupRanges(selected.config.groups) }}
</p>
</div>
<el-table :data="selected.config.groups" class="group-details">
<el-table-column prop="key" label="组别" width="80" />
<el-table-column label="分流比例" width="120"
><template #default="{ row }"
>{{ row.weight / 100 }}%</template
></el-table-column
>
<el-table-column label="返回值"
><template #default="{ row }"
><code>{{ JSON.stringify(row.value) }}</code></template
></el-table-column
>
</el-table>
<el-tabs v-model="detailTab" <el-tabs v-model="detailTab"
><el-tab-pane label="效果概览" name="metrics" ><el-tab-pane label="效果概览" name="metrics"
><el-alert ><el-alert
title="只统计实际入组流量,人工指定单列。曝光在可见页面渲染后记录,漏斗按服务端决策归因;仅作描述性统计。" title="只统计实际入组流量,人工指定单列。曝光在可见页面渲染后记录,漏斗按服务端决策归因;仅作描述性统计。"
type="info" type="info"
:closable="false" /><el-table :data="details?.metrics ?? []" :closable="false" /><el-table :data="details?.metrics ?? []"
><el-table-column prop="variant" label="方案" /><el-table-column ><el-table-column prop="variant" label="组别" /><el-table-column
label="人群" label="人群"
><template #default="{ row }">{{ ><template #default="{ row }">{{
row.cohort === "manual" ? "人工指定" : "规则分组" row.cohort === "manual" ? "人工指定" : "规则分组"
@@ -599,7 +767,7 @@ onMounted(load);
description="尚无决策记录" /> description="尚无决策记录" />
<h3 style="margin: 24px 0 12px">使用漏斗</h3> <h3 style="margin: 24px 0 12px">使用漏斗</h3>
<el-table :data="details?.funnel ?? []" <el-table :data="details?.funnel ?? []"
><el-table-column prop="variant" label="方案" /><el-table-column ><el-table-column prop="variant" label="组别" /><el-table-column
label="人群" label="人群"
><template #default="{ row }">{{ ><template #default="{ row }">{{
row.cohort === "manual" ? "人工指定" : "规则分组" row.cohort === "manual" ? "人工指定" : "规则分组"
@@ -631,76 +799,70 @@ onMounted(load);
></template ></template
></el-drawer ></el-drawer
> >
<el-dialog
v-model="guideVisible"
title="实验全流程操作指南"
width="min(760px,95vw)"
><ol class="workflow-guide">
<li>
<strong>实验类型:定义测什么</strong>
<p>
侧栏「实验类型 →
创建实验类型」,填写你自己的稳定标识、数据格式和默认值。系统
UI、对话预设是已有代码接入的类型,来源有标注。新类型先在应用读取决策并使用返回值,再到「接入与验收」确认效果。
</p>
</li>
<li>
<strong>测试方案:定义怎么测</strong>
<p>
选择类型,配置 A/B 返回值、人群与百分比。100% 流量、B 组 50%
表示所有入组用户 A/B
各一半。保存只是草稿,启动才生效;启动后规则冻结。
</p>
</li>
<li>
<strong>用户管理:查看与指定谁</strong>
<p>
从方案行点击「用户管理」,搜索账号,查看只读分组预览。点击「指定分组」可指定
A/B、有效期与原因;「恢复自动」取消人工指定,回到原稳定分组。预览本身不会分配用户或产生曝光。
</p>
</li>
<li>
<strong>先自己验收,再正式分流</strong>
<p>
新老 UI 可使用下方示例:指定名单只选自己,流量 100%、B 组
100%,启动后刷新前台看新版。再到用户管理指定 A/B
对照。其他账号按默认组。验收完成另建正式方案。
</p>
</li>
<li>
<strong>效果、暂停与结束</strong>
<p>
在「效果与审计」查看决策、曝光、漏斗和操作记录。暂停回方案默认组,恢复保留原分组;结束时选择最终
A/B,之后对所有用户长期生效。新类型须在消费者实际展示后调用曝光接口,不能把决策请求当作曝光。
</p>
</li>
</ol>
<el-alert
title="所有管理入口都在后台。前台只读取当前用户的决策,不提供实验控制。"
:closable="false"
/><template #footer
><el-button @click="guideVisible = false">知道了</el-button
><el-button type="primary" @click="createTrial"
>按“仅自己验收”示例创建</el-button
></template
></el-dialog
>
</div> </div>
</template> </template>
<style scoped> <style scoped>
.workflow-guide { .allocation-rule {
padding-left: 22px; padding: 12px 14px;
line-height: 1.8; margin: 12px 0;
}
.workflow-guide li {
margin-bottom: 16px;
}
.workflow-guide p {
margin: 6px 0;
font-size: 13px; font-size: 13px;
color: var(--el-text-color-secondary); line-height: 1.7;
background: var(--el-fill-color-light);
border: 1px solid var(--el-border-color-lighter);
border-radius: 6px;
}
.allocation-rule p {
margin: 6px 0;
}
.allocation-ranges {
font-variant-numeric: tabular-nums;
}
.allocation-rule code {
overflow-wrap: anywhere;
}
.allocation-steps {
padding-left: 20px;
margin: 8px 0;
}
:global(.experiment-dialog) {
display: flex;
flex-direction: column;
max-height: 90vh;
margin-bottom: 0;
}
:global(.experiment-dialog .el-dialog__body) {
min-height: 0;
overflow-y: auto;
}
.group-details {
margin-bottom: 20px;
}
.group-config {
margin: 8px 0 20px;
}
.group-heading,
.group-actions {
display: flex;
gap: 12px;
align-items: center;
}
.group-heading {
justify-content: space-between;
margin-bottom: 12px;
}
.group-actions {
margin: 16px 0;
} }
.heading { .heading {
+390
View File
@@ -0,0 +1,390 @@
<script setup lang="ts">
/** 增长可视化:真实聚合数据驱动图表;空样本、队列口径和成本估算边界保持可见。 */
import {
computed,
nextTick,
onBeforeUnmount,
onMounted,
ref,
watch
} from "vue";
import echarts from "@/plugins/echarts";
import type { EChartsCoreOption, EChartsType } from "echarts/core";
type Row = Record<string, string | number | boolean | null>;
const props = defineProps<{
overview: {
funnel: { stage: string; users: number }[];
quality: Row[];
retention: Row[];
budget: Row[];
experiments: Row[];
feedback: Row[];
};
}>();
const root = ref<HTMLElement>();
const titles = [
"用户转化路径",
"成熟队列 · 次日留存",
"推荐实验 · 转化对比",
"字符消耗 · 最近14个记账日"
];
const subtitles = [
"严格顺序去重用户 · 悬停查看人数",
"按首次访问日期 · 未成熟队列不纳入",
"按版本与排序组展示 · 不代表统计显著",
"已结算与预占 · 字符估算,非供应商账单"
];
const names = [
"访问",
"角色详情",
"开始故事",
"发送请求",
"完整回复",
"有效对话"
];
const total = (key: string) =>
props.overview.quality.reduce((sum, row) => sum + Number(row[key] ?? 0), 0);
const percent = (a: number, b: number) =>
b > 0 ? `${((a / b) * 100).toFixed(1)}%` : "暂无样本";
const metrics = computed(() => {
const f = props.overview.funnel;
const cohorts = props.overview.retention;
const requests = total("requests");
return [
{
label: "访问用户",
value: f[0]?.users ?? 0,
note: "所选周期 · 顺序漏斗入口"
},
{
label: "有效对话用户",
value: f.at(-1)?.users ?? 0,
note: `访问转化 ${percent(f.at(-1)?.users ?? 0, f[0]?.users ?? 0)}`
},
{
label: "有输出结算率",
value: percent(total("consumed"), requests),
note: `${requests.toLocaleString()} 次请求 · 含失败、中止与预占`
},
{
label: "成熟队列次留",
value: percent(
cohorts.reduce((n, r) => n + Number(r.returned), 0),
cohorts.reduce((n, r) => n + Number(r.users), 0)
),
note: "成熟队列用户加权 · 非每日比率平均"
}
];
});
const charts: EChartsType[] = [];
let observer: ResizeObserver | undefined;
const empty = computed(() => [
!props.overview.funnel.some(r => r.users > 0),
!props.overview.retention.length,
!props.overview.experiments.some(r => Number(r.exposedUsers) > 0),
!props.overview.budget.length
]);
/** 只对存在分母的实验与留存绘制百分比,零曝光以空点呈现。 */
function options(): EChartsCoreOption[] {
const color = ["#6366f1", "#2bb8a5", "#f6ad55"];
const base = {
color,
backgroundColor: "transparent",
textStyle: { color: "#8892a3", fontFamily: "inherit" },
tooltip: { trigger: "axis", confine: true },
grid: { top: 40, left: 16, right: 24, bottom: 20, containLabel: true },
xAxis: {
type: "category",
axisTick: { show: false },
axisLine: { show: false }
},
yAxis: {
type: "value",
splitLine: { lineStyle: { color: "#94a3b822", type: "dashed" } }
}
};
const retention = props.overview.retention;
const experiments = props.overview.experiments;
const budget = [...props.overview.budget].sort((a, b) =>
String(a.period).localeCompare(String(b.period))
);
const ratio = (a: unknown, b: unknown) =>
Number(b) > 0 ? Number(((Number(a) / Number(b)) * 100).toFixed(2)) : null;
return [
{
...base,
xAxis: { ...base.yAxis, minInterval: 1 },
yAxis: { ...base.xAxis, inverse: true, data: names },
series: [
{
type: "bar",
barMaxWidth: 24,
data: props.overview.funnel.map((r, i) => ({
value: r.users,
itemStyle: {
color: [
"#6366f1",
"#7c7ff2",
"#9396f5",
"#2bb8a5",
"#56c8b9",
"#83d8cd"
][i],
borderRadius: [0, 6, 6, 0]
}
})),
label: { show: true, position: "right", color: "#8892a3" }
}
]
},
{
...base,
xAxis: { ...base.xAxis, data: retention.map(r => String(r.cohort)) },
yAxis: {
...base.yAxis,
min: 0,
max: 100,
axisLabel: { formatter: "{value}%" }
},
series: [
{
type: "line",
smooth: false,
symbolSize: 8,
connectNulls: false,
areaStyle: { opacity: 0.08 },
data: retention.map(r => ratio(r.returned, r.users))
}
]
},
{
...base,
legend: { top: 0, textStyle: { color: "#8892a3" } },
xAxis: {
...base.xAxis,
data: experiments.map(r => `v${r.revision} · ${r.variant}`)
},
yAxis: {
...base.yAxis,
min: 0,
max: 100,
axisLabel: { formatter: "{value}%" }
},
series: [
["详情点击", "clickUsers"],
["开始故事", "startUsers"],
["有效对话", "activatedUsers"]
].map(([name, key]) => ({
name,
type: "bar",
barMaxWidth: 22,
itemStyle: { borderRadius: [4, 4, 0, 0] },
data: experiments.map(r => ratio(r[key], r.exposedUsers))
}))
},
{
...base,
legend: { top: 0, textStyle: { color: "#8892a3" } },
xAxis: {
...base.xAxis,
data: budget.map(r => String(r.period).slice(0, 10))
},
series: [
["已结算", "used"],
["预占", "reserved"]
].map(([name, key]) => ({
name,
type: "bar",
stack: "budget",
barMaxWidth: 30,
data: budget.map(r => Number(r[key]))
}))
}
];
}
function render() {
options().forEach((option, i) => charts[i]?.setOption(option, true));
}
onMounted(async () => {
await nextTick();
root.value
?.querySelectorAll<HTMLElement>(".chart-canvas")
.forEach(el =>
charts.push(echarts.init(el, undefined, { renderer: "svg" }))
);
observer = new ResizeObserver(() => charts.forEach(chart => chart.resize()));
if (root.value) observer.observe(root.value);
render();
});
watch(() => props.overview, render, { deep: true });
onBeforeUnmount(() => {
observer?.disconnect();
charts.forEach(chart => chart.dispose());
});
</script>
<template>
<div ref="root" class="growth-dashboard">
<div class="metric-grid">
<article
v-for="(metric, i) in metrics"
:key="metric.label"
class="metric-card"
:style="{ '--accent': ['#6366f1', '#2bb8a5', '#ec9c45', '#8b5cf6'][i] }"
>
<span>{{ metric.label }}</span
><strong>{{
typeof metric.value === "number"
? metric.value.toLocaleString()
: metric.value
}}</strong
><small>{{ metric.note }}</small>
</article>
</div>
<div class="chart-grid">
<article v-for="(title, i) in titles" :key="title" class="chart-panel">
<header>
<h3>{{ title }}</h3>
<span>{{ subtitles[i] }}</span>
</header>
<div
class="chart-body"
role="img"
:aria-label="`${title},下方提供对应数据明细`"
>
<div
class="chart-canvas"
:style="{ visibility: empty[i] ? 'hidden' : 'visible' }"
/>
<div v-if="empty[i]" class="chart-empty">
<span>暂无样本</span><small>真实数据积累后自动呈现</small>
</div>
</div>
</article>
</div>
</div>
</template>
<style scoped>
.metric-grid {
display: grid;
grid-template-columns: repeat(4, minmax(0, 1fr));
gap: 16px;
margin: 8px 0 20px;
}
.metric-card {
position: relative;
display: flex;
flex-direction: column;
gap: 12px;
padding: 22px;
overflow: hidden;
background: var(--el-bg-color);
border: 1px solid var(--el-border-color-lighter);
border-radius: 14px;
}
.metric-card::before {
position: absolute;
top: 22px;
left: 0;
width: 3px;
height: 24px;
content: "";
background: var(--accent);
border-radius: 3px;
}
.metric-card > span {
font-size: 13px;
color: var(--el-text-color-secondary);
}
.metric-card strong {
font-size: 32px;
font-variant-numeric: tabular-nums;
line-height: 1.2;
color: var(--el-text-color-primary);
}
.metric-card small {
font-size: 11px;
line-height: 1.6;
color: var(--el-text-color-secondary);
}
.chart-grid {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 20px;
}
.chart-panel {
min-width: 0;
padding: 22px 18px 12px;
border: 1px solid var(--el-border-color-lighter);
border-radius: 14px;
}
.chart-panel header {
display: flex;
flex-direction: column;
gap: 8px;
}
.chart-panel h3 {
margin: 0;
font-size: 15px;
font-weight: 600;
color: var(--el-text-color-primary);
}
.chart-panel header span {
font-size: 11px;
line-height: 1.6;
color: var(--el-text-color-secondary);
}
.chart-body {
position: relative;
}
.chart-canvas {
width: 100%;
height: 280px;
}
.chart-empty {
position: absolute;
inset: 0;
display: flex;
flex-direction: column;
gap: 10px;
align-items: center;
justify-content: center;
color: var(--el-text-color-secondary);
}
.chart-empty small {
color: var(--el-text-color-placeholder);
}
@media (width <= 1200px) {
.metric-grid {
grid-template-columns: repeat(2, minmax(0, 1fr));
}
}
@media (width <= 760px) {
.chart-grid {
grid-template-columns: minmax(0, 1fr);
}
.metric-card {
padding: 16px;
}
.metric-card strong {
font-size: 25px;
}
}
</style>
+584
View File
@@ -0,0 +1,584 @@
<script setup lang="ts">
/** C端增长运营:漏斗、推荐实验、质量与额度流水,配置写入采用版本校验和审计。 */
import { computed, onMounted, ref } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import GrowthCharts from "./growth-charts.vue";
import { digital } from "@/api/access";
type Row = Record<string, string | number | boolean | null>;
type Config = {
revision: number;
guestEnabled: boolean;
guestLifetime: number;
guestDailyStarts: number;
freeDaily: number;
memberDaily: number;
dailyCharacterBudget: number;
generationEnabled: boolean;
recommendationExperiment: boolean;
recommendationRevision: number;
explorationPercent: number;
};
type Overview = {
truncated: boolean;
funnel: { stage: string; users: number }[];
quality: Row[];
feedback: Row[];
experiments: Row[];
retention: Row[];
campaigns: Row[];
budget: Row[];
risks: Row[];
crossovers: number;
allocationHealth: Row[];
definitions: Record<string, string>;
};
type Campaign = {
id: string;
title: string;
content: string;
segment: "new" | "active" | "dormant";
enabled: boolean;
holdoutPercent: number;
startsAt: string;
endsAt: string;
revision: number;
};
const tab = ref("overview"),
days = ref(14),
loading = ref(false),
saving = ref(false),
error = ref(""),
overview = ref<Overview>(),
config = ref<Config>(),
requests = ref<Row[]>([]),
users = ref<Row[]>([]),
campaigns = ref<Row[]>([]),
editing = ref<Campaign>(),
grantUser = ref<number>(),
grantDays = ref(30),
grantReason = ref(""),
grantRequest = ref(crypto.randomUUID());
const labels: Record<string, string> = {
page_view: "访问",
card_open: "角色详情",
conversation_started: "开始故事",
chat_requested: "发送请求",
reply_complete: "完整回复",
conversation_activated: "有效对话(3次完整回复)"
};
const quotaFields: [keyof Config, string, number][] = [
["guestLifetime", "游客总体验次数", 20],
["guestDailyStarts", "每日最多创建游客数", 10000],
["freeDaily", "免费账号每日次数", 1000],
["memberDaily", "会员每日次数", 5000],
["dailyCharacterBudget", "全站每日字符估算预算", 100000000],
["recommendationRevision", "推荐实验版本", 1000000],
["explorationPercent", "推荐探索比例%", 50]
];
const rate = (a: unknown, b: unknown) =>
Number(b) > 0 ? `${((Number(a) / Number(b)) * 100).toFixed(1)}%` : "暂无样本";
const matureRetention = computed(
() =>
overview.value?.retention.map(r => ({
...r,
retention: rate(r.returned, r.users)
})) ?? []
);
/** 所有数据均来自真实后端,失败时保留错误而不注入示例指标。 */
async function load() {
loading.value = true;
error.value = "";
try {
const [o, c, r, u, p] = await Promise.all([
digital<Overview>(`growth/overview?days=${days.value}`),
digital<Config>("growth/config"),
digital<Row[]>("growth/requests"),
digital<Row[]>("growth/users"),
digital<Row[]>("growth/campaigns")
]);
overview.value = o;
config.value = c;
requests.value = r;
users.value = u;
campaigns.value = p;
} catch (e) {
error.value = e instanceof Error ? e.message : "读取失败";
} finally {
loading.value = false;
}
}
async function saveConfig() {
if (!config.value || saving.value) return;
saving.value = true;
try {
const { revision, ...body } = config.value;
config.value = await digital<Config>("growth/config", "put", {
revision,
config: body
});
ElMessage.success("增长策略已保存");
} catch (e) {
ElMessage.error(e instanceof Error ? e.message : "保存失败");
} finally {
saving.value = false;
}
}
async function grant() {
if (!grantUser.value || grantReason.value.trim().length < 4 || saving.value)
return;
try {
await ElMessageBox.confirm(
grantDays.value === 0
? "将取消该用户会员权益,历史用量继续保留。"
: "这是后台运营赠送权益,不会创建支付订单或收款。",
"确认权益变更",
{ type: "warning" }
);
} catch {
return;
}
saving.value = true;
try {
await digital("growth/entitlements", "post", {
userId: grantUser.value,
requestId: grantRequest.value,
days: grantDays.value,
reason: grantReason.value
});
grantRequest.value = crypto.randomUUID();
await load();
ElMessage.success("权益已更新");
} catch (e) {
ElMessage.error(
e instanceof Error ? e.message : "授予失败,请保留参数重试"
);
} finally {
saving.value = false;
}
}
function resetGrantRequest() {
grantRequest.value = crypto.randomUUID();
}
function newCampaign() {
const format = (date: Date) =>
new Intl.DateTimeFormat("sv-SE", {
timeZone: "Asia/Shanghai",
year: "numeric",
month: "2-digit",
day: "2-digit",
hour: "2-digit",
minute: "2-digit",
second: "2-digit",
hour12: false
}).format(date);
editing.value = {
id: crypto.randomUUID(),
title: "",
content: "",
segment: "new",
enabled: false,
holdoutPercent: 20,
startsAt: format(new Date()),
endsAt: format(new Date(Date.now() + 7 * 86400000)),
revision: 0
};
}
function editCampaign(row: Row) {
editing.value = {
id: String(row.id),
title: String(row.title),
content: String(row.content),
segment: row.segment as Campaign["segment"],
enabled: !!row.enabled,
holdoutPercent: Number(row.holdout_percent),
startsAt: String(row.startsAt),
endsAt: String(row.endsAt),
revision: Number(row.revision)
};
}
async function saveCampaign() {
if (!editing.value || saving.value) return;
saving.value = true;
try {
await digital(`growth/campaigns/${editing.value.id}`, "put", editing.value);
editing.value = undefined;
await load();
ElMessage.success("站内活动已保存");
} catch (e) {
ElMessage.error(e instanceof Error ? e.message : "保存失败");
} finally {
saving.value = false;
}
}
onMounted(load);
</script>
<template>
<section v-loading="loading" class="growth-admin">
<header>
<div>
<span class="eyebrow">GROWTH ANALYTICS</span>
<h2>增长与体验数据中心</h2>
<p>
真实事件驱动运营;指标空缺时显示暂无样本。字符预算估算不等同Token账单或收入。
</p>
</div>
<el-input-number v-model="days" :min="1" :max="30" /><el-button
@click="load"
>刷新最近天数</el-button
>
</header>
<el-alert v-if="error" :title="error" type="error" :closable="false" />
<el-tabs v-model="tab">
<el-tab-pane label="数据总览" name="overview"
><template v-if="overview"
><el-alert
v-if="overview.truncated"
title="事件超过50000条,本页漏斗为截断样本,不可用于总体结论"
type="warning"
:closable="false"
/>
<GrowthCharts :overview="overview" />
<h3>转化阶段明细</h3>
<div class="funnel">
<article v-for="(stage, i) in overview.funnel" :key="stage.stage">
<span>{{ labels[stage.stage] }}</span
><strong>{{ stage.users }}</strong
><small v-if="i"
>上一步转化
{{ rate(stage.users, overview.funnel[i - 1]?.users) }}</small
>
</article>
</div>
<h3>成熟队列次日留存</h3>
<el-table :data="matureRetention"
><el-table-column
prop="cohort"
label="首次访问日期" /><el-table-column
prop="users"
label="新增访问用户" /><el-table-column
prop="returned"
label="次日返回" /><el-table-column
prop="retention"
label="次日留存率"
/></el-table>
<p>{{ overview.definitions.retention }}</p></template
></el-tab-pane
>
<el-tab-pane label="推荐实验" name="recommendation"
><template v-if="overview"
><el-alert
:title="`跨组账号:${overview.crossovers}。请先检查分桶和样本,再解读差异;本页不自动宣称显著提升。`"
type="info"
:closable="false"
/><el-table :data="overview.experiments"
><el-table-column
prop="revision"
label="实验版本"
/><el-table-column prop="variant" label="排序组" /><el-table-column
prop="assignedUsers"
label="分配用户"
/><el-table-column
prop="exposedUsers"
label="实际曝光"
/><el-table-column label="详情点击率"
><template #default="{ row }">{{
rate(row.clickUsers, row.exposedUsers)
}}</template></el-table-column
><el-table-column label="开聊率"
><template #default="{ row }">{{
rate(row.startUsers, row.exposedUsers)
}}</template></el-table-column
><el-table-column label="有效开聊率"
><template #default="{ row }">{{
rate(row.activatedUsers, row.exposedUsers)
}}</template></el-table-column
></el-table
><el-table :data="overview.allocationHealth"
><el-table-column prop="revision" label="版本" /><el-table-column
prop="assigned"
label="分配总用户" /><el-table-column
prop="status"
label="样本比例检查"
/></el-table>
<p>{{ overview.definitions.experiments }}</p></template
></el-tab-pane
>
<el-tab-pane label="质量与成本" name="quality"
><template v-if="overview"
><h3>回答质量与性能</h3>
<el-table :data="overview.quality"
><el-table-column prop="model" label="模型" /><el-table-column
prop="purpose"
label="操作" /><el-table-column
prop="promptVersion"
label="提示词版本" /><el-table-column
prop="requests"
label="请求" /><el-table-column
prop="failed"
label="失败" /><el-table-column
prop="stopped"
label="中止" /><el-table-column
prop="avgFirstTokenMs"
label="平均首字毫秒" /><el-table-column
prop="estimatedCharacters"
label="估算字符消耗"
/></el-table>
<h3>用户评价</h3>
<el-table :data="overview.feedback"
><el-table-column prop="rating" label="评价" /><el-table-column
prop="reason"
label="原因" /><el-table-column prop="count" label="条数"
/></el-table>
<h3>预算与保护事件</h3>
<el-table :data="overview.budget"
><el-table-column prop="period" label="日期" /><el-table-column
prop="used"
label="已结算字符" /><el-table-column
prop="reserved"
label="预占字符" /></el-table
><el-table :data="overview.risks"
><el-table-column prop="event" label="保护事件" /><el-table-column
prop="count"
label="数量" /></el-table></template
></el-tab-pane>
<el-tab-pane label="权益与流水" name="rights"
><el-form inline
><el-form-item label="用户"
><el-select
v-model="grantUser"
filterable
style="width: 220px"
@change="resetGrantRequest"
><el-option
v-for="u in users"
:key="String(u.id)"
:value="Number(u.id)"
:label="`${u.displayName} (${u.account})`" /></el-select></el-form-item
><el-form-item label="赠送天数(0取消)"
><el-input-number
v-model="grantDays"
:min="0"
:max="365"
@change="resetGrantRequest" /></el-form-item
><el-form-item label="原因"
><el-input
v-model="grantReason"
maxlength="200"
@input="resetGrantRequest" /></el-form-item
><el-button :disabled="saving" @click="grant"
>确认权益</el-button
></el-form
><el-table :data="users"
><el-table-column prop="account" label="账号" /><el-table-column
prop="displayName"
label="名称" /><el-table-column
prop="memberUntil"
label="会员截至时间"
/></el-table>
<h3>最近100笔额度流水</h3>
<el-table :data="requests"
><el-table-column prop="account" label="账号" /><el-table-column
prop="requestId"
label="幂等请求号"
min-width="220" /><el-table-column
prop="state"
label="记账状态" /><el-table-column
prop="outcome"
label="回复结果" /><el-table-column
prop="usedCharacters"
label="估算字符" /><el-table-column
prop="durationMs"
label="耗时毫秒" /></el-table
></el-tab-pane>
<el-tab-pane label="生命周期运营" name="campaigns"
><p>
站内卡片按访问前状态分群;每人每日最多分配一张,固定保留对照组。不会发送短信、邮件或企微。
</p>
<el-button @click="newCampaign">新建站内活动</el-button
><el-table :data="campaigns"
><el-table-column prop="title" label="活动" /><el-table-column
prop="segment"
label="人群"
/><el-table-column prop="enabled" label="启用" /><el-table-column
prop="startsAt"
label="开始(北京时间)"
/><el-table-column prop="endsAt" label="结束" /><el-table-column
label="操作"
><template #default="{ row }"
><el-button @click="editCampaign(row)">编辑</el-button></template
></el-table-column
></el-table
><el-table :data="overview?.campaigns ?? []"
><el-table-column prop="title" label="活动" /><el-table-column
prop="revision"
label="版本" /><el-table-column
prop="heldOut"
label="是否对照组" /><el-table-column
prop="assigned"
label="分配" /><el-table-column
prop="exposed"
label="曝光" /><el-table-column
prop="clicked"
label="点击" /><el-table-column
prop="returnedToChat"
label="24小时内回聊" /></el-table
></el-tab-pane>
<el-tab-pane label="策略与保护" name="config"
><el-form v-if="config" label-width="230px"
><el-form-item label="允许生成"
><el-switch v-model="config.generationEnabled" /></el-form-item
><el-form-item label="开放游客体验"
><el-switch v-model="config.guestEnabled" /></el-form-item
><el-form-item label="推荐50/50实验"
><el-switch
v-model="config.recommendationExperiment" /></el-form-item
><el-form-item
v-for="[key, label, max] in quotaFields"
:key="key"
:label="label"
><el-input-number
:model-value="Number(config[key])"
:min="key === 'recommendationRevision' ? 1 : 0"
:max="max"
@update:model-value="
value => Object.assign(config!, { [key]: value })
"
/></el-form-item>
<p>
修改实验开关或探索比例时须递增实验版本。原UI实验保持独立;账号限流、并发和全站预算共同生效。
</p>
<el-button type="primary" :loading="saving" @click="saveConfig"
>保存策略</el-button
></el-form
></el-tab-pane
>
</el-tabs>
<el-dialog
:model-value="!!editing"
title="站内生命周期活动"
width="min(620px,94vw)"
:close-on-click-modal="false"
@close="editing = undefined"
><el-form v-if="editing" label-width="130px"
><el-form-item label="标题"
><el-input v-model="editing.title" maxlength="80" /></el-form-item
><el-form-item label="内容"
><el-input
v-model="editing.content"
type="textarea"
maxlength="500" /></el-form-item
><el-form-item label="分群"
><el-select v-model="editing.segment"
><el-option value="new" label="新用户激活" /><el-option
value="active"
label="活跃用户" /><el-option
value="dormant"
label="7天未访问用户" /></el-select></el-form-item
><el-form-item label="对照组比例%"
><el-input-number
v-model="editing.holdoutPercent"
:min="5"
:max="90" /></el-form-item
><el-form-item label="开始(北京时间)"
><el-input
v-model="editing.startsAt"
placeholder="YYYY-MM-DD HH:mm:ss" /></el-form-item
><el-form-item label="结束(北京时间)"
><el-input
v-model="editing.endsAt"
placeholder="YYYY-MM-DD HH:mm:ss" /></el-form-item
><el-form-item label="启用"
><el-switch v-model="editing.enabled" /></el-form-item></el-form
><template #footer
><el-button @click="editing = undefined">取消</el-button
><el-button type="primary" :loading="saving" @click="saveCampaign"
>保存</el-button
></template
></el-dialog
>
</section>
</template>
<style scoped>
.growth-admin {
padding: 24px;
background: var(--el-bg-color-page);
border-radius: 16px;
}
.growth-admin header {
display: flex;
gap: 16px;
align-items: center;
margin-bottom: 20px;
}
.growth-admin header > div {
flex: 1;
}
.growth-admin p {
line-height: 1.7;
color: var(--el-text-color-secondary);
}
.eyebrow {
font-size: 11px;
font-weight: 700;
color: var(--el-color-primary);
letter-spacing: 2px;
}
.growth-admin h2 {
margin: 8px 0;
font-size: 26px;
letter-spacing: -0.5px;
}
.growth-admin :deep(.el-tabs__content) {
padding: 20px;
background: var(--el-bg-color);
border-radius: 14px;
}
@media (width <= 760px) {
.growth-admin {
padding: 12px;
}
.growth-admin header {
flex-wrap: wrap;
}
.growth-admin header > div {
flex-basis: 100%;
}
}
.growth-admin h3 {
margin: 22px 0 12px;
}
.funnel {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(140px, 1fr));
gap: 12px;
margin: 16px 0;
}
.funnel article {
display: flex;
flex-direction: column;
gap: 8px;
padding: 16px;
border: 1px solid var(--el-border-color);
border-radius: 12px;
}
.funnel strong {
font-size: 28px;
}
.funnel small {
color: var(--el-text-color-secondary);
}
</style>
+703
View File
@@ -0,0 +1,703 @@
<script setup lang="ts">
/** 独立 C 端用户管理:开户、内容偏好、停用、改密与区分对白/叙述的持久化聊天记录。 */
import { onMounted, ref } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import DigitalMessageText from "@/components/DigitalMessageText.vue";
import {
digital,
type DigitalUser,
type UserConversation,
type UserChatMessage
} from "@/api/access";
const q = ref(""),
status = ref(""),
page = ref(1),
total = ref(0),
loading = ref(false),
users = ref<DigitalUser[]>([]);
const creating = ref(false),
saving = ref(false),
createForm = ref({
username: "",
displayName: "",
password: "",
nsfwEnabled: true
});
const editing = ref<DigitalUser | null>(null),
editForm = ref({ displayName: "", status: "ACTIVE", nsfwEnabled: true });
const resetTarget = ref<DigitalUser | null>(null),
newPassword = ref("");
const selected = ref<DigitalUser | null>(null),
history = ref(false),
conversations = ref<UserConversation[]>([]),
conversationPage = ref(1),
conversationTotal = ref(0),
conversationLoading = ref(false);
const active = ref<UserConversation | null>(null),
messages = ref<UserChatMessage[]>([]),
messagePage = ref(1),
messageTotal = ref(0),
messageLoading = ref(false);
let listVersion = 0,
chatVersion = 0,
messageVersion = 0;
const time = (value: string | null) =>
value ? new Date(value).toLocaleString() : "—";
const states: Record<string, string> = {
complete: "已完成",
stopped: "已停止",
failed: "生成失败",
generating: "生成中",
superseded: "旧版本"
};
/** 请求编号避免快速切换用户时把旧请求结果写进新用户的聊天面板。 */
async function load() {
const version = ++listVersion;
loading.value = true;
try {
const params = new URLSearchParams({
q: q.value,
page: String(page.value),
size: "20"
});
if (status.value) params.set("status", status.value);
const r = await digital<{ items: DigitalUser[]; total: number }>(
`users?${params}`
);
if (version === listVersion) {
users.value = r.items;
total.value = r.total;
}
} catch (e) {
ElMessage.error(e instanceof Error ? e.message : "加载失败");
} finally {
if (version === listVersion) loading.value = false;
}
}
function search() {
page.value = 1;
load();
}
async function create() {
if (
!createForm.value.username.trim() ||
!createForm.value.displayName.trim() ||
createForm.value.password.length < 8
)
return ElMessage.warning("请填写账号、昵称及至少8位密码");
saving.value = true;
try {
await digital("users", "post", createForm.value);
creating.value = false;
createForm.value = {
username: "",
displayName: "",
password: "",
nsfwEnabled: true
};
search();
ElMessage.success("C 端账号已创建,可在星港前台登录");
} catch (e) {
ElMessage.error(e instanceof Error ? e.message : "创建失败");
} finally {
saving.value = false;
}
}
function edit(user: DigitalUser) {
editing.value = user;
editForm.value = {
displayName: user.displayName,
status: user.status,
nsfwEnabled: user.nsfwEnabled ?? true
};
}
async function saveEdit() {
if (!editing.value) return;
saving.value = true;
try {
await digital(`users/${editing.value.id}`, "patch", editForm.value);
editing.value = null;
await load();
ElMessage.success("用户资料已保存");
} catch (e) {
ElMessage.error(e instanceof Error ? e.message : "保存失败");
} finally {
saving.value = false;
}
}
async function resetPassword() {
if (!resetTarget.value) return;
if (newPassword.value.length < 8) return ElMessage.warning("密码至少8位");
saving.value = true;
try {
await digital(`users/${resetTarget.value.id}/password`, "post", {
password: newPassword.value
});
newPassword.value = "";
resetTarget.value = null;
ElMessage.success("密码已重置,该用户需要重新登录");
} catch (e) {
ElMessage.error(e instanceof Error ? e.message : "重置失败");
} finally {
saving.value = false;
}
}
async function openHistory(user: DigitalUser) {
selected.value = user;
history.value = true;
conversationPage.value = 1;
active.value = null;
messages.value = [];
++messageVersion;
await loadConversations();
}
async function loadConversations() {
if (!selected.value) return;
const version = ++chatVersion;
conversationLoading.value = true;
conversations.value = [];
try {
const r = await digital<{ items: UserConversation[]; total: number }>(
`users/${selected.value.id}/conversations?page=${conversationPage.value}&size=20`
);
if (version === chatVersion) {
conversations.value = r.items;
conversationTotal.value = r.total;
}
} catch (e) {
if (version === chatVersion)
ElMessage.error(e instanceof Error ? e.message : "会话加载失败");
} finally {
if (version === chatVersion) conversationLoading.value = false;
}
}
const restoring = ref(false);
/** 恢复仅作用于选中的用户和会话,切换用户后的迟到结果不能覆盖当前详情。 */
async function restoreChat() {
if (!selected.value || !active.value?.deletedAt || restoring.value) return;
const user = selected.value.id,
conversation = active.value.id;
try {
await ElMessageBox.confirm(
"恢复后用户可在前台继续查看这段对话,原消息不会改变。",
"恢复会话",
{ type: "info" }
);
} catch {
return;
}
restoring.value = true;
try {
await digital(
`users/${user}/conversations/${conversation}/restore`,
"post",
{}
);
if (selected.value?.id === user) {
if (active.value?.id === conversation)
active.value = { ...active.value, deletedAt: null };
await loadConversations();
}
ElMessage.success("会话已恢复");
} catch (e) {
ElMessage.error(e instanceof Error ? e.message : "恢复失败");
} finally {
restoring.value = false;
}
}
async function chooseConversation(c: UserConversation) {
active.value = c;
messagePage.value = 1;
await loadMessages();
}
async function loadMessages() {
if (!selected.value || !active.value) return;
const version = ++messageVersion;
messageLoading.value = true;
messages.value = [];
try {
const r = await digital<{ items: UserChatMessage[]; total: number }>(
`users/${selected.value.id}/conversations/${active.value.id}/messages?page=${messagePage.value}&size=30`
);
if (version === messageVersion) {
messages.value = r.items;
messageTotal.value = r.total;
}
} catch (e) {
if (version === messageVersion)
ElMessage.error(e instanceof Error ? e.message : "聊天记录加载失败");
} finally {
if (version === messageVersion) messageLoading.value = false;
}
}
function closeHistory() {
++chatVersion;
++messageVersion;
selected.value = null;
active.value = null;
messages.value = [];
}
onMounted(load);
</script>
<template>
<div class="customer-page">
<div class="heading">
<div>
<h2>用户管理</h2>
<p>C 端账号独立于后台管理员,由后台开通。聊天记录按用户和会话查看。</p>
</div>
<el-button
type="primary"
@click="
createForm = {
username: '',
displayName: '',
password: '',
nsfwEnabled: true
};
creating = true;
"
>创建 C 端用户</el-button
>
</div>
<el-card shadow="never"
><div class="filters">
<el-input
v-model="q"
clearable
placeholder="搜索账号、昵称或用户 ID"
@keyup.enter="search"
@clear="search"
/><el-select
v-model="status"
clearable
placeholder="全部状态"
@change="search"
><el-option value="ACTIVE" label="正常" /><el-option
value="INACTIVE"
label="已停用" /></el-select
><el-button :loading="loading" @click="search">查询</el-button>
</div>
<el-table
v-loading="loading"
:data="users"
empty-text="暂无 C 端用户,可点击上方创建"
><el-table-column label="用户" min-width="220"
><template #default="{ row }"
><strong>{{ row.displayName }}</strong>
<p class="secondary">
{{ row.username }} · UID {{ row.id }}
</p></template
></el-table-column
><el-table-column label="状态" width="100"
><template #default="{ row }"
><el-tag :type="row.status === 'ACTIVE' ? 'success' : 'info'">{{
row.status === "ACTIVE" ? "正常" : "已停用"
}}</el-tag></template
></el-table-column
><el-table-column label="NSFW" width="100"
><template #default="{ row }"
><el-tag :type="row.nsfwEnabled === false ? 'info' : 'success'">{{
row.nsfwEnabled === false ? "已关闭" : "已开启"
}}</el-tag></template
></el-table-column
><el-table-column
prop="conversations"
label="会话数"
width="90"
/><el-table-column
prop="messages"
label="消息数"
width="90"
/><el-table-column label="创建时间" min-width="175"
><template #default="{ row }">{{
time(row.createdAt)
}}</template></el-table-column
><el-table-column label="最近登录" min-width="175"
><template #default="{ row }">{{
time(row.lastLoginAt)
}}</template></el-table-column
><el-table-column label="操作" min-width="235" fixed="right"
><template #default="{ row }"
><el-button link type="primary" @click="openHistory(row)"
>聊天记录</el-button
><el-button link type="primary" @click="edit(row)">编辑</el-button
><el-button
link
type="warning"
@click="
resetTarget = row;
newPassword = '';
"
>重置密码</el-button
></template
></el-table-column
></el-table
>
<el-pagination
v-model:current-page="page"
:page-size="20"
:total="total"
layout="total, prev, pager, next"
@current-change="load"
/>
</el-card>
<el-dialog
v-model="creating"
title="创建 C 端用户"
width="min(520px,95vw)"
:close-on-click-modal="false"
><el-form label-position="top"
><el-form-item label="登录账号" required
><el-input
v-model="createForm.username"
maxlength="120"
placeholder="字母、数字、手机号或邮箱"
autocomplete="off" /></el-form-item
><el-form-item label="用户昵称" required
><el-input
v-model="createForm.displayName"
maxlength="120" /></el-form-item
><el-form-item label="初始密码" required
><el-input
v-model="createForm.password"
type="password"
show-password
maxlength="128"
placeholder="至少8位"
autocomplete="new-password" /></el-form-item
><el-form-item label="NSFW 成人内容"
><el-switch
v-model="createForm.nsfwEnabled"
active-text="开启"
inactive-text="关闭"
/>
<p class="secondary">
登录账号默认开启,用户可在前台保存自己的选择。
</p>
</el-form-item></el-form
><template #footer
><el-button @click="creating = false">取消</el-button
><el-button type="primary" :loading="saving" @click="create"
>创建用户</el-button
></template
></el-dialog
>
<el-dialog
:model-value="!!editing"
title="编辑 C 端用户"
width="min(520px,95vw)"
@close="editing = null"
><el-form label-position="top"
><el-form-item label="登录账号">{{ editing?.username }}</el-form-item
><el-form-item label="用户昵称"
><el-input
v-model="editForm.displayName"
maxlength="120" /></el-form-item
><el-form-item label="账号状态"
><el-radio-group v-model="editForm.status"
><el-radio value="ACTIVE">正常</el-radio
><el-radio value="INACTIVE">停用</el-radio></el-radio-group
></el-form-item
><el-form-item label="NSFW 成人内容"
><el-switch
v-model="editForm.nsfwEnabled"
active-text="开启"
inactive-text="关闭"
/>
<p class="secondary">保存后用于该账号的后续回复。</p>
</el-form-item></el-form
><el-alert
title="停用后用户无法登录,已有会话记录仍保留。"
:closable="false"
/><template #footer
><el-button @click="editing = null">取消</el-button
><el-button type="primary" :loading="saving" @click="saveEdit"
>保存</el-button
></template
></el-dialog
>
<el-dialog
:model-value="!!resetTarget"
title="重置 C 端用户密码"
width="min(520px,95vw)"
@close="
resetTarget = null;
newPassword = '';
"
><p>{{ resetTarget?.displayName }} · {{ resetTarget?.username }}</p>
<el-input
v-model="newPassword"
type="password"
show-password
maxlength="128"
autocomplete="new-password"
placeholder="设置至少8位新密码"
/>
<p class="secondary">
重置后该 C 端账号的旧登录状态失效,不影响同名后台账号。
</p>
<template #footer
><el-button @click="resetTarget = null">取消</el-button
><el-button type="primary" :loading="saving" @click="resetPassword"
>确认重置</el-button
></template
></el-dialog
>
<el-dialog
v-model="history"
:title="`${selected?.displayName ?? ''} · 聊天记录`"
width="min(1280px,96vw)"
top="4vh"
@closed="closeHistory"
>
<div class="history-layout">
<aside v-loading="conversationLoading" class="conversation-list">
<p class="secondary">
{{ selected?.username }} · {{ conversationTotal }} 个会话
</p>
<el-empty
v-if="!conversations.length && !conversationLoading"
description="暂无聊天记录"
/><button
v-for="c in conversations"
:key="c.id"
class="conversation"
:class="{ active: active?.id === c.id }"
@click="chooseConversation(c)"
>
<strong>{{ c.characterName }}</strong
><span
>{{ c.title
}}<el-tag v-if="c.deletedAt" size="small" type="info"
>前台已删除 · {{ time(c.deletedAt) }}</el-tag
></span
><small
>{{ c.messages }} 条消息 · {{ time(c.updatedAt) }}</small
></button
><el-pagination
v-model:current-page="conversationPage"
small
:page-size="20"
:total="conversationTotal"
layout="prev, pager, next"
@current-change="loadConversations"
/>
</aside>
<section v-loading="messageLoading" class="message-pane">
<template v-if="active"
><header>
<strong>{{ active.characterName }} · {{ active.title }}</strong
><el-button
v-if="active.deletedAt"
size="small"
:loading="restoring"
@click="restoreChat"
>恢复给用户</el-button
><el-button size="small" @click="loadMessages"
>刷新记录</el-button
>
</header>
<p class="secondary">
第1页为最新记录,每页按发送顺序展示;较早内容可翻页查看。共
{{ messageTotal }} 条。
</p>
<div class="messages">
<el-empty
v-if="!messages.length && !messageLoading"
description="此会话尚无消息"
/>
<article v-for="m in messages" :key="m.id" :class="m.role">
<div class="message-meta">
<strong>{{
m.role === "user"
? selected?.displayName
: active.characterName
}}</strong
><time>{{ time(m.createdAt) }}</time
><el-tag
v-if="m.status !== 'complete'"
size="small"
type="info"
>{{ states[m.status] ?? m.status }}</el-tag
><el-tag v-if="m.pinned" size="small">已固定</el-tag>
</div>
<DigitalMessageText
class="history-message-body"
:text="m.content"
:role="m.role"
:incomplete="
['generating', 'stopped', 'failed'].includes(m.status)
"
/>
</article>
</div>
<el-pagination
v-model:current-page="messagePage"
:page-size="30"
:total="messageTotal"
layout="total, prev, pager, next"
@current-change="loadMessages" /></template
><el-empty v-else description="选择左侧会话查看聊天内容" />
</section>
</div>
</el-dialog>
</div>
</template>
<style scoped>
.heading,
.filters,
.message-pane header {
display: flex;
gap: 12px;
align-items: center;
justify-content: space-between;
margin-bottom: 18px;
}
h2 {
margin: 0 0 8px;
font-size: 24px;
}
.secondary,
.heading p {
margin: 6px 0;
font-size: 12px;
color: var(--el-text-color-secondary);
}
.filters .el-input {
max-width: 420px;
}
.filters .el-select {
width: 160px;
}
.filters {
justify-content: flex-start;
}
.el-pagination {
justify-content: flex-end;
margin-top: 16px;
}
.history-layout {
display: grid;
grid-template-columns: 280px minmax(0, 1fr);
gap: 20px;
height: 72vh;
}
.conversation-list,
.message-pane {
min-height: 0;
overflow: auto;
}
.conversation-list {
padding-right: 12px;
border-right: 1px solid var(--el-border-color-light);
}
.conversation {
display: flex;
flex-direction: column;
gap: 6px;
width: 100%;
padding: 14px 10px;
color: var(--el-text-color-primary);
text-align: left;
cursor: pointer;
background: transparent;
border: 0;
border-bottom: 1px solid var(--el-border-color-lighter);
}
.conversation.active {
color: var(--el-color-primary);
background: var(--el-color-primary-light-9);
}
.conversation small {
font-size: 11px;
color: var(--el-text-color-secondary);
}
.message-pane {
display: flex;
flex-direction: column;
}
.message-pane header {
margin-bottom: 8px;
}
.messages {
flex: 1;
min-height: 0;
padding: 8px;
overflow: auto;
}
.messages article {
margin-bottom: 18px;
}
.message-meta {
display: flex;
flex-wrap: wrap;
gap: 10px;
align-items: center;
font-size: 12px;
}
.message-meta time {
color: var(--el-text-color-secondary);
}
.messages article .history-message-body {
padding: 12px 14px;
margin: 6px 0;
overflow-wrap: anywhere;
white-space: pre-wrap;
background: var(--el-fill-color-light);
border-radius: 6px;
}
.messages article.user .history-message-body {
background: var(--el-color-primary-light-9);
}
.conversation:focus-visible {
outline: 2px solid var(--el-color-primary);
outline-offset: -2px;
}
@media (width<=760px) {
.heading,
.filters {
flex-direction: column;
align-items: stretch;
}
.filters .el-input,
.filters .el-select {
width: 100%;
max-width: none;
}
.history-layout {
grid-template-rows: 180px minmax(0, 1fr);
grid-template-columns: 1fr;
}
.conversation-list {
padding-right: 0;
border-right: 0;
border-bottom: 1px solid var(--el-border-color-light);
}
}
</style>
+480
View File
@@ -0,0 +1,480 @@
<script setup lang="ts">
/** 消息推送图文教程:共享内容源、截图来源、编号标注和技能下载,保持目录与阅读位置同步。 */
import {
nextTick,
onActivated,
onBeforeUnmount,
onMounted,
ref,
watch
} from "vue";
import { useRouter } from "vue-router";
import guide from "../../../docs/notifications/guide.json";
import screenshotSizes from "../../../docs/notifications/screenshots.json";
// 为懒加载截图预留真实比例,避免图片出现后章节位置发生跳动。
const sizes = screenshotSizes as Record<
string,
{ width: number; height: number; source: string }
>;
const router = useRouter();
const page = ref<HTMLElement>(),
body = ref<HTMLElement>(),
toc = ref<HTMLElement>();
const activeId = ref(guide.steps[0].id);
let frame = 0,
observer: ResizeObserver | undefined;
/** 正文是唯一阅读滚动容器,懒加载图片改变章节高度后也重新判定位置。 */
function updateReadingPosition() {
frame = 0;
if (!page.value?.offsetWidth || !body.value) return;
const available =
window.innerHeight - page.value.getBoundingClientRect().top - 24;
page.value.style.setProperty(
"--guide-height",
`${Math.max(360, available)}px`
);
const sections = Array.from(
body.value.querySelectorAll<HTMLElement>(".guide-section")
);
const top = body.value.getBoundingClientRect().top + 24;
let current = sections[0]?.id;
for (const section of sections) {
if (section.getBoundingClientRect().top <= top) current = section.id;
else break;
}
// 最后一章可能不足一屏;滚到底部时仍须选中它。
if (
body.value.scrollTop + body.value.clientHeight >=
body.value.scrollHeight - 2
)
current = sections.at(-1)?.id;
if (current) activeId.value = current.replace(/^guide-/, "");
}
function scheduleUpdate() {
if (!frame) frame = requestAnimationFrame(updateReadingPosition);
}
onMounted(() => {
window.addEventListener("resize", scheduleUpdate);
observer = new ResizeObserver(scheduleUpdate);
if (page.value) observer.observe(page.value);
if (body.value) {
observer.observe(body.value);
body.value
.querySelectorAll(".guide-section")
.forEach(section => observer!.observe(section));
}
scheduleUpdate();
});
onActivated(scheduleUpdate);
onBeforeUnmount(() => {
window.removeEventListener("resize", scheduleUpdate);
observer?.disconnect();
cancelAnimationFrame(frame);
});
watch(activeId, async id => {
await nextTick();
const button = toc.value?.querySelector<HTMLElement>(
`[data-section="${id}"]`
);
if (!button || !toc.value) return;
const item = button.getBoundingClientRect(),
menu = toc.value.getBoundingClientRect();
// 仅移动目录内部,避免 scrollIntoView 带动后台外层容器。
if (item.top < menu.top || item.bottom > menu.bottom)
toc.value.scrollTop +=
item.top - menu.top - toc.value.clientHeight / 2 + item.height / 2;
});
const images = guide.steps.flatMap(step =>
(step.images ?? []).map(image => `/guides/notifications/${image}.svg`)
);
/** 在当前二级页内滚动,不修改hash路由,也不触发任何配置保存或消息投递。 */
function jump(id: string) {
const section = body.value?.querySelector<HTMLElement>(`#guide-${id}`);
if (!section || !body.value) return;
body.value.scrollTo({
top:
body.value.scrollTop +
section.getBoundingClientRect().top -
body.value.getBoundingClientRect().top,
behavior: window.matchMedia("(prefers-reduced-motion: reduce)").matches
? "instant"
: "smooth"
});
}
</script>
<template>
<div ref="page" class="notification-guide">
<header class="guide-heading">
<div>
<el-tag type="info">企微篇 · {{ images.length }} 张操作图</el-tag>
<h1>{{ guide.title }}</h1>
<p>{{ guide.intro }}</p>
</div>
<div class="guide-actions">
<a
class="guide-action"
href="https://devops.mrzhan.top/settings?tab=notifications"
target="_blank"
rel="noopener noreferrer"
>打开通知配置 ↗</a
>
<a
class="guide-action primary"
href="/guides/notifications/wecom-notification-integration.zip"
download
>下载 Codex Skill</a
>
</div>
</header>
<el-alert :title="guide.notice" type="info" :closable="false" />
<div class="guide-layout">
<nav class="guide-toc" aria-label="教程目录">
<strong>本页目录</strong>
<div ref="toc" class="guide-links">
<button
v-for="step in guide.steps"
:key="step.id"
type="button"
:data-section="step.id"
:class="{ active: activeId === step.id }"
:aria-current="activeId === step.id ? 'location' : undefined"
@click="jump(step.id)"
>
{{ step.title }}
</button>
</div>
</nav>
<article
ref="body"
class="guide-body"
tabindex="0"
aria-label="教程正文"
@scroll="scheduleUpdate"
>
<section
v-for="step in guide.steps"
:id="`guide-${step.id}`"
:key="step.id"
class="guide-section"
>
<h2>{{ step.title }}</h2>
<p class="guide-lead">{{ step.lead }}</p>
<figure v-for="image in step.images ?? []" :key="image">
<el-image
:src="`/guides/notifications/${image}.svg`"
:style="{
aspectRatio: `${sizes[image].width} / ${sizes[image].height}`,
maxWidth: `${sizes[image].width}px`
}"
:alt="`${step.title},${sizes[image].source}`"
:preview-src-list="images"
:initial-index="
images.indexOf(`/guides/notifications/${image}.svg`)
"
preview-teleported
lazy
fit="contain"
><template #error
><div class="image-error">
教程图片加载失败,请刷新重试。
</div></template
></el-image
>
<figcaption>
{{ sizes[image].source }} · 点击放大<span
v-if="guide.captions[image].length"
>
· 编号对应下方操作</span
>
</figcaption>
<ol v-if="guide.captions[image].length" class="guide-callouts">
<li v-for="note in guide.captions[image]" :key="note">
{{ note }}
</li>
</ol>
</figure>
<ul>
<li v-for="line in step.bullets" :key="line">{{ line }}</li>
</ul>
<pre v-if="'code' in step"><code>{{ step.code }}</code></pre>
</section>
<footer class="guide-footer">
<h2>官方参考与维护</h2>
<ul>
<li v-for="reference in guide.references" :key="reference.url">
<a :href="reference.url" target="_blank" rel="noopener noreferrer"
>{{ reference.label }} ↗</a
>
</li>
</ul>
<p>
教程更新:{{ guide.updated }}。网页与图文 README
共用内容源,截图保留来源;配置操作和实际发送在运维平台完成。
</p>
<div class="guide-actions">
<a
class="guide-action primary"
href="/guides/notifications/wecom-notification-integration.zip"
download
>下载 Codex Skill</a
>
<el-button @click="router.push('/digital/experiments/guide')"
>实验操作指南</el-button
>
</div>
</footer>
</article>
</div>
</div>
</template>
<style scoped>
.notification-guide {
display: flex;
flex-direction: column;
max-width: 1440px;
height: var(--guide-height, calc(100dvh - 134px));
min-height: 360px;
margin: 0 auto;
overflow: hidden;
}
.guide-heading {
display: flex;
gap: 24px;
align-items: flex-start;
justify-content: space-between;
margin-bottom: 24px;
}
.guide-heading h1 {
margin: 12px 0;
font-size: 28px;
}
.guide-heading p {
max-width: 800px;
line-height: 1.8;
color: var(--el-text-color-secondary);
}
.guide-layout {
display: grid;
flex: 1;
grid-template-columns: 220px minmax(0, 1fr);
gap: 32px;
min-height: 0;
margin-top: 24px;
}
.guide-toc {
display: flex;
flex-direction: column;
gap: 6px;
min-height: 0;
max-height: 100%;
padding: 16px;
overflow: hidden;
background: var(--el-bg-color);
border: 1px solid var(--el-border-color-lighter);
border-radius: 8px;
}
.guide-links {
display: flex;
flex-direction: column;
gap: 6px;
min-height: 0;
overflow-y: auto;
}
.guide-toc strong {
flex-shrink: 0;
padding: 4px 8px 12px;
}
.guide-toc button {
padding: 8px;
font: inherit;
font-size: 13px;
color: var(--el-text-color-regular);
text-align: left;
cursor: pointer;
background: transparent;
border: 0;
border-radius: 4px;
}
.guide-toc button.active {
font-weight: 600;
color: var(--el-color-primary);
background: var(--el-color-primary-light-9);
box-shadow: inset 3px 0 var(--el-color-primary);
}
.guide-body {
min-width: 0;
min-height: 0;
overflow-y: auto;
overscroll-behavior: contain;
}
.guide-body:focus-visible {
outline: 2px solid var(--el-color-primary);
outline-offset: -2px;
}
.guide-toc button:hover {
color: var(--el-color-primary);
background: var(--el-fill-color-light);
}
.guide-toc button:focus-visible {
outline: 2px solid var(--el-color-primary);
outline-offset: 2px;
}
.guide-section {
padding: 24px;
margin-bottom: 24px;
scroll-margin-top: 0;
background: var(--el-bg-color);
border: 1px solid var(--el-border-color-lighter);
border-radius: 8px;
}
.guide-section h2 {
margin: 0 0 12px;
font-size: 21px;
}
.guide-lead {
line-height: 1.8;
}
.guide-section figure {
margin: 20px 0;
}
.guide-section .el-image {
display: block;
width: 100%;
min-height: 100px;
margin: 0 auto;
border: 1px solid var(--el-border-color-lighter);
border-radius: 6px;
}
.guide-section figcaption {
margin-top: 8px;
font-size: 12px;
color: var(--el-text-color-secondary);
text-align: center;
}
.guide-section ul {
padding-left: 22px;
line-height: 1.9;
}
.guide-section li {
margin-bottom: 12px;
overflow-wrap: anywhere;
}
.guide-section pre {
padding: 16px;
overflow-x: auto;
font-size: 12px;
line-height: 1.8;
white-space: pre-wrap;
background: var(--el-fill-color-light);
border-radius: 6px;
}
.image-error {
padding: 24px;
color: var(--el-text-color-secondary);
text-align: center;
}
.guide-footer {
padding: 20px 0 32px;
line-height: 1.8;
}
.guide-footer p {
color: var(--el-text-color-secondary);
}
@media (width <= 900px) {
.guide-layout {
grid-template-rows: auto minmax(0, 1fr);
grid-template-columns: 1fr;
gap: 16px;
}
.guide-toc {
max-height: 140px;
}
.guide-heading {
flex-direction: column;
gap: 8px;
margin-bottom: 12px;
}
.guide-heading h1 {
font-size: 22px;
}
.guide-heading p {
margin: 0;
font-size: 12px;
}
.guide-section {
padding: 16px;
}
}
.guide-actions {
display: flex;
flex-wrap: wrap;
gap: 10px;
align-items: center;
}
.guide-action {
display: inline-flex;
align-items: center;
justify-content: center;
min-height: 34px;
padding: 7px 12px;
font-size: 13px;
line-height: 1.5;
color: var(--el-color-primary);
text-decoration: none;
border: 1px solid var(--el-border-color);
border-radius: 5px;
}
.guide-action.primary {
color: white;
background: var(--el-color-primary);
border-color: var(--el-color-primary);
}
.guide-action:hover {
filter: brightness(0.95);
}
.guide-action:focus-visible {
outline: 2px solid var(--el-color-primary);
outline-offset: 3px;
}
.guide-footer a:not(.guide-action) {
color: var(--el-color-primary);
text-decoration: underline;
}
</style>
+107
View File
@@ -0,0 +1,107 @@
/** 对白、叙述、旧消息与累计流式文本的格式回归,不依赖浏览器或真实模型。 */
import test from "node:test";
import assert from "node:assert/strict";
import { parseDigitalMessage as parse } from "../src/utils/digital-message-format.ts";
test("标准消息按剧情顺序拆分叙述、对白与心理,隐藏星号并保留引号", () => {
assert.deepEqual(parse("*她合上书。*\n\n“你来了。”\n\n*她终于放松下来。*"), [
{ kind: "narration", text: "她合上书。" },
{ kind: "dialogue", text: "“你来了。”" },
{ kind: "narration", text: "她终于放松下来。" }
]);
});
test("旧消息的成对括号与括号外对白兼容,内层括号不会提前关闭叙述", () => {
assert.deepEqual(
parse(
"(她抱起书(封面有些旧),笑了笑)你来了。\n(她心里有些高兴)坐吧。"
),
[
{ kind: "narration", text: "她抱起书(封面有些旧),笑了笑" },
{ kind: "dialogue", text: "你来了。" },
{ kind: "narration", text: "她心里有些高兴" },
{ kind: "dialogue", text: "坐吧。" }
]
);
});
test("旧开场白的无标记叙述与引号对白分别展示,英文撇号不作为对白", () => {
assert.deepEqual(
parse('She picked up her book.\n"You’re early. Don\'t wait outside."'),
[
{ kind: "narration", text: "She picked up her book." },
{ kind: "dialogue", text: '"You’re early. Don\'t wait outside."' }
]
);
for (const [open, close] of [
["“", "”"],
["「", "」"],
["『", "』"],
["«", "»"],
[""", """]
]) {
assert.deepEqual(parse(`${open}你好${close}`), [
{ kind: "dialogue", text: `${open}你好${close}` }
]);
}
});
test("纯文本、普通备注、乘法与不完整的历史标记保留原文", () => {
for (const text of [
"普通文本",
"说明(选填)",
"3 * 4 = 12",
"file*name.txt",
"*未闭合",
"(未闭合"
]) {
assert.deepEqual(parse(text), [{ kind: "plain", text }]);
}
assert.deepEqual(parse(" \n\r\n"), []);
assert.deepEqual(parse("第一段\r\n\r\n第二段"), [
{ kind: "plain", text: "第一段" },
{ kind: "plain", text: "第二段" }
]);
});
test("显式叙述里的引号保持为故事文本,不再二次推断", () => {
assert.deepEqual(parse("*她想到“明天”这个词,轻轻笑了。*"), [
{ kind: "narration", text: "她想到“明天”这个词,轻轻笑了。" }
]);
assert.deepEqual(parse("**“你好。”**"), [
{ kind: "dialogue", text: "“你好。”" }
]);
assert.deepEqual(parse("\\*字面星号\\*"), [
{ kind: "plain", text: "*字面星号*" }
]);
});
test("累计流式输入的每个字符前缀都隐藏未闭合星号,完成态排版相同", () => {
const source = "*她推开门。*\n\n“你来了。”\n\n*她松了口气。*";
for (let end = 1; end <= source.length; end++) {
const blocks = parse(source.slice(0, end), true);
assert.equal(
blocks.some(block => block.text.includes("*")),
false,
`前缀 ${end}`
);
}
assert.deepEqual(parse(source, true), parse(source));
assert.deepEqual(parse("*她推开门", true), [
{ kind: "narration", text: "她推开门" }
]);
assert.deepEqual(parse("(她推开门", true), [
{ kind: "narration", text: "她推开门" }
]);
assert.deepEqual(parse("“你来了", true), [
{ kind: "dialogue", text: "“你来了" }
]);
assert.deepEqual(parse("**Hello", true), [
{ kind: "dialogue", text: "Hello" }
]);
});
test("HTML 与脚本内容只作为文本保留,格式解析不会生成任何标签", () => {
const text = "<script>globalThis.injected = true</script>";
assert.deepEqual(parse(text), [{ kind: "plain", text }]);
});