plan-activate-contract.spec.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276
  1. // ============================================================================
  2. // [F-1111-05 · SC-P-46/SC-T-05 · 能力键 teacher.plan.activate · TC-T-05*]
  3. // 三流(功能 / 异常 / 权限)e2e 契约用例 —— 方案激活拆任务(幂等)
  4. // 缺口来源:docs/tdd/orchestration/discovery-2026-11-30-1111.md F-1111-05
  5. // (台账 TC-T-05 e2e 栏指向的 ai-plan-task-flow.spec.js 实际只触达 /api/ai/chat/send,
  6. // 未触达本端点,有效覆盖缺失;D-04 归 plan.ai.generate,本 spec 归 teacher.plan.activate,不重复)
  7. // ----------------------------------------------------------------------------
  8. // 接口(API_REFERENCE.md L2397;PlanReviewController L125–146):
  9. // POST /api/guide/plans/activate {planId}
  10. // 角色闸门:非规划师/非 admin → Result.error("无权限")(**code=500,真实契约**,非 403);
  11. // 认证闸门:role=teacher 时 PlannerCertificationGuard.assertCertified(userId, 'planner'),
  12. // 未完成 planner 培训认证 → 403「规划师未完成【planner】培训认证,暂不可提供该类服务」;
  13. // admin 角色豁免认证闸门(S-cfc-180 口径);
  14. // 状态守卫(PlanActivationService.activate → IllegalStateException → 500):
  15. // 方案不存在 → 500「方案不存在」;status≠'reviewed' → 500「方案状态异常,需要先审核通过」;
  16. // 成员不存在(users/family_members 双 ID 域均查不到)→ 500「成员不存在」;
  17. // 成功:TaskPlanService.generateTasksFromTemplate(1 引导任务 + N 模板任务,
  18. // **幂等**:tasks 中 source_type='plan' AND source_id=planId 已有非 cancelled 行则跳过生成)
  19. // + 方案置 active + activated_at/total_days/completed_days 留痕;返回 data='方案已激活'
  20. // (注意:controller 调 Result.success(String) 重载被 Java 解析为 1 参 generic 版,
  21. // 实际 message='success'、data='方案已激活' —— 真实契约,按探针实测断言)
  22. //
  23. // 契约来源(已逐条核对后端实现,只读,不改生产源码):
  24. // cfc-backend/.../controller/guide/PlanReviewController.java L125–146
  25. // cfc-backend/.../service/PlanActivationService.java(状态守卫 + 成员双 ID 域)
  26. // cfc-backend/.../service/TaskPlanService.java generateTasksFromTemplate(幂等跳过)
  27. // cfc-backend/.../service/PlannerCertificationGuard.java(403 认证闸门)
  28. //
  29. // 真实契约探针(_probe_plan_activate.spec.js,gitignore,本地 127.0.0.1:9082 + 测试库 192.168.16.251/zxyj 实测):
  30. // ① reviewed→active:code=200,data='方案已激活';tasks 生成 1 引导 + 2 模板 = 3 条
  31. // (source_type='plan'、source_id=planId、executor=member、family 归属正确);方案 status='active';
  32. // ② 幂等:再次 activate 同一方案 → 500「方案状态异常,需要先审核通过」(状态守卫拦截),
  33. // tasks 数量保持 3 不重复生成;
  34. // ③ 非 reviewed(generated/active)→ 500「方案状态异常,需要先审核通过」;
  35. // ④ 越权(台账「越权 403」口径)实测分两条路径:
  36. // - 非规划师角色(parent 等)→ code=500「无权限」(角色闸门,Result.error(String)=500 口径,
  37. // **非 403**;台账/文档「403」表述与实现不一致,本 spec 按探针真实契约严格断言并登记差异,不放水不判红);
  38. // - 规划师未认证(teacher 无 planner certified)→ code=403「规划师未完成【planner】培训认证,暂不可提供该类服务」
  39. // (PlannerCertificationGuard,S-cfc-180 认证闸门);
  40. // ⑤ 匿名(无 token)→ http=200 code=500「无权限」(guide 族未列匿名 401 强制,降级匿名后角色闸门拒绝)。
  41. //
  42. // 方案构造:后端无「创建 reviewed 方案」的 HTTP 端点供 e2e 直接调用(/api/guide/plans/review 需 generated 态
  43. // 方案且属审核流),本 spec 经 mysql CLI 直接 seed task_plan_instances + admin_task_templates +
  44. // task_template_items(marker 前缀 QA- 便于清理),不改生产源码、不改台账。
  45. // mysql CLI 不可用时本 spec 明确失败(不造绿)。
  46. //
  47. // 运行:
  48. // CFC_API_BASE=http://127.0.0.1:9082 MYSQL_HOST=192.168.16.251 MYSQL_USER=zxyj MYSQL_PASS=zxyj@123 MYSQL_DB=zxyj \
  49. // npx playwright test api/plan-activate-contract.spec.js -c playwright.config.api.js --project=desktop
  50. // 安全约定:不打印 token / 手机号;测试数据自建自清(cleanupPlans)。
  51. // ============================================================================
  52. const { test, expect } = require('@playwright/test');
  53. const { execFileSync } = require('child_process');
  54. const { apiPost } = require('../helpers/api');
  55. async function register(request, role, tag) {
  56. const phone = '13' + String(Math.floor(Math.random() * 900000000) + 100000000);
  57. let lastErr;
  58. for (let i = 0; i < 3; i++) {
  59. try {
  60. const r = await request.post('/api/auth/direct-register', {
  61. data: { phone, role, nickname: 'QA-' + tag },
  62. timeout: 60000,
  63. });
  64. const body = await r.json().catch(() => ({}));
  65. if (body.code === 200 && body.data && body.data.token) {
  66. return { token: body.data.token, userId: body.data.userId, familyId: body.data.familyId, role: body.data.role };
  67. }
  68. lastErr = body;
  69. } catch (e) {
  70. lastErr = e && e.message ? e.message : String(e);
  71. }
  72. }
  73. throw new Error('register(' + role + ') 失败: ' + JSON.stringify(lastErr));
  74. }
  75. // ---------- mysql CLI(测试库约定;不可用即失败,不造绿) ----------
  76. const MYSQL_CLI = process.env.MYSQL_CLI || 'mysql';
  77. const MYSQL_HOST = process.env.MYSQL_HOST || '192.168.16.251';
  78. const MYSQL_PORT = process.env.MYSQL_PORT || '3306';
  79. const MYSQL_USER = process.env.MYSQL_USER || 'zxyj';
  80. const MYSQL_PASS = process.env.MYSQL_PASS != null ? process.env.MYSQL_PASS : 'zxyj@123';
  81. const MYSQL_DB = process.env.MYSQL_DB || 'zxyj';
  82. function sqlStr(s) {
  83. return "'" + String(s == null ? '' : s).replace(/\\/g, '\\\\').replace(/'/g, "''").replace(/\0/g, '') + "'";
  84. }
  85. function mysqlExec(sql) {
  86. const args = ['-h', MYSQL_HOST, '-P', MYSQL_PORT, '-u', MYSQL_USER];
  87. if (MYSQL_PASS !== '') args.push('-p' + MYSQL_PASS);
  88. // 实测该 mysql 客户端 --default-character-set 不生效(连接恒 latin1),每会话显式 SET NAMES utf8mb4
  89. args.push('-N', '-B', MYSQL_DB);
  90. return execFileSync(MYSQL_CLI, args, { input: 'SET NAMES utf8mb4;\n' + sql + ';\n', encoding: 'utf8', timeout: 30000 });
  91. }
  92. function oneNum(sql) {
  93. const out = mysqlExec(sql + ';').trim();
  94. const lines = out.split('\n').map(function (l) { return l.trim(); }).filter(function (l) { return l !== ''; });
  95. for (const line of lines) { if (/^\d+$/.test(line)) return Number(line); }
  96. return null;
  97. }
  98. /**
  99. * seed 一套隔离方案数据:新套餐(admin_task_templates)+ 2 条模板项 + 方案行(status 可指定)。
  100. * 生成任务数确定:1 引导 + 2 模板 = 3。
  101. */
  102. function seedPlan(familyId, memberId, status, marker) {
  103. const pkgTitle = marker + '-pkg';
  104. mysqlExec(
  105. 'INSERT INTO admin_task_templates (title, description, points, category, is_active, created_at, updated_at) VALUES (' +
  106. sqlStr(pkgTitle) + ', ' + sqlStr(marker + ' 套餐') + ', 2, ' + sqlStr('成长') + ', 1, NOW(), NOW())',
  107. );
  108. const packageId = oneNum('SELECT id FROM admin_task_templates WHERE title=' + sqlStr(pkgTitle) + ' LIMIT 1');
  109. if (packageId == null) throw new Error('seedPlan 套餐 seed 失败 title=' + pkgTitle);
  110. mysqlExec(
  111. "INSERT INTO task_template_items (package_id, task_name, description, points, frequency, duration, is_required, sort_order, created_at, updated_at) VALUES (" +
  112. Number(packageId) + ', ' + sqlStr(marker + '-模板任务1') + ', ' + sqlStr(marker + ' 描述') + ", 2, 'daily', 30, 0, 1, NOW(), NOW()), (" +
  113. Number(packageId) + ', ' + sqlStr(marker + '-模板任务2') + ', ' + sqlStr(marker + ' 描述') + ", 2, 'weekly', 15, 0, 2, NOW(), NOW())",
  114. );
  115. const planName = marker + '-plan';
  116. mysqlExec(
  117. 'INSERT INTO task_plan_instances (package_id, family_id, child_id, name, start_date, end_date, status, source, created_at, updated_at) VALUES (' +
  118. Number(packageId) + ', ' + Number(familyId) + ', ' + Number(memberId) + ', ' + sqlStr(planName) +
  119. ", CURDATE(), DATE_ADD(CURDATE(), INTERVAL 14 DAY), " + sqlStr(status) + ", 'manual', NOW(), NOW())",
  120. );
  121. const planId = oneNum('SELECT id FROM task_plan_instances WHERE package_id=' + Number(packageId) + ' ORDER BY id DESC LIMIT 1');
  122. if (planId == null) throw new Error('seedPlan 方案 seed 失败 planName=' + planName);
  123. return { planId: planId, packageId: packageId, planName: planName, marker: marker };
  124. }
  125. function cleanupPlans(plans) {
  126. const list = (plans || []).filter(Boolean).map(function (p) { return p.planId; }).map(String).join(',');
  127. if (list !== '') {
  128. mysqlExec('DELETE FROM tasks WHERE source_type=' + sqlStr('plan') + ' AND source_id IN (' + list + ')');
  129. mysqlExec('DELETE FROM task_plan_instances WHERE id IN (' + list + ')');
  130. }
  131. const pkgs = (plans || []).filter(Boolean).map(function (p) { return p.packageId; }).map(String).join(',');
  132. if (pkgs !== '') {
  133. mysqlExec('DELETE FROM task_template_items WHERE package_id IN (' + pkgs + ')');
  134. mysqlExec('DELETE FROM admin_task_templates WHERE id IN (' + pkgs + ')');
  135. }
  136. }
  137. function planTaskRows(planId) {
  138. const out = mysqlExec('SELECT COUNT(*) FROM tasks WHERE source_type=' + sqlStr('plan') + ' AND source_id=' + Number(planId)).trim();
  139. const lines = out.split('\n').map(function (l) { return l.trim(); }).filter(function (l) { return l !== ''; });
  140. for (const line of lines) { if (/^\d+$/.test(line)) return Number(line); }
  141. throw new Error('planTaskRows 读取失败 planId=' + planId + ' raw=' + JSON.stringify(out));
  142. }
  143. // ============================================================================
  144. // F-1111-05 · /api/guide/plans/activate(三流)
  145. // ============================================================================
  146. test.describe.serial('F-1111-05 · /api/guide/plans/activate(三流)', () => {
  147. test.setTimeout(180000);
  148. // -------------------------------------------------------------------------
  149. // 正常流 TC-T-05(reviewed→active 拆任务 + 幂等不重复生成)
  150. // -------------------------------------------------------------------------
  151. test('[功能] reviewed→active 拆任务(引导+模板),幂等不重复生成;留痕 status/activated_at', async ({ request }) => {
  152. const admin = await register(request, 'admin', 'pa-fn-admin');
  153. const owner = await register(request, 'parent', 'pa-fn-owner');
  154. const m = 'QApa' + Date.now() % 100000;
  155. const p1 = seedPlan(owner.familyId, owner.userId, 'reviewed', m + '-a');
  156. const p2 = seedPlan(owner.familyId, owner.userId, 'reviewed', m + '-b');
  157. try {
  158. // admin 激活 reviewed 方案(认证闸门豁免 S-cfc-180)
  159. const act = await apiPost(request, '/api/guide/plans/activate', { planId: p1.planId }, admin.token);
  160. expect(act.status, 'activate 不500').toBe(200);
  161. expect(act.code, 'activate code=200, 实际=' + act.code + ' msg=' + act.message).toBe(200);
  162. expect(act.data, '成功返回 data=方案已激活(真实契约:message 走 success 重载)').toBe('方案已激活');
  163. // 拆任务:1 引导 + 2 模板 = 3 条(source_type=plan、source_id=方案ID、归属家庭/执行成员)
  164. const n = planTaskRows(p1.planId);
  165. expect(n, '生成 1 引导 + 2 模板 = 3 条任务, 实际=' + n).toBe(3);
  166. const titles = mysqlExec(
  167. 'SELECT title FROM tasks WHERE source_type=' + sqlStr('plan') + ' AND source_id=' + Number(p1.planId) + " ORDER BY title",
  168. ).trim();
  169. expect(String(titles).indexOf('方案启动: ' + p1.planName) >= 0, '引导任务「方案启动: <方案名>」').toBe(true);
  170. expect(String(titles).indexOf(m + '-a-模板任务1') >= 0, '模板任务1 已拆出').toBe(true);
  171. expect(String(titles).indexOf(m + '-a-模板任务2') >= 0, '模板任务2 已拆出').toBe(true);
  172. const taskOwner = oneNum('SELECT COUNT(*) FROM tasks WHERE source_type=' + sqlStr('plan') + " AND source_id=" + Number(p1.planId) + ' AND family_id=' + Number(owner.familyId) + " AND executor_id=" + Number(owner.userId));
  173. expect(taskOwner, '任务归属家庭 + 执行成员留痕').toBe(3);
  174. // 方案状态流转:reviewed→active + activated_at 留痕
  175. const planActive = oneNum("SELECT 1 FROM task_plan_instances WHERE id=" + Number(p1.planId) + " AND status='active' AND activated_at IS NOT NULL");
  176. expect(planActive, '方案 status=active 且 activated_at 留痕').toBe(1);
  177. // 幂等不重复生成:再激活同一方案 → 状态守卫 500,任务数保持 3
  178. const again = await apiPost(request, '/api/guide/plans/activate', { planId: p1.planId }, admin.token);
  179. expect(again.code, '重复激活→500 状态守卫, 实际=' + again.code + ' msg=' + again.message).toBe(500);
  180. expect(again.message).toBe('方案状态异常,需要先审核通过');
  181. expect(planTaskRows(p1.planId), '幂等:任务数不重复生成(保持 3)').toBe(3);
  182. } finally {
  183. cleanupPlans([p1, p2]);
  184. }
  185. });
  186. // -------------------------------------------------------------------------
  187. // 异常流 TC-T-05-E(状态守卫 / 参数 / 不存在)
  188. // -------------------------------------------------------------------------
  189. test('[异常] 非 reviewed 拦截(generated/active)→500;缺 planId→500;方案不存在→500', async ({ request }) => {
  190. const admin = await register(request, 'admin', 'pa-exc-admin');
  191. const owner = await register(request, 'parent', 'pa-exc-owner');
  192. const m = 'QApa' + (Date.now() % 100000);
  193. const pGen = seedPlan(owner.familyId, owner.userId, 'generated', m + '-g');
  194. const pAct = seedPlan(owner.familyId, owner.userId, 'active', m + '-c');
  195. try {
  196. const r1 = await apiPost(request, '/api/guide/plans/activate', { planId: pGen.planId }, admin.token);
  197. expect(r1.code, 'generated(未审核)拦截→500, 实际=' + r1.code + ' msg=' + r1.message).toBe(500);
  198. expect(r1.message).toBe('方案状态异常,需要先审核通过');
  199. expect(planTaskRows(pGen.planId), '未审核方案不生成任务').toBe(0);
  200. const r2 = await apiPost(request, '/api/guide/plans/activate', { planId: pAct.planId }, admin.token);
  201. expect(r2.code, '已 active 再激活拦截→500, 实际=' + r2.code).toBe(500);
  202. expect(r2.message).toBe('方案状态异常,需要先审核通过');
  203. const r3 = await apiPost(request, '/api/guide/plans/activate', {}, admin.token);
  204. expect(r3.code, '缺 planId→500, 实际=' + r3.code + ' msg=' + r3.message).toBe(500);
  205. expect(r3.message).toBe('planId required');
  206. const r4 = await apiPost(request, '/api/guide/plans/activate', { planId: 99999999 }, admin.token);
  207. expect(r4.code, '方案不存在→500, 实际=' + r4.code).toBe(500);
  208. expect(r4.message).toBe('方案不存在');
  209. } finally {
  210. cleanupPlans([pGen, pAct]);
  211. }
  212. });
  213. // -------------------------------------------------------------------------
  214. // 权限流 TC-T-05-P(角色闸门 / 认证闸门 / 匿名)
  215. // -------------------------------------------------------------------------
  216. test('[权限] 非规划师→500「无权限」(真实契约非 403,已登记差异);未认证规划师→403;匿名→500「无权限」', async ({ request }) => {
  217. const admin = await register(request, 'admin', 'pa-perm-admin');
  218. const parent = await register(request, 'parent', 'pa-perm-parent');
  219. const teacher = await register(request, 'teacher', 'pa-perm-teacher'); // direct-register 无 planner 认证记录
  220. const m = 'QApa' + (Date.now() % 100000);
  221. const p1 = seedPlan(parent.familyId, parent.userId, 'reviewed', m + '-p');
  222. try {
  223. // ① 非规划师角色(parent):角色闸门拒绝。
  224. // 台账「越权 403」口径 vs 实现:Result.error("无权限")=500(探针实测)。
  225. // 按真实契约严格断言(不放水成 200、也不误判 403),差异已在文件头登记。
  226. const rParent = await apiPost(request, '/api/guide/plans/activate', { planId: p1.planId }, parent.token);
  227. expect(rParent.status, 'parent 越权不 5xx HTTP').toBe(200);
  228. expect(rParent.code, '非规划师→500「无权限」(真实契约), 实际=' + rParent.code + ' msg=' + rParent.message).toBe(500);
  229. expect(rParent.message).toBe('无权限');
  230. expect(planTaskRows(p1.planId), '越权不生成任务').toBe(0);
  231. // ② 规划师未完成 planner 培训认证 → 认证闸门 403(PlannerCertificationGuard)
  232. const rTeacher = await apiPost(request, '/api/guide/plans/activate', { planId: p1.planId }, teacher.token);
  233. expect(rTeacher.status, 'teacher 未认证不 5xx HTTP').toBe(200);
  234. expect(rTeacher.code, '未认证规划师→403, 实际=' + rTeacher.code + ' msg=' + rTeacher.message).toBe(403);
  235. expect(rTeacher.message, '认证闸门提示').toContain('planner');
  236. expect(planTaskRows(p1.planId), '未认证规划师不生成任务').toBe(0);
  237. // ③ 匿名(无 token):降级匿名后角色闸门拒绝(guide 族非 401 强制族,真实契约)
  238. const anon = await request.post('/api/guide/plans/activate', { data: { planId: p1.planId }, timeout: 30000 });
  239. const anonBody = await anon.json().catch(() => ({}));
  240. expect(anon.status(), '匿名 activate http=200(降级匿名,非 401), 实际=' + anon.status()).toBe(200);
  241. expect(anonBody.code, '匿名→500「无权限」, 实际=' + anonBody.code + ' msg=' + anonBody.message).toBe(500);
  242. expect(anonBody.message).toBe('无权限');
  243. // 方案状态未被越权请求改写(仍 reviewed)
  244. const stillReviewed = oneNum('SELECT 1 FROM task_plan_instances WHERE id=' + Number(p1.planId) + " AND status='reviewed'");
  245. expect(stillReviewed, '越权/未认证请求未改写方案状态').toBe(1);
  246. } finally {
  247. cleanupPlans([p1]);
  248. }
  249. });
  250. });
  251. // 安全约定:本文件不打印 token / 手机号;测试数据结束时清理(cleanupPlans)。