// 三省六部流程推进服务方法:中书拟案、门下审核、尚书派工、尚书汇总、门下验收与丞相交付。 import { randomUUID } from 'node:crypto' import { SEATS, SEAT_GROUPS } from '../../shared/roles.js' import { emptyTask } from '../../shared/schema.js' import { cleanText } from '../../shared/utils.js' import { OPEN_TASK_STATUS, REQUIREMENT_FILL_FIELDS, ServiceError, appendLeadReport, dispatchAndFlushReport, queueDelivery, voidDelivery, } from './shared.js' import { effectiveRequirementSnapshot, handOffReviewedTask, legacyApprovalDecision, taskDecisionBlock, } from './requirement-helpers.js' /** 挂载到 SanshengService 的流程阶段流转方法集。 */ export const workflowServiceMethods = { async workflowSubmitDraft(projectId, taskId, input = {}, actor = {}) { await this.store.ensureLoaded() if (actor.seatId !== 'zhongshu') throw new ServiceError('sansheng/forbidden', '只有中书省可以提交拟案') const draft = cleanText(input.draft) if (!draft) throw new ServiceError('sansheng/invalid', '拟案内容不能为空') const fill = {} for (const field of REQUIREMENT_FILL_FIELDS) fill[field] = cleanText(input[field]) const next = await this.store.mutate(s => { const project = s.projects[projectId] if (!project) throw new ServiceError('sansheng/not-found', `项目 ${projectId} 不存在`) const task = (project.tasks ?? []).find(item => item.id === taskId) if (!task || task.kind !== 'workflow') throw new ServiceError('sansheng/not-found', `流程任务 ${taskId} 不存在`) if (task.ownerSeatId !== 'zhongshu' || task.stage !== 'zhongshu_draft' || task.status === 'done' || task.status === 'cancelled') { throw new ServiceError('sansheng/stage-forbidden', '当前任务不在中书拟案阶段,不能提交拟案') } const req = (project.requirements ?? []).find(item => item.id === task.requirementId) if (!req || req.revision !== task.requirementRevision) throw new ServiceError('sansheng/requirement-changed', '需求版本已变化,旧任务不能再推进') const now = Date.now() // 中书补缺只写任务快照:需求正文、标题、原话和版本都不动;退回重提时可改自己补的字段。 const filledFields = [] const keptFields = [] const nextFill = { ...(task.requirementFill ?? {}) } for (const field of REQUIREMENT_FILL_FIELDS) { if (!fill[field]) continue if (cleanText(req[field])) { keptFields.push(field); continue } nextFill[field] = fill[field] filledFields.push(field) } task.requirementFill = nextFill task.draft = draft task.stage = 'menxia_review' task.ownerSeatId = 'menxia' task.status = 'draft' task.blockedReason = '待门下省审核' task.lastTransitionId = randomUUID() const report = appendLeadReport(s, projectId, task, 'zhongshu_submit', draft) queueDelivery(task, 'dispatched') task.result = null task.resultAt = null task.updatedAt = now // 有效快照 = 同版本需求字段 + 中书补缺;门下、会商、批准和派发都读这一份。 task.requirementSnapshot = effectiveRequirementSnapshot(task, req) req.status = 'published' req.blockedReason = '门下省审核中' req.updatedAt = now project.updatedAt = now project.revision = (project.revision ?? 0) + 1 return { task: { ...task }, filledFields, keptFields, reportCreated: Boolean(report?.created) } }) return dispatchAndFlushReport(this, projectId, taskId, next, { filledFields: next.filledFields, keptFields: next.keptFields, }) }, async workflowReview(projectId, taskId, input = {}, actor = {}) { await this.store.ensureLoaded() if (actor.seatId !== 'menxia') throw new ServiceError('sansheng/forbidden', '只有门下省可以审核拟案') const action = cleanText(input.action) if (!['approve', 'return'].includes(action)) throw new ServiceError('sansheng/invalid', '审核动作必须是 approve 或 return') const note = cleanText(input.note) if (action === 'return' && !note) throw new ServiceError('sansheng/invalid', '退回应写明原因') const next = await this.store.mutate(s => { const project = s.projects[projectId] const task = (project.tasks ?? []).find(item => item.id === taskId) if (!task || task.kind !== 'workflow') throw new ServiceError('sansheng/not-found', `流程任务 ${taskId} 不存在`) if (task.ownerSeatId !== 'menxia' || task.stage !== 'menxia_review') throw new ServiceError('sansheng/stage-forbidden', '当前任务不在门下审核阶段') const req = (project.requirements ?? []).find(item => item.id === task.requirementId) if (!req || req.revision !== task.requirementRevision) throw new ServiceError('sansheng/requirement-changed', '需求版本已变化,旧任务不能继续审核') const now = Date.now() taskDecisionBlock(task) if (action === 'return' && task.reviewReturns) throw new ServiceError('sansheng/consultation-required', '已有一次退回,请先三省会商,有分歧交丞相') if (action === 'return') { task.reviewReturns = 1 task.stage = 'zhongshu_draft' task.ownerSeatId = 'zhongshu' task.status = 'returned' task.reviewNote = note task.blockedReason = '门下退回中书省修订' req.status = 'returned' req.blockedReason = `门下退回:${note}` } else { if (!cleanText(task.draft)) throw new ServiceError('sansheng/invalid', '中书尚未提交拟案,不能审核通过') // 执行批准使用任务上的有效快照:需求字段优先,中书补缺或退回后的修订随任务走。 const effective = effectiveRequirementSnapshot(task, req) if (!cleanText(effective.scope) || !cleanText(effective.acceptanceCriteria)) { throw new ServiceError('sansheng/requirement-incomplete', '需求缺少范围或验收标准,请退回中书省在拟案中补齐后再批准') } task.requirementSnapshot = effective if (task.executionAuthorizedAtDispatch) { handOffReviewedTask(project, task, req, now, 'menxia') } else { task.stage = 'awaiting_execution_approval' task.ownerSeatId = 'lead' task.status = 'waiting_user' task.blockedReason = '待你处理:确认旧方案是否执行' req.status = 'published' req.blockedReason = task.blockedReason task.decisions ??= [] task.decisions.push(legacyApprovalDecision(now)) } task.reviewNote = note } task.lastTransitionId = randomUUID() const report = appendLeadReport(s, projectId, task, action === 'return' ? 'menxia_return' : 'menxia_approve', note || '审核通过') queueDelivery(task, task.status) task.updatedAt = now req.updatedAt = now project.updatedAt = now project.revision = (project.revision ?? 0) + 1 return { task: { ...task }, reportCreated: Boolean(report?.created) } }) return dispatchAndFlushReport(this, projectId, taskId, next) }, async workflowDispatch(projectId, taskId, input = {}, actor = {}) { await this.store.ensureLoaded() if (actor.seatId !== 'shangshu') throw new ServiceError('sansheng/forbidden', '只有尚书省可以调度六部') const assignments = Array.isArray(input.assignments) ? input.assignments : [] if (assignments.length === 0) throw new ServiceError('sansheng/invalid', '至少需要给一个六部席位分派任务') const liubu = new Set(SEAT_GROUPS.liubu) for (const assignment of assignments) { const seatId = cleanText(assignment?.seatId) if (!liubu.has(seatId)) throw new ServiceError('sansheng/route-forbidden', `尚书省只能调度六部,不能派给 ${seatId || '空目标'}`) if (!cleanText(assignment?.title)) throw new ServiceError('sansheng/invalid', '每个六部任务必须有标题') } const assignmentSummary = assignments.map(item => `${SEATS[item.seatId]?.label ?? item.seatId}:${item.title}`).join(';') const result = await this.store.mutate(s => { const project = s.projects[projectId] const task = (project.tasks ?? []).find(item => item.id === taskId) if (!task || task.kind !== 'workflow') throw new ServiceError('sansheng/not-found', `流程任务 ${taskId} 不存在`) if (task.ownerSeatId !== 'shangshu' || task.stage !== 'shangshu_dispatch') throw new ServiceError('sansheng/stage-forbidden', '当前任务不在尚书调度阶段') taskDecisionBlock(task) const req = (project.requirements ?? []).find(item => item.id === task.requirementId) if (!req || req.revision !== task.requirementRevision) throw new ServiceError('sansheng/requirement-changed', '需求版本已变化,批准失效') const approval = (project.approvals ?? []).find(item => item.id === task.approvalId) if (!approval || approval.status !== 'approved' || approval.requirementRevision !== req.revision || approval.scope !== task.approvalScope) { throw new ServiceError('sansheng/approval-invalid', '执行批准无效或已过期,不能向六部派工') } const now = Date.now() // 派发沿用批准时的有效快照:用户需求字段优先,中书补缺或修订随任务走。 const effective = effectiveRequirementSnapshot(task, req) task.requirementSnapshot = effective const children = [] for (const assignment of assignments) { const seatId = cleanText(assignment.seatId) project.taskSeq = (project.taskSeq ?? 0) + 1 const child = emptyTask({ id: `task-${project.taskSeq}`, title: cleanText(assignment.title), goal: cleanText(assignment.goal) || effective.scope || effective.title, requirement: req.originalText, ownerSeatId: seatId, kind: 'execution', requirementId: req.id, requirementRevision: req.revision, approvalId: approval.id, parentTaskId: task.id, stage: 'department_exec', now, }) child.approvalScope = approval.scope child.requirementSnapshot = { ...effective } child.blockedReason = '六部执行中' queueDelivery(child, 'dispatched') project.tasks.push(child) children.push({ ...child }) } task.stage = 'department_exec' task.status = 'running' task.blockedReason = '六部执行中' task.lastTransitionId = randomUUID() const report = appendLeadReport(s, projectId, task, 'shangshu_dispatch', assignmentSummary) voidDelivery(task) task.updatedAt = now req.blockedReason = '六部执行中' req.updatedAt = now project.updatedAt = now project.revision = (project.revision ?? 0) + 1 return { task: { ...task }, children, reportCreated: Boolean(report?.created) } }) const deliveries = await Promise.all(result.children.map(async child => { try { const delivered = await this.taskDispatch(projectId, child.id, { deliveryId: child.deliveryId }) return { taskId: child.id, seatId: child.ownerSeatId, delivered: delivered.delivered } } catch (error) { return { taskId: child.id, seatId: child.ownerSeatId, delivered: false, error: error?.message ?? String(error) } } })) if (result.reportCreated) this._flushLeadReports(projectId) return { ok: deliveries.every(item => item.delivered), task: result.task, children: result.children, deliveries } }, async workflowSummarize(projectId, taskId, input = {}, actor = {}) { await this.store.ensureLoaded() if (actor.seatId !== 'shangshu') throw new ServiceError('sansheng/forbidden', '只有尚书省可以汇总六部结果') const summaryInput = cleanText(input.summary) const next = await this.store.mutate(s => { const project = s.projects[projectId] const task = (project.tasks ?? []).find(item => item.id === taskId) if (!task || task.kind !== 'workflow') throw new ServiceError('sansheng/not-found', `流程任务 ${taskId} 不存在`) if (task.ownerSeatId !== 'shangshu' || task.stage !== 'department_exec') throw new ServiceError('sansheng/stage-forbidden', '当前任务不在六部执行阶段,不能汇总') const children = (project.tasks ?? []).filter(item => item.parentTaskId === task.id && item.kind === 'execution') if (children.length === 0) throw new ServiceError('sansheng/invalid', '没有六部执行任务可汇总') const open = children.filter(item => OPEN_TASK_STATUS.has(item.status)) if (open.length > 0) throw new ServiceError('sansheng/tasks-open', `还有 ${open.length} 个六部任务未结束,不能汇总:${open.map(item => item.id).join('、')}`) const summary = summaryInput || children.map(item => `- ${item.id} ${SEATS[item.ownerSeatId]?.label ?? item.ownerSeatId} [${item.status}]:${item.result || item.note || '无结果'}`).join('\n') const now = Date.now() task.summary = summary task.stage = 'menxia_acceptance' task.ownerSeatId = 'menxia' task.status = 'draft' task.blockedReason = '待门下省验收' task.lastTransitionId = randomUUID() const report = appendLeadReport(s, projectId, task, 'shangshu_summarize', summary) queueDelivery(task, 'dispatched') task.updatedAt = now const req = (project.requirements ?? []).find(item => item.id === task.requirementId) if (req) { req.blockedReason = '门下验收中'; req.updatedAt = now } project.updatedAt = now project.revision = (project.revision ?? 0) + 1 return { task: { ...task }, reportCreated: Boolean(report?.created) } }) return dispatchAndFlushReport(this, projectId, taskId, next) }, async workflowAccept(projectId, taskId, input = {}, actor = {}) { await this.store.ensureLoaded() if (actor.seatId !== 'menxia') throw new ServiceError('sansheng/forbidden', '只有门下省可以验收') const action = cleanText(input.action) if (!['accept', 'reject'].includes(action)) throw new ServiceError('sansheng/invalid', '验收动作必须是 accept 或 reject') const note = cleanText(input.note) if (action === 'reject' && !note) throw new ServiceError('sansheng/invalid', '验收退回必须写明原因') const next = await this.store.mutate(s => { const project = s.projects[projectId] const task = (project.tasks ?? []).find(item => item.id === taskId) if (!task || task.kind !== 'workflow') throw new ServiceError('sansheng/not-found', `流程任务 ${taskId} 不存在`) if (task.ownerSeatId !== 'menxia' || task.stage !== 'menxia_acceptance') throw new ServiceError('sansheng/stage-forbidden', '当前任务不在门下验收阶段') const req = (project.requirements ?? []).find(item => item.id === task.requirementId) const now = Date.now() task.reviewNote = note if (action === 'reject') { task.stage = 'shangshu_dispatch' task.ownerSeatId = 'shangshu' task.status = 'returned' task.blockedReason = '验收退回尚书省重新调度' if (req) { req.blockedReason = `验收退回:${note}`; req.updatedAt = now } } else { task.stage = 'lead_delivery' task.ownerSeatId = 'lead' task.status = 'prepared' task.blockedReason = '待丞相交付' if (req) { req.blockedReason = '待丞相交付'; req.updatedAt = now } } task.lastTransitionId = randomUUID() const liaisonHandlesDelivery = action === 'accept' && this.leadReporter?.liaisonEnabled const report = appendLeadReport(s, projectId, task, action === 'reject' ? 'menxia_accept_return' : 'menxia_accept', liaisonHandlesDelivery ? [note || '验收通过', task.summary].filter(Boolean).join('\n') : note || '验收通过', liaisonHandlesDelivery ? { nextStep: '请主丞相用任务编号查看真实结果并完成交付。' } : {}) if (liaisonHandlesDelivery) voidDelivery(task) else queueDelivery(task, task.status) task.updatedAt = now project.updatedAt = now project.revision = (project.revision ?? 0) + 1 return { task: { ...task }, reportCreated: Boolean(report?.created), liaisonHandlesDelivery } }) if (next.liaisonHandlesDelivery) { if (next.reportCreated) this._flushLeadReports(projectId) return { ok: true, task: next.task } } return dispatchAndFlushReport(this, projectId, taskId, next) }, async workflowDeliver(projectId, taskId, input = {}, actor = {}) { await this.store.ensureLoaded() if (actor.seatId !== 'lead') throw new ServiceError('sansheng/forbidden', '只有丞相可以交付') const deliveryNote = cleanText(input.delivery) if (!deliveryNote) throw new ServiceError('sansheng/invalid', '交付内容不能为空') return this.store.mutate(s => { const project = s.projects[projectId] const task = (project.tasks ?? []).find(item => item.id === taskId) if (!task || task.kind !== 'workflow') throw new ServiceError('sansheng/not-found', `流程任务 ${taskId} 不存在`) if (task.ownerSeatId !== 'lead' || task.stage !== 'lead_delivery') throw new ServiceError('sansheng/stage-forbidden', '当前任务不在丞相交付阶段') const now = Date.now() task.stage = 'delivered' task.status = 'done' task.deliveryNote = deliveryNote task.deliveredAt = now voidDelivery(task) task.deliveredBySessionId = actor.sessionId ?? null task.lastTransitionId = randomUUID() task.blockedReason = '' task.updatedAt = now const req = (project.requirements ?? []).find(item => item.id === task.requirementId) if (req) { req.blockedReason = '已交付'; req.updatedAt = now } project.updatedAt = now project.revision = (project.revision ?? 0) + 1 return { ok: true, task: { ...task } } }) }, }