import { resolve } from 'node:path' import { pathToFileURL } from 'node:url' import { randomUUID } from 'node:crypto' /** * 使用正常登录创建独立迭代阶段演示;已有同名项目只读取,不重置用户修改。 * @param {string} base 开发服务地址 * @param {string} name 独立演示项目名称 * @param {Function} [prepare] 可选示例筹备回调,在 PLANNED 阶段创建子任务等配置,执行前调用 * @returns {Promise} 显式迭代、完整分页工作项和服务端阶段摘要 */ export async function seedFlowView(base = process.env.PM_BASE_URL || 'http://127.0.0.1:8091', name = '项目阶段与流程视图示例', prepare) { let token = process.env.PM_TOKEN if (!token) { if (!process.env.PM_PASSWORD) throw new Error('请配置 PM_PASSWORD 或已有 PM_TOKEN;脚本不输出凭据或绕过验证码') const response = await fetch(base + '/login', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ username: process.env.PM_USER || 'admin', password: process.env.PM_PASSWORD, code: '', uuid: '' }) }) const login = await response.json(); if (!response.ok || login.code !== 200) throw new Error(login.msg || '登录失败') token = login.token } /** 所有示例通过真实受鉴权接口提交,不直接写数据库或指定生命周期。 */ async function call(path, method = 'GET', input) { const response = await fetch(base + '/project/manage' + path, { method, headers: { Authorization: 'Bearer ' + token, 'Content-Type': 'application/json' }, body: input === undefined ? undefined : JSON.stringify(input) }) const body = await response.json(); if (!response.ok || body.code !== 200) throw new Error(body.message || body.msg || '业务请求失败') return body.data } /** 工作项从显式迭代 flat 分页读取,flow-view 仅包含阶段摘要,不再内嵌任务明细。 */ async function listItems(projectId, iterationId) { const result = [] for (let page = 1; ; page++) { const data = await call(`/projects/${projectId}/iterations/${iterationId}/items?view=flat&page=${page}&pageSize=200`) result.push(...data.rows) if (!data.rows.length || result.length >= data.total) return result } } let project = (await call('/projects')).find(p => p.name === name) if (project) { const iterations = await call(`/projects/${project.id}/iterations?includeArchived=true`) const iteration = iterations.find(candidate => candidate.code === 'FLOW-DEMO') || iterations.find(candidate => candidate.code === 'LEGACY-DEFAULT') if (!iteration) throw new Error('同名项目没有对应演示迭代;请改用新的示例项目名称,脚本不会改写既有项目') return { base, token, project, iteration, call, created: false, items: await listItems(project.id, iteration.id), view: await call(`/projects/${project.id}/iterations/${iteration.id}/flow-view`) } } const spaces = await call('/spaces') const spaceId = spaces.find(space => space.name === '流程视图演示' && space.canCreateProject)?.id || await call('/spaces', 'POST', { name: '流程视图演示' }) const id = await call('/projects', 'POST', { name, spaceId }); project = (await call('/projects')).find(p => p.id === id) let iteration = await call(`/projects/${id}/iterations`, 'POST', { code: 'FLOW-DEMO', name: '阶段流程示例迭代', goal: '展示显式阶段门禁与任务 AND 前置。', sortOrder: 0, idempotencyKey: randomUUID() }) const scope = `/projects/${id}/iterations/${iteration.id}` const stageIds = {} const labels = ['需求分析', '方案设计', '研发实施', '测试验收', '发布'] for (const [index, label] of labels.entries()) stageIds[label] = await call(`${scope}/stages`, 'POST', { name: label, sortOrder: index * 10, ownerId: project.creatorId, description: '展示顺序只负责组织;显式阶段连线决定执行门禁。' }) // 新阶段不再根据排序自动连线,演示必须明确创建当前迭代内部的执行链。 for (let index = 1; index < labels.length; index++) await call(`${scope}/stage-edges`, 'POST', { predecessorStageId: stageIds[labels[index - 1]], successorStageId: stageIds[labels[index]] }) /** 工作项时间遵守真实依赖约束,需求/缺陷只显示分组,不创建无效依赖。 */ async function item(type, title, stage, start, end) { return call(`${scope}/items`, 'POST', { type, title, description: '流程视图展示阶段摘要,阶段抽屉查看任务及前置。', assigneeId: project.creatorId, priority: 'MEDIUM', stageId: stageIds[stage], plannedStartAt: start ? start + 'T09:00:00+08:00' : null, plannedEndAt: end ? end + 'T18:00:00+08:00' : null }) } const requirement = await item('REQUIREMENT', '需求:客户门户升级', '需求分析', '2026-10-19', '2026-10-20') const design = await item('TASK', '技术方案设计', '方案设计', '2026-10-21', '2026-10-22') const frontend = await item('TASK', '前端页面开发', '研发实施', '2026-10-23', '2026-10-25') const backend = await item('TASK', '接口开发', '研发实施', '2026-10-23', '2026-10-25') const testing = await item('TASK', '联调与验收测试', '测试验收', '2026-10-26', '2026-10-27') await item('BUG', '缺陷:旧页面兼容性', '测试验收', null, null) const release = await item('TASK', '版本发布', '发布', '2026-10-28', '2026-10-28') /** 添加任务边使用最新后续版本,所有开始和完成仍调用统一服务入口。 */ async function dependency(source, target) { const latest = await call('/items/' + target); await call('/items/' + target + '/dependencies', 'POST', { conditionType: 'TASK_COMPLETED', predecessorTaskId: source, taskVersion: latest.version }) } await dependency(design, frontend); await dependency(design, backend); await dependency(frontend, testing); await dependency(backend, testing); await dependency(testing, release) if (prepare) await prepare({ project, iteration, call, scope, items: await listItems(id, iteration.id) }) iteration = await call(scope) iteration = await call(`${scope}/activate`, 'POST', { version: iteration.version, graphVersion: iteration.graphVersion, idempotencyKey: randomUUID() }) // 先形成上游阶段真实完成事实,再开始后继任务;不靠排序或伪造状态绕过阶段门禁。 await call('/items/' + requirement + '/start', 'POST', { version: (await call('/items/' + requirement)).version }) await call('/items/' + requirement + '/transition', 'POST', { status: 'COMPLETED', version: (await call('/items/' + requirement)).version }) await call('/items/' + design + '/start', 'POST', { version: (await call('/items/' + design)).version }) await call('/items/' + design + '/transition', 'POST', { status: 'COMPLETED', version: (await call('/items/' + design)).version }) await call('/items/' + frontend + '/start', 'POST', { version: (await call('/items/' + frontend)).version }) return { base, token, project, iteration, call, created: true, items: await listItems(id, iteration.id), view: await call(`${scope}/flow-view`) } } if (process.argv[1] && import.meta.url === pathToFileURL(resolve(process.argv[1])).href) { const demo = await seedFlowView() console.log(JSON.stringify({ projectId: demo.project.id, projectName: demo.project.name, iterationId: demo.iteration.id, stages: demo.view.stages.length, stageEdges: demo.view.stageEdges.length, items: demo.items.length, dependencies: demo.items.reduce((count, item) => count + (item.dependencyConditions?.length || 0), 0), frontendPath: `/project/collaboration?projectId=${demo.project.id}&iterationId=${demo.iteration.id}` })) }