| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276 |
- // ============================================================================
- // [F-1111-05 · SC-P-46/SC-T-05 · 能力键 teacher.plan.activate · TC-T-05*]
- // 三流(功能 / 异常 / 权限)e2e 契约用例 —— 方案激活拆任务(幂等)
- // 缺口来源:docs/tdd/orchestration/discovery-2026-11-30-1111.md F-1111-05
- // (台账 TC-T-05 e2e 栏指向的 ai-plan-task-flow.spec.js 实际只触达 /api/ai/chat/send,
- // 未触达本端点,有效覆盖缺失;D-04 归 plan.ai.generate,本 spec 归 teacher.plan.activate,不重复)
- // ----------------------------------------------------------------------------
- // 接口(API_REFERENCE.md L2397;PlanReviewController L125–146):
- // POST /api/guide/plans/activate {planId}
- // 角色闸门:非规划师/非 admin → Result.error("无权限")(**code=500,真实契约**,非 403);
- // 认证闸门:role=teacher 时 PlannerCertificationGuard.assertCertified(userId, 'planner'),
- // 未完成 planner 培训认证 → 403「规划师未完成【planner】培训认证,暂不可提供该类服务」;
- // admin 角色豁免认证闸门(S-cfc-180 口径);
- // 状态守卫(PlanActivationService.activate → IllegalStateException → 500):
- // 方案不存在 → 500「方案不存在」;status≠'reviewed' → 500「方案状态异常,需要先审核通过」;
- // 成员不存在(users/family_members 双 ID 域均查不到)→ 500「成员不存在」;
- // 成功:TaskPlanService.generateTasksFromTemplate(1 引导任务 + N 模板任务,
- // **幂等**:tasks 中 source_type='plan' AND source_id=planId 已有非 cancelled 行则跳过生成)
- // + 方案置 active + activated_at/total_days/completed_days 留痕;返回 data='方案已激活'
- // (注意:controller 调 Result.success(String) 重载被 Java 解析为 1 参 generic 版,
- // 实际 message='success'、data='方案已激活' —— 真实契约,按探针实测断言)
- //
- // 契约来源(已逐条核对后端实现,只读,不改生产源码):
- // cfc-backend/.../controller/guide/PlanReviewController.java L125–146
- // cfc-backend/.../service/PlanActivationService.java(状态守卫 + 成员双 ID 域)
- // cfc-backend/.../service/TaskPlanService.java generateTasksFromTemplate(幂等跳过)
- // cfc-backend/.../service/PlannerCertificationGuard.java(403 认证闸门)
- //
- // 真实契约探针(_probe_plan_activate.spec.js,gitignore,本地 127.0.0.1:9082 + 测试库 192.168.16.251/zxyj 实测):
- // ① reviewed→active:code=200,data='方案已激活';tasks 生成 1 引导 + 2 模板 = 3 条
- // (source_type='plan'、source_id=planId、executor=member、family 归属正确);方案 status='active';
- // ② 幂等:再次 activate 同一方案 → 500「方案状态异常,需要先审核通过」(状态守卫拦截),
- // tasks 数量保持 3 不重复生成;
- // ③ 非 reviewed(generated/active)→ 500「方案状态异常,需要先审核通过」;
- // ④ 越权(台账「越权 403」口径)实测分两条路径:
- // - 非规划师角色(parent 等)→ code=500「无权限」(角色闸门,Result.error(String)=500 口径,
- // **非 403**;台账/文档「403」表述与实现不一致,本 spec 按探针真实契约严格断言并登记差异,不放水不判红);
- // - 规划师未认证(teacher 无 planner certified)→ code=403「规划师未完成【planner】培训认证,暂不可提供该类服务」
- // (PlannerCertificationGuard,S-cfc-180 认证闸门);
- // ⑤ 匿名(无 token)→ http=200 code=500「无权限」(guide 族未列匿名 401 强制,降级匿名后角色闸门拒绝)。
- //
- // 方案构造:后端无「创建 reviewed 方案」的 HTTP 端点供 e2e 直接调用(/api/guide/plans/review 需 generated 态
- // 方案且属审核流),本 spec 经 mysql CLI 直接 seed task_plan_instances + admin_task_templates +
- // task_template_items(marker 前缀 QA- 便于清理),不改生产源码、不改台账。
- // mysql CLI 不可用时本 spec 明确失败(不造绿)。
- //
- // 运行:
- // 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 \
- // npx playwright test api/plan-activate-contract.spec.js -c playwright.config.api.js --project=desktop
- // 安全约定:不打印 token / 手机号;测试数据自建自清(cleanupPlans)。
- // ============================================================================
- const { test, expect } = require('@playwright/test');
- const { execFileSync } = require('child_process');
- const { apiPost } = require('../helpers/api');
- async function register(request, role, tag) {
- const phone = '13' + String(Math.floor(Math.random() * 900000000) + 100000000);
- let lastErr;
- for (let i = 0; i < 3; i++) {
- try {
- const r = await request.post('/api/auth/direct-register', {
- data: { phone, role, nickname: 'QA-' + tag },
- timeout: 60000,
- });
- const body = await r.json().catch(() => ({}));
- if (body.code === 200 && body.data && body.data.token) {
- return { token: body.data.token, userId: body.data.userId, familyId: body.data.familyId, role: body.data.role };
- }
- lastErr = body;
- } catch (e) {
- lastErr = e && e.message ? e.message : String(e);
- }
- }
- throw new Error('register(' + role + ') 失败: ' + JSON.stringify(lastErr));
- }
- // ---------- mysql CLI(测试库约定;不可用即失败,不造绿) ----------
- const MYSQL_CLI = process.env.MYSQL_CLI || 'mysql';
- const MYSQL_HOST = process.env.MYSQL_HOST || '192.168.16.251';
- const MYSQL_PORT = process.env.MYSQL_PORT || '3306';
- const MYSQL_USER = process.env.MYSQL_USER || 'zxyj';
- const MYSQL_PASS = process.env.MYSQL_PASS != null ? process.env.MYSQL_PASS : 'zxyj@123';
- const MYSQL_DB = process.env.MYSQL_DB || 'zxyj';
- function sqlStr(s) {
- return "'" + String(s == null ? '' : s).replace(/\\/g, '\\\\').replace(/'/g, "''").replace(/\0/g, '') + "'";
- }
- function mysqlExec(sql) {
- const args = ['-h', MYSQL_HOST, '-P', MYSQL_PORT, '-u', MYSQL_USER];
- if (MYSQL_PASS !== '') args.push('-p' + MYSQL_PASS);
- // 实测该 mysql 客户端 --default-character-set 不生效(连接恒 latin1),每会话显式 SET NAMES utf8mb4
- args.push('-N', '-B', MYSQL_DB);
- return execFileSync(MYSQL_CLI, args, { input: 'SET NAMES utf8mb4;\n' + sql + ';\n', encoding: 'utf8', timeout: 30000 });
- }
- function oneNum(sql) {
- const out = mysqlExec(sql + ';').trim();
- const lines = out.split('\n').map(function (l) { return l.trim(); }).filter(function (l) { return l !== ''; });
- for (const line of lines) { if (/^\d+$/.test(line)) return Number(line); }
- return null;
- }
- /**
- * seed 一套隔离方案数据:新套餐(admin_task_templates)+ 2 条模板项 + 方案行(status 可指定)。
- * 生成任务数确定:1 引导 + 2 模板 = 3。
- */
- function seedPlan(familyId, memberId, status, marker) {
- const pkgTitle = marker + '-pkg';
- mysqlExec(
- 'INSERT INTO admin_task_templates (title, description, points, category, is_active, created_at, updated_at) VALUES (' +
- sqlStr(pkgTitle) + ', ' + sqlStr(marker + ' 套餐') + ', 2, ' + sqlStr('成长') + ', 1, NOW(), NOW())',
- );
- const packageId = oneNum('SELECT id FROM admin_task_templates WHERE title=' + sqlStr(pkgTitle) + ' LIMIT 1');
- if (packageId == null) throw new Error('seedPlan 套餐 seed 失败 title=' + pkgTitle);
- mysqlExec(
- "INSERT INTO task_template_items (package_id, task_name, description, points, frequency, duration, is_required, sort_order, created_at, updated_at) VALUES (" +
- Number(packageId) + ', ' + sqlStr(marker + '-模板任务1') + ', ' + sqlStr(marker + ' 描述') + ", 2, 'daily', 30, 0, 1, NOW(), NOW()), (" +
- Number(packageId) + ', ' + sqlStr(marker + '-模板任务2') + ', ' + sqlStr(marker + ' 描述') + ", 2, 'weekly', 15, 0, 2, NOW(), NOW())",
- );
- const planName = marker + '-plan';
- mysqlExec(
- 'INSERT INTO task_plan_instances (package_id, family_id, child_id, name, start_date, end_date, status, source, created_at, updated_at) VALUES (' +
- Number(packageId) + ', ' + Number(familyId) + ', ' + Number(memberId) + ', ' + sqlStr(planName) +
- ", CURDATE(), DATE_ADD(CURDATE(), INTERVAL 14 DAY), " + sqlStr(status) + ", 'manual', NOW(), NOW())",
- );
- const planId = oneNum('SELECT id FROM task_plan_instances WHERE package_id=' + Number(packageId) + ' ORDER BY id DESC LIMIT 1');
- if (planId == null) throw new Error('seedPlan 方案 seed 失败 planName=' + planName);
- return { planId: planId, packageId: packageId, planName: planName, marker: marker };
- }
- function cleanupPlans(plans) {
- const list = (plans || []).filter(Boolean).map(function (p) { return p.planId; }).map(String).join(',');
- if (list !== '') {
- mysqlExec('DELETE FROM tasks WHERE source_type=' + sqlStr('plan') + ' AND source_id IN (' + list + ')');
- mysqlExec('DELETE FROM task_plan_instances WHERE id IN (' + list + ')');
- }
- const pkgs = (plans || []).filter(Boolean).map(function (p) { return p.packageId; }).map(String).join(',');
- if (pkgs !== '') {
- mysqlExec('DELETE FROM task_template_items WHERE package_id IN (' + pkgs + ')');
- mysqlExec('DELETE FROM admin_task_templates WHERE id IN (' + pkgs + ')');
- }
- }
- function planTaskRows(planId) {
- const out = mysqlExec('SELECT COUNT(*) FROM tasks WHERE source_type=' + sqlStr('plan') + ' AND source_id=' + Number(planId)).trim();
- const lines = out.split('\n').map(function (l) { return l.trim(); }).filter(function (l) { return l !== ''; });
- for (const line of lines) { if (/^\d+$/.test(line)) return Number(line); }
- throw new Error('planTaskRows 读取失败 planId=' + planId + ' raw=' + JSON.stringify(out));
- }
- // ============================================================================
- // F-1111-05 · /api/guide/plans/activate(三流)
- // ============================================================================
- test.describe.serial('F-1111-05 · /api/guide/plans/activate(三流)', () => {
- test.setTimeout(180000);
- // -------------------------------------------------------------------------
- // 正常流 TC-T-05(reviewed→active 拆任务 + 幂等不重复生成)
- // -------------------------------------------------------------------------
- test('[功能] reviewed→active 拆任务(引导+模板),幂等不重复生成;留痕 status/activated_at', async ({ request }) => {
- const admin = await register(request, 'admin', 'pa-fn-admin');
- const owner = await register(request, 'parent', 'pa-fn-owner');
- const m = 'QApa' + Date.now() % 100000;
- const p1 = seedPlan(owner.familyId, owner.userId, 'reviewed', m + '-a');
- const p2 = seedPlan(owner.familyId, owner.userId, 'reviewed', m + '-b');
- try {
- // admin 激活 reviewed 方案(认证闸门豁免 S-cfc-180)
- const act = await apiPost(request, '/api/guide/plans/activate', { planId: p1.planId }, admin.token);
- expect(act.status, 'activate 不500').toBe(200);
- expect(act.code, 'activate code=200, 实际=' + act.code + ' msg=' + act.message).toBe(200);
- expect(act.data, '成功返回 data=方案已激活(真实契约:message 走 success 重载)').toBe('方案已激活');
- // 拆任务:1 引导 + 2 模板 = 3 条(source_type=plan、source_id=方案ID、归属家庭/执行成员)
- const n = planTaskRows(p1.planId);
- expect(n, '生成 1 引导 + 2 模板 = 3 条任务, 实际=' + n).toBe(3);
- const titles = mysqlExec(
- 'SELECT title FROM tasks WHERE source_type=' + sqlStr('plan') + ' AND source_id=' + Number(p1.planId) + " ORDER BY title",
- ).trim();
- expect(String(titles).indexOf('方案启动: ' + p1.planName) >= 0, '引导任务「方案启动: <方案名>」').toBe(true);
- expect(String(titles).indexOf(m + '-a-模板任务1') >= 0, '模板任务1 已拆出').toBe(true);
- expect(String(titles).indexOf(m + '-a-模板任务2') >= 0, '模板任务2 已拆出').toBe(true);
- 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));
- expect(taskOwner, '任务归属家庭 + 执行成员留痕').toBe(3);
- // 方案状态流转:reviewed→active + activated_at 留痕
- const planActive = oneNum("SELECT 1 FROM task_plan_instances WHERE id=" + Number(p1.planId) + " AND status='active' AND activated_at IS NOT NULL");
- expect(planActive, '方案 status=active 且 activated_at 留痕').toBe(1);
- // 幂等不重复生成:再激活同一方案 → 状态守卫 500,任务数保持 3
- const again = await apiPost(request, '/api/guide/plans/activate', { planId: p1.planId }, admin.token);
- expect(again.code, '重复激活→500 状态守卫, 实际=' + again.code + ' msg=' + again.message).toBe(500);
- expect(again.message).toBe('方案状态异常,需要先审核通过');
- expect(planTaskRows(p1.planId), '幂等:任务数不重复生成(保持 3)').toBe(3);
- } finally {
- cleanupPlans([p1, p2]);
- }
- });
- // -------------------------------------------------------------------------
- // 异常流 TC-T-05-E(状态守卫 / 参数 / 不存在)
- // -------------------------------------------------------------------------
- test('[异常] 非 reviewed 拦截(generated/active)→500;缺 planId→500;方案不存在→500', async ({ request }) => {
- const admin = await register(request, 'admin', 'pa-exc-admin');
- const owner = await register(request, 'parent', 'pa-exc-owner');
- const m = 'QApa' + (Date.now() % 100000);
- const pGen = seedPlan(owner.familyId, owner.userId, 'generated', m + '-g');
- const pAct = seedPlan(owner.familyId, owner.userId, 'active', m + '-c');
- try {
- const r1 = await apiPost(request, '/api/guide/plans/activate', { planId: pGen.planId }, admin.token);
- expect(r1.code, 'generated(未审核)拦截→500, 实际=' + r1.code + ' msg=' + r1.message).toBe(500);
- expect(r1.message).toBe('方案状态异常,需要先审核通过');
- expect(planTaskRows(pGen.planId), '未审核方案不生成任务').toBe(0);
- const r2 = await apiPost(request, '/api/guide/plans/activate', { planId: pAct.planId }, admin.token);
- expect(r2.code, '已 active 再激活拦截→500, 实际=' + r2.code).toBe(500);
- expect(r2.message).toBe('方案状态异常,需要先审核通过');
- const r3 = await apiPost(request, '/api/guide/plans/activate', {}, admin.token);
- expect(r3.code, '缺 planId→500, 实际=' + r3.code + ' msg=' + r3.message).toBe(500);
- expect(r3.message).toBe('planId required');
- const r4 = await apiPost(request, '/api/guide/plans/activate', { planId: 99999999 }, admin.token);
- expect(r4.code, '方案不存在→500, 实际=' + r4.code).toBe(500);
- expect(r4.message).toBe('方案不存在');
- } finally {
- cleanupPlans([pGen, pAct]);
- }
- });
- // -------------------------------------------------------------------------
- // 权限流 TC-T-05-P(角色闸门 / 认证闸门 / 匿名)
- // -------------------------------------------------------------------------
- test('[权限] 非规划师→500「无权限」(真实契约非 403,已登记差异);未认证规划师→403;匿名→500「无权限」', async ({ request }) => {
- const admin = await register(request, 'admin', 'pa-perm-admin');
- const parent = await register(request, 'parent', 'pa-perm-parent');
- const teacher = await register(request, 'teacher', 'pa-perm-teacher'); // direct-register 无 planner 认证记录
- const m = 'QApa' + (Date.now() % 100000);
- const p1 = seedPlan(parent.familyId, parent.userId, 'reviewed', m + '-p');
- try {
- // ① 非规划师角色(parent):角色闸门拒绝。
- // 台账「越权 403」口径 vs 实现:Result.error("无权限")=500(探针实测)。
- // 按真实契约严格断言(不放水成 200、也不误判 403),差异已在文件头登记。
- const rParent = await apiPost(request, '/api/guide/plans/activate', { planId: p1.planId }, parent.token);
- expect(rParent.status, 'parent 越权不 5xx HTTP').toBe(200);
- expect(rParent.code, '非规划师→500「无权限」(真实契约), 实际=' + rParent.code + ' msg=' + rParent.message).toBe(500);
- expect(rParent.message).toBe('无权限');
- expect(planTaskRows(p1.planId), '越权不生成任务').toBe(0);
- // ② 规划师未完成 planner 培训认证 → 认证闸门 403(PlannerCertificationGuard)
- const rTeacher = await apiPost(request, '/api/guide/plans/activate', { planId: p1.planId }, teacher.token);
- expect(rTeacher.status, 'teacher 未认证不 5xx HTTP').toBe(200);
- expect(rTeacher.code, '未认证规划师→403, 实际=' + rTeacher.code + ' msg=' + rTeacher.message).toBe(403);
- expect(rTeacher.message, '认证闸门提示').toContain('planner');
- expect(planTaskRows(p1.planId), '未认证规划师不生成任务').toBe(0);
- // ③ 匿名(无 token):降级匿名后角色闸门拒绝(guide 族非 401 强制族,真实契约)
- const anon = await request.post('/api/guide/plans/activate', { data: { planId: p1.planId }, timeout: 30000 });
- const anonBody = await anon.json().catch(() => ({}));
- expect(anon.status(), '匿名 activate http=200(降级匿名,非 401), 实际=' + anon.status()).toBe(200);
- expect(anonBody.code, '匿名→500「无权限」, 实际=' + anonBody.code + ' msg=' + anonBody.message).toBe(500);
- expect(anonBody.message).toBe('无权限');
- // 方案状态未被越权请求改写(仍 reviewed)
- const stillReviewed = oneNum('SELECT 1 FROM task_plan_instances WHERE id=' + Number(p1.planId) + " AND status='reviewed'");
- expect(stillReviewed, '越权/未认证请求未改写方案状态').toBe(1);
- } finally {
- cleanupPlans([p1]);
- }
- });
- });
- // 安全约定:本文件不打印 token / 手机号;测试数据结束时清理(cleanupPlans)。
|