feat: 1、实现负责人提审、发起人审批/驳回,以及设计、加工、采购阶段的独立交付规则;2、接入站内通知、可选邮件、MinIO 附件和版本证据保留。

This commit is contained in:
zhanghao 2026-10-27 14:54:55 +08:00
parent f3e181a158
commit 84f0efecba
57 changed files with 1950 additions and 85 deletions

View File

@ -295,7 +295,13 @@ CREATE TABLE `pm_collab_stage_revision` (
`stage_name_snapshot` varchar(120) NOT NULL COMMENT '本执行版本的阶段名称快照', `stage_name_snapshot` varchar(120) NOT NULL COMMENT '本执行版本的阶段名称快照',
`stage_owner_snapshot` bigint DEFAULT NULL COMMENT '本执行版本的阶段负责人用户ID快照', `stage_owner_snapshot` bigint DEFAULT NULL COMMENT '本执行版本的阶段负责人用户ID快照',
`started_at` bigint DEFAULT NULL COMMENT '本版本首次执行时间(UTC时间戳,微秒)', `started_at` bigint DEFAULT NULL COMMENT '本版本首次执行时间(UTC时间戳,微秒)',
`completed_at` bigint DEFAULT NULL COMMENT '本版本全部有效工作项完成或关闭的时间(UTC微秒)', `completed_at` bigint DEFAULT NULL COMMENT '本版本审批通过、采购确认或组聚合完成时间(UTC微秒)',
`approval_status` varchar(20) NOT NULL DEFAULT 'NONE' COMMENT '本版本最近审批状态,工作项齐备不等于审批通过',
`completion_note` text COMMENT '本轮实际交付说明,与阶段目标分开',
`completion_source` varchar(24) DEFAULT NULL COMMENT '完成来源MANUAL人工审批、PURCHASE采购确认、LEGACY_AUTO历史自动完成',
`delivery_snapshot_json` json DEFAULT NULL COMMENT '通过或换版时冻结的交付证据,不读取未来采购数据',
`purchase_scope_confirmed` tinyint(1) NOT NULL DEFAULT 0 COMMENT '本轮采购范围经人员确认,回退参考批次默认未确认',
`ready_notified_at` bigint DEFAULT NULL COMMENT '本轮首次采购达标提醒时间(UTC微秒)',
`superseded_at` bigint DEFAULT NULL COMMENT '被新版本替代的时间(UTC微秒;当前版本为空)', `superseded_at` bigint DEFAULT NULL COMMENT '被新版本替代的时间(UTC微秒;当前版本为空)',
`legacy_passed_at` bigint DEFAULT NULL COMMENT '历史迁移确认的空阶段兼容放行时间(UTC微秒)', `legacy_passed_at` bigint DEFAULT NULL COMMENT '历史迁移确认的空阶段兼容放行时间(UTC微秒)',
`created_by` bigint NOT NULL COMMENT '创建人用户ID', `created_by` bigint NOT NULL COMMENT '创建人用户ID',
@ -572,3 +578,63 @@ ALTER TABLE pm_collab_project_stage
(node_type='GROUP' AND stage_kind='GROUP') OR (node_type='GROUP' AND stage_kind='GROUP') OR
(node_type IN ('STAGE','REQUIREMENT','PROPOSAL','PURCHASE','DESIGN','MACHINING','ASSEMBLY','DEBUGGING','DEVELOPMENT','TESTING') AND stage_kind='WORK') (node_type IN ('STAGE','REQUIREMENT','PROPOSAL','PURCHASE','DESIGN','MACHINING','ASSEMBLY','DEBUGGING','DEVELOPMENT','TESTING') AND stage_kind='WORK')
); );
-- 阶段版本交付、人工完成审批及采购批次引用。
CREATE TABLE IF NOT EXISTS pm_collab_stage_approval (
id BIGINT NOT NULL AUTO_INCREMENT COMMENT '审批记录ID',
project_id BIGINT NOT NULL COMMENT '协作扩展项目ID,非原项目ID',
iteration_id BIGINT NOT NULL COMMENT '所属迭代ID',
stage_id BIGINT NOT NULL COMMENT '所属阶段ID',
revision_id BIGINT NOT NULL COMMENT '精确执行版本ID,回退不继承审批',
submission_no INT NOT NULL COMMENT '本版本申请次数,从1开始递增',
request_source VARCHAR(24) NOT NULL COMMENT 'OWNER负责人申请或PURCHASE_CONFIRM采购验收确认',
submitted_by BIGINT NULL COMMENT '负责人申请人ID;采购直接确认没有虚构申请人',
approver_id BIGINT NOT NULL COMMENT '阶段创建人ID,不能使用回退版本创建人',
owner_id BIGINT NULL COMMENT '提交时阶段负责人ID快照',
status VARCHAR(20) NOT NULL COMMENT 'PENDING待审、APPROVED通过、REJECTED驳回、WITHDRAWN撤回、SUPERSEDED换版失效、TERMINATED迭代终止、INVALIDATED证据变化',
pending_revision_id BIGINT GENERATED ALWAYS AS (CASE WHEN status='PENDING' THEN revision_id ELSE NULL END) STORED COMMENT '仅待审轮次参与唯一约束,防止重复有效申请',
evidence_hash CHAR(64) CHARACTER SET ascii COLLATE ascii_bin NOT NULL COMMENT '本次审批相关证据的SHA-256,排除采样时刻等非业务变化',
snapshot_json JSON NOT NULL COMMENT '服务端采样的交付和采购验收证据,不含对象键或金额',
submitted_at BIGINT NOT NULL COMMENT '申请或采购核验采样时间(UTC微秒)',
decided_by BIGINT NULL COMMENT '实际决定人ID',
decided_at BIGINT NULL COMMENT '决定时间(UTC微秒)',
reason VARCHAR(2000) NULL COMMENT '驳回、撤回、失效及终止原因',
command_actor BIGINT NOT NULL COMMENT '本次提交命令的真实用户ID',
idempotency_key VARCHAR(100) CHARACTER SET ascii COLLATE ascii_bin NOT NULL COMMENT '提交或采购确认幂等键',
decision_key VARCHAR(100) CHARACTER SET ascii COLLATE ascii_bin NULL COMMENT '审批决定的幂等键',
PRIMARY KEY(id),
UNIQUE KEY uk_pm_approval_submission(revision_id,submission_no),
UNIQUE KEY uk_pm_approval_pending(pending_revision_id),
UNIQUE KEY uk_pm_approval_command(project_id,command_actor,idempotency_key),
KEY idx_pm_approval_scope(project_id,iteration_id,stage_id,revision_id),
CONSTRAINT fk_pm_approval_revision FOREIGN KEY(project_id,iteration_id,stage_id,revision_id) REFERENCES pm_collab_stage_revision(project_id,iteration_id,stage_id,id),
CONSTRAINT ck_pm_approval_status CHECK(status IN ('PENDING','APPROVED','REJECTED','WITHDRAWN','SUPERSEDED','TERMINATED','INVALIDATED'))
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='项目协作:阶段完成申请和采购验收确认历史';
CREATE TABLE IF NOT EXISTS pm_collab_stage_attachment (
id BIGINT NOT NULL AUTO_INCREMENT COMMENT '阶段附件ID',
revision_id BIGINT NOT NULL COMMENT '所属阶段执行版本ID',
name VARCHAR(255) NOT NULL COMMENT '原文件名,仅用于显示和鉴权下载',
media_type VARCHAR(120) NOT NULL COMMENT '经过校验的媒体类型',
object_key VARCHAR(512) CHARACTER SET ascii COLLATE ascii_bin NOT NULL COMMENT 'MinIO私有对象键,不向浏览器暴露',
sha256 CHAR(64) CHARACTER SET ascii COLLATE ascii_bin NOT NULL COMMENT '服务端计算的文件摘要',
size BIGINT NOT NULL COMMENT '文件大小(字节),最多10MiB',
created_by BIGINT NOT NULL COMMENT '上传者用户ID',
created_at BIGINT NOT NULL COMMENT '上传时间(UTC微秒)',
deleted TINYINT(1) NOT NULL DEFAULT 0 COMMENT '软删除标志,保留私有对象和历史证据',
deleted_by BIGINT NULL COMMENT '软删除操作者ID',
deleted_at BIGINT NULL COMMENT '软删除时间(UTC微秒)',
PRIMARY KEY(id), UNIQUE KEY uk_pm_stage_attachment_object(object_key), KEY idx_pm_stage_attachment_revision(revision_id,id),
CONSTRAINT fk_pm_stage_attachment_revision FOREIGN KEY(revision_id) REFERENCES pm_collab_stage_revision(id),
CONSTRAINT ck_pm_stage_attachment_size CHECK(size>0 AND size<=10485760)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='项目协作:阶段版本交付附件(MinIO及软删除)';
-- 采购批次只作进度引用,不增加跨模块级联外键,不修改或占用采购数量。
CREATE TABLE IF NOT EXISTS pm_collab_stage_purchase_batch (
revision_id BIGINT NOT NULL COMMENT '阶段执行版本ID',
purchase_batch_id BIGINT NOT NULL COMMENT '采购源批次ID,须在原项目范围内校验',
created_by BIGINT NOT NULL COMMENT '本轮范围确认人ID',
created_at BIGINT NOT NULL COMMENT '确认时间(UTC微秒)',
PRIMARY KEY(revision_id,purchase_batch_id),
CONSTRAINT fk_pm_stage_purchase_revision FOREIGN KEY(revision_id) REFERENCES pm_collab_stage_revision(id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='项目协作:阶段版本采购批次范围';

View File

@ -0,0 +1,93 @@
-- 项目协作阶段完成审批。022 后执行;只增加协作结构并保留历史完成事实,不修改采购源数据。
-- 可重复执行。必须先升级数据库,再部署读取新字段的应用;MySQL DDL 不参与业务事务。
SET NAMES utf8mb4;
SET @pm_approval_ddl=(SELECT IF(COUNT(*)=0,'ALTER TABLE pm_collab_stage_revision ADD COLUMN approval_status VARCHAR(20) NOT NULL DEFAULT ''NONE'' COMMENT ''本执行版本最近审批状态:NONE未申请、PENDING待审批、REJECTED待整改、APPROVED已通过、WITHDRAWN已撤回、INVALIDATED已失效、TERMINATED已终止''','SELECT 1') FROM information_schema.columns WHERE table_schema=DATABASE() AND table_name='pm_collab_stage_revision' AND column_name='approval_status');
PREPARE pm_approval_stmt FROM @pm_approval_ddl;
EXECUTE pm_approval_stmt;
DEALLOCATE PREPARE pm_approval_stmt;
SET @pm_approval_ddl=(SELECT IF(COUNT(*)=0,'ALTER TABLE pm_collab_stage_revision ADD COLUMN completion_note TEXT NULL COMMENT ''本执行版本的实际交付说明,与阶段目标描述分开''','SELECT 1') FROM information_schema.columns WHERE table_schema=DATABASE() AND table_name='pm_collab_stage_revision' AND column_name='completion_note');
PREPARE pm_approval_stmt FROM @pm_approval_ddl;
EXECUTE pm_approval_stmt;
DEALLOCATE PREPARE pm_approval_stmt;
SET @pm_approval_ddl=(SELECT IF(COUNT(*)=0,'ALTER TABLE pm_collab_stage_revision ADD COLUMN completion_source VARCHAR(24) NULL COMMENT ''完成依据:MANUAL人工审批、PURCHASE采购确认、LEGACY_AUTO旧版自动完成;组聚合不伪造人工审批''','SELECT 1') FROM information_schema.columns WHERE table_schema=DATABASE() AND table_name='pm_collab_stage_revision' AND column_name='completion_source');
PREPARE pm_approval_stmt FROM @pm_approval_ddl;
EXECUTE pm_approval_stmt;
DEALLOCATE PREPARE pm_approval_stmt;
SET @pm_approval_ddl=(SELECT IF(COUNT(*)=0,'ALTER TABLE pm_collab_stage_revision ADD COLUMN delivery_snapshot_json JSON NULL COMMENT ''完成或换版时冻结的交付快照,历史不得读取当前采购数据''','SELECT 1') FROM information_schema.columns WHERE table_schema=DATABASE() AND table_name='pm_collab_stage_revision' AND column_name='delivery_snapshot_json');
PREPARE pm_approval_stmt FROM @pm_approval_ddl;
EXECUTE pm_approval_stmt;
DEALLOCATE PREPARE pm_approval_stmt;
SET @pm_approval_ddl=(SELECT IF(COUNT(*)=0,'ALTER TABLE pm_collab_stage_revision ADD COLUMN purchase_scope_confirmed TINYINT(1) NOT NULL DEFAULT 0 COMMENT ''本轮采购范围是否经人员确认;回退复制的参考批次必须重新确认''','SELECT 1') FROM information_schema.columns WHERE table_schema=DATABASE() AND table_name='pm_collab_stage_revision' AND column_name='purchase_scope_confirmed');
PREPARE pm_approval_stmt FROM @pm_approval_ddl;
EXECUTE pm_approval_stmt;
DEALLOCATE PREPARE pm_approval_stmt;
SET @pm_approval_ddl=(SELECT IF(COUNT(*)=0,'ALTER TABLE pm_collab_stage_revision ADD COLUMN ready_notified_at BIGINT NULL COMMENT ''本轮首次采购达标提醒时间(UTC微秒),轮询和验收波动不重复通知''','SELECT 1') FROM information_schema.columns WHERE table_schema=DATABASE() AND table_name='pm_collab_stage_revision' AND column_name='ready_notified_at');
PREPARE pm_approval_stmt FROM @pm_approval_ddl;
EXECUTE pm_approval_stmt;
DEALLOCATE PREPARE pm_approval_stmt;
-- 只承认已有工作阶段完成时间,不虚构人工审批;容器的新聚合完成也没有人工来源,重跑时不得误标为旧版自动完成。
UPDATE pm_collab_stage_revision r JOIN pm_collab_project_stage s ON s.id=r.stage_id
SET r.completion_source='LEGACY_AUTO'
WHERE s.stage_kind<>'GROUP' AND r.completed_at IS NOT NULL AND r.completion_source IS NULL;
ALTER TABLE pm_collab_stage_revision MODIFY COLUMN completed_at BIGINT NULL COMMENT '本版本审批通过、采购确认或组聚合完成时间(UTC微秒),旧数据保留历史完成时间';
CREATE TABLE IF NOT EXISTS pm_collab_stage_approval (
id BIGINT NOT NULL AUTO_INCREMENT COMMENT '审批记录ID',
project_id BIGINT NOT NULL COMMENT '协作扩展项目ID,非原项目ID',
iteration_id BIGINT NOT NULL COMMENT '所属迭代ID',
stage_id BIGINT NOT NULL COMMENT '所属阶段ID',
revision_id BIGINT NOT NULL COMMENT '精确执行版本ID,回退不继承审批',
submission_no INT NOT NULL COMMENT '本版本申请次数,从1开始递增',
request_source VARCHAR(24) NOT NULL COMMENT 'OWNER负责人申请或PURCHASE_CONFIRM采购验收确认',
submitted_by BIGINT NULL COMMENT '负责人申请人ID;采购直接确认没有虚构申请人',
approver_id BIGINT NOT NULL COMMENT '阶段创建人ID,不能使用回退版本创建人',
owner_id BIGINT NULL COMMENT '提交时阶段负责人ID快照',
status VARCHAR(20) NOT NULL COMMENT 'PENDING待审、APPROVED通过、REJECTED驳回、WITHDRAWN撤回、SUPERSEDED换版失效、TERMINATED迭代终止、INVALIDATED证据变化',
pending_revision_id BIGINT GENERATED ALWAYS AS (CASE WHEN status='PENDING' THEN revision_id ELSE NULL END) STORED COMMENT '仅待审轮次参与唯一约束,防止重复有效申请',
evidence_hash CHAR(64) CHARACTER SET ascii COLLATE ascii_bin NOT NULL COMMENT '本次审批相关证据的SHA-256,排除采样时刻等非业务变化',
snapshot_json JSON NOT NULL COMMENT '服务端采样的交付和采购验收证据,不含对象键或金额',
submitted_at BIGINT NOT NULL COMMENT '申请或采购核验采样时间(UTC微秒)',
decided_by BIGINT NULL COMMENT '实际决定人ID',
decided_at BIGINT NULL COMMENT '决定时间(UTC微秒)',
reason VARCHAR(2000) NULL COMMENT '驳回、撤回、失效及终止原因',
command_actor BIGINT NOT NULL COMMENT '本次提交命令的真实用户ID',
idempotency_key VARCHAR(100) CHARACTER SET ascii COLLATE ascii_bin NOT NULL COMMENT '提交或采购确认幂等键',
decision_key VARCHAR(100) CHARACTER SET ascii COLLATE ascii_bin NULL COMMENT '审批决定的幂等键',
PRIMARY KEY(id),
UNIQUE KEY uk_pm_approval_submission(revision_id,submission_no),
UNIQUE KEY uk_pm_approval_pending(pending_revision_id),
UNIQUE KEY uk_pm_approval_command(project_id,command_actor,idempotency_key),
KEY idx_pm_approval_scope(project_id,iteration_id,stage_id,revision_id),
CONSTRAINT fk_pm_approval_revision FOREIGN KEY(project_id,iteration_id,stage_id,revision_id) REFERENCES pm_collab_stage_revision(project_id,iteration_id,stage_id,id),
CONSTRAINT ck_pm_approval_status CHECK(status IN ('PENDING','APPROVED','REJECTED','WITHDRAWN','SUPERSEDED','TERMINATED','INVALIDATED'))
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='项目协作:阶段完成申请和采购验收确认历史';
CREATE TABLE IF NOT EXISTS pm_collab_stage_attachment (
id BIGINT NOT NULL AUTO_INCREMENT COMMENT '阶段附件ID',
revision_id BIGINT NOT NULL COMMENT '所属阶段执行版本ID',
name VARCHAR(255) NOT NULL COMMENT '原文件名,仅用于显示和鉴权下载',
media_type VARCHAR(120) NOT NULL COMMENT '经过校验的媒体类型',
object_key VARCHAR(512) CHARACTER SET ascii COLLATE ascii_bin NOT NULL COMMENT 'MinIO私有对象键,不向浏览器暴露',
sha256 CHAR(64) CHARACTER SET ascii COLLATE ascii_bin NOT NULL COMMENT '服务端计算的文件摘要',
size BIGINT NOT NULL COMMENT '文件大小(字节),最多10MiB',
created_by BIGINT NOT NULL COMMENT '上传者用户ID',
created_at BIGINT NOT NULL COMMENT '上传时间(UTC微秒)',
deleted TINYINT(1) NOT NULL DEFAULT 0 COMMENT '软删除标志,保留私有对象和历史证据',
deleted_by BIGINT NULL COMMENT '软删除操作者ID',
deleted_at BIGINT NULL COMMENT '软删除时间(UTC微秒)',
PRIMARY KEY(id), UNIQUE KEY uk_pm_stage_attachment_object(object_key), KEY idx_pm_stage_attachment_revision(revision_id,id),
CONSTRAINT fk_pm_stage_attachment_revision FOREIGN KEY(revision_id) REFERENCES pm_collab_stage_revision(id),
CONSTRAINT ck_pm_stage_attachment_size CHECK(size>0 AND size<=10485760)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='项目协作:阶段版本交付附件(MinIO及软删除)';
-- 采购批次只作进度引用,不增加跨模块级联外键,不修改或占用采购数量。
CREATE TABLE IF NOT EXISTS pm_collab_stage_purchase_batch (
revision_id BIGINT NOT NULL COMMENT '阶段执行版本ID',
purchase_batch_id BIGINT NOT NULL COMMENT '采购源批次ID,须在原项目范围内校验',
created_by BIGINT NOT NULL COMMENT '本轮范围确认人ID',
created_at BIGINT NOT NULL COMMENT '确认时间(UTC微秒)',
PRIMARY KEY(revision_id,purchase_batch_id),
CONSTRAINT fk_pm_stage_purchase_revision FOREIGN KEY(revision_id) REFERENCES pm_collab_stage_revision(id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='项目协作:阶段版本采购批次范围';

View File

@ -0,0 +1,81 @@
package com.ruoyi.project.manage.controller;
import com.fasterxml.jackson.databind.*;
import com.ruoyi.project.manage.dto.StageCompletionInput;
import com.ruoyi.project.manage.dto.StagePurchaseInput;
import com.ruoyi.project.manage.exception.PmException;
import com.ruoyi.project.manage.service.IPmStageCompletionService;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import org.springframework.http.*;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import static com.ruoyi.project.manage.util.PmValues.*;
/** 阶段审批HTTP适配;不接收审批人、采购数量或存储路径,决定由持锁服务完成。 */
@RestController
@RequestMapping("/project/manage/projects/{projectId}/iterations/{iterationId}")
public class PmStageCompletionController {
private final IPmStageCompletionService service;
private final ObjectMapper strict;
/** 所有命令严格解码,阻止展示字段或伪造审批身份混入业务写入。 */
public PmStageCompletionController(IPmStageCompletionService service,ObjectMapper json) {this.service=service;strict=json.copy().enable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES).disable(DeserializationFeature.ACCEPT_FLOAT_AS_INT);}
/** 当前和历史交付共用精确轮次上下文,历史始终只读。 */
@GetMapping("/stages/{stageId}/completion")
public Map<String,Object> detail(@PathVariable long projectId,@PathVariable long iterationId,@PathVariable long stageId,@RequestParam(required=false) Long revisionId) {return ok(service.detail(projectId,iterationId,stageId,revisionId));}
/** 申请详情读取提交时快照,不以当前交付替代被驳回的原始证据。 */
@GetMapping("/stages/{stageId}/completion-requests/{approvalId}")
public Map<String,Object> evidence(@PathVariable long projectId,@PathVariable long iterationId,@PathVariable long stageId,@PathVariable long approvalId) {return ok(service.approvalEvidence(projectId,iterationId,stageId,approvalId));}
/** 无工作项阶段显式开始,仍需满足前置和进行中迭代门禁。 */
@PostMapping("/stages/{stageId}/start")
public Map<String,Object> start(@PathVariable long projectId,@PathVariable long iterationId,@PathVariable long stageId,@RequestBody JsonNode body) {service.start(projectId,iterationId,stageId,decode(body,StageCompletionInput.class));return ok(null);}
/** 交付说明独立于阶段目标,避免编辑名称时覆盖本轮实际成果。 */
@PatchMapping("/stages/{stageId}/completion-note")
public Map<String,Object> note(@PathVariable long projectId,@PathVariable long iterationId,@PathVariable long stageId,@RequestBody JsonNode body) {service.note(projectId,iterationId,stageId,decode(body,StageCompletionInput.class));return ok(null);}
/** 负责人提交完成申请,工作项齐备不会自动调用此接口。 */
@PostMapping("/stages/{stageId}/completion-requests")
public Map<String,Object> submit(@PathVariable long projectId,@PathVariable long iterationId,@PathVariable long stageId,@RequestBody JsonNode body) {return ok(service.submit(projectId,iterationId,stageId,decode(body,StageCompletionInput.class)));}
/** 失效状态先在服务事务提交,再返回冲突,防止失效被异常回滚。 */
@PostMapping("/stages/{stageId}/completion-requests/{approvalId}/{action}")
public Map<String,Object> decide(@PathVariable long projectId,@PathVariable long iterationId,@PathVariable long stageId,@PathVariable long approvalId,@PathVariable String action,@RequestBody JsonNode body) {
var result=service.decide(projectId,iterationId,stageId,approvalId,action,decode(body,StageCompletionInput.class));
if(Boolean.TRUE.equals(result.get("conflict")))throw new PmException(409,text(result,"code"),text(result,"message"),result);
return ok(result);
}
/** 采购创建人基于当前所见范围重新核验,再显式通过或填写原因退回。 */
@PostMapping("/stages/{stageId}/purchase-confirmation")
public Map<String,Object> confirm(@PathVariable long projectId,@PathVariable long iterationId,@PathVariable long stageId,@RequestBody JsonNode body) {return ok(service.confirmPurchase(projectId,iterationId,stageId,decode(body,StageCompletionInput.class)));}
/** 原项目批次最小投影,协作接口不提供采购金额或其他项目内容。 */
@GetMapping("/purchase-batch-options")
public Map<String,Object> options(@PathVariable long projectId,@PathVariable long iterationId,@RequestParam(required=false) String keyword) {return ok(service.purchaseOptions(projectId,iterationId,keyword));}
/** 确认本轮采购范围,不修改源采购批次及验收事实。 */
@PutMapping("/stages/{stageId}/purchase-batches")
public Map<String,Object> batches(@PathVariable long projectId,@PathVariable long iterationId,@PathVariable long stageId,@RequestBody JsonNode body) {service.batches(projectId,iterationId,stageId,decode(body,StagePurchaseInput.class));return ok(null);}
/** 文件大小在读取字节之前校验;服务再次检查当前轮次、身份及实际内容长度。 */
@PostMapping("/stages/{stageId}/revisions/{revisionId}/attachments")
public Map<String,Object> upload(@PathVariable long projectId,@PathVariable long iterationId,@PathVariable long stageId,@PathVariable long revisionId,@RequestParam("file") MultipartFile file) throws java.io.IOException {
if(file.getSize()>10*1024*1024)throw PmException.bad("附件不能超过10MiB");
return ok(service.attach(projectId,iterationId,stageId,revisionId,file.getOriginalFilename(),file.getContentType(),file.getBytes()));
}
/** 人员显式确认沿用旧版交付,复制新对象且不继承审批通过。 */
@PostMapping("/stages/{stageId}/revisions/{revisionId}/attachments/reuse")
public Map<String,Object> reuse(@PathVariable long projectId,@PathVariable long iterationId,@PathVariable long stageId,@PathVariable long revisionId,@RequestBody JsonNode body) {
var input=decode(body,com.ruoyi.project.manage.dto.StageAttachmentReuseInput.class);
return ok(service.reuseAttachment(projectId,iterationId,stageId,revisionId,input.sourceRevisionId(),input.attachmentId()));
}
/** 当前交付维护人可软删文件,历史证据及MinIO对象仍保留。 */
@DeleteMapping("/stages/{stageId}/revisions/{revisionId}/attachments/{attachmentId}")
public Map<String,Object> remove(@PathVariable long projectId,@PathVariable long iterationId,@PathVariable long stageId,@PathVariable long revisionId,@PathVariable long attachmentId) {service.deleteAttachment(projectId,iterationId,stageId,revisionId,attachmentId);return ok(null);}
/** 强制附件下载并禁止嗅探,文件对象键从不暴露给浏览器。 */
@GetMapping("/stages/{stageId}/revisions/{revisionId}/attachments/{attachmentId}")
public ResponseEntity<byte[]> download(@PathVariable long projectId,@PathVariable long iterationId,@PathVariable long stageId,@PathVariable long revisionId,@PathVariable long attachmentId) {
var file=service.attachment(projectId,iterationId,stageId,revisionId,attachmentId);
return ResponseEntity.ok().contentType(MediaType.APPLICATION_OCTET_STREAM).header("X-Content-Type-Options","nosniff").header(HttpHeaders.CACHE_CONTROL,"no-store")
.header(HttpHeaders.CONTENT_DISPOSITION,ContentDisposition.attachment().filename(text(file,"name"),StandardCharsets.UTF_8).build().toString()).body((byte[])file.get("content"));
}
/** 沿用若依响应契约,业务失败不包装成成功。 */
private static Map<String,Object> ok(Object value) {return map("code",200,"msg","操作成功","data",value);}
/** 拒绝未知字段及整数截断,客户端只能提交端口允许的参数。 */
private <T>T decode(JsonNode body,Class<T> type) {try{if(body==null||!body.isObject())throw PmException.bad("请求必须为JSON对象");return strict.treeToValue(body,type);}catch(Exception failure){throw PmException.bad("请求字段或格式无效");}}
}

View File

@ -1,7 +1,9 @@
package com.ruoyi.project.manage.domain; package com.ruoyi.project.manage.domain;
/** 阶段组织身份与执行版本分离;父级表达包含关系,执行先后仍由显式边决定。 */ /** 阶段组织身份与执行版本分离;父级表达包含关系,执行先后仍由显式边决定。 */
public record StageInfo(long id,String kind,Long parentId,String description) { public record StageInfo(long id,String kind,Long parentId,String description,String nodeType,Long creatorId,Long ownerId) {
/** 结构候选图可以省略人员,但仍明确区分容器和普通工作阶段。 */
public StageInfo(long id,String kind,Long parentId,String description) { this(id,kind,parentId,description,"GROUP".equals(kind)?"GROUP":"STAGE",null,null); }
/** 容器只承载子阶段,不能接受工作项,避免完成规则出现两种来源。 */ /** 容器只承载子阶段,不能接受工作项,避免完成规则出现两种来源。 */
public boolean group() { return "GROUP".equals(kind); } public boolean group() { return "GROUP".equals(kind); }
} }

View File

@ -3,18 +3,24 @@ package com.ruoyi.project.manage.domain;
/** 当前阶段执行轮次的最小快照;历史轮次只能通过独立只读查询获取。 */ /** 当前阶段执行轮次的最小快照;历史轮次只能通过独立只读查询获取。 */
public record StageRevision(long id,long stageId,int revisionNo,Long startedAt,Long completedAt,Long legacyPassedAt, public record StageRevision(long id,long stageId,int revisionNo,Long startedAt,Long completedAt,Long legacyPassedAt,
Long plannedStart,Long plannedEnd,Long referenceStart,Long referenceEnd,Long scheduleReviewReworkId, Long plannedStart,Long plannedEnd,Long referenceStart,Long referenceEnd,Long scheduleReviewReworkId,
String planSource,Long planRecordedAt,int version) { String planSource,Long planRecordedAt,int version,String approvalStatus,String completionSource,String completionNote) {
/** 旧内部构造保留字段兼容;未提供审批事实的轮次绝不从工作项推测已通过。 */
public StageRevision(long id,long stageId,int revisionNo,Long startedAt,Long completedAt,Long legacyPassedAt,
Long plannedStart,Long plannedEnd,Long referenceStart,Long referenceEnd,Long scheduleReviewReworkId,
String planSource,Long planRecordedAt,int version) {
this(id,stageId,revisionNo,startedAt,completedAt,legacyPassedAt,plannedStart,plannedEnd,referenceStart,referenceEnd,scheduleReviewReworkId,planSource,planRecordedAt,version,"NONE",null,null);
}
/** 旧规则测试与初始轮次没有计划,空值不能被推断为实际时间或当前时间。 */ /** 旧规则测试与初始轮次没有计划,空值不能被推断为实际时间或当前时间。 */
public StageRevision(long id,long stageId,int revisionNo,Long startedAt,Long completedAt,Long legacyPassedAt) { public StageRevision(long id,long stageId,int revisionNo,Long startedAt,Long completedAt,Long legacyPassedAt) {
this(id,stageId,revisionNo,startedAt,completedAt,legacyPassedAt,null,null,null,null,null,null,null,0); this(id,stageId,revisionNo,startedAt,completedAt,legacyPassedAt,null,null,null,null,null,null,null,0);
} }
/** 最终图中确认新计划;仅正式事务提交后才增加数据版本,不创建新执行轮次。 */ /** 最终图中确认新计划;仅正式事务提交后才增加数据版本,不创建新执行轮次。 */
public StageRevision scheduled(Long start,Long end,String source,Long recordedAt) { public StageRevision scheduled(Long start,Long end,String source,Long recordedAt) {
return new StageRevision(id,stageId,revisionNo,startedAt,completedAt,legacyPassedAt,start,end,null,null,null,source,recordedAt,version); return new StageRevision(id,stageId,revisionNo,startedAt,completedAt,legacyPassedAt,start,end,null,null,null,source,recordedAt,version,approvalStatus,completionSource,completionNote);
} }
/** 回退使原计划失效时保留参考值;连续回退不能用空值覆盖尚未确认的参考。 */ /** 回退使原计划失效时保留参考值;连续回退不能用空值覆盖尚未确认的参考。 */
public StageRevision pending(long reworkId) { public StageRevision pending(long reworkId) {
return new StageRevision(id,stageId,revisionNo,startedAt,completedAt,legacyPassedAt,null,null, return new StageRevision(id,stageId,revisionNo,startedAt,completedAt,legacyPassedAt,null,null,
plannedStart!=null?plannedStart:referenceStart,plannedEnd!=null?plannedEnd:referenceEnd,reworkId,planSource,planRecordedAt,version); plannedStart!=null?plannedStart:referenceStart,plannedEnd!=null?plannedEnd:referenceEnd,reworkId,planSource,planRecordedAt,version,approvalStatus,completionSource,completionNote);
} }
} }

View File

@ -0,0 +1,4 @@
package com.ruoyi.project.manage.dto;
/** 沿用仅引用同一阶段旧轮次的文件,不能提供对象键或跨项目文件地址。 */
public record StageAttachmentReuseInput(long sourceRevisionId,long attachmentId) { }

View File

@ -0,0 +1,5 @@
package com.ruoyi.project.manage.dto;
/** 审批命令绑定执行版本及证据摘要;操作人和审批人只从服务端身份取得。 */
public record StageCompletionInput(Long revisionId, Integer version, String evidenceHash,
String note, String reason, String idempotencyKey, Boolean sendEmail) { }

View File

@ -1,7 +1,9 @@
package com.ruoyi.project.manage.dto; package com.ruoyi.project.manage.dto;
/** 阶段创建同时提交固定节点分类、组织身份和整日计划;编辑不能迁移父级或修改节点类型。 */ /** 阶段创建同时提交固定节点分类、组织身份和整日计划;编辑不能迁移父级或修改节点类型。 */
public record StageInput(String name,Integer sortOrder,Long ownerId,String description,Integer version,String stageKind,Long parentStageId,String plannedStartAt,String plannedEndAt,String nodeType) { public record StageInput(String name,Integer sortOrder,Long ownerId,String description,Integer version,String stageKind,Long parentStageId,String plannedStartAt,String plannedEndAt,String nodeType,java.util.List<Long> purchaseBatchIds) {
/** 原分类调用没有采购范围;新建和编辑传入范围时与阶段元数据原子保存。 */
public StageInput(String name,Integer sortOrder,Long ownerId,String description,Integer version,String stageKind,Long parentStageId,String plannedStartAt,String plannedEndAt,String nodeType) {this(name,sortOrder,ownerId,description,version,stageKind,parentStageId,plannedStartAt,plannedEndAt,nodeType,null);}
/** 兼容仅提交结构身份的内部调用;缺失分类时按普通阶段或阶段组处理。 */ /** 兼容仅提交结构身份的内部调用;缺失分类时按普通阶段或阶段组处理。 */
public StageInput(String name,Integer sortOrder,Long ownerId,String description,Integer version,String stageKind,Long parentStageId,String plannedStartAt,String plannedEndAt) { this(name,sortOrder,ownerId,description,version,stageKind,parentStageId,plannedStartAt,plannedEndAt,null); } public StageInput(String name,Integer sortOrder,Long ownerId,String description,Integer version,String stageKind,Long parentStageId,String plannedStartAt,String plannedEndAt) { this(name,sortOrder,ownerId,description,version,stageKind,parentStageId,plannedStartAt,plannedEndAt,null); }
/** 原内部元数据调用省略结构字段;创建入口仍要求显式有效计划。 */ /** 原内部元数据调用省略结构字段;创建入口仍要求显式有效计划。 */

View File

@ -0,0 +1,6 @@
package com.ruoyi.project.manage.dto;
import java.util.List;
/** 采购范围只引用当前原项目的批次,不接受数量、验收结果或采购对象内容。 */
public record StagePurchaseInput(Long revisionId, Integer version, List<Long> batchIds) { }

View File

@ -0,0 +1,82 @@
package com.ruoyi.project.manage.event;
import com.ruoyi.project.manage.mapper.*;
import com.ruoyi.project.manage.notification.PmNotificationPlanner;
import com.ruoyi.project.manage.rule.PmStageRules;
import com.ruoyi.project.manage.service.support.PmGraphService;
import com.ruoyi.project.manage.service.support.PmStageEvidenceService;
import com.ruoyi.project.manage.service.support.PmGroupVersionService;
import com.ruoyi.project.manage.util.PmJson;
import com.ruoyi.project.manage.util.PmTime;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.support.TransactionTemplate;
import static com.ruoyi.project.manage.util.PmValues.*;
/** 采购只读轮询只发一次站内提醒,不生成申请、不冻结批次,也不冒用创建人的人工操作历史。 */
@Component
public class PmPurchaseReadyMonitor {
private static final Logger LOG=LoggerFactory.getLogger(PmPurchaseReadyMonitor.class);
private final PmStageCompletionMapper mapper;
private final PmStageMapper stages;
private final PmRevisionMapper revisions;
private final PmWorkspaceMapper workspace;
private final PmGraphService graphs;
private final PmStageEvidenceService evidence;
private final PmNotificationPlanner notifications;
private final PmEventMapper events;
private final PmJson json;
private final PmGroupVersionService groups;
private final TransactionTemplate transaction;
/** 每个候选独立事务;源项目→图锁与人工确认一致,不持全表锁或跨项目长事务。 */
public PmPurchaseReadyMonitor(PmStageCompletionMapper mapper,PmStageMapper stages,PmRevisionMapper revisions,PmWorkspaceMapper workspace,
PmGraphService graphs,PmStageEvidenceService evidence,PmNotificationPlanner notifications,PmEventMapper events,PmJson json,PlatformTransactionManager manager,PmGroupVersionService groups) {
this.groups=groups;
this.mapper=mapper;this.stages=stages;this.revisions=revisions;this.workspace=workspace;this.graphs=graphs;this.evidence=evidence;this.notifications=notifications;this.events=events;this.json=json;
transaction=new TransactionTemplate(manager);transaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED);
}
/** 最多30秒发现首次齐备;某项目异常只记录该次失败,不阻止其他项目下一轮检查。 */
@Scheduled(fixedDelayString="${project.manage.purchase-progress-delay:30000}",initialDelayString="${project.manage.purchase-progress-initial-delay:30000}")
public void scan() {
for(var candidate:mapper.selectPurchaseCandidates())try {
transaction.executeWithoutResult(status->{
long projectId=number(candidate,"project_id"),iterationId=number(candidate,"iteration_id"),stageId=number(candidate,"id");
workspace.lockProject(projectId);var stage=stages.selectActiveStage(stageId,projectId,iterationId);if(stage==null)return;
var revision=revisions.selectRevision(projectId,iterationId,stageId,number(stage,"current_revision_id"));
if(nullable(revision,"completed_at")!=null||nullable(revision,"ready_notified_at")!=null||"REJECTED".equals(text(revision,"approval_status")))return;
var graph=graphs.load(projectId,iterationId);if(!graph.iteration().active()||!PmStageRules.blockedStage(graph,stageId).isEmpty()||graph.stageRevisions().get(stageId).scheduleReviewReworkId()!=null)return;
if(workspace.selectMembers(projectId).stream().noneMatch(member->number(member,"userId")==number(stage,"created_by")))return;
var snapshot=evidence.sample(stage,revision);
// 验收或待验收到货出现后,登记“本轮已观察到执行”,不回填历史到货日,也不自动审批完成。
if(nullable(revision,"started_at")==null&&flag(revision,"purchase_scope_confirmed")&&hasProgress(snapshot)) {
long at=PmTime.now(),id=number(revision,"id");revisions.updateRevisionState(id,at,null);
revisions.refreshStartedIdentity(id,text(stage,"name"),nullable(stage,"owner_id"));var definition=revisions.selectLatestDefinition(projectId,iterationId);if(definition!=null)revisions.bindStartedDefinition(id,number(definition,"id"));
revisions.advanceGraphVersion(projectId,iterationId);groups.syncAutomatic(projectId,iterationId);
events.insertEvent(map("project_id",projectId,"iteration_id",iterationId,"work_item_id",null,"event_type","STAGE_STATUS_CHANGED","payload",json.encode(map("stageId",stageId,"revisionId",id,"from","NOT_STARTED","to","IN_PROGRESS","automatic",true)),"next_attempt_at",at,"created_at",at));
}
if(!evidence.reasons(stage,snapshot).isEmpty())return;
long at=PmTime.now();if(mapper.markReadyNotified(number(revision,"id"),at)!=1)return;
var detail=map("stageId",stageId,"stageName",stage.get("name"),"revisionId",revision.get("id"),"automatic",true,"notifyUserIds",List.of(number(stage,"created_by")));
var plan=notifications.plan(projectId,iterationId,null,"STAGE_PURCHASE_READY",detail,false);
events.insertEvent(map("project_id",projectId,"iteration_id",iterationId,"work_item_id",null,"event_type","STAGE_PURCHASE_READY","payload",json.encode(map("detail",detail,"notification",plan)),"next_attempt_at",at,"created_at",at));
});
}catch(Exception failure){LOG.warn("采购阶段达标提醒检查失败,阶段ID={}",candidate.get("id"),failure);}
}
/** 只看本项目未取消明细;零验收但已有待验收到货也属于执行中,不能把全取消当进度。 */
private static boolean hasProgress(java.util.Map<String,Object> snapshot) {
if(!(snapshot.get("purchase") instanceof java.util.Map<?,?> purchase)||!(purchase.get("batches") instanceof java.util.List<?> batches))return false;
for(Object value:batches)for(Object item:(java.util.List<?>)((java.util.Map<?,?>)value).get("lines")) {
var line=(java.util.Map<?,?>)item;
if(!Boolean.TRUE.equals(line.get("cancelled"))&&(new java.math.BigDecimal(line.get("acceptedQuantity").toString()).signum()>0||new java.math.BigDecimal(line.get("pendingQuantity").toString()).signum()>0))return true;
}
return false;
}
}

View File

@ -0,0 +1,17 @@
package com.ruoyi.project.manage.mapper;
import java.util.List;
import java.util.Map;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
/** 采购只读投影;只返回原项目验收所需字段,不能通过协作权限取得金额或其他项目明细。 */
@Mapper
public interface PmPurchaseReadMapper {
/** 从协作扩展确定原项目,不能将扩展主键用作采购 project_id。 */
Long selectSourceProjectId(@Param("projectId") long projectId);
/** 批次候选仅包含当前项目有效明细,搜索不扩大项目范围。 */
List<Map<String,Object>> selectOptions(@Param("sourceProjectId") long sourceProjectId,@Param("keyword") String keyword);
/** 单条 SQL 取得全部关联批次的原项目验收事实;禁用 MyBatis 缓存以建立明确采样点。 */
List<Map<String,Object>> selectLines(@Param("sourceProjectId") long sourceProjectId,@Param("batchIds") List<Long> batchIds);
}

View File

@ -0,0 +1,58 @@
package com.ruoyi.project.manage.mapper;
import com.ruoyi.project.manage.mapper.support.PmMapperWrite;
import java.util.List;
import java.util.Map;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
/** 阶段交付和审批持久层;所有写入由调用方持有项目图锁并与历史、outbox 原子提交。 */
@Mapper
public interface PmStageCompletionMapper {
/** 读取单轮审批历史;不把其他轮次的通过结果作为当前准入依据。 */
List<Map<String,Object>> selectApprovals(@Param("revisionId") long revisionId);
/** 查当前唯一待审批记录,唯一键作为项目锁之外的最后一道重复提交保护。 */
Map<String,Object> selectPending(@Param("revisionId") long revisionId);
/** 幂等提交只能重用原操作人的同一业务键。 */
Map<String,Object> selectByKey(@Param("projectId") long projectId,@Param("actor") long actor,@Param("key") String key);
/** 审批记录通过主键读取后仍须在服务层检查阶段、版本和操作者归属。 */
Map<String,Object> selectApproval(@Param("id") long id);
/** 服务器提供快照和真实身份;数据库生成申请序号及唯一主键。 */
int insertApprovalRow(@Param("values") Map<String,Object> values);
/** 在原事务中取得审批主键,不能用客户端 ID 替换数据库生成值。 */
default long insertApproval(Map<String,Object> values) { insertApprovalRow(values); return PmMapperWrite.generatedId(values); }
/** 只允许待审记录决定一次;幂等重试在服务层核对决定键和操作内容。 */
int decide(@Param("id") long id,@Param("status") String status,@Param("actor") long actor,@Param("at") long at,@Param("reason") String reason,@Param("key") String key);
/** 保存说明或状态并推进证据版本;历史轮次及过期请求不能覆盖当前内容。 */
int updateRevision(@Param("id") long id,@Param("version") int version,@Param("values") Map<String,Object> values);
/** 回退或迭代终止时使未决定的旧申请失效,不能把失效当作审批通过。 */
int invalidate(@Param("revisionId") long revisionId,@Param("status") String status,@Param("actor") long actor,@Param("at") long at,@Param("reason") String reason);
/** 一次首次齐备提醒;后续波动、轮询、驳回均不能重复通知。 */
int markReadyNotified(@Param("revisionId") long revisionId,@Param("at") long at);
/** 冻结完整交付内容,历史读取不连接当前采购数据或当前附件集合。 */
int freezeDelivery(@Param("revisionId") long revisionId,@Param("snapshot") String snapshot);
/** 当前和历史附件均返回元信息;私有对象键仅由单附件受鉴权读取使用。 */
List<Map<String,Object>> selectAttachments(@Param("revisionId") long revisionId);
/** 画布一次加载当前全部附件元数据,避免每个阶段分别查询文件列表。 */
List<Map<String,Object>> selectCurrentAttachments(@Param("projectId") long projectId,@Param("iterationId") long iterationId);
/** 并行子版本仍可继续执行时,旧父组合中的交付引用也必须保持可下载。 */
List<String> selectFrozenGroupSnapshots(@Param("revisionId") long revisionId);
/** 对象归属由服务复核,不通过文件名查找或下载任意 MinIO 对象。 */
Map<String,Object> selectAttachment(@Param("id") long id);
/** 上传成功后保存不可变对象元数据,数据库失败由存储适配器补偿删除新对象。 */
int insertAttachmentRow(@Param("values") Map<String,Object> values);
/** 返回真实附件主键,便于审计和后续受鉴权下载。 */
default long insertAttachment(Map<String,Object> values) { insertAttachmentRow(values); return PmMapperWrite.generatedId(values); }
/** 附件软删保留对象及历史引用;只允许一次有效删除。 */
int deleteAttachment(@Param("id") long id,@Param("actor") long actor,@Param("at") long at);
/** 批次关联属于精确执行版本,旧版本不跟随新版本范围变化。 */
List<Map<String,Object>> selectBatches(@Param("revisionId") long revisionId);
/** 一次读取当前采购阶段范围,历史批次不能加入画布实时进度。 */
List<Map<String,Object>> selectCurrentBatches(@Param("projectId") long projectId,@Param("iterationId") long iterationId);
/** 调整当前未完成范围,原关联保留在审批快照和操作历史中。 */
int deleteBatches(@Param("revisionId") long revisionId);
/** 一轮同一批次只关联一次;采购真实数据保持只读。 */
int insertBatch(@Param("revisionId") long revisionId,@Param("batchId") long batchId,@Param("actor") long actor,@Param("at") long at);
/** 仅扫描进行中迭代的当前采购轮次;调度器逐项目使用相同锁序重查。 */
List<Map<String,Object>> selectPurchaseCandidates();
}

View File

@ -3,6 +3,7 @@ package com.ruoyi.project.manage.notification;
import com.ruoyi.project.manage.mapper.PmNotificationMapper; import com.ruoyi.project.manage.mapper.PmNotificationMapper;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Set;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.annotation.Transactional;
@ -21,6 +22,10 @@ public class PmNotificationPlanner {
Map.entry("COMMENT_ADDED","工作项新增评论"),Map.entry("ATTACHMENT_ADDED","工作项新增附件"), Map.entry("COMMENT_ADDED","工作项新增评论"),Map.entry("ATTACHMENT_ADDED","工作项新增附件"),
Map.entry("ATTACHMENT_DELETED","工作项附件已删除")); Map.entry("ATTACHMENT_DELETED","工作项附件已删除"));
private final PmNotificationMapper mapper; private final PmNotificationMapper mapper;
private static final Map<String,String> STAGE_ACTIONS=Map.of(
"STAGE_COMPLETION_SUBMITTED","阶段完成待审批","STAGE_COMPLETION_APPROVED","阶段完成已通过",
"STAGE_COMPLETION_REJECTED","阶段完成已驳回","STAGE_COMPLETION_WITHDRAWN","阶段完成申请已撤回",
"STAGE_COMPLETION_INVALIDATED","阶段完成申请已失效","STAGE_PURCHASE_READY","采购阶段待审核完成");
/** 注入本模块的受控读取入口;通知内容不接受客户端提交的收件地址或模板。 */ /** 注入本模块的受控读取入口;通知内容不接受客户端提交的收件地址或模板。 */
public PmNotificationPlanner(PmNotificationMapper mapper) { this.mapper=mapper; } public PmNotificationPlanner(PmNotificationMapper mapper) { this.mapper=mapper; }
@ -38,6 +43,7 @@ public class PmNotificationPlanner {
*/ */
@Transactional(propagation=Propagation.MANDATORY) @Transactional(propagation=Propagation.MANDATORY)
public Map<String,Object> plan(long projectId,Long iterationId,Long itemId,String action,Object detail,boolean sendEmail) { public Map<String,Object> plan(long projectId,Long iterationId,Long itemId,String action,Object detail,boolean sendEmail) {
if(iterationId!=null&&STAGE_ACTIONS.containsKey(action)) return stagePlan(projectId,iterationId,action,detail,sendEmail);
boolean rework="STAGE_REWORKED".equals(action); boolean rework="STAGE_REWORKED".equals(action);
if(iterationId==null||(!rework&&(!ITEM_ACTIONS.containsKey(action)||itemId==null))) return null; if(iterationId==null||(!rework&&(!ITEM_ACTIONS.containsKey(action)||itemId==null))) return null;
Map<?,?> values=detail instanceof Map<?,?> map?map:Map.of(); Map<?,?> values=detail instanceof Map<?,?> map?map:Map.of();
@ -57,6 +63,19 @@ public class PmNotificationPlanner {
return map("userIds",targets,"title","【项目协作】"+actionName,"content",content,"sourcePath",path,"sendEmail",sendEmail); return map("userIds",targets,"title","【项目协作】"+actionName,"content",content,"sourcePath",path,"sendEmail",sendEmail);
} }
/** 阶段没有工作项ID,必须单独规划;收件人仅来自持锁服务构造的创建人/负责人快照。 */
private Map<String,Object> stagePlan(long projectId,long iterationId,String action,Object detail,boolean sendEmail) {
Map<?,?> values=detail instanceof Map<?,?> value?value:Map.of();
if(!(values.get("notifyUserIds") instanceof List<?> recipients)) return null;
Set<Long> ids=new java.util.TreeSet<>();for(Object value:recipients)if(value instanceof Number id&&id.longValue()>0)ids.add(id.longValue());
if(ids.isEmpty())return null;Map<String,Object> context=mapper.selectContext(projectId,iterationId,null);
if(context==null)throw new IllegalStateException("无法读取阶段通知所属项目和迭代");
String reason=values.get("reason")==null?"":"\n原因:"+oneLine(values.get("reason"));
String content="项目:"+oneLine(context.get("projectName"))+"\n迭代:"+oneLine(context.get("iterationName"))+"\n阶段:"+oneLine(values.get("stageName"))+"\n变更:"+STAGE_ACTIONS.get(action)+reason+"\n请进入项目协作的阶段详情处理。";
String path=text(context,"sourcePath");if(path==null||!path.matches("/[A-Za-z0-9_/-]*")||path.startsWith("//"))path="";
return map("userIds",List.copyOf(ids),"title","【项目协作】"+STAGE_ACTIONS.get(action),"content",content,"sourcePath",path,"sendEmail",sendEmail);
}
/** 名称保持为单行纯文本,避免标题或项目名称中的控制字符污染通知排版。 */ /** 名称保持为单行纯文本,避免标题或项目名称中的控制字符污染通知排版。 */
private static String oneLine(Object value) { return java.util.Objects.toString(value,"").replaceAll("\\p{Cntrl}"," ").strip(); } private static String oneLine(Object value) { return java.util.Objects.toString(value,"").replaceAll("\\p{Cntrl}"," ").strip(); }
} }

View File

@ -53,13 +53,14 @@ public final class PmIterationRules {
List<Item> current=graph.items().values().stream().filter(i->!i.deleted()).sorted(Comparator.comparingLong(Item::id)).toList(); List<Item> current=graph.items().values().stream().filter(i->!i.deleted()).sorted(Comparator.comparingLong(Item::id)).toList();
List<Map<String,Object>> unfinished=current.stream().filter(i->Set.of("READY","IN_PROGRESS").contains(i.status())).map(PmIterationRules::itemSummary).toList(); List<Map<String,Object>> unfinished=current.stream().filter(i->Set.of("READY","IN_PROGRESS").contains(i.status())).map(PmIterationRules::itemSummary).toList();
List<Map<String,Object>> exceptions=new ArrayList<>(); List<Map<String,Object>> exceptions=new ArrayList<>();
if(current.isEmpty()) exceptions.add(map("key","EMPTY_ITERATION","message","迭代没有有效工作项,不能按正常完成结束")); if(current.isEmpty()&&graph.stageNames().isEmpty()) exceptions.add(map("key","EMPTY_ITERATION","message","迭代没有有效阶段或工作项,不能按正常完成结束"));
for(Item item:current) if("CANCELLED".equals(item.status())) exceptions.add(map("key","ITEM_CANCELLED:"+item.id(),"message","工作项已取消","itemId",item.id())); for(Item item:current) if("CANCELLED".equals(item.status())) exceptions.add(map("key","ITEM_CANCELLED:"+item.id(),"message","工作项已取消","itemId",item.id()));
for(Long stageId:new TreeSet<>(graph.stageNames().keySet())) { for(Long stageId:new TreeSet<>(graph.stageNames().keySet())) {
if(!Set.of("COMPLETED","LEGACY_PASSED").contains(PmStageRules.executionStatus(graph,stageId))) if(!Set.of("COMPLETED","LEGACY_PASSED").contains(PmStageRules.executionStatus(graph,stageId)))
exceptions.add(map("key","STAGE_INCOMPLETE:"+stageId,"message","阶段尚未完成:"+graph.stageNames().get(stageId),"stageId",stageId)); exceptions.add(map("key","STAGE_INCOMPLETE:"+stageId,"message",(graph.stageRevisions().containsKey(stageId)&&"PENDING".equals(graph.stageRevisions().get(stageId).approvalStatus()))?"阶段存在待审批申请:"+graph.stageNames().get(stageId)+";异常结束将终止申请,重新打开后须重新提交":"阶段尚未完成:"+graph.stageNames().get(stageId),"stageId",stageId));
} }
return map("iterationId",iterationId,"version",version,"graphVersion",graphVersion,"unfinishedItems",unfinished, var pending=graph.stageRevisions().values().stream().filter(revision->"PENDING".equals(revision.approvalStatus())).map(revision->map("stageId",revision.stageId(),"name",graph.stageNames().get(revision.stageId()),"revisionId",revision.id())).toList();
return map("pendingApprovals",pending,"iterationId",iterationId,"version",version,"graphVersion",graphVersion,"unfinishedItems",unfinished,
"exceptions",exceptions,"finishResult",exceptions.isEmpty()?"COMPLETED":"WITH_EXCEPTIONS", "exceptions",exceptions,"finishResult",exceptions.isEmpty()?"COMPLETED":"WITH_EXCEPTIONS",
"canCommit","cancel".equals(action)||unfinished.isEmpty(),"itemsToCancel","cancel".equals(action)?unfinished:List.of()); "canCommit","cancel".equals(action)||unfinished.isEmpty(),"itemsToCancel","cancel".equals(action)?unfinished:List.of());
} }

View File

@ -25,7 +25,7 @@ public final class PmStageRules {
return blockedStage(graph,item.stageId()); return blockedStage(graph,item.stageId());
} }
/** 工作阶段按当前工作项、阶段组按全部子阶段汇总;空节点不自动放行,迁移事实保持只读兼容。 */ /** 工作阶段仅由已保存的审批或历史完成事实放行;阶段组聚合子阶段审批,工作项齐备不再等于完成。 */
public static String executionStatus(Graph graph,long stageId) { public static String executionStatus(Graph graph,long stageId) {
var revision=graph.stageRevisions().get(stageId); var revision=graph.stageRevisions().get(stageId);
if(revision!=null&&revision.legacyPassedAt()!=null) return "LEGACY_PASSED"; if(revision!=null&&revision.legacyPassedAt()!=null) return "LEGACY_PASSED";
@ -35,12 +35,20 @@ public final class PmStageRules {
if(children.stream().anyMatch(id->!"NOT_STARTED".equals(executionStatus(graph,id)))) return "IN_PROGRESS"; if(children.stream().anyMatch(id->!"NOT_STARTED".equals(executionStatus(graph,id)))) return "IN_PROGRESS";
return "NOT_STARTED"; return "NOT_STARTED";
} }
if(revision!=null&&revision.completedAt()!=null&&Set.of("MANUAL","PURCHASE","LEGACY_AUTO").contains(Objects.toString(revision.completionSource(),""))) return "COMPLETED";
List<Item> items=graph.items().values().stream().filter(i->!i.deleted()&&Objects.equals(i.stageId(),stageId)).toList(); List<Item> items=graph.items().values().stream().filter(i->!i.deleted()&&Objects.equals(i.stageId(),stageId)).toList();
if(!items.isEmpty()&&items.stream().allMatch(PmRules::completed)) return "COMPLETED";
if(revision!=null&&revision.startedAt()!=null || items.stream().anyMatch(i->Set.of("IN_PROGRESS","COMPLETED","CLOSED").contains(i.status()))) return "IN_PROGRESS"; if(revision!=null&&revision.startedAt()!=null || items.stream().anyMatch(i->Set.of("IN_PROGRESS","COMPLETED","CLOSED").contains(i.status()))) return "IN_PROGRESS";
return "NOT_STARTED"; return "NOT_STARTED";
} }
/** 所有交付写入口统一检查当前版本冻结状态;评论等不构成交付的讨论由独立入口鉴权。 */
public static void requireDeliveryMutable(Graph graph,Long stageId) {
if(stageId==null) return;
var revision=graph.stageRevisions().get(stageId);
if(revision!=null&&"PENDING".equals(revision.approvalStatus())) throw PmException.conflict("STAGE_APPROVAL_PENDING","阶段正在审批,请先撤回完成申请再修改交付内容");
if(Set.of("COMPLETED","LEGACY_PASSED").contains(executionStatus(graph,stageId))) throw PmException.conflict("STAGE_REVISION_FROZEN","阶段已完成,请通过流程回退创建新版本");
}
/** /**
* 从当前版本事实判断流程推进到的阶段,不用持久化指针限制并行分支。 * 从当前版本事实判断流程推进到的阶段,不用持久化指针限制并行分支。
* 未执行和执行中的阶段,只要所有上游已经完成便是当前阶段;空阶段仍未完成。 * 未执行和执行中的阶段,只要所有上游已经完成便是当前阶段;空阶段仍未完成。

View File

@ -0,0 +1,38 @@
package com.ruoyi.project.manage.service;
import com.ruoyi.project.manage.dto.StageCompletionInput;
import com.ruoyi.project.manage.dto.StagePurchaseInput;
import java.util.List;
import java.util.Map;
/** 阶段交付命令端口;状态、证据、历史与通知必须经过同一项目锁策略。 */
public interface IPmStageCompletionService {
/** 批量当前摘要包含提审、确认能力和采购进度;查询数不随节点数量增长。 */
Map<Long,Map<String,Object>> summaries(long projectId,long iterationId,List<Map<String,Object>> stages,com.ruoyi.project.manage.domain.Graph graph);
/** 读取当前或历史轮次的交付、完成条件及服务端操作能力。 */
Map<String,Object> detail(long projectId,long iterationId,long stageId,Long revisionId);
/** 审批证据按阶段及轮次校验,不能借另一条申请ID跨项目读取。 */
Map<String,Object> approvalEvidence(long projectId,long iterationId,long stageId,long approvalId);
/** 明确记录无工作项阶段的开始,不能绕过前置和迭代准入。 */
void start(long projectId,long iterationId,long stageId,StageCompletionInput input);
/** 保存当前轮次交付说明;待审批或已通过时禁止覆盖。 */
void note(long projectId,long iterationId,long stageId,StageCompletionInput input);
/** 负责人提交一次不可变证据申请,重复命令不产生重复通知。 */
long submit(long projectId,long iterationId,long stageId,StageCompletionInput input);
/** 创建人审批或负责人撤回,决定只能发生一次并绑定当前版本。 */
Map<String,Object> decide(long projectId,long iterationId,long stageId,long approvalId,String action,StageCompletionInput input);
/** 采购达标仍可调整范围;创建人显式确认时才保存通过快照。 */
long confirmPurchase(long projectId,long iterationId,long stageId,StageCompletionInput input);
/** 返回原项目必要批次信息,不授予原采购详情访问权限。 */
List<Map<String,Object>> purchaseOptions(long projectId,long iterationId,String keyword);
/** 绑定当前轮次的原项目采购批次,不修改真实采购数据。 */
void batches(long projectId,long iterationId,long stageId,StagePurchaseInput input);
/** 阶段附件使用MinIO私有对象,数据库失败补偿新上传对象。 */
long attach(long projectId,long iterationId,long stageId,long revisionId,String name,String mediaType,byte[] content);
/** 人员显式沿用旧交付,复制为新MinIO对象,不继承旧审批或伪造新上传来源。 */
long reuseAttachment(long projectId,long iterationId,long stageId,long revisionId,long sourceRevisionId,long attachmentId);
/** 交付维护人软删当前附件,历史对象保留供审批证据读取。 */
void deleteAttachment(long projectId,long iterationId,long stageId,long revisionId,long attachmentId);
/** 受鉴权下载绑定到精确阶段和轮次,不返回对象键给客户端。 */
Map<String,Object> attachment(long projectId,long iterationId,long stageId,long revisionId,long attachmentId);
}

View File

@ -40,10 +40,12 @@ public class PmIterationServiceImpl implements IPmIterationService {
private final PmJson codec; private final PmJson codec;
private final ObjectMapper json; private final ObjectMapper json;
private final com.ruoyi.project.manage.service.support.PmGroupVersionService groups; private final com.ruoyi.project.manage.service.support.PmGroupVersionService groups;
private final com.ruoyi.project.manage.service.support.PmStageApprovalLifecycle approvals;
/** 所有依赖共享上层事务连接;取消复用现有最终图校验,避免直接批量改状态。 */ /** 所有依赖共享上层事务连接;取消复用现有最终图校验,避免直接批量改状态。 */
public PmIterationServiceImpl(PmIterationMapper mapper,PmWorkspaceMapper workspace,PmAccess access,PmIterationAccess iterations, public PmIterationServiceImpl(PmIterationMapper mapper,PmWorkspaceMapper workspace,PmAccess access,PmIterationAccess iterations,
PmGraphService graphs,PmAuditService audit,IPmService business,PmJson codec,ObjectMapper json,com.ruoyi.project.manage.service.support.PmGroupVersionService groups) { PmGraphService graphs,PmAuditService audit,IPmService business,PmJson codec,ObjectMapper json,com.ruoyi.project.manage.service.support.PmGroupVersionService groups,com.ruoyi.project.manage.service.support.PmStageApprovalLifecycle approvals) {
this.approvals=approvals;
this.groups=groups; this.groups=groups;
this.mapper=mapper; this.workspace=workspace; this.access=access; this.iterations=iterations; this.mapper=mapper; this.workspace=workspace; this.access=access; this.iterations=iterations;
this.graphs=graphs; this.audit=audit; this.business=business; this.codec=codec; this.json=json; this.graphs=graphs; this.audit=audit; this.business=business; this.codec=codec; this.json=json;
@ -142,11 +144,13 @@ public class PmIterationServiceImpl implements IPmIterationService {
case "finish" -> { case "finish" -> {
Map<String,Object> preview=previewOf(projectId,iterationId,row,action); Map<String,Object> preview=previewOf(projectId,iterationId,row,action);
PmIterationRules.confirmFinish(preview,input.acceptedExceptionIds(),input.reason()); PmIterationRules.confirmFinish(preview,input.acceptedExceptionIds(),input.reason());
if("WITH_EXCEPTIONS".equals(preview.get("finishResult")))approvals.terminate(projectId,iterationId,access.actor());
values.putAll(map("status","FINISHED","finish_result",preview.get("finishResult"),"finish_note",input.reason(),"actual_end_at",now)); values.putAll(map("status","FINISHED","finish_result",preview.get("finishResult"),"finish_note",input.reason(),"actual_end_at",now));
} }
case "cancel" -> { case "cancel" -> {
Map<String,Object> preview=previewOf(projectId,iterationId,row,action); Map<String,Object> preview=previewOf(projectId,iterationId,row,action);
PmIterationRules.confirmCancel(preview,input.acceptedItemIds()); PmIterationRules.confirmCancel(preview,input.acceptedItemIds());
approvals.terminate(projectId,iterationId,access.actor());
business.cancelRemaining(projectId,iterationId,input.acceptedItemIds()==null?List.of():input.acceptedItemIds()); business.cancelRemaining(projectId,iterationId,input.acceptedItemIds()==null?List.of():input.acceptedItemIds());
values.putAll(map("status","CANCELLED","finish_result",null,"finish_note",input.reason(),"actual_end_at",now)); values.putAll(map("status","CANCELLED","finish_result",null,"finish_note",input.reason(),"actual_end_at",now));
} }

View File

@ -51,11 +51,14 @@ public class PmReworkServiceImpl implements IPmReworkService {
private final ObjectMapper decoder; private final ObjectMapper decoder;
private final PmParticipantService participants; private final PmParticipantService participants;
private final PmGroupVersionService groups; private final PmGroupVersionService groups;
private final com.ruoyi.project.manage.service.support.PmStageApprovalLifecycle approvals;
private final com.ruoyi.project.manage.mapper.PmStageCompletionMapper completion;
/** 只注入本模块 Mapper 和统一鉴权,事务失败时版本、工作项与 outbox 一同回滚。 */ /** 只注入本模块 Mapper 和统一鉴权,事务失败时版本、工作项与 outbox 一同回滚。 */
public PmReworkServiceImpl(PmWorkspaceMapper workspace,PmStageMapper stages,PmWorkItemMapper workItems, public PmReworkServiceImpl(PmWorkspaceMapper workspace,PmStageMapper stages,PmWorkItemMapper workItems,
PmDependencyMapper dependencies,PmRevisionMapper revisions,PmGraphService graphs, PmDependencyMapper dependencies,PmRevisionMapper revisions,PmGraphService graphs,
PmAuditService audit,PmAccess access,PmJson json,ObjectMapper decoder,PmIterationAccess iterationAccess,com.ruoyi.project.manage.mapper.PmScheduleMapper schedules,com.ruoyi.project.manage.service.IPmScheduleService scheduleService,PmParticipantService participants,PmGroupVersionService groups) { PmAuditService audit,PmAccess access,PmJson json,ObjectMapper decoder,PmIterationAccess iterationAccess,com.ruoyi.project.manage.mapper.PmScheduleMapper schedules,com.ruoyi.project.manage.service.IPmScheduleService scheduleService,PmParticipantService participants,PmGroupVersionService groups,com.ruoyi.project.manage.service.support.PmStageApprovalLifecycle approvals,com.ruoyi.project.manage.mapper.PmStageCompletionMapper completion) {
this.approvals=approvals;this.completion=completion;
this.groups=groups; this.groups=groups;
this.participants=participants; this.participants=participants;
this.schedules=schedules; this.scheduleService=scheduleService; this.schedules=schedules; this.scheduleService=scheduleService;
@ -109,6 +112,7 @@ public class PmReworkServiceImpl implements IPmReworkService {
for(Long stageId:versioned) if(PmStageHierarchyRules.info(before,stageId).group()) groups.freeze(before,stageId); for(Long stageId:versioned) if(PmStageHierarchyRules.info(before,stageId).group()) groups.freeze(before,stageId);
for(Long stageId:versioned) { for(Long stageId:versioned) {
var old=before.stageRevisions().get(stageId); var old=before.stageRevisions().get(stageId);
approvals.supersede(projectId,iterationId,stageId,old.id(),actor);
Map<String,Object> stage=stages.selectActiveStage(stageId,projectId,iterationId); Map<String,Object> stage=stages.selectActiveStage(stageId,projectId,iterationId);
boolean aggregate=plan.aggregates().contains(stageId); boolean aggregate=plan.aggregates().contains(stageId);
long next=revisions.insertRevision(map("project_id",projectId,"iteration_id",iterationId,"stage_id",stageId,"revision_no",old.revisionNo()+1, long next=revisions.insertRevision(map("project_id",projectId,"iteration_id",iterationId,"stage_id",stageId,"revision_no",old.revisionNo()+1,
@ -120,6 +124,8 @@ public class PmReworkServiceImpl implements IPmReworkService {
"reference_planned_end_at",aggregate?old.referenceEnd():old.plannedEnd()==null?old.referenceEnd():old.plannedEnd(), "reference_planned_end_at",aggregate?old.referenceEnd():old.plannedEnd()==null?old.referenceEnd():old.plannedEnd(),
"schedule_review_rework_id",aggregate?old.scheduleReviewReworkId():Long.valueOf(reworkId),"created_by",actor,"created_at",at)); "schedule_review_rework_id",aggregate?old.scheduleReviewReworkId():Long.valueOf(reworkId),"created_by",actor,"created_at",at));
nextRevisions.put(stageId,next); nextRevisions.put(stageId,next);
// 新轮次只复制批次参考,不复制验收通过或范围确认;采购真实数量不受回退影响。
if("PURCHASE".equals(text(stage,"node_type")))for(var batch:completion.selectBatches(old.id()))completion.insertBatch(next,number(batch,"batchId"),actor,at);
} }
Map<Long,Long> mapped=new LinkedHashMap<>(); Map<Long,Long> mapped=new LinkedHashMap<>();
// 父项先于子项插入;复制只继承业务文本和仍有效的成员,不继承执行与排期事实。 // 父项先于子项插入;复制只继承业务文本和仍有效的成员,不继承执行与排期事实。
@ -304,6 +310,8 @@ public class PmReworkServiceImpl implements IPmReworkService {
} }
for(Long id:additions(input).keySet()) if(!affected.contains(id)||PmStageHierarchyRules.info(graph,id).group()) blockers.add(map("code","ADDITION_STAGE_INVALID","stageId",id,"message","补录工作项只能归入受影响的工作阶段,阶段组不能直接放工作项")); for(Long id:additions(input).keySet()) if(!affected.contains(id)||PmStageHierarchyRules.info(graph,id).group()) blockers.add(map("code","ADDITION_STAGE_INVALID","stageId",id,"message","补录工作项只能归入受影响的工作阶段,阶段组不能直接放工作项"));
for(var entry:additions(input).entrySet()) for(ReworkItemInput added:entry.getValue()) validateAddition(projectId,added); for(var entry:additions(input).entrySet()) for(ReworkItemInput added:entry.getValue()) validateAddition(projectId,added);
for(var entry:additions(input).entrySet())if("PURCHASE".equals(PmStageHierarchyRules.info(graph,entry.getKey()).nodeType())&&!entry.getValue().isEmpty())blockers.add(map("code","PURCHASE_WORK_ITEMS_FORBIDDEN","stageId",entry.getKey(),"message","采购阶段不能在回退补录中创建工作项"));
for(Item item:copies)if("PURCHASE".equals(PmStageHierarchyRules.info(graph,item.stageId()).nodeType()))blockers.add(map("code","PURCHASE_LEGACY_WORK_ITEMS","stageId",item.stageId(),"message","请先处理采购阶段旧工作项归属,再执行回退"));
// 空版本仍是未执行且阻塞后继,允许先回退再补工作项,不能强制生成虚假任务。 // 空版本仍是未执行且阻塞后继,允许先回退再补工作项,不能强制生成虚假任务。
Set<Long> aggregates=new TreeSet<>(); Set<Long> aggregates=new TreeSet<>();
for(Long id:affected) aggregates.addAll(PmStageHierarchyRules.parents(graph,id)); for(Long id:affected) aggregates.addAll(PmStageHierarchyRules.parents(graph,id));

View File

@ -68,6 +68,7 @@ public class PmScheduleServiceImpl implements IPmScheduleService {
for(StageScheduleInput change:stageChanges) { for(StageScheduleInput change:stageChanges) {
if(change==null||!seen.add(change.id())) throw PmException.bad("阶段排期为空或重复"); if(change==null||!seen.add(change.id())) throw PmException.bad("阶段排期为空或重复");
StageRevision old=before.stageRevisions().get(change.id()); if(old==null) throw PmAccess.denied(); StageRevision old=before.stageRevisions().get(change.id()); if(old==null) throw PmAccess.denied();
if("PENDING".equals(old.approvalStatus())) throw PmException.conflict("STAGE_APPROVAL_PENDING","阶段待审批,请先撤回申请再改期");
if(change.revisionId()==null||change.revisionId()!=old.id()) throw PmException.conflict("STAGE_REVISION_CHANGED","阶段已换版,请刷新后重试"); if(change.revisionId()==null||change.revisionId()!=old.id()) throw PmException.conflict("STAGE_REVISION_CHANGED","阶段已换版,请刷新后重试");
version(change.version(),old.version()); boolean finished=finished(before,change.id()); version(change.version(),old.version()); boolean finished=finished(before,change.id());
if(backfill) { if(backfill) {
@ -90,6 +91,7 @@ public class PmScheduleServiceImpl implements IPmScheduleService {
throw PmAccess.denied(); throw PmAccess.denied();
} }
if(old.deleted()) throw PmAccess.denied(); version(change.version(),old.version()); if(old.deleted()) throw PmAccess.denied(); version(change.version(),old.version());
if(old.stageId()!=null) PmStageRules.requireDeliveryMutable(before,old.stageId());
if(old.stageId()!=null&&finished(before,old.stageId())) throw PmException.conflict("STAGE_REVISION_FROZEN","已完成阶段不能修改工作项排期"); if(old.stageId()!=null&&finished(before,old.stageId())) throw PmException.conflict("STAGE_REVISION_FROZEN","已完成阶段不能修改工作项排期");
PmTime.Plan plan=PmTime.planned(change.plannedStartAt(),change.plannedEndAt()); Long start=plan.start(),end=plan.end(); PmTime.Plan plan=PmTime.planned(change.plannedStartAt(),change.plannedEndAt()); Long start=plan.start(),end=plan.end();
if(old.scheduleReviewReworkId()!=null) { if(old.scheduleReviewReworkId()!=null) {

View File

@ -262,6 +262,7 @@ public class PmServiceImpl implements IPmService {
if(!"READY".equals(existing.status())) throw PmException.conflict("ITEM_STAGE_LOCKED","只有待开始工作项可以调整阶段"); if(!"READY".equals(existing.status())) throw PmException.conflict("ITEM_STAGE_LOCKED","只有待开始工作项可以调整阶段");
if(input.stageId()!=null&&stageMapper.selectActiveStageId(input.stageId(),projectId,iterationId)==null) throw PmAccess.denied(); if(input.stageId()!=null&&stageMapper.selectActiveStageId(input.stageId(),projectId,iterationId)==null) throw PmAccess.denied();
requireStageMutable(graph,input.stageId()); validateInheritedStage(graph,existing,input.stageId()); if(Objects.equals(existing.stageId(),input.stageId())) return; requireStageMutable(graph,input.stageId()); validateInheritedStage(graph,existing,input.stageId()); if(Objects.equals(existing.stageId(),input.stageId())) return;
if(input.stageId()!=null&&"PURCHASE".equals(com.ruoyi.project.manage.rule.PmStageHierarchyRules.info(graph,input.stageId()).nodeType())) throw PmException.bad("采购阶段不能承载工作项");
Graph before=graph.copy(); simulateStage(graph,existing,input.stageId()); Graph before=graph.copy(); simulateStage(graph,existing,input.stageId());
PmRules.validateSchedules(graph,zone(projectId)); PmRules.validateAcyclic(graph); PmStageRules.validateRegression(before,graph); PmRules.validateSchedules(graph,zone(projectId)); PmRules.validateAcyclic(graph); PmStageRules.validateRegression(before,graph);
workItemMapper.updateWorkItem(id,existing.version(),map("stage_id",input.stageId(),"stage_revision_id",currentRevision(graph,input.stageId()))); workItemMapper.updateWorkItem(id,existing.version(),map("stage_id",input.stageId(),"stage_revision_id",currentRevision(graph,input.stageId())));
@ -419,9 +420,10 @@ public class PmServiceImpl implements IPmService {
return targets.stream().map(graph.items()::get).filter(i->!i.deleted()).map(i->view(graph,i,zone,writable)).toList(); return targets.stream().map(graph.items()::get).filter(i->!i.deleted()).map(i->view(graph,i,zone,writable)).toList();
} }
/** 评论在受限工作项事务内保存,不把客户端内容当作 HTML 执行。 */ /** 待审批仍允许讨论,但历史、已完成阶段和终态迭代继续只读;评论不改写交付证据。 */
public void comment(long id,CommentInput input) { public void comment(long id,CommentInput input) {
long projectId=projectOf(id),iterationId=iterationOf(id); locked(projectId,iterationId,"write"); writableItem(graphService.load(projectId,iterationId),id); long projectId=projectOf(id),iterationId=iterationOf(id); locked(projectId,iterationId,"write"); Graph graph=graphService.load(projectId,iterationId); Item current=item(graph,id);
if(current.stageId()!=null&&Set.of("COMPLETED","LEGACY_PASSED").contains(PmStageRules.executionStatus(graph,current.stageId()))) throw PmException.conflict("STAGE_REVISION_FROZEN","已完成阶段保持只读");
activityMapper.insertComment(map("work_item_id",id,"body",required(input.body(),10000,"评论"),"created_by",access.actor(),"created_at",PmTime.now())); auditService.record(projectId,iterationId,id,"COMMENT_ADDED",map("message","新增评论"),access.actor()); activityMapper.insertComment(map("work_item_id",id,"body",required(input.body(),10000,"评论"),"created_by",access.actor(),"created_at",PmTime.now())); auditService.record(projectId,iterationId,id,"COMMENT_ADDED",map("message","新增评论"),access.actor());
} }
@ -615,13 +617,16 @@ public class PmServiceImpl implements IPmService {
response.put("stageGroupId",item.stageId()==null?null:com.ruoyi.project.manage.rule.PmStageHierarchyRules.info(graph,item.stageId()).parentId()); response.put("stageGroupId",item.stageId()==null?null:com.ruoyi.project.manage.rule.PmStageHierarchyRules.info(graph,item.stageId()).parentId());
response.put("collaborators",item.collaborators()); response.put("collaborators",item.collaborators());
boolean mutable=graph.iteration()!=null&&graph.iteration().mutable(); boolean mutable=graph.iteration()!=null&&graph.iteration().mutable();
var stageRevision=item.stageId()==null?null:graph.stageRevisions().get(item.stageId());
boolean frozen=stageRevision!=null&&("PENDING".equals(stageRevision.approvalStatus())||Set.of("COMPLETED","LEGACY_PASSED").contains(PmStageRules.executionStatus(graph,item.stageId())));
response.put("stageApprovalStatus",stageRevision==null?null:stageRevision.approvalStatus());response.put("stageReadOnly",frozen);
response.putAll(map("iterationId",graph.iteration()==null?null:graph.iteration().id(),"iterationStatus",graph.iteration()==null?null:graph.iteration().status(),"iterationReadOnly",!mutable)); response.putAll(map("iterationId",graph.iteration()==null?null:graph.iteration().id(),"iterationStatus",graph.iteration()==null?null:graph.iteration().status(),"iterationReadOnly",!mutable));
Item parent=item.parentTaskId()==null?null:graph.items().get(item.parentTaskId()); Item parent=item.parentTaskId()==null?null:graph.items().get(item.parentTaskId());
List<Item> children=PmRules.children(graph,item.id()); List<Map<String,Object>> unfinished=PmRules.unfinishedChildren(graph,item.id()); List<Item> children=PmRules.children(graph,item.id()); List<Map<String,Object>> unfinished=PmRules.unfinishedChildren(graph,item.id());
boolean overdue=PmRules.overdue(item,PmTime.now()); boolean overdue=PmRules.overdue(item,PmTime.now());
response.putAll(map("parentTaskId",item.parentTaskId(),"parentTaskTitle",parent==null?null:parent.title(),"parentPlannedStartAt",parent==null?null:PmTime.format(parent.start(),zone),"parentPlannedEndAt",parent==null?null:PmTime.format(parent.end(),zone),"childCount",children.size(),"childTerminalCount",children.stream().filter(PmRules::terminal).count(),"canCreateChild",writable&&"TASK".equals(item.type())&&item.parentTaskId()==null&&!PmRules.terminal(item),"canComplete",writable&&"IN_PROGRESS".equals(item.status())&&unfinished.isEmpty(),"completionBlockedReasons",unfinished,"overdue",overdue,"displayStatus",overdue?"OVERDUE":item.status())); response.putAll(map("parentTaskId",item.parentTaskId(),"parentTaskTitle",parent==null?null:parent.title(),"parentPlannedStartAt",parent==null?null:PmTime.format(parent.start(),zone),"parentPlannedEndAt",parent==null?null:PmTime.format(parent.end(),zone),"childCount",children.size(),"childTerminalCount",children.stream().filter(PmRules::terminal).count(),"canCreateChild",writable&&"TASK".equals(item.type())&&item.parentTaskId()==null&&!PmRules.terminal(item),"canComplete",writable&&"IN_PROGRESS".equals(item.status())&&unfinished.isEmpty(),"completionBlockedReasons",unfinished,"overdue",overdue,"displayStatus",overdue?"OVERDUE":item.status()));
response.put("stageId",item.stageId()); response.put("stageRevisionId",item.stageRevisionId()); response.put("stageRevisionNo",item.stageId()==null?null:graph.stageRevisions().get(item.stageId())==null?null:graph.stageRevisions().get(item.stageId()).revisionNo()); response.put("originWorkItemId",item.originWorkItemId()); response.put("scheduleReviewRequired",item.scheduleReviewReworkId()!=null); response.put("scheduleReviewClosed",item.scheduleReviewReworkId()!=null&&(!mutable||PmRules.completed(item)||item.stageId()!=null&&Set.of("COMPLETED","LEGACY_PASSED").contains(PmStageRules.executionStatus(graph,item.stageId())))); response.put("referencePlannedStartAt",PmTime.format(item.referenceStart(),zone)); response.put("referencePlannedEndAt",PmTime.format(item.referenceEnd(),zone)); response.put("stageId",item.stageId()); response.put("stageRevisionId",item.stageRevisionId()); response.put("stageRevisionNo",item.stageId()==null?null:graph.stageRevisions().get(item.stageId())==null?null:graph.stageRevisions().get(item.stageId()).revisionNo()); response.put("originWorkItemId",item.originWorkItemId()); response.put("scheduleReviewRequired",item.scheduleReviewReworkId()!=null); response.put("scheduleReviewClosed",item.scheduleReviewReworkId()!=null&&(!mutable||PmRules.completed(item)||item.stageId()!=null&&Set.of("COMPLETED","LEGACY_PASSED").contains(PmStageRules.executionStatus(graph,item.stageId())))); response.put("referencePlannedStartAt",PmTime.format(item.referenceStart(),zone)); response.put("referencePlannedEndAt",PmTime.format(item.referenceEnd(),zone));
if(!mutable) { response.put("canCreateChild",false); response.put("canComplete",false); } if(!mutable||frozen) { response.put("canCreateChild",false); response.put("canComplete",false); }
response.putAll(startability(graph,item,zone,writable)); response.put("dependencyBlocked",!PmRules.blocked(graph,item.id(),zone).isEmpty()||!PmStageRules.blocked(graph,item.id()).isEmpty()); response.put("scheduleConstraints",PmRules.schedule(graph,item,zone)); return response; response.putAll(startability(graph,item,zone,writable)); response.put("dependencyBlocked",!PmRules.blocked(graph,item.id(),zone).isEmpty()||!PmStageRules.blocked(graph,item.id()).isEmpty()); response.put("scheduleConstraints",PmRules.schedule(graph,item,zone)); return response;
} }
@ -657,17 +662,17 @@ public class PmServiceImpl implements IPmService {
Item current=graph.items().get(id); Item current=graph.items().get(id);
if(!writable||graph.iteration()==null||!graph.iteration().mutable()||current==null||current.deleted()) return false; if(!writable||graph.iteration()==null||!graph.iteration().mutable()||current==null||current.deleted()) return false;
if(current.stageId()!=null&&Set.of("COMPLETED","LEGACY_PASSED").contains(PmStageRules.executionStatus(graph,current.stageId()))) return false; if(current.stageId()!=null&&Set.of("COMPLETED","LEGACY_PASSED").contains(PmStageRules.executionStatus(graph,current.stageId()))) return false;
if(current.stageId()!=null&&"PENDING".equals(graph.stageRevisions().get(current.stageId()).approvalStatus())) return false;
long actor=access.actor(); long actor=access.actor();
Map<String,Object> reference=workItemMapper.selectProjectReference(id); Map<String,Object> reference=workItemMapper.selectProjectReference(id);
return Long.valueOf(actor).equals(current.assigneeId())||reference!=null&&Long.valueOf(actor).equals(nullable(reference,"created_by")); return Long.valueOf(actor).equals(current.assigneeId())||reference!=null&&Long.valueOf(actor).equals(nullable(reference,"created_by"));
} }
/** 已完成或迁移放行阶段不可增减和改写工作项,重做必须走经理回退入口。 */ /** 待审批和已完成阶段统一冻结交付,所有工作项写入口必须复用此规则。 */
private static void requireStageMutable(Graph graph,Long stageId) { private static void requireStageMutable(Graph graph,Long stageId) {
if(stageId==null) return; if(stageId==null) return;
if(com.ruoyi.project.manage.rule.PmStageHierarchyRules.info(graph,stageId).group()) throw PmException.bad("阶段组承载子阶段,请选择具体工作阶段"); if(com.ruoyi.project.manage.rule.PmStageHierarchyRules.info(graph,stageId).group()) throw PmException.bad("阶段组承载子阶段,请选择具体工作阶段");
String status=PmStageRules.executionStatus(graph,stageId); PmStageRules.requireDeliveryMutable(graph,stageId);
if(Set.of("COMPLETED","LEGACY_PASSED").contains(status)) throw PmException.conflict("STAGE_REVISION_FROZEN","阶段已完成,需由项目经理创建回退版本后重做");
} }
/** 所有写入口识别旧版 ID 并拒绝,避免当前图过滤后把历史项误当作可写。 */ /** 所有写入口识别旧版 ID 并拒绝,避免当前图过滤后把历史项误当作可写。 */
@ -683,7 +688,7 @@ public class PmServiceImpl implements IPmService {
return current; return current;
} }
/** 工作项写入后从事务内新图推导阶段状态,并将转换时间、审计和 outbox 一并提交。 */ /** 工作项只能触发阶段首次开始;完成事实由审批服务保存,不能再随最后一个工作项自动完成。 */
private void syncStage(long projectId,long iterationId,Long stageId,String previousStatus) { private void syncStage(long projectId,long iterationId,Long stageId,String previousStatus) {
if(stageId==null) return; if(stageId==null) return;
Graph after=graphService.load(projectId,iterationId); String status=PmStageRules.executionStatus(after,stageId); Graph after=graphService.load(projectId,iterationId); String status=PmStageRules.executionStatus(after,stageId);
@ -730,7 +735,11 @@ public class PmServiceImpl implements IPmService {
required(input.title(),200,"标题"); if(input.type()==null||!Set.of("REQUIREMENT","TASK","BUG").contains(input.type())) throw PmException.bad("工作项类型无效"); required(input.title(),200,"标题"); if(input.type()==null||!Set.of("REQUIREMENT","TASK","BUG").contains(input.type())) throw PmException.bad("工作项类型无效");
if(input.priority()!=null&&!Set.of("LOW","MEDIUM","HIGH","URGENT").contains(input.priority())) throw PmException.bad("优先级无效"); if(input.priority()!=null&&!Set.of("LOW","MEDIUM","HIGH","URGENT").contains(input.priority())) throw PmException.bad("优先级无效");
if(input.description()!=null&&input.description().length()>50000) throw PmException.bad("描述过长"); access.assignee(projectId,input.assigneeId()); if(input.description()!=null&&input.description().length()>50000) throw PmException.bad("描述过长"); access.assignee(projectId,input.assigneeId());
if(input.stageId()!=null&&stageMapper.selectActiveStageId(input.stageId(),projectId,iterationId)==null) throw PmAccess.denied(); if(input.stageId()!=null) {
var stage=stageMapper.selectActiveStage(input.stageId(),projectId,iterationId);
if(stage==null) throw PmAccess.denied();
if("PURCHASE".equals(text(stage,"node_type"))) throw PmException.bad("采购阶段不能创建或移入工作项,请选择其他阶段");
}
} }
/** 标题等文本拒绝空白和过长值,调用方使用返回的修剪值保存。 */ /** 标题等文本拒绝空白和过长值,调用方使用返回的修剪值保存。 */

View File

@ -0,0 +1,337 @@
package com.ruoyi.project.manage.service.impl;
import com.ruoyi.project.manage.domain.Graph;
import com.ruoyi.project.manage.dto.StageCompletionInput;
import com.ruoyi.project.manage.dto.StagePurchaseInput;
import com.ruoyi.project.manage.exception.PmException;
import com.ruoyi.project.manage.mapper.*;
import com.ruoyi.project.manage.rule.PmStageRules;
import com.ruoyi.project.manage.security.PmAccess;
import com.ruoyi.project.manage.security.PmIterationAccess;
import com.ruoyi.project.manage.service.IPmStageCompletionService;
import com.ruoyi.project.manage.service.support.*;
import com.ruoyi.project.manage.util.PmJson;
import com.ruoyi.project.manage.util.PmTime;
import java.util.*;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;
import static com.ruoyi.project.manage.util.PmValues.*;
/** 人工审批与采购确认的唯一命令入口;采购确认的是采样事实,不假装冻结外部采购写入。 */
@Service
@Transactional(isolation=Isolation.READ_COMMITTED,rollbackFor=Exception.class)
public class PmStageCompletionServiceImpl implements IPmStageCompletionService {
/** 同一次项目锁事务复用人员资格,避免画布逐节点重复执行身份SQL。 */
private record Viewer(long actor,boolean writable,boolean manager,Set<Long> members) { }
private final PmWorkspaceMapper workspace;
private final PmStageMapper stages;
private final PmRevisionMapper revisions;
private final PmStageCompletionMapper mapper;
private final PmGraphService graphs;
private final PmStageEvidenceService evidence;
private final PmPurchaseProgressReader purchases;
private final PmAttachmentStorage storage;
private final PmAccess access;
private final PmIterationAccess iterations;
private final PmAuditService audit;
private final PmGroupVersionService groups;
private final PmJson json;
/** 仅依赖协作端口和只读采购适配器,不调用其他业务模块的写服务。 */
public PmStageCompletionServiceImpl(PmWorkspaceMapper workspace,PmStageMapper stages,PmRevisionMapper revisions,PmStageCompletionMapper mapper,
PmGraphService graphs,PmStageEvidenceService evidence,PmPurchaseProgressReader purchases,PmAttachmentStorage storage,
PmAccess access,PmIterationAccess iterations,PmAuditService audit,PmGroupVersionService groups,PmJson json) {
this.workspace=workspace;this.stages=stages;this.revisions=revisions;this.mapper=mapper;this.graphs=graphs;this.evidence=evidence;
this.purchases=purchases;this.storage=storage;this.access=access;this.iterations=iterations;this.audit=audit;this.groups=groups;this.json=json;
}
/**
* 当前读提供实时证据,历史只读冻结快照;采购源变化与历史审批依据分开展示。
* @param revisionId 空值读取当前版本;历史ID必须属于同项目、同迭代、同阶段
* @return 交付、审批历史及当前用户能力;审批历史不重复携带每次完整证据
*/
public Map<String,Object> detail(long projectId,long iterationId,long stageId,Long revisionId) {
locked(projectId,iterationId,"read");Map<String,Object> stage=stage(projectId,iterationId,stageId);
long id=revisionId==null?number(stage,"current_revision_id"):revisionId;
Map<String,Object> revision=revision(projectId,iterationId,stageId,id);
boolean historical=id!=number(stage,"current_revision_id");
Graph graph=graphs.load(projectId,iterationId);
Map<String,Object> frozen=evidence.decode(text(revision,"delivery_snapshot_json"));
Map<String,Object> snapshot=historical?frozen:evidence.sample(stage,revision);
List<Map<String,Object>> approvals=mapper.selectApprovals(id);
for(Map<String,Object> row:approvals) { row.remove("snapshot_json"); row.put("submittedAt",time(nullable(row,"submitted_at")));row.put("decidedAt",time(nullable(row,"decided_at"))); }
Map<String,Object> capabilities=capabilities(stage,revision,graph,snapshot,historical||revisionId!=null);
return map("revisionId",id,"revisionVersion",number(revision,"version"),"historical",historical||revisionId!=null,"approvalStatus",revision.get("approval_status"),
"completionSource",revision.get("completion_source"),"note",revision.get("completion_note"),"delivery",snapshot,"approvedDelivery",frozen,
"sourceChanged",!historical&&frozen!=null&&snapshot!=null&&!evidence.fingerprint(frozen).equals(evidence.fingerprint(snapshot)),
"evidenceHash",snapshot==null?null:evidence.fingerprint(snapshot),"approvals",approvals,"capabilities",capabilities);
}
/** 批量摘要复用锁内图及人员投影;只携带稳定指纹,采样时刻不导致无变化画布重建。 */
public Map<Long,Map<String,Object>> summaries(long projectId,long iterationId,List<Map<String,Object>> definitions,Graph graph) {
var batch=evidence.sampleAll(projectId,iterationId,graph,definitions);var viewer=viewer(projectId,graph);Map<Long,Map<String,Object>> result=new LinkedHashMap<>();
for(var stage:definitions) {
long id=number(stage,"id");var revision=batch.revisions().get(id);var snapshot=batch.snapshots().get(id);var capabilities=capabilities(stage,revision,graph,snapshot,false,viewer);
Map<?,?> purchase=snapshot.get("purchase") instanceof Map<?,?> value?value:Map.of();
result.put(id,map("approvalStatus",revision.get("approval_status"),"completionSource",revision.get("completion_source"),"creatorId",stage.get("created_by"),
"canEditDelivery",capabilities.get("canEditDelivery"),"canSubmitCompletion",capabilities.get("canSubmit"),"canApproveCompletion",capabilities.get("canApprove"),"canConfirmPurchase",capabilities.get("canConfirmPurchase"),
"deliveryReady",capabilities.get("deliveryReady"),"deliveryAttachmentCount",((List<?>)snapshot.get("attachments")).size(),"deliveryEvidenceHash",evidence.fingerprint(snapshot),"purchaseProgress",purchase.get("progress"),"purchaseBatchCount",purchase.get("batches") instanceof List<?> batches?batches.size():0));
}
return result;
}
/** 单条申请证据始终按归属鉴权,客户端不能指定任意JSON或其他阶段的申请。 */
public Map<String,Object> approvalEvidence(long projectId,long iterationId,long stageId,long approvalId) {
locked(projectId,iterationId,"read");stage(projectId,iterationId,stageId); Map<String,Object> row=approval(projectId,iterationId,stageId,approvalId);
return evidence.decode(text(row,"snapshot_json"));
}
/** 无任务阶段可显式开始;第一工作项开始也仍由原服务的统一准入保护。 */
public void start(long projectId,long iterationId,long stageId,StageCompletionInput input) {
locked(projectId,iterationId,"start");var stage=stage(projectId,iterationId,stageId);maintainer(stage);Graph graph=graphs.load(projectId,iterationId);
var revision=current(stage,projectId,iterationId,input);mutable(graph,stageId);admission(graph,stageId);
if(nullable(revision,"started_at")!=null) return;
update(revision,map("started_at",PmTime.now()));bindStartedIdentity(stage,revision);revisions.advanceGraphVersion(projectId,iterationId);groups.sync(projectId,iterationId);
record(stage,"STAGE_STARTED",map("message","开始阶段"),List.of(),false);
}
/** 说明保存与证据版本一同推进,待审与历史版本禁止覆盖。 */
public void note(long projectId,long iterationId,long stageId,StageCompletionInput input) {
locked(projectId,iterationId,"write");var stage=stage(projectId,iterationId,stageId);maintainer(stage);
var revision=current(stage,projectId,iterationId,input);mutable(graphs.load(projectId,iterationId),stageId);
String note=input.note()==null?"":input.note().strip();if(note.length()>10000)throw PmException.bad("交付说明不能超过10000字");
update(revision,map("completion_note",note));revisions.advanceGraphVersion(projectId,iterationId);
record(stage,"STAGE_DELIVERY_EDITED",map("message","修改阶段交付说明"),List.of(),false);
}
/** 负责人提交完整快照;幂等键重试不得修改原申请或重复发送提醒。 */
public long submit(long projectId,long iterationId,long stageId,StageCompletionInput input) {
locked(projectId,iterationId,"start");var stage=stage(projectId,iterationId,stageId);owner(stage);String key=key(input);
var replay=mapper.selectByKey(projectId,access.actor(),key);if(replay!=null)return replay(replay,stage,input,"OWNER");
var revision=current(stage,projectId,iterationId,input);Graph graph=graphs.load(projectId,iterationId);mutable(graph,stageId);admission(graph,stageId);
if("PURCHASE".equals(text(stage,"node_type")))throw PmException.bad("采购阶段由创建人直接核验确认");
access.assignee(projectId,nullable(stage,"created_by"));
var snapshot=evidence.sample(stage,revision);eligible(stage,snapshot);hash(input,snapshot);
long at=PmTime.now(),id=insert(stage,revision,snapshot,"OWNER","PENDING",key,null,null,at);
update(revision,map("approval_status","PENDING","started_at",at));bindStartedIdentity(stage,revision);revisions.advanceGraphVersion(projectId,iterationId);groups.sync(projectId,iterationId);
record(stage,"STAGE_COMPLETION_SUBMITTED",map("approvalId",id,"message","负责人申请阶段完成"),List.of(number(stage,"created_by")),Boolean.TRUE.equals(input.sendEmail()));return id;
}
/**
* 通过、驳回和撤回仅决定一次;证据过期返回已提交的失效结果,控制器再映射409,避免异常回滚失效标记。
* @param action approve、reject或withdraw;决定者必须为创建人或原申请负责人
* @return 成功或业务失效结果,历史、通知及状态在同一事务内提交
*/
public Map<String,Object> decide(long projectId,long iterationId,long stageId,long approvalId,String action,StageCompletionInput input) {
if(!Set.of("approve","reject","withdraw").contains(action))throw PmException.bad("不支持的审批动作");
locked(projectId,iterationId,"start");var stage=stage(projectId,iterationId,stageId);var request=approval(projectId,iterationId,stageId,approvalId);
if("withdraw".equals(action))owner(stage);else creator(stage);
if(number(request,"revision_id")!=number(stage,"current_revision_id"))throw PmException.conflict("STAGE_REVISION_CHANGED","申请所属版本已被替换,请查看历史或重新提交");
String desired=switch(action){case "approve"->"APPROVED";case "reject"->"REJECTED";default->"WITHDRAWN";};String command=key(input);
if(!"PENDING".equals(text(request,"status"))) {
String replayReason=input.reason()==null||input.reason().isBlank()?null:input.reason().strip();
if(desired.equals(text(request,"status"))&&command.equals(text(request,"decision_key"))&&Objects.equals(nullable(request,"decided_by"),access.actor())&&Objects.equals(text(request,"reason"),replayReason))return map("status",desired,"approvalId",approvalId);
throw PmException.conflict("STAGE_APPROVAL_ALREADY_DECIDED","该申请已被处理,请刷新");
}
var revision=current(stage,projectId,iterationId,input);
if(number(request,"revision_id")!=number(revision,"id"))throw PmException.conflict("STAGE_REVISION_CHANGED","申请所属版本已被替换");
Graph graph=graphs.load(projectId,iterationId);admission(graph,stageId);long at=PmTime.now();String reason=input.reason()==null?null:input.reason().strip();
if("reject".equals(action))reason=required(reason,2000,"驳回原因");else if(reason!=null&&reason.length()>2000)throw PmException.bad("说明不能超过2000字");
Map<String,Object> snapshot=null;
if("approve".equals(action)) {
snapshot=evidence.sample(stage,revision);
if(!text(request,"evidence_hash").equals(evidence.fingerprint(snapshot))||!evidence.reasons(stage,snapshot).isEmpty()) {
mapper.decide(approvalId,"INVALIDATED",access.actor(),at,"交付依据已变化,请负责人重新提交",command);
update(revision,map("approval_status","INVALIDATED"));revisions.advanceGraphVersion(projectId,iterationId);
record(stage,"STAGE_COMPLETION_INVALIDATED",map("approvalId",approvalId,"message","申请证据变化,原申请已失效"),recipients(stage),false);
return map("conflict",true,"code","STAGE_EVIDENCE_CHANGED","message","交付依据已变化,申请已失效,请重新提交");
}
hash(input,snapshot);
}
if(mapper.decide(approvalId,desired,access.actor(),at,reason,command)!=1)throw PmException.conflict("STAGE_APPROVAL_ALREADY_DECIDED","申请已被其他操作处理");
Map<String,Object> values=map("approval_status",desired);
if("APPROVED".equals(desired)){values.putAll(map("completed_at",at,"completion_source","MANUAL"));mapper.freezeDelivery(number(revision,"id"),json.encode(snapshot));}
update(revision,values);revisions.advanceGraphVersion(projectId,iterationId);groups.sync(projectId,iterationId);
List<Long> targets="withdraw".equals(action)?List.of(number(stage,"created_by")):nullable(stage,"owner_id")==null?List.of():List.of(number(stage,"owner_id"));
record(stage,"STAGE_COMPLETION_"+desired,map("approvalId",approvalId,"reason",reason,"message",desired),targets,Boolean.TRUE.equals(input.sendEmail()));
return map("status",desired,"approvalId",approvalId);
}
/** 采购只在创建人操作时保存通过或退回记录;100%本身不冻结范围,也不自动提交申请。 */
public long confirmPurchase(long projectId,long iterationId,long stageId,StageCompletionInput input) {
locked(projectId,iterationId,"start");var stage=stage(projectId,iterationId,stageId);creator(stage);
if(!"PURCHASE".equals(text(stage,"node_type")))throw PmException.bad("仅采购阶段使用验收确认");
String key=key(input);var replay=mapper.selectByKey(projectId,access.actor(),key);if(replay!=null)return replay(replay,stage,input,"PURCHASE_CONFIRM");
var revision=current(stage,projectId,iterationId,input);Graph graph=graphs.load(projectId,iterationId);mutable(graph,stageId);admission(graph,stageId);
var snapshot=evidence.sample(stage,revision);eligible(stage,snapshot);hash(input,snapshot);
boolean reject=input.reason()!=null&&!input.reason().isBlank();String reason=reject?required(input.reason(),2000,"退回原因"):null;
long at=PmTime.now();String status=reject?"REJECTED":"APPROVED";
long id=insert(stage,revision,snapshot,"PURCHASE_CONFIRM",status,key,access.actor(),reason,at);
Map<String,Object> values=map("approval_status",status,"started_at",at);
if(!reject){values.putAll(map("completed_at",at,"completion_source","PURCHASE"));mapper.freezeDelivery(number(revision,"id"),json.encode(snapshot));}
update(revision,values);bindStartedIdentity(stage,revision);revisions.advanceGraphVersion(projectId,iterationId);groups.sync(projectId,iterationId);
record(stage,"STAGE_COMPLETION_"+status,map("approvalId",id,"reason",reason,"message",reject?"采购验收退回处理":"采购验收确认完成"),nullable(stage,"owner_id")==null?List.of():List.of(number(stage,"owner_id")),Boolean.TRUE.equals(input.sendEmail()));return id;
}
/** 仅返回已鉴权项目的批次摘要,选择器搜索不能突破原项目数据范围。 */
public List<Map<String,Object>> purchaseOptions(long projectId,long iterationId,String keyword) { locked(projectId,iterationId,"read");if(keyword!=null&&keyword.length()>100)throw PmException.bad("搜索词过长");return purchases.options(projectId,keyword); }
/** 采购范围可在确认完成前调整;回退复制后首次保存同时确认本轮范围。 */
public void batches(long projectId,long iterationId,long stageId,StagePurchaseInput input) {
locked(projectId,iterationId,"write");var stage=stage(projectId,iterationId,stageId);maintainerOrManager(stage);
if(!"PURCHASE".equals(text(stage,"node_type")))throw PmException.bad("只有采购阶段能绑定批次");
var revision=revision(projectId,iterationId,stageId,number(stage,"current_revision_id"));expected(input.revisionId(),input.version(),revision);mutable(graphs.load(projectId,iterationId),stageId);
List<Long> ids=input.batchIds()==null?List.of():input.batchIds();
if(ids.size()>100||ids.stream().anyMatch(id->id==null||id<=0)||new HashSet<>(ids).size()!=ids.size())throw PmException.bad("批次最多100个,不能重复或为空");
Map<String,Object> progress=purchases.readBatches(projectId,ids);
for(Object batch:(List<?>)progress.get("batches"))if(!Boolean.TRUE.equals(((Map<?,?>)batch).get("available")))throw PmException.bad("批次不存在或没有当前项目的有效明细");
mapper.deleteBatches(number(revision,"id"));long actor=access.actor(),at=PmTime.now();for(Long id:ids)mapper.insertBatch(number(revision,"id"),id,actor,at);
update(revision,map("purchase_scope_confirmed",true));revisions.advanceGraphVersion(projectId,iterationId);
record(stage,"STAGE_PURCHASE_SCOPE_CHANGED",map("batchIds",ids,"message","确认本轮采购批次范围"),List.of(),false);
}
/** 当前交付维护人上传真实MinIO附件,空文件、超限和不合法媒体类型均拒绝。 */
public long attach(long projectId,long iterationId,long stageId,long revisionId,String name,String mediaType,byte[] content) {
locked(projectId,iterationId,"write");var stage=stage(projectId,iterationId,stageId);maintainer(stage);var revision=currentId(stage,projectId,iterationId,revisionId);mutable(graphs.load(projectId,iterationId),stageId);
if(content==null||content.length==0||content.length>PmAttachmentStorage.MAX_BYTES)throw PmException.bad("附件需为1字节至10MiB");
String path=name==null?"附件":name.replace('\\','/');String safeName=required(path.substring(path.lastIndexOf('/')+1),255,"附件名称");
if(safeName.chars().anyMatch(Character::isISOControl))throw PmException.bad("附件名不能包含控制字符");
String type=mediaType==null?"application/octet-stream":required(mediaType,120,"文件类型");
try{org.springframework.http.MediaType.parseMediaType(type);}catch(IllegalArgumentException failure){throw PmException.bad("文件类型格式无效");}
var object=storage.save(projectId,iterationId,content,type);
long id=mapper.insertAttachment(map("revision_id",revisionId,"name",safeName,"media_type",type,"object_key",object.key(),"sha256",object.sha256(),"size",content.length,"created_by",access.actor(),"created_at",PmTime.now()));
update(revision,Map.of());revisions.advanceGraphVersion(projectId,iterationId);record(stage,"STAGE_ATTACHMENT_ADDED",map("attachmentId",id,"name",safeName),List.of(),false);return id;
}
/** 显式复用同阶段已被替换轮次的交付,复制私有对象以保持两轮软删及回滚补偿相互独立。 */
public long reuseAttachment(long projectId,long iterationId,long stageId,long revisionId,long sourceRevisionId,long attachmentId) {
locked(projectId,iterationId,"write");var stage=stage(projectId,iterationId,stageId);maintainer(stage);currentId(stage,projectId,iterationId,revisionId);mutable(graphs.load(projectId,iterationId),stageId);
var previous=revision(projectId,iterationId,stageId,sourceRevisionId);
if(sourceRevisionId==revisionId||nullable(previous,"superseded_at")==null)throw PmException.bad("只能沿用同一阶段已被替换旧版本的交付附件");
var file=attachment(projectId,iterationId,stageId,sourceRevisionId,attachmentId);var metadata=mapper.selectAttachment(attachmentId);
long id=attach(projectId,iterationId,stageId,revisionId,text(file,"name"),text(metadata,"media_type"),(byte[])file.get("content"));
record(stage,"STAGE_ATTACHMENT_REUSED",map("attachmentId",id,"sourceRevisionId",sourceRevisionId,"sourceAttachmentId",attachmentId),List.of(),false);return id;
}
/** 软删不销毁对象,历史审批依据仍可完整下载;阶段创建人和负责人均可维护。 */
public void deleteAttachment(long projectId,long iterationId,long stageId,long revisionId,long attachmentId) {
locked(projectId,iterationId,"write");var stage=stage(projectId,iterationId,stageId);maintainer(stage);var revision=currentId(stage,projectId,iterationId,revisionId);mutable(graphs.load(projectId,iterationId),stageId);
var file=mapper.selectAttachment(attachmentId);if(file==null||number(file,"revision_id")!=revisionId||flag(file,"deleted"))throw PmAccess.denied();
mapper.deleteAttachment(attachmentId,access.actor(),PmTime.now());update(revision,Map.of());revisions.advanceGraphVersion(projectId,iterationId);record(stage,"STAGE_ATTACHMENT_DELETED",map("attachmentId",attachmentId,"name",file.get("name")),List.of(),false);
}
/** 仅当前有效文件或真实历史证据引用可下载,不能用附件ID读取其他版本。 */
public Map<String,Object> attachment(long projectId,long iterationId,long stageId,long revisionId,long attachmentId) {
locked(projectId,iterationId,"read");stage(projectId,iterationId,stageId);var revision=revision(projectId,iterationId,stageId,revisionId);
var file=mapper.selectAttachment(attachmentId);if(file==null||number(file,"revision_id")!=revisionId)throw PmAccess.denied();
if(flag(file,"deleted")) {
boolean referenced=references(evidence.decode(text(revision,"delivery_snapshot_json")),attachmentId);
if(!referenced)for(var request:mapper.selectApprovals(revisionId))if(references(evidence.decode(text(request,"snapshot_json")),attachmentId)){referenced=true;break;}
if(!referenced)for(String saved:mapper.selectFrozenGroupSnapshots(revisionId)) {
var parent=evidence.decode(saved);Object delivery=parent==null?null:parent.get("delivery");
if(delivery instanceof Map<?,?> value&&value.get("attachments") instanceof List<?> files&&files.stream().anyMatch(entry->entry instanceof Map<?,?> item&&item.get("id") instanceof Number id&&id.longValue()==attachmentId)){referenced=true;break;}
}
if(!referenced)throw PmAccess.denied();
}
return map("name",file.get("name"),"content",storage.read(projectId,iterationId,text(file,"object_key"),number(file,"size"),text(file,"sha256")));
}
/** 单阶段详情只计算一次查看者资格;实际命令仍独立重查,不能信任旧布尔值。 */
private Map<String,Object> capabilities(Map<String,Object> stage,Map<String,Object> revision,Graph graph,Map<String,Object> snapshot,boolean historical) {
return capabilities(stage,revision,graph,snapshot,historical,viewer(number(stage,"project_id"),graph));
}
/** 后端能力与命令共用身份及类型规则;缺负责人、创建人不可用和排期待复核均给出明确原因。 */
private Map<String,Object> capabilities(Map<String,Object> stage,Map<String,Object> revision,Graph graph,Map<String,Object> snapshot,boolean historical,Viewer viewer) {
long id=number(stage,"id"),actor=viewer.actor();boolean owner=Objects.equals(nullable(stage,"owner_id"),actor),creator=number(stage,"created_by")==actor;
boolean writable=!historical&&viewer.writable();
boolean complete=Set.of("COMPLETED","LEGACY_PASSED").contains(PmStageRules.executionStatus(graph,id));boolean pending="PENDING".equals(text(revision,"approval_status"));
boolean group="GROUP".equals(text(stage,"stage_kind")),purchase="PURCHASE".equals(text(stage,"node_type"));
List<Map<String,Object>> reasons=new ArrayList<>(snapshot==null?List.of(map("code","HISTORY_NOT_CAPTURED","message","旧轮次未留存完整交付快照")):evidence.reasons(stage,snapshot));
if(!group&&!purchase&&nullable(stage,"owner_id")==null)reasons.add(map("code","STAGE_OWNER_REQUIRED","message","请项目管理者先为阶段设置负责人"));
if(!group&&!viewer.members().contains(number(stage,"created_by")))reasons.add(map("code","STAGE_CREATOR_UNAVAILABLE","message","阶段创建人不是有效项目成员,不能自动代审,请先恢复其资格"));
List<Map<String,Object>> stageReasons=admissionReasons(graph,id);
boolean admitted=graph.iteration().active()&&stageReasons.isEmpty();boolean ready=reasons.isEmpty();
boolean mutable=writable&&!complete&&!pending&&!group;
return map("deliveryReady",ready,"blockedReasons",reasons,"stageBlockedReasons",stageReasons,
"canEditDelivery",mutable&&(owner||creator),"canEditPurchase",mutable&&purchase&&(owner||creator||viewer.manager()),
"canStart",mutable&&admitted&&(owner||creator)&&nullable(revision,"started_at")==null,
"canSubmit",mutable&&!purchase&&owner&&admitted&&ready,"canWithdraw",writable&&pending&&owner&&admitted,
"canApprove",writable&&pending&&creator&&admitted,"canConfirmPurchase",mutable&&purchase&&creator&&admitted&&ready);
}
/** 一次成员查询同时服务全图;创建者隐式成员与显式成员按原项目绑定合并。 */
private Viewer viewer(long projectId,Graph graph) {
long actor=access.actor();boolean writable=graph.iteration().mutable()&&access.canWrite(projectId),manager=false;
if(writable)try{access.project(projectId,"admin");manager=true;}catch(PmException denied){if(denied.getHttpStatus()!=403)throw denied;}
Set<Long> members=new HashSet<>();for(var member:workspace.selectMembers(projectId))members.add(number(member,"userId"));
return new Viewer(actor,writable,manager,members);
}
/** 项目→协作图固定锁序覆盖权限复查和所有审批写入;采购源仅作明确时点采样。 */
private void locked(long projectId,long iterationId,String action) { access.project(projectId,"read".equals(action)?"read":"write");workspace.lockProject(projectId);access.project(projectId,"read".equals(action)?"read":"write");iterations.require(projectId,iterationId,action); }
/** 对象不存在和越权使用相同响应,避免泄露其他项目阶段。 */
private Map<String,Object> stage(long projectId,long iterationId,long id) {var value=stages.selectActiveStage(id,projectId,iterationId);if(value==null)throw PmAccess.denied();return value;}
/** 历史轮次必须属于精确的项目、迭代和阶段。 */
private Map<String,Object> revision(long projectId,long iterationId,long stageId,long revisionId) {var value=revisions.selectRevision(projectId,iterationId,stageId,revisionId);if(value==null)throw PmAccess.denied();return value;}
/** 申请ID不能替代归属校验;回退后的旧申请只能只读。 */
private Map<String,Object> approval(long projectId,long iterationId,long stageId,long id) {var value=mapper.selectApproval(id);if(value==null||number(value,"project_id")!=projectId||number(value,"iteration_id")!=iterationId||number(value,"stage_id")!=stageId)throw PmAccess.denied();return value;}
/** 命令必须同时绑定当前轮次和版本,历史ID或过期表单不得覆盖新交付。 */
private Map<String,Object> current(Map<String,Object> stage,long projectId,long iterationId,StageCompletionInput input) {var row=revision(projectId,iterationId,number(stage,"id"),number(stage,"current_revision_id"));if(input==null)throw PmException.bad("缺少执行版本");expected(input.revisionId(),input.version(),row);return row;}
/** 文件命令也必须显式携带当前轮次,不能在回退期间上传到旧轮次。 */
private Map<String,Object> currentId(Map<String,Object> stage,long projectId,long iterationId,long revisionId) {if(number(stage,"current_revision_id")!=revisionId)throw PmException.conflict("STAGE_REVISION_CHANGED","阶段已换版,请刷新");return revision(projectId,iterationId,number(stage,"id"),revisionId);}
/** 对版本缺失返回400,对已变化返回409,不采用最后写入覆盖。 */
private static void expected(Long id,Integer version,Map<String,Object> row) {if(id==null||version==null)throw PmException.bad("缺少执行版本和数据版本");if(id!=number(row,"id")||version!=number(row,"version"))throw PmException.conflict("VERSION_CONFLICT","阶段交付已变化,请刷新");}
/** 只有当前负责人可提交或撤回,项目经理不能冒充负责人。 */
private void owner(Map<String,Object> stage) {if(!Objects.equals(nullable(stage,"owner_id"),access.actor()))throw PmAccess.denied();}
/** 审批身份固定为阶段创建人,不能使用执行版本创建人或管理员兜底。 */
private void creator(Map<String,Object> stage) {if(number(stage,"created_by")!=access.actor())throw PmAccess.denied();}
/** 创建人及负责人可维护交付,但仍受项目写权限和冻结状态约束。 */
private void maintainer(Map<String,Object> stage) {long actor=access.actor();if(number(stage,"created_by")!=actor&&!Objects.equals(nullable(stage,"owner_id"),actor))throw PmAccess.denied();}
/** 批次配置允许项目经理维护,审批权限仍不因此扩大。 */
private void maintainerOrManager(Map<String,Object> stage) {long actor=access.actor();if(number(stage,"created_by")!=actor&&!Objects.equals(nullable(stage,"owner_id"),actor))access.project(number(stage,"project_id"),"admin");}
/** 容器不能变成交付阶段;其完成来自子阶段审批聚合。 */
private static void mutable(Graph graph,long stageId) {PmStageRules.requireDeliveryMutable(graph,stageId);if(graph.hierarchy().get(stageId).group())throw PmException.bad("阶段组仅聚合子阶段,不单独提交交付");}
/** 即使没有工作项,阶段开始、提审和采购确认也不能绕过上游。 */
private static void admission(Graph graph,long stageId) {var reasons=admissionReasons(graph,stageId);if(!reasons.isEmpty())throw new PmException(409,"STAGE_NOT_ADMITTED","前置阶段未通过或本轮排期待复核",map("blockedReasons",reasons));}
/** 零任务阶段也必须确认回退后的阶段排期,不能绕过工作项原有的排期复核门禁。 */
private static List<Map<String,Object>> admissionReasons(Graph graph,long stageId) {var reasons=new ArrayList<>(PmStageRules.blockedStage(graph,stageId));var revision=graph.stageRevisions().get(stageId);if(revision!=null&&revision.scheduleReviewReworkId()!=null)reasons.add(map("code","SCHEDULE_REVIEW_REQUIRED","message","请先确认本轮阶段预计开始和结束日期"));return reasons;}
/** 齐备理由以结构化错误返回,取消项和空集合都不能被当作全部完成。 */
private void eligible(Map<String,Object> stage,Map<String,Object> snapshot) {var reasons=evidence.reasons(stage,snapshot);if(!reasons.isEmpty())throw new PmException(409,"STAGE_DELIVERY_INCOMPLETE","阶段交付条件尚未满足",map("blockedReasons",reasons));}
/** 比较用户看过的证据,不能在界面显示旧内容时悄悄通过新范围。 */
private void hash(StageCompletionInput input,Map<String,Object> snapshot) {if(input.evidenceHash()==null||!input.evidenceHash().equals(evidence.fingerprint(snapshot)))throw PmException.conflict("STAGE_EVIDENCE_CHANGED","交付或采购验收数据已变化,请刷新后重新确认");}
/** 所有命令键使用受限ASCII字符,避免截断或同一键绑定多个不同动作。 */
private static String key(StageCompletionInput input) {if(input==null||input.idempotencyKey()==null||!input.idempotencyKey().matches("[A-Za-z0-9:_-]{1,100}"))throw PmException.bad("缺少有效幂等键");return input.idempotencyKey();}
/** 重试仅返回原结果,不能把同一键用于另一阶段、轮次或采购确认类型。 */
private long replay(Map<String,Object> row,Map<String,Object> stage,StageCompletionInput input,String source) {
if(number(row,"revision_id")!=number(stage,"current_revision_id"))throw PmException.conflict("STAGE_REVISION_CHANGED","原请求所属版本已被替换,不能继续提交历史版本");
String reason=input.reason()==null||input.reason().isBlank()?null:input.reason().strip();
boolean purchaseChanged="PURCHASE_CONFIRM".equals(source)&&(!Objects.equals(reason,text(row,"reason"))||!(reason==null?"APPROVED":"REJECTED").equals(text(row,"status")));
if(number(row,"stage_id")!=number(stage,"id")||!Objects.equals(nullable(row,"revision_id"),input.revisionId())||!source.equals(text(row,"request_source"))||!Objects.equals(text(row,"evidence_hash"),input.evidenceHash())||purchaseChanged)throw PmException.conflict("IDEMPOTENCY_CONFLICT","该幂等键已经用于其他交付命令");return number(row,"id");
}
/** 在持锁事务内插入证据及真实身份,采购直接确认不伪造负责人申请。 */
private long insert(Map<String,Object> stage,Map<String,Object> revision,Map<String,Object> snapshot,String source,String status,String key,Long decider,String reason,long at) {
return mapper.insertApproval(map("project_id",stage.get("project_id"),"iteration_id",stage.get("iteration_id"),"stage_id",stage.get("id"),"revision_id",revision.get("id"),"request_source",source,"submitted_by","OWNER".equals(source)?access.actor():null,"approver_id",stage.get("created_by"),"owner_id",stage.get("owner_id"),"status",status,"evidence_hash",evidence.fingerprint(snapshot),"snapshot_json",json.encode(snapshot),"submitted_at",at,"decided_by",decider,"decided_at",decider==null?null:at,"reason",reason,"command_actor",access.actor(),"idempotency_key",key,"decision_key",decider==null?null:key));
}
/** CAS和项目锁共同防止跨入口覆盖,更新失败不留下成功历史。 */
private void update(Map<String,Object> revision,Map<String,Object> values) {if(mapper.updateRevision(number(revision,"id"),(int)number(revision,"version"),values)!=1)throw PmException.conflict("VERSION_CONFLICT","阶段版本已变化,请刷新");}
/** 零工作项开始或首次提审也要固定当时名称、负责人和流程定义,不能只为任务开始保留历史。 */
private void bindStartedIdentity(Map<String,Object> stage,Map<String,Object> revision) {
if(nullable(revision,"started_at")!=null)return;
long projectId=number(stage,"project_id"),iterationId=number(stage,"iteration_id"),id=number(revision,"id");
revisions.refreshStartedIdentity(id,text(stage,"name"),nullable(stage,"owner_id"));
var definition=revisions.selectLatestDefinition(projectId,iterationId);
if(definition!=null)revisions.bindStartedDefinition(id,number(definition,"id"));
}
/** 业务收件人只能来自服务端阶段身份,客户端不能注入通知目标。 */
private void record(Map<String,Object> stage,String action,Map<String,Object> detail,List<Long> targets,boolean sendEmail) {Map<String,Object> value=map("stageId",stage.get("id"),"stageName",stage.get("name"),"revisionId",stage.get("current_revision_id"),"notifyUserIds",targets);value.putAll(detail);audit.record(number(stage,"project_id"),number(stage,"iteration_id"),null,action,value,access.actor(),sendEmail);}
/** 去重后的双方用于失效提醒;采购可没有负责人。 */
private static List<Long> recipients(Map<String,Object> stage) {var ids=new TreeSet<Long>();ids.add(number(stage,"created_by"));if(nullable(stage,"owner_id")!=null)ids.add(number(stage,"owner_id"));return List.copyOf(ids);}
/** 下载已删除对象时必须证明它确实属于已保存审批证据。 */
private static boolean references(Map<String,Object> snapshot,long attachmentId) {return snapshot!=null&&snapshot.get("attachments") instanceof List<?> files&&files.stream().anyMatch(value->value instanceof Map<?,?> file&&file.get("id") instanceof Number id&&id.longValue()==attachmentId);}
/** 审批时间保留准确时刻,页面预计日期仍遵循整日规则。 */
private static String time(Long value) {return PmTime.format(value,"Asia/Shanghai");}
/** 服务端统一拒绝空白和超长业务文本,不能依赖前端maxlength或浏览器文件名校验。 */
private static String required(String value,int maximum,String name) {if(value==null||value.isBlank()||value.strip().length()>maximum)throw PmException.bad(name+"不能为空且不能超过"+maximum+"个字符");return value.strip();}
}

View File

@ -45,9 +45,11 @@ public class PmStageServiceImpl implements IPmStageService {
private final PmIterationAccess iterationAccess; private final PmIterationAccess iterationAccess;
private final IPmService business; private final IPmService business;
private final com.ruoyi.project.manage.service.support.PmGroupVersionService groups; private final com.ruoyi.project.manage.service.support.PmGroupVersionService groups;
private final com.ruoyi.project.manage.service.IPmStageCompletionService completion;
/** 注入当前阶段业务需要的 Mapper 和规则,浏览器布局不再依赖数据库 Mapper。 */ /** 注入当前阶段业务需要的 Mapper 和规则,浏览器布局不再依赖数据库 Mapper。 */
public PmStageServiceImpl(PmWorkspaceMapper workspaceMapper,PmWorkItemMapper workItemMapper,PmStageMapper stageMapper,PmRevisionMapper revisionMapper,PmGraphService graphService,PmAuditService auditService,PmJson jsonCodec,PmAccess access,IPmService business,PmIterationAccess iterationAccess,com.ruoyi.project.manage.mapper.PmScheduleMapper schedules,com.ruoyi.project.manage.service.support.PmGroupVersionService groups) { public PmStageServiceImpl(PmWorkspaceMapper workspaceMapper,PmWorkItemMapper workItemMapper,PmStageMapper stageMapper,PmRevisionMapper revisionMapper,PmGraphService graphService,PmAuditService auditService,PmJson jsonCodec,PmAccess access,IPmService business,PmIterationAccess iterationAccess,com.ruoyi.project.manage.mapper.PmScheduleMapper schedules,com.ruoyi.project.manage.service.support.PmGroupVersionService groups,com.ruoyi.project.manage.service.IPmStageCompletionService completion) {
this.completion=completion;
this.groups=groups; this.groups=groups;
this.schedules=schedules; this.schedules=schedules;
this.iterationAccess=iterationAccess; this.iterationAccess=iterationAccess;
@ -81,6 +83,8 @@ public class PmStageServiceImpl implements IPmStageService {
catch(PmException error) { if(error.getHttpStatus()!=403) throw error; canManage=false; } catch(PmException error) { if(error.getHttpStatus()!=403) throw error; canManage=false; }
} }
boolean canWrite=graph.iteration()!=null&&graph.iteration().mutable()&&access.canWrite(projectId); boolean canWrite=graph.iteration()!=null&&graph.iteration().mutable()&&access.canWrite(projectId);
List<Map<String,Object>> definitions=stages.stream().map(stage->map("id",stage.get("id"),"project_id",projectId,"iteration_id",iterationId,"name",stage.get("name"),"node_type",stage.get("nodeType"),"stage_kind",stage.get("stageKind"),"current_revision_id",stage.get("currentRevisionId"),"created_by",stage.get("creatorId"),"owner_id",stage.get("ownerId"))).toList();
var completionSummaries=completion.summaries(projectId,iterationId,definitions,graph);
for(Map<String,Object> stage:stages) { for(Map<String,Object> stage:stages) {
long stageId=number(stage,"id"); stage.putAll(summary(items,stageId,graph)); long stageId=number(stage,"id"); stage.putAll(summary(items,stageId,graph));
String executionStatus=PmStageRules.executionStatus(graph,stageId); String executionStatus=PmStageRules.executionStatus(graph,stageId);
@ -90,7 +94,8 @@ public class PmStageServiceImpl implements IPmStageService {
var children=com.ruoyi.project.manage.rule.PmStageHierarchyRules.children(graph,stageId); var children=com.ruoyi.project.manage.rule.PmStageHierarchyRules.children(graph,stageId);
boolean group=com.ruoyi.project.manage.rule.PmStageHierarchyRules.info(graph,stageId).group(); boolean group=com.ruoyi.project.manage.rule.PmStageHierarchyRules.info(graph,stageId).group();
boolean topologyMutable=canManage&&"NOT_STARTED".equals(executionStatus)&&!flag(stage,"executionHistory"); boolean topologyMutable=canManage&&"NOT_STARTED".equals(executionStatus)&&!flag(stage,"executionHistory");
stage.putAll(map("childStageCount",children.size(),"completedChildStageCount",children.stream().filter(child->Set.of("COMPLETED","LEGACY_PASSED").contains(PmStageRules.executionStatus(graph,child))).count(),"stagePath",com.ruoyi.project.manage.rule.PmStageHierarchyRules.path(graph,stageId),"canCreateWorkItem",canWrite&&!group&&!Set.of("COMPLETED","LEGACY_PASSED").contains(executionStatus),"canCreateChildStage",topologyMutable&&group,"canEditStructure",topologyMutable)); stage.putAll(map("childStageCount",children.size(),"completedChildStageCount",children.stream().filter(child->Set.of("COMPLETED","LEGACY_PASSED").contains(PmStageRules.executionStatus(graph,child))).count(),"stagePath",com.ruoyi.project.manage.rule.PmStageHierarchyRules.path(graph,stageId),"canCreateWorkItem",canWrite&&!group&&!"PURCHASE".equals(stage.get("nodeType"))&&!"PENDING".equals(graph.stageRevisions().get(stageId).approvalStatus())&&!Set.of("COMPLETED","LEGACY_PASSED").contains(executionStatus),"canCreateChildStage",topologyMutable&&group,"canEditStructure",topologyMutable));
stage.putAll(completionSummaries.get(stageId));
stage.put("blockedReasons",PmStageRules.blockedStage(graph,stageId)); stage.put("blockedReasons",PmStageRules.blockedStage(graph,stageId));
List<Map<String,Object>> reworkBlocked=PmStageRules.reworkBlocked(graph,stageId); List<Map<String,Object>> reworkBlocked=PmStageRules.reworkBlocked(graph,stageId);
stage.put("isCurrent",PmStageRules.isCurrent(graph,stageId)); stage.put("isCurrent",PmStageRules.isCurrent(graph,stageId));
@ -117,6 +122,8 @@ public class PmStageServiceImpl implements IPmStageService {
public long createStage(long projectId,long iterationId,StageInput input) { public long createStage(long projectId,long iterationId,StageInput input) {
locked(projectId,iterationId,"admin"); validateStage(projectId,input); locked(projectId,iterationId,"admin"); validateStage(projectId,input);
StageNodeType nodeType=StageNodeType.resolve(input.nodeType(),input.stageKind()); StageNodeType nodeType=StageNodeType.resolve(input.nodeType(),input.stageKind());
if(nodeType!=StageNodeType.PURCHASE&&input.ownerId()==null) throw PmException.bad("非采购阶段必须选择负责人");
if(nodeType!=StageNodeType.PURCHASE&&input.purchaseBatchIds()!=null&&!input.purchaseBatchIds().isEmpty()) throw PmException.bad("只有采购阶段能绑定批次");
String kind=nodeType.kind(); String kind=nodeType.kind();
if("GROUP".equals(kind)&&input.parentStageId()!=null) throw PmException.conflict("STAGE_HIERARCHY_INVALID","阶段组只能创建在根画布,不支持第三层阶段"); if("GROUP".equals(kind)&&input.parentStageId()!=null) throw PmException.conflict("STAGE_HIERARCHY_INVALID","阶段组只能创建在根画布,不支持第三层阶段");
var plan=PmTime.planned(input.plannedStartAt(),input.plannedEndAt()); var plan=PmTime.planned(input.plannedStartAt(),input.plannedEndAt());
@ -131,6 +138,10 @@ public class PmStageServiceImpl implements IPmStageService {
"stage_kind",kind,"node_type",nodeType.name(),"parent_stage_id",input.parentStageId(),"owner_id",input.ownerId(),"description",input.description(),"created_by",access.actor(),"created_at",PmTime.now())); "stage_kind",kind,"node_type",nodeType.name(),"parent_stage_id",input.parentStageId(),"owner_id",input.ownerId(),"description",input.description(),"created_by",access.actor(),"created_at",PmTime.now()));
long revision=revisionMapper.insertRevision(map("project_id",projectId,"iteration_id",iterationId,"stage_id",id,"revision_no",1,"stage_name_snapshot",input.name().trim(),"stage_owner_snapshot",input.ownerId(),"stage_kind_snapshot",kind,"parent_stage_snapshot_id",input.parentStageId(),"stage_description_snapshot",input.description(),"planned_start_at",plan.start(),"planned_end_at",plan.end(),"plan_source","NORMAL","plan_recorded_at",PmTime.now(),"created_by",access.actor(),"created_at",PmTime.now())); long revision=revisionMapper.insertRevision(map("project_id",projectId,"iteration_id",iterationId,"stage_id",id,"revision_no",1,"stage_name_snapshot",input.name().trim(),"stage_owner_snapshot",input.ownerId(),"stage_kind_snapshot",kind,"parent_stage_snapshot_id",input.parentStageId(),"stage_description_snapshot",input.description(),"planned_start_at",plan.start(),"planned_end_at",plan.end(),"plan_source","NORMAL","plan_recorded_at",PmTime.now(),"created_by",access.actor(),"created_at",PmTime.now()));
if(revisionMapper.initializeCurrentRevision(projectId,id,revision)!=1) throw PmException.conflict("VERSION_CONFLICT","阶段初始版本建立失败"); if(revisionMapper.initializeCurrentRevision(projectId,id,revision)!=1) throw PmException.conflict("VERSION_CONFLICT","阶段初始版本建立失败");
if(nodeType==StageNodeType.PURCHASE&&input.purchaseBatchIds()!=null) {
groups.bind(projectId,iterationId);
completion.batches(projectId,iterationId,id,new com.ruoyi.project.manage.dto.StagePurchaseInput(revision,0,input.purchaseBatchIds()));
}
groups.bind(projectId,iterationId); Graph after=graphService.load(projectId,iterationId); groups.bind(projectId,iterationId); Graph after=graphService.load(projectId,iterationId);
PmRules.validateAcyclic(after); PmRules.validateSchedules(after,"Asia/Shanghai"); PmStageRules.validateRegression(before,after); PmRules.validateAcyclic(after); PmRules.validateSchedules(after,"Asia/Shanghai"); PmStageRules.validateRegression(before,after);
snapshotDefinition(projectId,iterationId); snapshotDefinition(projectId,iterationId);
@ -150,13 +161,20 @@ public class PmStageServiceImpl implements IPmStageService {
Graph before=graphService.load(projectId,iterationId),after=before.copy(); Graph before=graphService.load(projectId,iterationId),after=before.copy();
String kind=text(existing,"stage_kind"); String kind=text(existing,"stage_kind");
StageNodeType existingType=StageNodeType.resolve(text(existing,"node_type"),kind); StageNodeType existingType=StageNodeType.resolve(text(existing,"node_type"),kind);
PmStageRules.requireDeliveryMutable(before,id);
if(existingType!=StageNodeType.PURCHASE&&input.ownerId()==null) throw PmException.bad("非采购阶段必须选择负责人");
if(existingType!=StageNodeType.PURCHASE&&input.purchaseBatchIds()!=null&&!input.purchaseBatchIds().isEmpty()) throw PmException.bad("只有采购阶段能绑定批次");
if ((input.nodeType()!=null&&!existingType.name().equals(input.nodeType()))||(input.stageKind()!=null&&!kind.equals(input.stageKind()))) throw PmException.conflict("STAGE_NODE_TYPE_LOCKED","节点类型创建后不可修改"); if ((input.nodeType()!=null&&!existingType.name().equals(input.nodeType()))||(input.stageKind()!=null&&!kind.equals(input.stageKind()))) throw PmException.conflict("STAGE_NODE_TYPE_LOCKED","节点类型创建后不可修改");
if(input.parentStageId()!=null&&!Objects.equals(input.parentStageId(),nullable(existing,"parent_stage_id"))) throw PmException.bad("请使用结构调整入口修改父级"); if(input.parentStageId()!=null&&!Objects.equals(input.parentStageId(),nullable(existing,"parent_stage_id"))) throw PmException.bad("请使用结构调整入口修改父级");
if(input.plannedStartAt()!=null||input.plannedEndAt()!=null) throw PmException.bad("阶段改期请使用版本排期入口"); if(input.plannedStartAt()!=null||input.plannedEndAt()!=null) throw PmException.bad("阶段改期请使用版本排期入口");
after.hierarchy().put(id,new com.ruoyi.project.manage.domain.StageInfo(id,kind,nullable(existing,"parent_stage_id"),input.description())); after.hierarchy().put(id,new com.ruoyi.project.manage.domain.StageInfo(id,kind,nullable(existing,"parent_stage_id"),input.description(),existingType.name(),nullable(existing,"created_by"),input.ownerId()));
PmRules.validateAcyclic(after); PmStageRules.validateExecutedAncestors(before,after); PmRules.validateAcyclic(after); PmStageRules.validateExecutedAncestors(before,after);
stageMapper.updateStage(id,(int)number(existing,"version"),map("name",input.name().trim(),"sort_order",input.sortOrder()==null?0:input.sortOrder(),"owner_id",input.ownerId(),"description",input.description())); stageMapper.updateStage(id,(int)number(existing,"version"),map("name",input.name().trim(),"sort_order",input.sortOrder()==null?0:input.sortOrder(),"owner_id",input.ownerId(),"description",input.description()));
stageMapper.refreshDraftRevisionIdentity(number(existing,"current_revision_id"),kind,nullable(existing,"parent_stage_id"),input.description()); stageMapper.refreshDraftRevisionIdentity(number(existing,"current_revision_id"),kind,nullable(existing,"parent_stage_id"),input.description());
if(existingType==StageNodeType.PURCHASE&&input.purchaseBatchIds()!=null) {
var r=revisionMapper.selectRevision(projectId,iterationId,id,number(existing,"current_revision_id"));
completion.batches(projectId,iterationId,id,new com.ruoyi.project.manage.dto.StagePurchaseInput(number(r,"id"),(int)number(r,"version"),input.purchaseBatchIds()));
}
groups.bind(projectId,iterationId); snapshotDefinition(projectId,iterationId); groups.bind(projectId,iterationId); snapshotDefinition(projectId,iterationId);
auditService.record(projectId,iterationId,null,"STAGE_EDITED",map("stageId",id,"name",input.name().trim()),access.actor()); auditService.record(projectId,iterationId,null,"STAGE_EDITED",map("stageId",id,"name",input.name().trim()),access.actor());
} }
@ -166,6 +184,10 @@ public class PmStageServiceImpl implements IPmStageService {
locked(projectId,iterationId,"admin"); Map<String,Object> existing=stage(projectId,iterationId,id); version(input.version(),(int)number(existing,"version")); locked(projectId,iterationId,"admin"); Map<String,Object> existing=stage(projectId,iterationId,id); version(input.version(),(int)number(existing,"version"));
if(!com.ruoyi.project.manage.rule.PmStageHierarchyRules.children(graphService.load(projectId,iterationId),id).isEmpty()) throw PmException.conflict("STAGE_NOT_EMPTY","阶段组仍有子阶段,不能删除"); if(!com.ruoyi.project.manage.rule.PmStageHierarchyRules.children(graphService.load(projectId,iterationId),id).isEmpty()) throw PmException.conflict("STAGE_NOT_EMPTY","阶段组仍有子阶段,不能删除");
if(workItemMapper.selectItemInStage(projectId,id)!=null) throw PmException.conflict("STAGE_NOT_EMPTY","阶段仍有未删除工作项,请先调整这些工作项的阶段"); if(workItemMapper.selectItemInStage(projectId,id)!=null) throw PmException.conflict("STAGE_NOT_EMPTY","阶段仍有未删除工作项,请先调整这些工作项的阶段");
// 零工作项不等于空交付:设计草稿和采购范围也不能随删除节点而失去可访问入口。
var delivery=completion.detail(projectId,iterationId,id,null).get("delivery");
if(delivery instanceof Map<?,?> value&&value.get("attachments") instanceof List<?> files&&!files.isEmpty()) throw PmException.conflict("STAGE_DELIVERY_NOT_EMPTY","请先移除本轮交付附件,再删除尚未执行阶段");
if(delivery instanceof Map<?,?> value&&value.get("purchase") instanceof Map<?,?> purchase&&purchase.get("batches") instanceof List<?> batches&&!batches.isEmpty()) throw PmException.conflict("STAGE_DELIVERY_NOT_EMPTY","请先清空采购批次范围,再删除尚未执行阶段");
Graph before=graphService.load(projectId,iterationId),after=before.copy(); Graph before=graphService.load(projectId,iterationId),after=before.copy();
requireNoExecutionHistory(projectId,iterationId,id); requireNoExecutionHistory(projectId,iterationId,id);
Long parent=com.ruoyi.project.manage.rule.PmStageHierarchyRules.info(before,id).parentId(); Long parent=com.ruoyi.project.manage.rule.PmStageHierarchyRules.info(before,id).parentId();
@ -233,7 +255,7 @@ public class PmStageServiceImpl implements IPmStageService {
var old=com.ruoyi.project.manage.rule.PmStageHierarchyRules.info(before,move.id()); var old=com.ruoyi.project.manage.rule.PmStageHierarchyRules.info(before,move.id());
if(old.parentId()!=null) requireNoExecutionHistory(projectId,iterationId,old.parentId()); if(old.parentId()!=null) requireNoExecutionHistory(projectId,iterationId,old.parentId());
if(move.parentStageId()!=null) requireNoExecutionHistory(projectId,iterationId,move.parentStageId()); if(move.parentStageId()!=null) requireNoExecutionHistory(projectId,iterationId,move.parentStageId());
after.hierarchy().put(move.id(),new com.ruoyi.project.manage.domain.StageInfo(move.id(),old.kind(),move.parentStageId(),old.description())); after.hierarchy().put(move.id(),new com.ruoyi.project.manage.domain.StageInfo(move.id(),old.kind(),move.parentStageId(),old.description(),old.nodeType(),old.creatorId(),old.ownerId()));
} }
after.stageLinks().clear(); Set<String> edges=new HashSet<>(); long temporary=-1; after.stageLinks().clear(); Set<String> edges=new HashSet<>(); long temporary=-1;
for(var edge:input.edges()) { for(var edge:input.edges()) {

View File

@ -53,7 +53,7 @@ public class PmGraphService {
Map<Long,String> names=new LinkedHashMap<>(); Map<Long,com.ruoyi.project.manage.domain.StageInfo> hierarchy=new LinkedHashMap<>(); Map<Long,String> names=new LinkedHashMap<>(); Map<Long,com.ruoyi.project.manage.domain.StageInfo> hierarchy=new LinkedHashMap<>();
for(Map<String,Object> row:stageMapper.selectVisibleStages(projectId,iterationId)) { for(Map<String,Object> row:stageMapper.selectVisibleStages(projectId,iterationId)) {
long id=number(row,"id"); names.put(id,text(row,"name")); long id=number(row,"id"); names.put(id,text(row,"name"));
hierarchy.put(id,new com.ruoyi.project.manage.domain.StageInfo(id,text(row,"stageKind"),nullable(row,"parentStageId"),text(row,"description"))); hierarchy.put(id,new com.ruoyi.project.manage.domain.StageInfo(id,text(row,"stageKind"),nullable(row,"parentStageId"),text(row,"description"),text(row,"nodeType"),nullable(row,"creatorId"),nullable(row,"ownerId")));
} }
List<StageLink> links=new ArrayList<>(); List<StageLink> links=new ArrayList<>();
for(Map<String,Object> row:stageMapper.selectStageEdges(projectId,iterationId)) links.add(new StageLink(number(row,"id"),projectId,number(row,"predecessor_stage_id"),number(row,"successor_stage_id"),(int)number(row,"version"))); for(Map<String,Object> row:stageMapper.selectStageEdges(projectId,iterationId)) links.add(new StageLink(number(row,"id"),projectId,number(row,"predecessor_stage_id"),number(row,"successor_stage_id"),(int)number(row,"version")));
@ -74,5 +74,5 @@ public class PmGraphService {
return graph; return graph;
} }
/** 当前与历史版本使用相同字段解码,但历史不会被加入当前依赖图。 */ /** 当前与历史版本使用相同字段解码,但历史不会被加入当前依赖图。 */
public static StageRevision revision(Map<String,Object> row) { return new StageRevision(number(row,"id"),number(row,"stage_id"),(int)number(row,"revision_no"),nullable(row,"started_at"),nullable(row,"completed_at"),nullable(row,"legacy_passed_at"),nullable(row,"planned_start_at"),nullable(row,"planned_end_at"),nullable(row,"reference_planned_start_at"),nullable(row,"reference_planned_end_at"),nullable(row,"schedule_review_rework_id"),text(row,"plan_source"),nullable(row,"plan_recorded_at"),(int)number(row,"version")); } public static StageRevision revision(Map<String,Object> row) { return new StageRevision(number(row,"id"),number(row,"stage_id"),(int)number(row,"revision_no"),nullable(row,"started_at"),nullable(row,"completed_at"),nullable(row,"legacy_passed_at"),nullable(row,"planned_start_at"),nullable(row,"planned_end_at"),nullable(row,"reference_planned_start_at"),nullable(row,"reference_planned_end_at"),nullable(row,"schedule_review_rework_id"),text(row,"plan_source"),nullable(row,"plan_recorded_at"),(int)number(row,"version"),text(row,"approval_status"),text(row,"completion_source"),text(row,"completion_note")); }
} }

View File

@ -26,8 +26,12 @@ public class PmGroupVersionService {
private final ObjectMapper decoder; private final ObjectMapper decoder;
private final PmAuditService audit; private final PmAuditService audit;
private final PmAccess access; private final PmAccess access;
private final PmStageEvidenceService evidence;
private final com.ruoyi.project.manage.mapper.PmEventMapper events;
/** 只在调用方已持项目图锁时使用,不创建独立事务或读取用户提交的快照。 */ /** 只在调用方已持项目图锁时使用,不创建独立事务或读取用户提交的快照。 */
public PmGroupVersionService(PmGroupMapper mapper,PmStageMapper stages,PmRevisionMapper revisions,PmActivityMapper activities,PmGraphService graphs,PmJson json,ObjectMapper decoder,PmAuditService audit,PmAccess access) { public PmGroupVersionService(PmGroupMapper mapper,PmStageMapper stages,PmRevisionMapper revisions,PmActivityMapper activities,PmGraphService graphs,PmJson json,ObjectMapper decoder,PmAuditService audit,PmAccess access,PmStageEvidenceService evidence,com.ruoyi.project.manage.mapper.PmEventMapper events) {
this.events=events;
this.evidence=evidence;
this.audit=audit;this.access=access; this.audit=audit;this.access=access;
this.mapper=mapper;this.stages=stages;this.revisions=revisions;this.activities=activities;this.graphs=graphs;this.json=json;this.decoder=decoder; this.mapper=mapper;this.stages=stages;this.revisions=revisions;this.activities=activities;this.graphs=graphs;this.json=json;this.decoder=decoder;
} }
@ -48,8 +52,18 @@ public class PmGroupVersionService {
} }
} }
/** 子阶段状态改变后按当前组合汇总父级实际时间;完成时冻结该组合的全部可读内容。 */ /** 子阶段审批通过后聚合父级完成,工作项齐备不触发组完成;冻结含新交付和审批依据。 */
public void sync(long projectId,long iterationId) { public void sync(long projectId,long iterationId) {
syncState(projectId,iterationId,false);
}
/** 采购后台观察没有登录用户;系统事件存入同事务outbox,不伪造创建人执行操作。 */
public void syncAutomatic(long projectId,long iterationId) {
syncState(projectId,iterationId,true);
}
/** 人工和系统采样复用相同组聚合规则,只区别事件的真实来源。 */
private void syncState(long projectId,long iterationId,boolean automatic) {
Graph graph=graphs.load(projectId,iterationId); Graph graph=graphs.load(projectId,iterationId);
for(Long id:graph.stageNames().keySet()) if(PmStageHierarchyRules.info(graph,id).group()) { for(Long id:graph.stageNames().keySet()) if(PmStageHierarchyRules.info(graph,id).group()) {
StageRevision old=graph.stageRevisions().get(id); Long first=null,last=null; StageRevision old=graph.stageRevisions().get(id); Long first=null,last=null;
@ -68,7 +82,9 @@ public class PmGroupVersionService {
} }
mapper.updateGroupState(old.id(),first,last); mapper.updateGroupState(old.id(),first,last);
String previous=old.completedAt()!=null?"COMPLETED":old.startedAt()!=null?"IN_PROGRESS":"NOT_STARTED"; String previous=old.completedAt()!=null?"COMPLETED":old.startedAt()!=null?"IN_PROGRESS":"NOT_STARTED";
audit.record(projectId,iterationId,null,"STAGE_STATUS_CHANGED",map("stageId",id,"from",previous,"to",PmStageRules.executionStatus(graph,id),"revisionId",old.id(),"aggregate",true),access.actor()); var detail=map("stageId",id,"from",previous,"to",PmStageRules.executionStatus(graph,id),"revisionId",old.id(),"aggregate",true,"automatic",automatic);
if(automatic){long at=PmTime.now();events.insertEvent(map("project_id",projectId,"iteration_id",iterationId,"work_item_id",null,"event_type","STAGE_STATUS_CHANGED","payload",json.encode(detail),"next_attempt_at",at,"created_at",at));}
else audit.record(projectId,iterationId,null,"STAGE_STATUS_CHANGED",detail,access.actor());
} }
if(last!=null)freeze(graph,id); if(last!=null)freeze(graph,id);
} }
@ -138,6 +154,12 @@ public class PmGroupVersionService {
items.add(row); items.add(row);
} }
Map<String,Object> result=map("stageId",childId,"name",graph.stageNames().get(childId),"description",PmStageHierarchyRules.info(graph,childId).description(),"revisionId",graph.stageRevisions().get(childId).id(),"revisionNo",graph.stageRevisions().get(childId).revisionNo(),"executionStatus",PmStageRules.executionStatus(graph,childId),"items",items); Map<String,Object> result=map("stageId",childId,"name",graph.stageNames().get(childId),"description",PmStageHierarchyRules.info(graph,childId).description(),"revisionId",graph.stageRevisions().get(childId).id(),"revisionNo",graph.stageRevisions().get(childId).revisionNo(),"executionStatus",PmStageRules.executionStatus(graph,childId),"items",items);
var revision=revisions.selectRevision(graph.iteration().projectId(),graph.iteration().id(),childId,graph.stageRevisions().get(childId).id());
var delivery=evidence.decode(text(revision,"delivery_snapshot_json"));
// 父级换版时可能保留并行子分支;只冻结父成员快照,不能冻结仍会继续执行的子版本。
if(delivery==null)delivery=evidence.sample(stages.selectActiveStage(childId,graph.iteration().projectId(),graph.iteration().id()),revision);
result.put("delivery",delivery);
result.put("approvalStatus",revision.get("approval_status"));
result.putAll(PmStageScheduleRules.times(graph.stageRevisions().get(childId)));return result; result.putAll(PmStageScheduleRules.times(graph.stageRevisions().get(childId)));return result;
} }
/** JSON 仅来自服务器保存的冻结内容,解码失败使历史查询明确失败而非退回实时内容。 */ /** JSON 仅来自服务器保存的冻结内容,解码失败使历史查询明确失败而非退回实时内容。 */

View File

@ -0,0 +1,90 @@
package com.ruoyi.project.manage.service.support;
import com.ruoyi.project.manage.mapper.PmPurchaseReadMapper;
import com.ruoyi.project.manage.mapper.PmStageCompletionMapper;
import com.ruoyi.project.manage.exception.PmException;
import com.ruoyi.project.manage.util.PmTime;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import org.springframework.stereotype.Service;
import static com.ruoyi.project.manage.util.PmValues.*;
/** 采购进度是只读验收投影;不同单位仅平均明细比例,完成门槛始终逐条精确比较。 */
@Service
public class PmPurchaseProgressReader {
private final PmPurchaseReadMapper source;
private final PmStageCompletionMapper deliveries;
/** 通过协作本地适配器读取采购,避免引入采购模块的写服务和全局锁依赖。 */
public PmPurchaseProgressReader(PmPurchaseReadMapper source,PmStageCompletionMapper deliveries) { this.source=source; this.deliveries=deliveries; }
/** 返回原项目的受控批次候选,最多200条,界面可继续关键词搜索。 */
public List<Map<String,Object>> options(long projectId,String keyword) { return source.selectOptions(sourceId(projectId),keyword==null?"":keyword.strip()); }
/** 一次读取该执行版本的全部绑定批次,空范围不允许视作验收完成。 */
public Map<String,Object> read(long projectId,long revisionId) {
return readBatches(projectId,deliveries.selectBatches(revisionId).stream().map(row->number(row,"batchId")).toList());
}
/**
* 从一条无缓存 SQL 取得采样事实,再计算所有批次;调用方不得重读后混合为另一份审批依据。
* @param batchIds 已归属校验或待校验的批次,最多100个
* @return 本项目明细、逐批次进度与采样时间;不存在、全取消及异常数量均不达标
*/
public Map<String,Object> readBatches(long projectId,List<Long> batchIds) {
List<Map<String,Object>> lines=batchIds.isEmpty()?List.of():source.selectLines(sourceId(projectId),batchIds);
return aggregate(batchIds,lines);
}
/** 画布按迭代批量采样,查询数不随采购阶段个数增长;同一批次引用不重复读取源数据。 */
public Map<Long,Map<String,Object>> readAll(long projectId,long iterationId) {
Map<Long,List<Long>> ranges=new LinkedHashMap<>();
for(var row:deliveries.selectCurrentBatches(projectId,iterationId))ranges.computeIfAbsent(number(row,"revisionId"),unused->new ArrayList<>()).add(number(row,"batchId"));
List<Long> ids=ranges.values().stream().flatMap(Collection::stream).distinct().sorted().toList();
List<Map<String,Object>> lines=ids.isEmpty()?List.of():source.selectLines(sourceId(projectId),ids);
Map<Long,Map<String,Object>> result=new LinkedHashMap<>();ranges.forEach((revision,range)->result.put(revision,aggregate(range,lines)));return result;
}
/** 展示和完成校验共用同一纯聚合,批量读取不能改变逐明细验收口径。 */
private Map<String,Object> aggregate(List<Long> batchIds,List<Map<String,Object>> lines) {
long sampledAt=PmTime.now();
List<Map<String,Object>> batches=new ArrayList<>();
BigDecimal total=BigDecimal.ZERO; int effective=0,complete=0;
for(Long id:batchIds) {
List<Map<String,Object>> entries=lines.stream().filter(row->number(row,"batchId")==id).toList();
BigDecimal sum=BigDecimal.ZERO; int count=0,done=0; boolean invalid=false;
for(Map<String,Object> line:entries) {
boolean cancelled=number(line,"purchaseStatus")==5;
line.put("cancelled",cancelled);
BigDecimal quantity=decimal(line.get("quantity")),accepted=decimal(line.get("acceptedQuantity"));
BigDecimal pending=decimal(line.get("pendingQuantity"));
boolean satisfied=!cancelled&&quantity.signum()>0&&accepted.compareTo(quantity)>=0;
line.put("complete",satisfied);
line.put("notArrivedQuantity",quantity.subtract(accepted).subtract(pending).max(BigDecimal.ZERO));
BigDecimal ratio=quantity.signum()>0?accepted.max(BigDecimal.ZERO).divide(quantity,10,RoundingMode.DOWN).min(BigDecimal.ONE):BigDecimal.ZERO;
line.put("progress",ratio.multiply(BigDecimal.valueOf(100)).setScale(2,RoundingMode.DOWN));
if(cancelled) continue;
count++; sum=sum.add(ratio); if(satisfied) done++; if(quantity.signum()<=0) invalid=true;
}
boolean ready=count>0&&!invalid&&done==count;
Map<String,Object> first=entries.isEmpty()?Map.of():entries.get(0);
batches.add(map("batchId",id,"batchNo",first.get("batchNo"),"batchName",first.get("batchName"),"available",!entries.isEmpty(),"effectiveLines",count,"completedLines",done,"complete",ready,"progress",percentage(sum,count,ready),"lines",entries));
total=total.add(sum); effective+=count; complete+=done;
}
boolean ready=!batches.isEmpty()&&batches.stream().allMatch(row->Boolean.TRUE.equals(row.get("complete")));
return map("sampledAt",sampledAt,"complete",ready,"progress",percentage(total,effective,ready),"effectiveLines",effective,"completedLines",complete,"batches",batches);
}
/** 显示舍入不能制造100%;是否齐备与显示百分比分开判断。 */
private static BigDecimal percentage(BigDecimal sum,int count,boolean ready) {
if(ready) return BigDecimal.valueOf(100);
return count==0?BigDecimal.ZERO:sum.multiply(BigDecimal.valueOf(100)).divide(BigDecimal.valueOf(count),2,RoundingMode.DOWN).min(new BigDecimal("99.99"));
}
/** 数量始终用十进制定点比较,避免浮点精度将未验收完的明细误判完成。 */
private static BigDecimal decimal(Object value) { return value==null?BigDecimal.ZERO:new BigDecimal(value.toString()); }
/** 源项目是权限和数据归属边界,不能用协作扩展ID替代或猜测。 */
private long sourceId(long projectId) { Long id=source.selectSourceProjectId(projectId); if(id==null) throw PmException.bad("项目协作尚未绑定有效原项目"); return id; }
}

View File

@ -0,0 +1,45 @@
package com.ruoyi.project.manage.service.support;
import com.ruoyi.project.manage.mapper.PmRevisionMapper;
import com.ruoyi.project.manage.mapper.PmStageCompletionMapper;
import com.ruoyi.project.manage.mapper.PmStageMapper;
import com.ruoyi.project.manage.util.PmTime;
import java.util.*;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import static com.ruoyi.project.manage.util.PmValues.*;
/** 回退和迭代终止共用申请失效处理,不把未审批完成的交付伪造为通过。 */
@Service
@Transactional(propagation=Propagation.MANDATORY)
public class PmStageApprovalLifecycle {
private final PmStageCompletionMapper mapper;
private final PmRevisionMapper revisions;
private final PmStageMapper stages;
private final PmStageEvidenceService evidence;
private final PmAuditService audit;
/** 只在调用方已持项目锁的事务内使用,失效、换版及通知不能分开提交。 */
public PmStageApprovalLifecycle(PmStageCompletionMapper mapper,PmRevisionMapper revisions,PmStageMapper stages,PmStageEvidenceService evidence,PmAuditService audit) {this.mapper=mapper;this.revisions=revisions;this.stages=stages;this.evidence=evidence;this.audit=audit;}
/** 换版前保存旧交付并关闭待审申请;不会改变已有通过或驳回历史。 */
public void supersede(long projectId,long iterationId,long stageId,long revisionId,long actor) {
evidence.freeze(projectId,iterationId,stageId,revisionId);invalidate(projectId,iterationId,stageId,revisionId,actor,"SUPERSEDED","流程回退,原执行版本已被替换");
}
/** 终态迭代不留下悬挂申请;重新打开后必须新提审,不能恢复旧PENDING。 */
public void terminate(long projectId,long iterationId,long actor) {
for(var revision:revisions.selectCurrentRevisions(projectId,iterationId))invalidate(projectId,iterationId,number(revision,"stage_id"),number(revision,"id"),actor,"TERMINATED","迭代异常结束或取消,原完成申请已终止");
}
/** 只对真实待审申请生成一次失效审计和双方通知,失败随主业务回滚。 */
private void invalidate(long projectId,long iterationId,long stageId,long revisionId,long actor,String status,String reason) {
var pending=mapper.selectPending(revisionId);if(pending==null)return;long at=PmTime.now();
if(mapper.invalidate(revisionId,status,actor,at,reason)==0)return;
var revision=revisions.selectRevision(projectId,iterationId,stageId,revisionId);
mapper.updateRevision(revisionId,(int)number(revision,"version"),map("approval_status","SUPERSEDED".equals(status)?"INVALIDATED":status));
var stage=stages.selectActiveStage(stageId,projectId,iterationId);Set<Long> targets=new TreeSet<>();targets.add(number(pending,"approver_id"));if(nullable(pending,"owner_id")!=null)targets.add(number(pending,"owner_id"));
audit.record(projectId,iterationId,null,"STAGE_COMPLETION_INVALIDATED",map("stageId",stageId,"stageName",stage.get("name"),"revisionId",revisionId,"approvalId",pending.get("id"),"reason",reason,"notifyUserIds",List.copyOf(targets)),actor);
}
}

View File

@ -0,0 +1,123 @@
package com.ruoyi.project.manage.service.support;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.project.manage.mapper.PmRevisionMapper;
import com.ruoyi.project.manage.mapper.PmStageCompletionMapper;
import com.ruoyi.project.manage.mapper.PmStageMapper;
import com.ruoyi.project.manage.util.PmJson;
import com.ruoyi.project.manage.util.PmTime;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;
import org.springframework.stereotype.Service;
import static com.ruoyi.project.manage.util.PmValues.*;
/** 当前交付采样和历史冻结共用一个白名单投影;不缓存准入结果,不保存私有对象键或采购金额。 */
@Service
public class PmStageEvidenceService {
/** 单次画布采样的轮次与证据索引;只存在当前事务内,不作为跨请求缓存。 */
public record Batch(Map<Long,Map<String,Object>> revisions,Map<Long,Map<String,Object>> snapshots) { }
private final PmStageCompletionMapper mapper;
private final PmRevisionMapper revisions;
private final PmStageMapper stages;
private final PmPurchaseProgressReader purchases;
private final PmJson json;
private final ObjectMapper decoder;
/** 此服务不依赖阶段组或审批服务,避免历史冻结与审批状态同步形成循环依赖。 */
public PmStageEvidenceService(PmStageCompletionMapper mapper,PmRevisionMapper revisions,PmStageMapper stages,PmPurchaseProgressReader purchases,PmJson json,ObjectMapper decoder) {
this.mapper=mapper;this.revisions=revisions;this.stages=stages;this.purchases=purchases;this.json=json;this.decoder=decoder;
}
/**
* 在调用方项目锁内采样当前交付;采购仅查询一次,审核和指纹必须使用同一个返回值。
* @param stage 已检查项目/迭代归属的数据库阶段
* @param revision 精确执行版本,不从客户端字段拼装身份
* @return 可公开给本项目成员的证据,历史可直接持久化这一结果
*/
public Map<String,Object> sample(Map<String,Object> stage,Map<String,Object> revision) {
long revisionId=number(revision,"id");
List<Map<String,Object>> items=new ArrayList<>();
for(var row:revisions.selectRevisionItems(revisionId)) if(!flag(row,"deleted")) items.add(map("id",row.get("id"),"title",row.get("title"),"status",row.get("status"),"version",row.get("version"),"assigneeId",row.get("assignee_id"),"parentTaskId",row.get("parent_task_id")));
Map<String,Object> purchase="PURCHASE".equals(text(stage,"node_type"))?purchases.read(number(stage,"project_id"),revisionId):null;
return snapshot(stage,revision,items,mapper.selectAttachments(revisionId),purchase);
}
/**
* 画布使用已加载工作项图并批量读取附件/采购,避免每个阶段重复查轮次、任务和成员。
* @param definitions 当前已鉴权的原始阶段字段,范围由调用服务构造
* @return 全阶段证据和轮次索引,SQL次数与阶段数量无关
*/
public Batch sampleAll(long projectId,long iterationId,com.ruoyi.project.manage.domain.Graph graph,List<Map<String,Object>> definitions) {
Map<Long,Map<String,Object>> rounds=new LinkedHashMap<>();for(var row:revisions.selectCurrentRevisions(projectId,iterationId))rounds.put(number(row,"stage_id"),row);
Map<Long,List<Map<String,Object>>> items=new LinkedHashMap<>(),files=new LinkedHashMap<>();
for(var item:graph.items().values())if(!item.deleted()&&item.stageId()!=null)items.computeIfAbsent(item.stageId(),unused->new ArrayList<>()).add(map("id",item.id(),"title",item.title(),"status",item.status(),"version",item.version(),"assigneeId",item.assigneeId(),"parentTaskId",item.parentTaskId()));
for(var file:mapper.selectCurrentAttachments(projectId,iterationId))files.computeIfAbsent(number(file,"revisionId"),unused->new ArrayList<>()).add(file);
Map<Long,Map<String,Object>> progress=purchases.readAll(projectId,iterationId),snapshots=new LinkedHashMap<>();
for(var stage:definitions) {
long id=number(stage,"id");var revision=rounds.get(id);long revisionId=number(revision,"id");
Map<String,Object> purchase="PURCHASE".equals(text(stage,"node_type"))?progress.getOrDefault(revisionId,purchases.readBatches(projectId,List.of())):null;
snapshots.put(id,snapshot(stage,revision,items.getOrDefault(id,List.of()),files.getOrDefault(revisionId,List.of()),purchase));
}
return new Batch(rounds,snapshots);
}
/** 单阶段和批量采样必须生成同一白名单结构,防止界面与提交摘要不同。 */
private Map<String,Object> snapshot(Map<String,Object> stage,Map<String,Object> revision,List<Map<String,Object>> items,List<Map<String,Object>> files,Map<String,Object> purchase) {
return map("formatVersion",1,"sampledAt",PmTime.now(),"stageId",stage.get("id"),"revisionId",revision.get("id"),"nodeType",stage.get("node_type"),"name",stage.get("name"),"creatorId",stage.get("created_by"),"ownerId",stage.get("owner_id"),"note",revision.get("completion_note"),"purchaseScopeConfirmed",flag(revision,"purchase_scope_confirmed"),"items",items,"attachments",files,"purchase",purchase);
}
/** 按类型校验齐备条件,取消项不冒充已完成;采购阶段即使混入旧任务也不能确认。 */
public List<Map<String,Object>> reasons(Map<String,Object> stage,Map<String,Object> snapshot) {
List<Map<String,Object>> result=new ArrayList<>(); String type=text(stage,"node_type");
List<?> items=(List<?>)snapshot.get("items");
if("GROUP".equals(type)) { result.add(map("code","STAGE_GROUP_AGGREGATE","message","阶段组由子阶段审批结果聚合,不单独提交")); return result; }
if("PURCHASE".equals(type)) {
if(!items.isEmpty()) result.add(map("code","PURCHASE_HAS_WORK_ITEMS","message","采购阶段仍有旧工作项,请由管理者先调整其归属"));
if(!Boolean.TRUE.equals(snapshot.get("purchaseScopeConfirmed"))) result.add(map("code","PURCHASE_SCOPE_UNCONFIRMED","message","请先确认本轮采购批次范围"));
if(!(snapshot.get("purchase") instanceof Map<?,?> progress)||!Boolean.TRUE.equals(progress.get("complete"))) result.add(map("code","PURCHASE_NOT_ACCEPTED","message","所有批次的本项目有效明细必须全部验收完成"));
return result;
}
if(!Set.of("DESIGN","MACHINING").contains(Objects.toString(type,"STAGE"))&&items.isEmpty()) result.add(map("code","STAGE_EMPTY","message","该类型至少需要一个有效工作项"));
for(Object item:items) { Map<?,?> row=(Map<?,?>)item; if(!Set.of("COMPLETED","CLOSED").contains(Objects.toString(row.get("status"),""))) result.add(map("code","WORK_ITEM_INCOMPLETE","itemId",row.get("id"),"sourceName",row.get("title"),"message","工作项尚未完成或关闭")); }
if("DESIGN".equals(type)) {
if(((List<?>)snapshot.get("attachments")).isEmpty()) result.add(map("code","DESIGN_ATTACHMENT_REQUIRED","message","设计阶段至少需要一个本轮交付附件"));
if(text(snapshot,"note")==null||text(snapshot,"note").isBlank()) result.add(map("code","DESIGN_NOTE_REQUIRED","message","设计阶段需要填写实际交付说明"));
}
return result;
}
/** 采样时刻不是证据变化;规范化Map顺序和数值,保证数据库值与JSON历史重算同一指纹。 */
public String fingerprint(Map<String,Object> snapshot) {
Map<String,Object> stable=new LinkedHashMap<>(snapshot);stable.remove("sampledAt");
if(stable.get("attachments") instanceof List<?> files)stable.put("attachments",files.stream().map(value->{Map<String,Object> file=new LinkedHashMap<>();((Map<?,?>)value).forEach((key,item)->{if(!"creatorName".equals(key))file.put(key.toString(),item);});return file;}).toList());
if(stable.get("purchase") instanceof Map<?,?> purchase) { Map<String,Object> value=new LinkedHashMap<>();purchase.forEach((key,item)->{ if(!"sampledAt".equals(key))value.put(key.toString(),item); }); stable.put("purchase",value); }
try { return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(json.encode(canonical(stable)).getBytes(StandardCharsets.UTF_8))); }
catch(NoSuchAlgorithmException impossible) { throw new IllegalStateException("运行环境不支持证据摘要",impossible); }
}
/** JSON字段按语义排序,BigDecimal尾零不改变验收证据;不使用不稳定的Map迭代顺序。 */
private Object canonical(Object value) {
if(value instanceof Map<?,?> map) { var result=new TreeMap<String,Object>();map.forEach((key,item)->result.put(key.toString(),canonical(item)));return result; }
if(value instanceof List<?> list) return list.stream().map(this::canonical).toList();
if(value instanceof Number number) return new java.math.BigDecimal(number.toString()).stripTrailingZeros();
return value;
}
/** 历史缺失时明确返回空,不能以当前采购结果伪造从未留存的历史。 */
public Map<String,Object> decode(String value) {
if(value==null) return null;
try { return decoder.readValue(value,new TypeReference<LinkedHashMap<String,Object>>(){}); }
catch(Exception failure) { throw new IllegalStateException("阶段交付历史快照无法读取",failure); }
}
/** 换版之前冻结旧证据;已审批快照不覆盖,采样失败使换版整体失败而不是丢失历史。 */
public void freeze(long projectId,long iterationId,long stageId,long revisionId) {
Map<String,Object> revision=revisions.selectRevision(projectId,iterationId,stageId,revisionId);
if(revision==null||text(revision,"delivery_snapshot_json")!=null) return;
Map<String,Object> stage=stages.selectActiveStage(stageId,projectId,iterationId);
mapper.freezeDelivery(revisionId,json.encode(sample(stage,revision)));
}
}

View File

@ -0,0 +1,31 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--suppress SqlNoDataSourceInspection -->
<mapper namespace="com.ruoyi.project.manage.mapper.PmPurchaseReadMapper">
<select id="selectSourceProjectId" resultType="java.lang.Long">SELECT e.source_project_id FROM pm_collab_project e JOIN project_info p ON p.id=e.source_project_id AND p.del_flag='0' WHERE e.id=#{projectId}</select>
<select id="selectOptions" resultType="java.util.LinkedHashMap" useCache="false" flushCache="true">
SELECT b.id,b.batch_no AS batchNo,b.batch_name AS batchName,COUNT(*) AS lineCount FROM purchase_batch b
JOIN purchase_request r ON r.purchase_batch_id=b.id AND r.project_id=#{sourceProjectId} AND r.del_flag='0'
<where><if test="keyword != null and keyword != ''">b.batch_no LIKE CONCAT('%',#{keyword},'%') OR b.batch_name LIKE CONCAT('%',#{keyword},'%')</if></where>
GROUP BY b.id,b.batch_no,b.batch_name ORDER BY b.id DESC LIMIT 200
</select>
<!-- 与采购明细页口径一致:历史采购视为已验收,普通明细扣除不良和退回;不再叠加入库量。
源状态为tinyint(1),显式转整数,避免JDBC布尔映射丢失取消状态5与其他非零状态的区别。 -->
<select id="selectLines" resultType="java.util.LinkedHashMap" useCache="false" flushCache="true">
SELECT b.id AS batchId,b.batch_no AS batchNo,b.batch_name AS batchName,r.id AS requestId,r.request_no AS requestNo,
COALESCE(r.material_name,p.product_name,r.request_no) AS name,r.unit,r.quantity,CAST(r.purchase_status AS UNSIGNED) AS purchaseStatus,r.historical,
CASE WHEN r.historical=1 THEN r.quantity ELSE COALESCE(a.accepted,0) END AS acceptedQuantity,
COALESCE(a.pending,0) AS pendingQuantity
FROM purchase_batch b JOIN purchase_request r ON r.purchase_batch_id=b.id AND r.project_id=#{sourceProjectId} AND r.del_flag='0'
LEFT JOIN product_info p ON p.id=r.product_id
LEFT JOIN (SELECT purchase_request_id,
SUM(CASE WHEN acceptance_status=1 THEN arrival_quantity-defective_quantity-returned_quantity ELSE 0 END) AS accepted,
SUM(CASE WHEN acceptance_status=0 THEN arrival_quantity ELSE 0 END) AS pending
FROM purchase_arrival arrival JOIN purchase_request scope_request ON scope_request.id=arrival.purchase_request_id
AND scope_request.project_id=#{sourceProjectId} AND scope_request.del_flag='0'
AND scope_request.purchase_batch_id IN <foreach collection="batchIds" item="id" open="(" close=")" separator=",">#{id}</foreach>
WHERE acceptance_status IN (0,1) GROUP BY purchase_request_id) a ON a.purchase_request_id=r.id
WHERE b.id IN <foreach collection="batchIds" item="id" open="(" close=")" separator=",">#{id}</foreach>
ORDER BY b.id,r.id
</select>
</mapper>

View File

@ -0,0 +1,63 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--suppress SqlNoDataSourceInspection -->
<mapper namespace="com.ruoyi.project.manage.mapper.PmStageCompletionMapper">
<select id="selectApprovals" resultType="java.util.LinkedHashMap">
SELECT a.*,u.nick_name AS submitterName,v.nick_name AS deciderName FROM pm_collab_stage_approval a
LEFT JOIN sys_user u ON u.user_id=a.submitted_by LEFT JOIN sys_user v ON v.user_id=a.decided_by
WHERE a.revision_id=#{revisionId} ORDER BY a.submission_no DESC
</select>
<select id="selectPending" resultType="java.util.LinkedHashMap">SELECT * FROM pm_collab_stage_approval WHERE revision_id=#{revisionId} AND status='PENDING'</select>
<select id="selectByKey" resultType="java.util.LinkedHashMap">SELECT * FROM pm_collab_stage_approval WHERE project_id=#{projectId} AND command_actor=#{actor} AND idempotency_key=#{key}</select>
<select id="selectApproval" resultType="java.util.LinkedHashMap">SELECT * FROM pm_collab_stage_approval WHERE id=#{id}</select>
<insert id="insertApprovalRow" useGeneratedKeys="true" keyProperty="values.id" keyColumn="id">
INSERT INTO pm_collab_stage_approval(project_id,iteration_id,stage_id,revision_id,submission_no,request_source,submitted_by,approver_id,owner_id,status,evidence_hash,snapshot_json,submitted_at,decided_by,decided_at,reason,command_actor,idempotency_key,decision_key)
SELECT #{values.project_id},#{values.iteration_id},#{values.stage_id},#{values.revision_id},COALESCE(MAX(submission_no),0)+1,
#{values.request_source},#{values.submitted_by},#{values.approver_id},#{values.owner_id},#{values.status},#{values.evidence_hash},#{values.snapshot_json},#{values.submitted_at},#{values.decided_by},#{values.decided_at},#{values.reason},#{values.command_actor},#{values.idempotency_key},#{values.decision_key}
FROM pm_collab_stage_approval WHERE revision_id=#{values.revision_id}
</insert>
<update id="decide">UPDATE pm_collab_stage_approval SET status=#{status},decided_by=#{actor},decided_at=#{at},reason=#{reason},decision_key=#{key} WHERE id=#{id} AND status='PENDING'</update>
<update id="updateRevision">
UPDATE pm_collab_stage_revision
<set>
<if test="values.containsKey('approval_status')">approval_status=#{values.approval_status},</if>
<if test="values.containsKey('completion_note')">completion_note=#{values.completion_note},</if>
<if test="values.containsKey('completion_source')">completion_source=#{values.completion_source},</if>
<if test="values.containsKey('started_at')">started_at=COALESCE(started_at,#{values.started_at}),</if>
<if test="values.containsKey('completed_at')">completed_at=#{values.completed_at},</if>
<if test="values.containsKey('purchase_scope_confirmed')">purchase_scope_confirmed=#{values.purchase_scope_confirmed},</if>
version=version+1
</set>
WHERE id=#{id} AND version=#{version} AND superseded_at IS NULL
</update>
<update id="invalidate">UPDATE pm_collab_stage_approval SET status=#{status},decided_by=#{actor},decided_at=#{at},reason=#{reason} WHERE revision_id=#{revisionId} AND status='PENDING'</update>
<update id="markReadyNotified">UPDATE pm_collab_stage_revision SET ready_notified_at=#{at} WHERE id=#{revisionId} AND ready_notified_at IS NULL AND superseded_at IS NULL AND completed_at IS NULL</update>
<update id="freezeDelivery">UPDATE pm_collab_stage_revision SET delivery_snapshot_json=#{snapshot} WHERE id=#{revisionId} AND delivery_snapshot_json IS NULL</update>
<select id="selectAttachments" resultType="java.util.LinkedHashMap">
SELECT a.id,a.revision_id AS revisionId,a.name,a.media_type AS mediaType,a.sha256,a.size,a.created_by AS creatorId,u.nick_name AS creatorName,a.created_at AS createdAt
FROM pm_collab_stage_attachment a LEFT JOIN sys_user u ON u.user_id=a.created_by WHERE a.revision_id=#{revisionId} AND a.deleted=false ORDER BY a.id
</select>
<select id="selectAttachment" resultType="java.util.LinkedHashMap">SELECT * FROM pm_collab_stage_attachment WHERE id=#{id}</select>
<select id="selectCurrentAttachments" resultType="java.util.LinkedHashMap">
SELECT a.id,a.revision_id AS revisionId,a.name,a.media_type AS mediaType,a.sha256,a.size,a.created_by AS creatorId,u.nick_name AS creatorName,a.created_at AS createdAt
FROM pm_collab_stage_attachment a JOIN pm_collab_project_stage s ON s.current_revision_id=a.revision_id
LEFT JOIN sys_user u ON u.user_id=a.created_by WHERE s.project_id=#{projectId} AND s.iteration_id=#{iterationId} AND s.deleted=false AND a.deleted=false ORDER BY a.id
</select>
<select id="selectFrozenGroupSnapshots" resultType="java.lang.String">SELECT snapshot_json FROM pm_collab_stage_revision_member WHERE child_revision_id=#{revisionId} AND frozen_at IS NOT NULL AND snapshot_json IS NOT NULL ORDER BY id</select>
<insert id="insertAttachmentRow" useGeneratedKeys="true" keyProperty="values.id" keyColumn="id">
INSERT INTO pm_collab_stage_attachment(revision_id,name,media_type,object_key,sha256,size,created_by,created_at)
VALUES(#{values.revision_id},#{values.name},#{values.media_type},#{values.object_key},#{values.sha256},#{values.size},#{values.created_by},#{values.created_at})
</insert>
<update id="deleteAttachment">UPDATE pm_collab_stage_attachment SET deleted=true,deleted_by=#{actor},deleted_at=#{at} WHERE id=#{id} AND deleted=false</update>
<select id="selectBatches" resultType="java.util.LinkedHashMap">SELECT purchase_batch_id AS batchId FROM pm_collab_stage_purchase_batch WHERE revision_id=#{revisionId} ORDER BY purchase_batch_id</select>
<select id="selectCurrentBatches" resultType="java.util.LinkedHashMap">
SELECT b.revision_id AS revisionId,b.purchase_batch_id AS batchId FROM pm_collab_stage_purchase_batch b JOIN pm_collab_project_stage s ON s.current_revision_id=b.revision_id
WHERE s.project_id=#{projectId} AND s.iteration_id=#{iterationId} AND s.deleted=false AND s.node_type='PURCHASE' ORDER BY b.revision_id,b.purchase_batch_id
</select>
<delete id="deleteBatches">DELETE FROM pm_collab_stage_purchase_batch WHERE revision_id=#{revisionId}</delete>
<insert id="insertBatch">INSERT INTO pm_collab_stage_purchase_batch(revision_id,purchase_batch_id,created_by,created_at) VALUES(#{revisionId},#{batchId},#{actor},#{at})</insert>
<select id="selectPurchaseCandidates" resultType="java.util.LinkedHashMap">
SELECT s.project_id,s.iteration_id,s.id FROM pm_collab_project_stage s JOIN pm_collab_iteration i ON i.id=s.iteration_id AND i.project_id=s.project_id
JOIN pm_collab_stage_revision r ON r.id=s.current_revision_id WHERE s.deleted=false AND s.node_type='PURCHASE' AND i.deleted=false AND i.status='ACTIVE' AND i.archived_at IS NULL AND r.completed_at IS NULL AND r.superseded_at IS NULL AND r.ready_notified_at IS NULL AND r.approval_status&lt;&gt;'REJECTED'
</select>
</mapper>

View File

@ -18,9 +18,10 @@
<select id="selectVisibleStages" resultType="java.util.LinkedHashMap"> <select id="selectVisibleStages" resultType="java.util.LinkedHashMap">
<!-- 仅返回当前版本的回退来源,避免画布把有历史回退记录的正常阶段持续标记为待重做。 --> <!-- 仅返回当前版本的回退来源,避免画布把有历史回退记录的正常阶段持续标记为待重做。 -->
SELECT s.id,s.name,s.stage_kind AS stageKind,s.node_type AS nodeType,s.parent_stage_id AS parentStageId,s.sort_order AS sortOrder,s.owner_id AS ownerId,u.nick_name AS ownerName,s.description,s.version,s.current_revision_id AS currentRevisionId,r.revision_no AS revisionNo,r.rework_id AS reworkId,s.created_by AS creatorId,s.created_at AS createdAt, SELECT s.id,s.name,s.stage_kind AS stageKind,s.node_type AS nodeType,s.parent_stage_id AS parentStageId,s.sort_order AS sortOrder,s.owner_id AS ownerId,u.nick_name AS ownerName,c.nick_name AS creatorName,s.description,s.version,s.current_revision_id AS currentRevisionId,r.revision_no AS revisionNo,r.rework_id AS reworkId,s.created_by AS creatorId,s.created_at AS createdAt,
EXISTS(SELECT 1 FROM pm_collab_stage_revision h WHERE h.stage_id=s.id AND h.project_id=s.project_id AND (h.started_at IS NOT NULL OR h.legacy_passed_at IS NOT NULL)) AS executionHistory EXISTS(SELECT 1 FROM pm_collab_stage_revision h WHERE h.stage_id=s.id AND h.project_id=s.project_id AND (h.started_at IS NOT NULL OR h.legacy_passed_at IS NOT NULL)) AS executionHistory
FROM pm_collab_project_stage s LEFT JOIN sys_user u ON u.user_id=s.owner_id FROM pm_collab_project_stage s LEFT JOIN sys_user u ON u.user_id=s.owner_id
LEFT JOIN sys_user c ON c.user_id=s.created_by
LEFT JOIN pm_collab_stage_revision r ON r.id=s.current_revision_id LEFT JOIN pm_collab_stage_revision r ON r.id=s.current_revision_id
WHERE s.project_id=#{projectId} AND s.iteration_id=#{iterationId} AND s.deleted=false ORDER BY s.sort_order,s.id WHERE s.project_id=#{projectId} AND s.iteration_id=#{iterationId} AND s.deleted=false ORDER BY s.sort_order,s.id
</select> </select>

View File

@ -80,4 +80,4 @@ npx --no-install vue-tsc --noEmit -p src/views/project/manage/tsconfig.json --no
npm run build:prod npm run build:prod
``` ```
实施范围、验收标准和实际结果见 [前端分层实施记录](docs/frontend-structure-plan.md)。 实施范围、验收标准和实际结果见 [前端分层实施记录](docs/frontend-structure-plan.md)。阶段交付、采购核验、完成审批和数据库升级见 [阶段完成审批实施记录](docs/stage-completion-implementation.md)。

View File

@ -3,8 +3,17 @@ import { client } from './client'
/** 下载时携带当前 Token,并通过受鉴权接口取 Blob,浏览器完成保存后释放临时 URL。 */ /** 下载时携带当前 Token,并通过受鉴权接口取 Blob,浏览器完成保存后释放临时 URL。 */
export async function downloadAttachment(id: number, name: string): Promise<void> { export async function downloadAttachment(id: number, name: string): Promise<void> {
await downloadFile(`/attachments/${id}`, name)
}
const response = await client.get(`/attachments/${id}`, { responseType: 'blob', headers: { Authorization: `Bearer ${getToken()}` } }) /** 阶段文件绑定精确轮次,历史下载仍由后端核验项目成员与证据引用。 */
export async function downloadStageAttachment(projectId: number, iterationId: number, stageId: number, revisionId: number, id: number, name: string): Promise<void> {
await downloadFile(`/projects/${projectId}/iterations/${iterationId}/stages/${stageId}/revisions/${revisionId}/attachments/${id}`, name)
}
/** 所有协作附件共用私有Blob下载,完成保存后释放浏览器URL,不使用公开桶链接。 */
async function downloadFile(path: string, name: string): Promise<void> {
const response = await client.get(path, { responseType: 'blob', headers: { Authorization: `Bearer ${getToken()}` } })
if (response.data.type.includes('json')) throw new Error('附件不可访问,请刷新会话或项目权限') if (response.data.type.includes('json')) throw new Error('附件不可访问,请刷新会话或项目权限')

View File

@ -3,6 +3,7 @@ import { iterationApi } from './iterations'
import { memberApi } from './members' import { memberApi } from './members'
import { workItemApi } from './work-items' import { workItemApi } from './work-items'
import { stageApi } from './stages' import { stageApi } from './stages'
import { stageCompletionApi } from './stage-completion'
import { scheduleApi } from './schedules' import { scheduleApi } from './schedules'
import { notificationApi } from './notifications' import { notificationApi } from './notifications'
@ -13,9 +14,10 @@ export const api = {
...memberApi, ...memberApi,
...workItemApi, ...workItemApi,
...stageApi, ...stageApi,
...stageCompletionApi,
...scheduleApi, ...scheduleApi,
...notificationApi, ...notificationApi,
} }
export { PmApiError, errorText, isAccessFailure } from './errors' export { PmApiError, errorText, isAccessFailure } from './errors'
export { downloadAttachment } from './attachments' export { downloadAttachment, downloadStageAttachment } from './attachments'

View File

@ -0,0 +1,39 @@
import { request } from './client'
import { iterationPath } from './paths'
import type { PurchaseBatchOption, StageCompletion, StageCompletionCommand, StageDeliverySnapshot } from '../types'
/** 阶段审批请求显式携带项目、迭代和阶段,不能隐式选取另一个执行版本。 */
function path(projectId: number, iterationId: number, stageId: number, suffix: string): string {
return iterationPath(projectId, iterationId, `stages/${stageId}/${suffix}`)
}
export const stageCompletionApi = {
/** 历史只读轮次可指定revisionId;当前读由后端确定最新轮次。 */
stageCompletion: (projectId: number, iterationId: number, stageId: number, revisionId?: number) => request<StageCompletion>('get', path(projectId, iterationId, stageId, `completion${revisionId ? `?revisionId=${revisionId}` : ''}`)),
/** 原申请证据独立读取,避免审批历史列表重复下载所有完整快照。 */
stageApprovalEvidence: (projectId: number, iterationId: number, stageId: number, approvalId: number) => request<StageDeliverySnapshot>('get', path(projectId, iterationId, stageId, `completion-requests/${approvalId}`)),
/** 无工作项阶段也必须通过后端准入后才能开始。 */
startStage: (projectId: number, iterationId: number, stageId: number, input: StageCompletionCommand) => request<void>('post', path(projectId, iterationId, stageId, 'start'), input),
/** 实际交付说明与阶段目标分开保存并校验版本。 */
saveStageCompletionNote: (projectId: number, iterationId: number, stageId: number, input: StageCompletionCommand) => request<void>('patch', path(projectId, iterationId, stageId, 'completion-note'), input),
/** 同一业务尝试复用幂等键,只有负责人可以提交。 */
submitStageCompletion: (projectId: number, iterationId: number, stageId: number, input: StageCompletionCommand) => request<number>('post', path(projectId, iterationId, stageId, 'completion-requests'), input),
/** 通过、驳回、撤回使用明确命令,不发送可随意覆盖的阶段状态。 */
decideStageCompletion: (projectId: number, iterationId: number, stageId: number, approvalId: number, action: 'approve' | 'reject' | 'withdraw', input: StageCompletionCommand) => request<{ status: string }>('post', path(projectId, iterationId, stageId, `completion-requests/${approvalId}/${action}`), input),
/** 采购100%仅是待确认条件,此命令重新核验后保存人工确认事实。 */
confirmPurchaseStage: (projectId: number, iterationId: number, stageId: number, input: StageCompletionCommand) => request<number>('post', path(projectId, iterationId, stageId, 'purchase-confirmation'), input),
/** 批次候选为当前原项目最小投影,不返回其他项目或金额。 */
purchaseBatchOptions: (projectId: number, iterationId: number, keyword = '') => request<PurchaseBatchOption[]>('get', iterationPath(projectId, iterationId, `purchase-batch-options?keyword=${encodeURIComponent(keyword)}`)),
/** 当前轮次范围确认与采购真实数据更新互不混用。 */
saveStagePurchaseBatches: (projectId: number, iterationId: number, stageId: number, input: { revisionId: number; version: number; batchIds: number[] }) => request<void>('put', path(projectId, iterationId, stageId, 'purchase-batches'), input),
/** 浏览器生成multipart边界,文件通过已有会话鉴权上传。 */
uploadStageAttachment: (projectId: number, iterationId: number, stageId: number, revisionId: number, file: File) => {
const body = new FormData()
body.append('file', file)
return request<number>('post', path(projectId, iterationId, stageId, `revisions/${revisionId}/attachments`), body)
},
/** 显式沿用同阶段旧版附件,后端复制为独立新对象,不继承审批。 */
reuseStageAttachment: (projectId: number, iterationId: number, stageId: number, revisionId: number, sourceRevisionId: number, attachmentId: number) => request<number>('post', path(projectId, iterationId, stageId, `revisions/${revisionId}/attachments/reuse`), { sourceRevisionId, attachmentId }),
/** 软删除只绑定数据库文件ID,不接收MinIO对象路径。 */
deleteStageAttachment: (projectId: number, iterationId: number, stageId: number, revisionId: number, attachmentId: number) => request<void>('delete', path(projectId, iterationId, stageId, `revisions/${revisionId}/attachments/${attachmentId}`)),
}

View File

@ -0,0 +1,135 @@
# 阶段交付与完成审批实施记录
实施日期:2026-10-27。前端改动限于 `views/project/manage`,后端改动限于 `ruoyi-project`。采购模块和系统通知模块仅通过现有数据及端口接入,未修改其业务代码。
## 需求、范围与验收
| 编号 | 目标与验收条件 |
| --- | --- |
| FR-001 / AC-001 | 工作项完成只代表交付齐备;负责人提交、阶段发起人审批通过后,下游阶段才能开始。驳回必须填写原因,可在原执行版本整改后重新申请。 |
| FR-002 / AC-002 | 采购阶段不允许创建或移入工作项;绑定当前原项目的一个或多个采购批次,逐条核验净验收数量,全部达标后仍需发起人明确确认。 |
| FR-003 / AC-003 | 设计允许零工作项,但需要本轮附件和交付说明;加工允许零工作项、零附件。两者都经过人工审批。 |
| FR-004 / AC-004 | 申请和处理结果默认站内通知,可单次勾选邮件;邮件主题沿用 `【CMVR-WMS】`,无邮箱的人员仅接收站内通知。 |
| FR-005 / AC-005 | 审批历史、交付附件和采购采样证据保留。流程回退换版不继承审批,审批与回退并发后状态仍合法。 |
| FR-006 / AC-006 | 阶段组只汇总子阶段通过结果;空组不能完成。合法的零工作项迭代可以正常结束,异常结束或取消会终止待审申请。 |
不在本次范围:修改采购或验收数据、自动审批、自动代审、跨模块统一锁、自动调整下游排期。阶段发起人为阶段原始创建者,不使用回退版本创建者替代;当前版本负责人提交申请。
## 业务规则
| 阶段类型 | 交付齐备要求 | 完成方式 |
| --- | --- | --- |
| 普通、需求、方案、组装、调试、研发、测试等 | 至少一个有效工作项,全部完成或关闭;取消不算完成 | 负责人申请,发起人审批 |
| 设计 | 可无工作项;有工作项时必须全部完成或关闭;至少一个当前版本交付附件及非空交付说明 | 负责人申请,发起人审批 |
| 加工 | 可无工作项或附件;有工作项时必须全部完成或关闭 | 负责人申请,发起人审批 |
| 采购 | 已确认本轮批次范围,无工作项,所有批次的有效明细全部验收达标 | 发起人直接核验确认或填写原因退回 |
| 阶段组 | 至少一个子阶段,所有子阶段已审批通过或保留旧版完成事实 | 聚合结果,无额外组审批 |
- 阶段创建者与负责人相同时,仍需显式执行提交和审批两个动作,不自动通过。采购可不设负责人。
- 创建者必须保持有效项目资格。缺失资格时提示恢复人员资格,不授权管理员冒名审批。
- 非采购阶段新增或编辑时需要负责人;迁移前缺失负责人的数据保持原状,不自动选人。
- 待审期间冻结工作项交付变更、附件、负责人和排期,工作项评论仍可讨论。需要改交付时,负责人先撤回。
- 审批通过后本轮交付只读;需要重做时使用现有流程回退,保留旧版本并创建新版本。
- 驳回保持同一执行版本,下一次提交新增申请次数。撤回、失效、换版和迭代终止保留原申请,不伪造成功。
- 回退中的待审申请标为 `SUPERSEDED`,新版本从 `NONE` 开始。采购批次只复制为参考范围,须再次确认;设计附件仅在用户明确选择沿用时复制为新的 MinIO 对象。
- 回退后的阶段排期待复核时,零工作项阶段同样不能绕过开始、提交或采购确认门禁。
- 原有已完成工作阶段保留 `LEGACY_AUTO` 来源,不补造审批人或审批记录。阶段组仍按子阶段聚合。
执行状态与审批状态分开:执行状态保持未执行、执行中、完成等原流程语义;`PENDING` 显示待审批,`REJECTED` 显示待整改。交付齐备和采购 100% 均不等于已完成。连线只有上游真正通过后才按完成状态展示。
## 采购采样口径
1. 由协作扩展的 `source_project_id` 获取原项目范围;混合项目批次仅读取该原项目的明细,不返回其他项目明细或金额。
2. 普通明细的净已验收数量为验收通过的到货数量减不良数量、退回数量;待验收数量独立展示,不重复叠加入库数量。历史采购沿用采购页面口径,按需求数量视为已验收。
3. 每条未取消明细必须需求量大于零且净已验收量不小于需求量;空范围、无有效明细、全部取消或异常数量不能通过。
4. 不同单位不直接相加。展示进度取有效明细比例的平均值;完成校验始终逐条使用 `BigDecimal`。未全部达标时显示值最多 99.99%。
5. 查询在一条无缓存 SQL 中取得事实;确认绑定用户看过的证据指纹,数据变化返回冲突,要求刷新后重新核验。
6. 后台每 30 秒检查有效采购阶段。已确认范围首次观察到验收或待验收到货后,记录本轮开始事实;首次达标发送一次站内提醒,不生成待审申请、不冻结批次。它不回填外部实际到货时间。
7. 确认通过时冻结采样证据;后续采购退货、追加明细等源变化显示差异提示,不悄悄修改已通过历史。需要业务重做时使用回退或新迭代。
每个阶段最多绑定 100 个批次;候选一次最多返回 200 个,可用关键词搜索。阶段开始事实的发现存在一次后台检查间隔;页面继续采用后台静默同步。
## 数据库与事务
增量文件:`ruoyi-project/sql/upgrade/023_stage_completion_approval.sql`,在 022 后执行,可重复执行。全新安装使用已同步更新的 `ruoyi-project/sql/project_collaboration.sql`。DDL 不在应用运行时自动执行。
| 结构 | 用途 |
| --- | --- |
| `pm_collab_stage_revision` 新增 6 列 | `approval_status`、`completion_note`、`completion_source`、`delivery_snapshot_json`、`purchase_scope_confirmed`、`ready_notified_at` |
| `pm_collab_stage_approval` | 精确执行版本的申请、决定、幂等键和证据快照;唯一约束确保一个版本最多一个待审申请 |
| `pm_collab_stage_attachment` | 精确执行版本的 MinIO 交付附件,保存摘要、大小、上传人和软删除信息 |
| `pm_collab_stage_purchase_batch` | 精确执行版本与源采购批次的引用,不修改采购数据或数量 |
新增表、列均有中文注释;三个版本归属外键和相关唯一约束已建立。当前配置的开发库已执行增量升级,保留既有数据;未重置项目、迭代或工作项。
所有协作命令遵循既有“源项目共享锁 → 协作项目图更新锁”顺序,在 `READ_COMMITTED` 事务内重查权限、当前版本和前置准入。审批、工作项变更、排期、回退及后台采购观察使用同一项目图锁;版本 CAS 和数据库待审唯一约束提供额外保护。
采购模块仍独立写入,协作不声称锁住外部采购。确认依据为同一条查询产生的一致采样;已看到旧证据而数据变化时拒绝直接确认,后续源变化作为差异展示。
业务更新、历史和通知 outbox 同事务保存;异步通知沿用重试、去重及发送时成员校验。后台观察事件标明自动来源,不冒用创建人的登录身份。
附件保存为 MinIO 私有对象,通过带项目、迭代、阶段和版本的接口鉴权下载,不暴露对象键。软删除保留对象;已被审批证据或冻结组版本引用的文件仍可在对应历史中下载。沿用旧附件会创建独立新对象,不继承原审批。
## 接口与代码入口
统一前缀:`/project/manage/projects/{projectId}/iterations/{iterationId}`。
| 方法与相对路径 | 能力 |
| --- | --- |
| `GET /stages/{stageId}/completion?revisionId=...` | 当前或历史交付、审批记录、阻塞原因和操作能力 |
| `POST /stages/{stageId}/start` | 无工作项阶段显式开始 |
| `PATCH /stages/{stageId}/completion-note` | 保存本轮实际交付说明 |
| `POST /stages/{stageId}/completion-requests` | 负责人提交 |
| `GET /stages/{stageId}/completion-requests/{approvalId}` | 当次申请证据 |
| `POST /stages/{stageId}/completion-requests/{approvalId}/{approve\|reject\|withdraw}` | 审批或撤回 |
| `GET /purchase-batch-options` | 原项目批次候选 |
| `PUT /stages/{stageId}/purchase-batches` | 确认或调整本轮批次范围 |
| `POST /stages/{stageId}/purchase-confirmation` | 发起人核验通过或退回 |
| `POST /stages/{stageId}/revisions/{revisionId}/attachments` | 上传交付附件 |
| `GET /stages/{stageId}/revisions/{revisionId}/attachments/{attachmentId}` | 鉴权下载 |
| `DELETE /stages/{stageId}/revisions/{revisionId}/attachments/{attachmentId}` | 软删除 |
| `POST /stages/{stageId}/revisions/{revisionId}/attachments/reuse` | 显式沿用旧版本附件 |
前端入口为 `features/stages/components/StageCompletionPanel.vue`、`PurchaseBatchPicker.vue` 和 `StageDeliverySnapshot.vue`;由阶段抽屉统一承载。流程节点、看板、列表和甘特同步展示审批状态和冻结能力。后台交付命令集中于 `PmStageCompletionServiceImpl`,采购只读适配位于 `PmPurchaseReadMapper`、`PmPurchaseProgressReader`,历史采样位于 `PmStageEvidenceService`。
所有新表单使用 small 控件、主题变量和禁止点击遮罩关闭;静默同步在发起和响应返回两个时点保护未保存草稿。审批弹窗固定用户已查看的版本、证据和幂等键,冲突后刷新并要求重新核对。
## 验证与本地使用
后端使用 JDK 17,在仓库根目录执行:
```powershell
mvn -pl ruoyi-admin -am -DskipTests package
```
前端在 `ruoyi-ui-vue3` 执行:
```powershell
npx --no-install vue-tsc --noEmit -p src/views/project/manage/tsconfig.json --noUnusedLocals --noUnusedParameters
npm run build:prod
```
本地启动沿用现有 IDEA 后端启动配置和前端 `npm run dev`,保持 MySQL、MinIO 和系统通知配置可用。其他环境先执行 023,再部署新应用;数据库升级本身不会刷新正在运行的应用代码。
本次临时验证入口使用独立 MySQL 测试库、实际 MyBatis XML、事务服务和真实 MinIO。覆盖普通提审、不同类型零任务交付、冻结期间写入、采购跨项目隔离和源变化、历史下载和沿用、迭代结束、重复命令、审批与回退竞争。前端交互验证覆盖默认邮件选项、驳回原因、历史只读、颜色及静默同步草稿保护。
本次实际结果:
- 真实 MySQL/MinIO 集成验证:79 项检查通过,包含双线程审批与回退竞争及外部采购未提交更新的采样验证。
- 前端交互验证:7 项通过。
- 严格类型检查:通过;后端整包构建(`-DskipTests`):通过;前端生产构建:通过。
- 新 Mapper XML、Mapper 类及控制器已检查包含在后端构建产物中;临时测试类未被打包。
- 前端构建仍有既有的全局 Editor 混合静态/动态导入提示,未产生构建错误;未改动其他业务模块处理该提示。
临时验证实际执行命令为 `python -X utf8 ruoyi-project/target/run-stage-approval-verification.py` 和 `npx --no-install vitest run --config src/views/project/manage/.verification/vitest.config.mjs`。这些临时入口、辅助文件、独立测试库和测试对象已按本模块规定在验证后删除,不作为运行依赖交付。通知收件人、邮件渠道和主题通过现有投递端口的记录实现验证,未向真实用户发送测试邮件。
人工验收可按以下顺序操作,无需修改既有测试数据:
1. 新建测试迭代,创建普通阶段并设置另一成员为负责人;完成工作项后检查下游仍被阻塞。
2. 用负责人提交,检查发起人站内通知;用发起人填写原因驳回,检查负责人通知和原版本内新增申请记录,再重新提交通过。
3. 创建无任务设计阶段,先检查无附件或说明不能提交;补交后完成审批。创建无任务加工阶段,验证无需附件仍可申请。
4. 创建采购阶段,选择当前原项目批次;检查明细数量和进度。达标后先调整批次,再由发起人确认,验证没有自动完成。
5. 从当前阶段发起流程回退,检查旧审批证据可读、新版本需要重新确认排期和交付,采购范围和设计附件没有自动继承审批。
6. 勾选一次邮件通知后操作,检查有邮箱人员收到邮件;其他操作默认仅站内通知。
已知数据准备项:本次检查开发库时,有 7 个旧普通工作阶段未设置负责人。升级保留原数据;后续需要为可编辑阶段指定有效项目成员,已完成阶段保持历史事实,重做时在新版本配置。系统不替用户选择负责人或审批人。

View File

@ -23,9 +23,10 @@
</el-dialog> </el-dialog>
<el-dialog :close-on-click-modal="false" v-model="previewOpen" :title="previewAction === 'finish' ? '结束迭代预览' : '取消迭代预览'" width="min(680px, 95%)" append-to-body> <el-dialog :close-on-click-modal="false" v-model="previewOpen" :title="previewAction === 'finish' ? '结束迭代预览' : '取消迭代预览'" width="min(680px, 95%)" append-to-body>
<template v-if="preview"> <template v-if="preview">
<el-alert v-if="previewAction === 'cancel'" title="确认后将原子取消下列所有未结束工作项;已结束工作项保持原状态。" type="warning" :closable="false" /> <el-alert v-if="previewAction === 'cancel'" title="确认后将取消下列未结束工作项,并终止阶段待审批申请;不会将未审批阶段标为完成。已结束工作项保持原状态。" type="warning" :closable="false" />
<el-alert v-else-if="preview.unfinishedItems.length" title="仍有待开始或进行中的工作项,暂不能结束迭代。" type="warning" :closable="false" /> <el-alert v-else-if="preview.unfinishedItems.length" title="仍有待开始或进行中的工作项,暂不能结束迭代。" type="warning" :closable="false" />
<el-alert v-else :title="preview.finishResult === 'WITH_EXCEPTIONS' ? '本次将带异常结束;请逐条确认异常并填写原因。' : '工作项全部结束,可正常结束迭代。'" type="info" :closable="false" /> <el-alert v-else :title="preview.finishResult === 'WITH_EXCEPTIONS' ? '本次将带异常结束;请逐条确认异常并填写原因。' : '本次无未完成阶段或工作项,可正常结束迭代。'" type="info" :closable="false" />
<el-alert v-if="preview.pendingApprovals?.length" :title="`将终止 ${preview.pendingApprovals.length} 条阶段待审批申请:${preview.pendingApprovals.map(row => row.name).join('、')}。原记录保留,重新打开后须重新提交。`" type="warning" :closable="false" />
<el-table :data="previewAction === 'cancel' ? preview.itemsToCancel : preview.unfinishedItems" size="small" max-height="260"><el-table-column label="工作项" prop="title" /><el-table-column label="状态" width="100" class-name="business-status-cell"><template #default="{ row }">{{ statusNames[row.status as Lifecycle] }}</template></el-table-column></el-table> <el-table :data="previewAction === 'cancel' ? preview.itemsToCancel : preview.unfinishedItems" size="small" max-height="260"><el-table-column label="工作项" prop="title" /><el-table-column label="状态" width="100" class-name="business-status-cell"><template #default="{ row }">{{ statusNames[row.status as Lifecycle] }}</template></el-table-column></el-table>
<div v-if="previewAction === 'finish'"><el-checkbox v-for="exception in preview.exceptions" :key="exception.key" :model-value="accepted.includes(exception.key)" @update:model-value="toggleException(exception.key, !!$event)">{{ exception.message }}</el-checkbox></div> <div v-if="previewAction === 'finish'"><el-checkbox v-for="exception in preview.exceptions" :key="exception.key" :model-value="accepted.includes(exception.key)" @update:model-value="toggleException(exception.key, !!$event)">{{ exception.message }}</el-checkbox></div>
<el-input v-model="reason" type="textarea" :rows="3" maxlength="2000" :placeholder="previewAction === 'cancel' ? '填写取消原因' : '填写结束说明(存在异常时必填)'" /> <el-input v-model="reason" type="textarea" :rows="3" maxlength="2000" :placeholder="previewAction === 'cancel' ? '填写取消原因' : '填写结束说明(存在异常时必填)'" />

View File

@ -0,0 +1,39 @@
<template>
<div class="batch-picker">
<el-select :model-value="modelValue" size="small" multiple :multiple-limit="100" filterable remote reserve-keyword collapse-tags collapse-tags-tooltip :remote-method="search" :loading="loading" :disabled="disabled" placeholder="搜索并选择本项目采购批次(可多选)" @update:model-value="emit('update:modelValue', $event)">
<el-option v-for="row in choices" :key="row.id" :value="row.id" :label="`${row.batchNo || '#' + row.id} · ${row.batchName || '未命名批次'}`" />
</el-select>
<p class="hint">混合批次仅统计本项目明细;不会修改采购源数据。</p>
<el-alert v-if="failure" type="error" :closable="false" :title="failure" />
</div>
</template>
<script setup lang="ts">
import { computed, onBeforeUnmount, ref, watch } from 'vue'
import { api, errorText } from '../../../api'
import type { PurchaseBatchOption, PurchaseBatchProgress } from '../../../types'
const props = defineProps<{ modelValue: number[]; projectId: number; iterationId?: number; disabled?: boolean; selected?: PurchaseBatchProgress[] }>()
const emit = defineEmits<{ 'update:modelValue': [ids: number[]] }>()
const rows = ref<PurchaseBatchOption[]>([]), loading = ref(false), failure = ref('')
let sequence = 0
/** 保留已选批次标签;远程搜索结果不能让其他已选批次退化为纯ID。 */
const choices = computed(() => {
const values = new Map<number, PurchaseBatchOption>()
for (const row of props.selected || []) values.set(row.batchId, { id: row.batchId, batchNo: row.batchNo || '', batchName: row.batchName, lineCount: row.effectiveLines })
for (const row of rows.value) values.set(row.id, row)
return [...values.values()]
})
/** 搜索令牌绑定项目与迭代,迟到响应不能将另一项目候选带入表单。 */
async function search(keyword = '') {
const request = ++sequence, iterationId = props.iterationId
if (!iterationId) return
loading.value = true; failure.value = ''
try { const result = await api.purchaseBatchOptions(props.projectId, iterationId, keyword); if (request === sequence) rows.value = result }
catch (error) { if (request === sequence) failure.value = errorText(error) }
finally { if (request === sequence) loading.value = false }
}
/** 换范围清空候选,不改动由所属表单控制的选中值。 */
watch(() => [props.projectId, props.iterationId], () => { rows.value = []; void search() }, { immediate: true })
/** 离开表单废弃未完成的搜索,避免卸载后写入界面状态。 */
onBeforeUnmount(() => { sequence++ })
</script>
<style scoped>.batch-picker{width:100%;min-width:0}.batch-picker :deep([class~="el-select"]){width:100%}.hint{font-size:12px;color:var(--el-text-color-secondary);line-height:1.5;margin:5px 0}</style>

View File

@ -0,0 +1,177 @@
<template>
<section v-loading="loading && !data" class="completion-panel">
<div class="heading"><strong>阶段交付与完成确认</strong><el-button size="small" :disabled="busy || operationOpen" @click="refresh">刷新</el-button></div>
<el-alert v-if="failure" type="error" :title="failure" :closable="false" class="message" />
<template v-if="data">
<div class="identity"><span>发起人:{{ stage.creatorName || `用户 #${stage.creatorId}` }}</span><span>负责人:{{ data.delivery?.ownerId === stage.ownerId ? stage.ownerName || '未设置' : data.delivery?.ownerId ? `用户 #${data.delivery.ownerId}` : '未设置' }}</span><el-tag size="small" :type="data.approvalStatus === 'REJECTED' ? 'danger' : data.approvalStatus === 'APPROVED' ? 'success' : 'info'">{{ approvalStatusNames[data.approvalStatus] || data.approvalStatus }}</el-tag><el-tag v-if="data.completionSource === 'LEGACY_AUTO'" size="small" type="info">历史自动完成</el-tag></div>
<el-alert v-if="stage.stageKind === 'GROUP'" title="阶段组聚合子阶段的审批结果,不额外提交组审批;空阶段组不能完成。" type="info" :closable="false" class="message" />
<el-alert v-if="data.approvalStatus === 'PENDING'" title="申请正在审批。交付内容已冻结,需要修改时请负责人先撤回;工作项评论仍可讨论。" type="warning" :closable="false" class="message" />
<el-alert v-if="data.sourceChanged" title="当前数据与已通过的交付依据存在差异。原审批历史保留,请核对变化并按需发起流程回退或新迭代。" type="warning" :closable="false" class="message" />
<div v-if="stage.nodeType === 'PURCHASE' && data.capabilities.canEditPurchase" class="purchase-editor">
<PurchaseBatchPicker v-model="batchIds" :project-id="projectId" :iteration-id="iterationId" :selected="data.delivery?.purchase?.batches" :disabled="busy" />
<el-button size="small" :loading="busy" @click="saveBatches">{{ data.delivery?.purchaseScopeConfirmed ? '保存采购批次范围' : '确认本轮采购范围' }}</el-button>
</div>
<template v-if="stage.stageKind !== 'GROUP'">
<el-form v-if="data.capabilities.canEditDelivery && stage.nodeType !== 'PURCHASE'" size="small" label-position="top" class="note-editor">
<el-form-item label="实际交付说明" :required="stage.nodeType === 'DESIGN'"><el-input v-model="note" type="textarea" :rows="3" maxlength="10000" :disabled="busy" placeholder="说明本轮实际交付成果,与阶段目标描述分开" /></el-form-item>
<el-button size="small" :disabled="note === (data.note || '') || busy" @click="saveNote">保存说明</el-button>
<label class="upload"><el-button size="small" :disabled="busy" tag="span">上传交付附件</el-button><input type="file" :disabled="busy" @change="upload" /></label>
<span class="muted">MinIO私有存储,单个文件最多10MiB</span>
</el-form>
<StageDeliverySnapshot :snapshot="data.delivery" :project-id="projectId" :iteration-id="iterationId" :show-items="false" :show-note="!data.capabilities.canEditDelivery || stage.nodeType === 'PURCHASE'">
<template #file-action="{ file }"><el-button v-if="data.capabilities.canEditDelivery" size="small" link type="danger" :disabled="busy" @click="removeFile(file)">删除</el-button><el-button v-else-if="data.historical && stage.canEditDelivery && stage.currentRevisionId !== data.revisionId" size="small" link type="primary" :disabled="busy" @click="reuseFile(file)">沿用到当前版本</el-button></template>
</StageDeliverySnapshot>
</template>
<div v-if="!data.historical && !data.completionSource && stage.stageKind !== 'GROUP'" class="conditions"><p v-for="(reason, index) in [...data.capabilities.stageBlockedReasons, ...data.capabilities.blockedReasons]" :key="index">{{ reason.message }}{{ reason.sourceName ? `:${reason.sourceName}` : '' }}</p><p v-if="data.capabilities.deliveryReady" class="ready">交付条件已满足。{{ stage.nodeType === 'PURCHASE' ? '等待发起人确认完成,确认前仍可调整批次。' : '仍须负责人申请、发起人审批后才放行下游。' }}</p></div>
<div class="actions">
<el-button v-if="data.capabilities.canStart" size="small" :disabled="busy || dirty" @click="start">开始阶段</el-button>
<el-button v-if="data.capabilities.canSubmit" size="small" type="primary" :disabled="busy || dirty" @click="openOperation('submit')">申请阶段完成</el-button>
<el-button v-if="data.capabilities.canWithdraw" size="small" :disabled="busy" @click="openOperation('withdraw')">撤回申请</el-button>
<el-button v-if="data.capabilities.canApprove" size="small" type="success" :disabled="busy" @click="openOperation('approve')">审批通过</el-button>
<el-button v-if="data.capabilities.canApprove" size="small" type="danger" :disabled="busy" @click="openOperation('reject')">驳回</el-button>
<el-button v-if="data.capabilities.canConfirmPurchase" size="small" type="success" :disabled="busy || dirty" @click="openOperation('purchaseConfirm')">确认采购阶段完成</el-button>
<el-button v-if="data.capabilities.canConfirmPurchase" size="small" :disabled="busy || dirty" @click="openOperation('purchaseReject')">退回处理</el-button>
<span v-if="dirty" class="muted">存在未保存修改,请先保存后再操作。</span>
</div>
<el-collapse v-if="data.approvedDelivery && data.sourceChanged" class="message"><el-collapse-item title="查看审批通过时的交付依据" name="approved"><StageDeliverySnapshot :snapshot="data.approvedDelivery" :project-id="projectId" :iteration-id="iterationId" /></el-collapse-item></el-collapse>
<h4>完成审批记录</h4>
<el-table :data="data.approvals.slice((historyPage - 1) * 10, historyPage * 10)" size="small" max-height="300" empty-text="尚无申请或采购确认记录">
<el-table-column label="次数" width="55"><template #default="{ row }">{{ row.submission_no }}</template></el-table-column>
<el-table-column label="提交" min-width="110"><template #default="{ row }">{{ row.request_source === 'PURCHASE_CONFIRM' ? '采购人工确认' : row.submitterName || '#' + row.submitted_by }}</template></el-table-column>
<el-table-column label="结果" width="90"><template #default="{ row }">{{ approvalStatusNames[row.status as StageApprovalStatus] }}</template></el-table-column>
<el-table-column label="审批人" min-width="85"><template #default="{ row }">{{ row.deciderName || '—' }}</template></el-table-column>
<el-table-column prop="reason" label="原因" min-width="150" show-overflow-tooltip />
<el-table-column label="时间" min-width="145"><template #default="{ row }">{{ displayTime(row.decidedAt || row.submittedAt) }}</template></el-table-column>
<el-table-column label="证据" width="65" fixed="right"><template #default="{ row }"><el-button size="small" link type="primary" @click="showEvidence(row)">查看</el-button></template></el-table-column>
</el-table>
<el-pagination v-if="data.approvals.length > 10" v-model:current-page="historyPage" size="small" :page-size="10" :total="data.approvals.length" layout="prev, pager, next" />
</template>
</section>
<el-dialog v-model="operationOpen" :close-on-click-modal="false" :title="operationNames[operation]" width="min(520px, 94vw)" append-to-body>
<p>阶段:{{ stage.name }}。{{ operation === 'approve' || operation === 'purchaseConfirm' ? '通过后才会放行后续阶段,当前版本交付内容将保持只读。' : '本次操作会保留完整审批历史。' }}</p>
<el-form size="small" label-position="top"><el-form-item v-if="requiresReason || operation === 'withdraw'" :label="requiresReason ? '驳回/退回原因' : '撤回说明'" :required="requiresReason"><el-input v-model="reason" type="textarea" :rows="3" maxlength="2000" /></el-form-item><el-checkbox v-model="sendEmail" size="small">发送邮件通知</el-checkbox><p class="muted">默认仅发送站内通知;勾选后向有邮箱的接收人发送邮件。</p></el-form>
<el-alert v-if="operationFailure" :title="operationFailure" type="error" :closable="false" />
<template #footer><el-button size="small" :disabled="busy" @click="operationOpen = false">取消</el-button><el-button size="small" type="primary" :loading="busy" :disabled="requiresReason && !reason.trim()" @click="commitOperation">确认</el-button></template>
</el-dialog>
<el-dialog v-model="evidenceOpen" :close-on-click-modal="false" title="本次申请提交时的交付依据" width="min(880px, 95vw)" append-to-body><StageDeliverySnapshot :snapshot="selectedEvidence" :project-id="projectId" :iteration-id="iterationId" /></el-dialog>
</template>
<script setup lang="ts">
import { computed, onBeforeUnmount, ref, watch } from 'vue'
import { ElMessageBox, vLoading } from 'element-plus'
import { api, errorText, PmApiError } from '../../../api'
import { createIdempotencyKey } from '../../../shared/utils/idempotency'
import { localTime } from '../../../shared/utils/time'
import { approvalStatusNames } from '../../../shared/constants/labels'
import type { Stage, StageApproval, StageApprovalStatus, StageCompletion, StageCompletionCommand, StageDeliveryAttachment, StageDeliverySnapshot as DeliverySnapshot } from '../../../types'
import PurchaseBatchPicker from './PurchaseBatchPicker.vue'
import StageDeliverySnapshot from './StageDeliverySnapshot.vue'
type Operation = 'submit' | 'approve' | 'reject' | 'withdraw' | 'purchaseConfirm' | 'purchaseReject'
const props = defineProps<{ projectId: number; iterationId: number; stage: Stage; revisionId?: number; refreshKey?: number }>()
const emit = defineEmits<{ changed: []; editing: [value: boolean] }>()
const data = ref<StageCompletion | null>(null), loading = ref(false), busy = ref(false), failure = ref(''), note = ref(''), batchIds = ref<number[]>([]), historyPage = ref(1)
const operationOpen = ref(false), operation = ref<Operation>('submit'), reason = ref(''), sendEmail = ref(false), operationFailure = ref('')
const evidenceOpen = ref(false), selectedEvidence = ref<DeliverySnapshot | null>(null)
const operationNames: Record<Operation, string> = { submit: '申请阶段完成', approve: '审批通过', reject: '驳回完成申请', withdraw: '撤回完成申请', purchaseConfirm: '确认采购验收完成', purchaseReject: '采购阶段退回处理' }
const requiresReason = computed(() => operation.value === 'reject' || operation.value === 'purchaseReject')
const dirty = computed(() => !!data.value && (note.value !== (data.value.note || '') || [...batchIds.value].sort((a, b) => a - b).join(',') !== (data.value.delivery?.purchase?.batches.map(row => row.batchId) || []).sort((a, b) => a - b).join(',')))
const pending = computed(() => data.value?.approvals.find(row => row.status === 'PENDING'))
let sequence = 0, command: StageCompletionCommand | null = null
/** 请求范围包含历史轮次,换项目或切历史时不能复用旧申请ID和草稿。 */
function scope(): string { return `${props.projectId}:${props.iterationId}:${props.stage.id}:${props.revisionId || 'current'}` }
/** 静默请求开始和返回均保护草稿;只有已确认的手动刷新及成功命令才能强制重新装载。 */
async function load(force = false) {
const request = ++sequence, range = scope(); loading.value = true
try {
const result = await api.stageCompletion(props.projectId, props.iterationId, props.stage.id, props.revisionId)
if (request !== sequence || range !== scope()) return
if (!force && data.value && (dirty.value || busy.value || operationOpen.value)) return
data.value = result; note.value = result.note || ''; batchIds.value = result.delivery?.purchase?.batches.map(row => row.batchId) || []; failure.value = ''
} catch (error) { if (request === sequence && range === scope()) failure.value = errorText(error) }
finally { if (request === sequence) loading.value = false }
}
/** 只在范围切换时重置;同阶段状态更新保留未保存内容。 */
watch(() => [props.projectId, props.iterationId, props.stage.id, props.revisionId], () => { sequence++; data.value = null; note.value = ''; batchIds.value = []; historyPage.value = 1; operationOpen.value = false; evidenceOpen.value = false; void load(true) }, { immediate: true })
/** 图版本变化不会中断编辑;实际提交仍由后端版本校验阻止覆盖。 */
watch(() => [props.refreshKey, props.stage.deliveryEvidenceHash, props.stage.approvalStatus], () => { if (!dirty.value && !busy.value && !operationOpen.value) void load() })
/** 外层可据此暂停编辑期间轮询;卸载后必须释放编辑信号。 */
watch(() => dirty.value || busy.value || operationOpen.value, value => emit('editing', value))
/** 废弃全部在途响应,避免关闭抽屉后弹出旧证据。 */
onBeforeUnmount(() => { sequence++; emit('editing', false) })
/** 命令取当前显示版本,不使用阶段元数据版本替代执行版本。 */
function input(): StageCompletionCommand {
if (!data.value) throw new Error('阶段交付尚未加载')
return { revisionId: data.value.revisionId, version: data.value.revisionVersion, evidenceHash: data.value.evidenceHash }
}
/** 可逆交付修改共用范围检查与刷新,服务器成功但已离开当前阶段时不影响新抽屉。 */
async function mutate(action: () => Promise<unknown>, preserveNote = true) {
if (busy.value) return
const range = scope(), draftNote = note.value, unsavedNote = note.value !== (data.value?.note || ''); busy.value = true; failure.value = ''
try { await action(); if (range === scope()) { await load(true); if (preserveNote && unsavedNote) note.value = draftNote; emit('changed') } }
catch (error) { if (range === scope()) failure.value = errorText(error) }
finally { if (range === scope()) busy.value = false }
}
/** 交付说明先保存,提审时使用保存后的证据摘要。 */
function saveNote() { void mutate(() => api.saveStageCompletionNote(props.projectId, props.iterationId, props.stage.id, { ...input(), note: note.value }), false) }
/** 本轮范围确认可沿用回退参考批次,但需人员明确点击。 */
function saveBatches() { void mutate(() => api.saveStagePurchaseBatches(props.projectId, props.iterationId, props.stage.id, { revisionId: input().revisionId, version: input().version, batchIds: batchIds.value })) }
/** 无工作项阶段也通过后端准入记录首次开始时间。 */
function start() { void mutate(() => api.startStage(props.projectId, props.iterationId, props.stage.id, input())) }
/** 冲突后仍可刷新;存在草稿时必须由用户明确选择放弃,不能被后台轮询悄悄覆盖。 */
async function refresh() {
if (dirty.value) { try { await ElMessageBox.confirm('刷新将放弃尚未保存的交付说明或采购范围,是否继续?', '刷新阶段交付', { closeOnClickModal: false, type: 'warning' }) } catch { return } }
await load(true)
}
/** 原生文件输入只交给模块客户端,不能生成公开MinIO地址或本地路径。 */
function upload(event: Event) {
const element = event.target as HTMLInputElement, file = element.files?.[0]; element.value = ''
if (!file || !data.value) return
if (!file.size || file.size > 10 * 1024 * 1024) { failure.value = '附件需为1字节至10MiB'; return }
void mutate(() => api.uploadStageAttachment(props.projectId, props.iterationId, props.stage.id, input().revisionId, file))
}
/** 软删确认不会销毁历史对象,取消确认不触发后端操作。 */
async function removeFile(file: StageDeliveryAttachment) {
try { await ElMessageBox.confirm(`删除交付附件「${file.name}」?历史审批引用将保留。`, '删除附件', { closeOnClickModal: false, type: 'warning' }) } catch { return }
await mutate(() => api.deleteStageAttachment(props.projectId, props.iterationId, props.stage.id, input().revisionId, file.id))
}
/** 历史文件经用户明确确认复制到新轮次,原审批结果不会随附件继承。 */
async function reuseFile(file: StageDeliveryAttachment) {
const revisionId = props.stage.currentRevisionId
if (!revisionId) return
try { await ElMessageBox.confirm(`将「${file.name}」沿用为当前版本交付?仍需重新提交完成审批。`, '沿用交付附件', { closeOnClickModal: false }) } catch { return }
await mutate(() => api.reuseStageAttachment(props.projectId, props.iterationId, props.stage.id, revisionId, file.revisionId, file.id))
}
/** 确认弹窗固定用户实际看过的证据和幂等键,失败重试不静默替换为新范围。 */
function openOperation(value: Operation) {
try { command = { ...input(), idempotencyKey: createIdempotencyKey() }; operation.value = value; reason.value = ''; sendEmail.value = false; operationFailure.value = ''; operationOpen.value = true }
catch (error) { failure.value = errorText(error) }
}
/** 采购直接确认与负责人申请走不同端口;所有决定仍由后端身份及证据校验。 */
async function commitOperation() {
if (busy.value || !command || requiresReason.value && !reason.value.trim()) return
const range = scope(), payload = { ...command, reason: reason.value.trim() || undefined, sendEmail: sendEmail.value }, approvalId = pending.value?.id
busy.value = true; operationFailure.value = ''
try {
if (operation.value === 'submit') await api.submitStageCompletion(props.projectId, props.iterationId, props.stage.id, payload)
else if (operation.value === 'purchaseConfirm' || operation.value === 'purchaseReject') await api.confirmPurchaseStage(props.projectId, props.iterationId, props.stage.id, payload)
else { if (!approvalId) throw new Error('待审批申请已变化,请刷新'); await api.decideStageCompletion(props.projectId, props.iterationId, props.stage.id, approvalId, operation.value, payload) }
if (range === scope()) { operationOpen.value = false; await load(true); emit('changed') }
} catch (error) {
if (range === scope()) {
operationFailure.value = errorText(error)
if (error instanceof PmApiError && ['VERSION_CONFLICT', 'STAGE_EVIDENCE_CHANGED', 'STAGE_APPROVAL_ALREADY_DECIDED', 'STAGE_REVISION_CHANGED'].includes(error.code)) { operationOpen.value = false; await load(true); failure.value = `${errorText(error)}。请核对最新内容后重新操作。`; emit('changed') }
}
} finally { if (range === scope()) busy.value = false }
}
/** 审批历史显示提交时证据,不能用当前说明或当前采购进度替代。 */
async function showEvidence(row: StageApproval) {
const request = ++sequence, range = scope()
try { const result = await api.stageApprovalEvidence(props.projectId, props.iterationId, props.stage.id, row.id); if (request === sequence && range === scope()) { selectedEvidence.value = result; evidenceOpen.value = true } }
catch (error) { if (request === sequence) failure.value = errorText(error) }
}
/** 审批保留时刻,预计排期仍仅显示年月日。 */
function displayTime(value: string | null): string { return value ? localTime(value, 'Asia/Shanghai').replace('T', ' ').slice(0, 19) : '—' }
</script>
<style scoped>.completion-panel{padding:10px;border:1px solid var(--el-border-color-light);border-radius:6px;margin:8px 0 12px;color:var(--el-text-color-regular);min-width:0}.heading,.identity,.actions{display:flex;align-items:center;gap:8px;flex-wrap:wrap}.heading{justify-content:space-between;font-size:13px}.identity{font-size:12px;margin:10px 0}.message{margin:8px 0}.note-editor{margin:10px 0}.note-editor :deep([class~="el-form-item"]){margin-bottom:7px}.muted{font-size:12px;color:var(--el-text-color-secondary);line-height:1.6}.upload{position:relative;display:inline-flex;overflow:hidden;margin:0 8px;vertical-align:middle}.upload input{position:absolute;inset:0;opacity:0;cursor:pointer;width:100%}.conditions{font-size:12px;color:var(--el-color-warning);line-height:1.5}.conditions p{margin:5px 0}.conditions .ready{color:var(--el-color-success)}.actions{margin:10px 0}.purchase-editor{padding:8px 0}h4{font-size:13px;margin:14px 0 7px}</style>

View File

@ -3,14 +3,15 @@
<el-form size="small" label-position="top" @submit.prevent> <el-form size="small" label-position="top" @submit.prevent>
<el-form-item label="节点类型(创建后不可修改)"><el-tag v-if="nodeType" size="small">{{ stageNodeTypeLabel({ nodeType: draft.nodeType }) }}</el-tag><el-select v-else v-model="draft.nodeType" placeholder="选择节点类型"><el-option v-for="type in WORK_STAGE_NODE_TYPES" :key="type.value" :value="type.value" :label="type.label" /></el-select></el-form-item> <el-form-item label="节点类型(创建后不可修改)"><el-tag v-if="nodeType" size="small">{{ stageNodeTypeLabel({ nodeType: draft.nodeType }) }}</el-tag><el-select v-else v-model="draft.nodeType" placeholder="选择节点类型"><el-option v-for="type in WORK_STAGE_NODE_TYPES" :key="type.value" :value="type.value" :label="type.label" /></el-select></el-form-item>
<p v-if="parent" class="hint">所属阶段组:{{ parent.name }}</p> <p v-if="parent" class="hint">所属阶段组:{{ parent.name }}</p>
<p class="hint">{{ draft.nodeType === 'GROUP' ? '阶段组只承载子阶段,全部子阶段完成后才放行后续。' : '工作阶段可以保持为空;添加工作项并全部完成后才放行后续。' }}</p> <p class="hint">{{ draft.nodeType === 'GROUP' ? '阶段组只承载子阶段,子阶段全部审批通过后才放行后续。' : draft.nodeType === 'PURCHASE' ? '采购阶段不创建工作项,验收齐备后由阶段创建人确认完成。' : ['DESIGN', 'MACHINING'].includes(draft.nodeType) ? '可以没有工作项,由负责人提交交付内容、阶段创建人审批完成。' : '工作项全部完成后,由负责人申请、阶段创建人审批通过才放行后续。' }}</p>
<el-form-item label="阶段名称" required><el-input v-model="draft.name" maxlength="120" /></el-form-item> <el-form-item label="阶段名称" required><el-input v-model="draft.name" maxlength="120" /></el-form-item>
<el-form-item label="阶段描述"><el-input v-model="draft.description" type="textarea" :rows="3" maxlength="10000" placeholder="说明本阶段需要完成的事项" /></el-form-item> <el-form-item label="阶段描述"><el-input v-model="draft.description" type="textarea" :rows="3" maxlength="10000" placeholder="说明本阶段需要完成的事项" /></el-form-item>
<el-form-item label="阶段负责人"><el-select v-model="draft.ownerId" clearable><el-option v-for="member in members" :key="member.userId" :value="member.userId" :label="member.name" /></el-select></el-form-item> <el-form-item label="阶段负责人" :required="draft.nodeType !== 'PURCHASE'"><el-select v-model="draft.ownerId" clearable><el-option v-for="member in members" :key="member.userId" :value="member.userId" :label="member.name" /></el-select></el-form-item>
<el-form-item v-if="draft.nodeType === 'PURCHASE'" label="采购批次"><PurchaseBatchPicker v-model="draft.purchaseBatchIds" :project-id="projectId" :iteration-id="iterationId" :disabled="busy" /></el-form-item>
<el-row :gutter="16"><el-col :span="12"><el-form-item label="预计开始" required><TimeField v-model="draft.plannedStartAt" zone="Asia/Shanghai" boundary="start" :earliest="parent?.plannedStartAt" :latest="parent?.plannedEndAt" /></el-form-item></el-col><el-col :span="12"><el-form-item label="预计结束" required><TimeField v-model="draft.plannedEndAt" zone="Asia/Shanghai" boundary="end" :earliest="draft.plannedStartAt" :latest="parent?.plannedEndAt" /></el-form-item></el-col></el-row> <el-row :gutter="16"><el-col :span="12"><el-form-item label="预计开始" required><TimeField v-model="draft.plannedStartAt" zone="Asia/Shanghai" boundary="start" :earliest="parent?.plannedStartAt" :latest="parent?.plannedEndAt" /></el-form-item></el-col><el-col :span="12"><el-form-item label="预计结束" required><TimeField v-model="draft.plannedEndAt" zone="Asia/Shanghai" boundary="end" :earliest="draft.plannedStartAt" :latest="parent?.plannedEndAt" /></el-form-item></el-col></el-row>
</el-form> </el-form>
<el-alert v-if="failure" :title="failure" type="error" :closable="false" /> <el-alert v-if="failure" :title="failure" type="error" :closable="false" />
<template #footer><el-button size="small" @click="emit('close')">取消</el-button><el-button size="small" type="primary" :loading="busy" :disabled="!draft.name.trim() || !draft.plannedStartAt || !draft.plannedEndAt" @click="save">创建</el-button></template> <template #footer><el-button size="small" @click="emit('close')">取消</el-button><el-button size="small" type="primary" :loading="busy" :disabled="!draft.name.trim() || !draft.plannedStartAt || !draft.plannedEndAt || draft.nodeType !== 'PURCHASE' && !draft.ownerId" @click="save">创建</el-button></template>
</el-dialog> </el-dialog>
</template> </template>
<script setup lang="ts"> <script setup lang="ts">
@ -18,21 +19,22 @@ import { onBeforeUnmount, reactive, ref, watch } from 'vue'
import type { Member, Stage, StageNodeType } from '../../../types' import type { Member, Stage, StageNodeType } from '../../../types'
import { api, errorText } from '../../../api' import { api, errorText } from '../../../api'
import TimeField from '../../../shared/components/TimeField.vue' import TimeField from '../../../shared/components/TimeField.vue'
import PurchaseBatchPicker from './PurchaseBatchPicker.vue'
import { stageNodeTypeLabel, WORK_STAGE_NODE_TYPES } from '../../../shared/constants/stageNodeTypes' import { stageNodeTypeLabel, WORK_STAGE_NODE_TYPES } from '../../../shared/constants/stageNodeTypes'
const props = defineProps<{ visible: boolean; projectId: number; iterationId?: number; parent?: Stage | null; nodeType?: StageNodeType; members: Member[] }>() const props = defineProps<{ visible: boolean; projectId: number; iterationId?: number; parent?: Stage | null; nodeType?: StageNodeType; members: Member[] }>()
const emit = defineEmits<{ close: []; created: [id: number] }>() const emit = defineEmits<{ close: []; created: [id: number] }>()
const busy = ref(false), failure = ref('') const busy = ref(false), failure = ref('')
const draft = reactive({ name: '', description: '', nodeType: 'REQUIREMENT' as StageNodeType, ownerId: null as number | null, plannedStartAt: null as string | null, plannedEndAt: null as string | null }) const draft = reactive({ name: '', description: '', nodeType: 'REQUIREMENT' as StageNodeType, ownerId: null as number | null, plannedStartAt: null as string | null, plannedEndAt: null as string | null, purchaseBatchIds: [] as number[] })
let generation = 0 let generation = 0
/** 每次打开从素材分类重置草稿;组内快捷创建只提供工作分类,不继承其他迭代的输入。 */ /** 每次打开从素材分类重置草稿;组内快捷创建只提供工作分类,不继承其他迭代的输入。 */
watch(() => props.visible, visible => { generation++; if (visible) { Object.assign(draft, { name: '', description: '', nodeType: props.nodeType || 'REQUIREMENT', ownerId: null, plannedStartAt: null, plannedEndAt: null }); failure.value = '' } }) watch(() => props.visible, visible => { generation++; if (visible) { Object.assign(draft, { name: '', description: '', nodeType: props.nodeType || 'REQUIREMENT', ownerId: null, plannedStartAt: null, plannedEndAt: null, purchaseBatchIds: [] }); failure.value = '' } })
/** 离开项目或迭代后不再处理旧创建请求的界面回调,服务端事务结果仍由后续同步读取。 */ /** 离开项目或迭代后不再处理旧创建请求的界面回调,服务端事务结果仍由后续同步读取。 */
onBeforeUnmount(() => { generation++ }) onBeforeUnmount(() => { generation++ })
/** 固定分类与整日计划在同一事务创建;结构类型由分类派生,失败保留草稿供修正日期等输入。 */ /** 固定分类与整日计划在同一事务创建;结构类型由分类派生,失败保留草稿供修正日期等输入。 */
async function save() { async function save() {
if (busy.value || !draft.name.trim() || !draft.plannedStartAt || !draft.plannedEndAt) return if (busy.value || !draft.name.trim() || !draft.plannedStartAt || !draft.plannedEndAt) return
const request = generation; busy.value = true; failure.value = '' const request = generation; busy.value = true; failure.value = ''
try { const id = await api.createStage(props.projectId, { ...draft, stageKind: draft.nodeType === 'GROUP' ? 'GROUP' : 'WORK', name: draft.name.trim(), sortOrder: 0, parentStageId: props.parent?.id ?? null }, props.iterationId); if (request === generation) emit('created', id) } try { const id = await api.createStage(props.projectId, { ...draft, purchaseBatchIds: draft.nodeType === 'PURCHASE' ? draft.purchaseBatchIds : undefined, stageKind: draft.nodeType === 'GROUP' ? 'GROUP' : 'WORK', name: draft.name.trim(), sortOrder: 0, parentStageId: props.parent?.id ?? null }, props.iterationId); if (request === generation) emit('created', id) }
catch (error) { if (request === generation) failure.value = errorText(error) } finally { busy.value = false } catch (error) { if (request === generation) failure.value = errorText(error) } finally { busy.value = false }
} }
</script> </script>

View File

@ -0,0 +1,37 @@
<template>
<div v-if="snapshot" class="delivery-snapshot">
<p v-if="showNote && snapshot.note" class="note">{{ snapshot.note }}</p>
<div v-if="snapshot.purchase" class="purchase-progress">
<div class="progress-heading"><strong>本项目验收进度</strong><span>{{ snapshot.purchase.completedLines }}/{{ snapshot.purchase.effectiveLines }} 条已齐备 · {{ snapshot.purchase.progress }}%</span></div>
<el-progress :percentage="Number(snapshot.purchase.progress)" :stroke-width="6" :status="snapshot.purchase.complete ? 'success' : undefined" />
<el-table :data="snapshot.purchase.batches" size="small" row-key="batchId" empty-text="尚未绑定采购批次">
<el-table-column type="expand" width="34"><template #default="{ row }"><el-table :data="row.lines" size="small" max-height="280" class="line-table"><el-table-column prop="name" label="本项目明细" min-width="160" show-overflow-tooltip /><el-table-column prop="quantity" label="需求数量" width="90" /><el-table-column prop="acceptedQuantity" label="已验收" width="85" /><el-table-column prop="pendingQuantity" label="待验收" width="85" /><el-table-column prop="notArrivedQuantity" label="未到" width="80" /><el-table-column label="状态" width="105"><template #default="{ row: line }"><el-tag size="small" :type="line.cancelled ? 'info' : line.complete ? 'success' : 'warning'">{{ line.cancelled ? '已取消' : line.complete ? '已齐备' : '未齐备' }}</el-tag><span v-if="line.historical" class="muted">历史</span></template></el-table-column></el-table></template></el-table-column>
<el-table-column label="采购批次" min-width="190" show-overflow-tooltip><template #default="{ row }">{{ row.batchNo || '#' + row.batchId }} · {{ row.batchName || (row.available ? '未命名' : '当前项目无有效明细') }}</template></el-table-column>
<el-table-column label="齐备明细" width="95"><template #default="{ row }">{{ row.completedLines }}/{{ row.effectiveLines }}</template></el-table-column>
<el-table-column label="进度" width="90"><template #default="{ row }">{{ row.progress }}%</template></el-table-column>
</el-table>
<p class="muted">采样时间:{{ sampledAt }}。是否完成按每条有效明细精确核验,显示百分比不代替验收条件。</p>
</div>
<div v-if="snapshot.attachments.length" class="files"><div v-for="file in snapshot.attachments" :key="file.id" class="file"><el-link :title="file.name" @click="download(file)">{{ file.name }}</el-link><span class="muted">{{ (file.size / 1024).toFixed(1) }} KB</span><slot name="file-action" :file="file" /></div></div>
<el-table v-if="showItems && snapshot.items.length" :data="snapshot.items" size="small" max-height="240"><el-table-column prop="title" label="当时的工作项" min-width="190" /><el-table-column label="当时状态" width="100"><template #default="{ row }">{{ statusNames[row.status as Lifecycle] || row.status }}</template></el-table-column></el-table>
<el-alert v-if="failure" :title="failure" type="error" :closable="false" />
</div>
<p v-else class="muted">该历史轮次未留存完整交付快照。</p>
</template>
<script setup lang="ts">
import { computed, ref } from 'vue'
import { downloadStageAttachment, errorText } from '../../../api'
import { statusNames } from '../../../shared/constants/labels'
import type { Lifecycle, StageDeliveryAttachment, StageDeliverySnapshot } from '../../../types'
const props = withDefaults(defineProps<{ snapshot: StageDeliverySnapshot | null; projectId: number; iterationId: number; showItems?: boolean; showNote?: boolean }>(), { showItems: true, showNote: true })
const failure = ref('')
const sampledAt = computed(() => props.snapshot?.purchase ? new Date(props.snapshot.purchase.sampledAt / 1000).toLocaleString('zh-CN', { timeZone: 'Asia/Shanghai', hour12: false }) : '')
/** 下载必须使用快照内精确阶段和版本,不以当前版本替代历史附件归属。 */
async function download(file: StageDeliveryAttachment) {
if (!props.snapshot) return
failure.value = ''
try { await downloadStageAttachment(props.projectId, props.iterationId, props.snapshot.stageId, file.revisionId, file.id, file.name) }
catch (error) { failure.value = errorText(error) }
}
</script>
<style scoped>.note{white-space:pre-wrap;overflow-wrap:anywhere;line-height:1.7}.progress-heading,.file{display:flex;align-items:center;gap:8px;flex-wrap:wrap}.progress-heading{justify-content:space-between;font-size:12px;margin:8px 0}.muted{color:var(--el-text-color-secondary);font-size:12px;line-height:1.6}.files{margin:8px 0}.file{padding:6px 0;border-bottom:1px solid var(--el-border-color-lighter)}.file :deep([class~="el-link"]){min-width:0;overflow-wrap:anywhere;flex:1;justify-content:flex-start}.line-table{width:calc(100% - 24px);margin:4px 12px}.purchase-progress{margin:8px 0}</style>

View File

@ -1,14 +1,15 @@
<template> <template>
<el-dialog :close-on-click-modal="false" :model-value="visible" title="项目阶段" width="min(1100px, 96vw)" append-to-body @close="emit('close')"> <el-dialog :close-on-click-modal="false" :model-value="visible" title="项目阶段" width="min(1100px, 96vw)" append-to-body @close="emit('close')">
<div class="stage-manager-content"> <div class="stage-manager-content">
<el-alert title="从左侧节点库拖入阶段并手工连线确定执行顺序;前置阶段全部工作项完成或关闭后,下游工作项才可开始。含工作项的阶段须先调整归属再删除。" type="info" :closable="false" /> <el-alert title="从左侧节点库拖入阶段并连线确定顺序;交付齐备后须经阶段创建人审批,才放行后续。阶段组聚合子阶段结果;采购按批次验收人工确认。" type="info" :closable="false" />
<el-button v-if="iterationId && view" size="small" class="structure-button" @click="structureOpen = true">调整阶段层级与连线</el-button> <el-button v-if="iterationId && view" size="small" class="structure-button" @click="structureOpen = true">调整阶段层级与连线</el-button>
<el-table :data="stages" size="small" table-layout="fixed" max-height="min(55vh, 520px)" class="stage-table"> <el-table :data="stages" size="small" table-layout="fixed" max-height="min(55vh, 520px)" class="stage-table">
<el-table-column label="阶段" min-width="245"><template #default="{ row }"><div class="stage-name"><el-tag size="small" type="info">{{ stageNodeTypeLabel(row) }}</el-tag><span :title="row.stagePath || row.name">{{ row.stagePath || row.name }}</span></div></template></el-table-column> <el-table-column label="阶段" min-width="245"><template #default="{ row }"><div class="stage-name"><el-tag size="small" type="info">{{ stageNodeTypeLabel(row) }}</el-tag><span :title="row.stagePath || row.name">{{ row.stagePath || row.name }}</span></div></template></el-table-column>
<el-table-column label="负责人" width="100" show-overflow-tooltip><template #default="{ row }">{{ row.ownerName || '未分配' }}</template></el-table-column> <el-table-column label="负责人" width="100" show-overflow-tooltip><template #default="{ row }">{{ row.ownerName || '未分配' }}</template></el-table-column>
<el-table-column label="发起人" width="100" show-overflow-tooltip><template #default="{ row }">{{ row.creatorName || '#' + row.creatorId }}</template></el-table-column>
<el-table-column label="工作项" width="70"><template #default="{ row }">{{ row.counts.total }}</template></el-table-column><el-table-column label="完成" width="80"><template #default="{ row }">{{ row.complete ? '已完成' : '未完成' }}</template></el-table-column> <el-table-column label="工作项" width="70"><template #default="{ row }">{{ row.counts.total }}</template></el-table-column><el-table-column label="完成" width="80"><template #default="{ row }">{{ row.complete ? '已完成' : '未完成' }}</template></el-table-column>
<el-table-column label="描述" prop="description" min-width="200" show-overflow-tooltip /> <el-table-column label="描述" prop="description" min-width="200" show-overflow-tooltip />
<el-table-column label="操作" width="126" fixed="right" class-name="business-operation-cell"><template #default="{ row }"><div class="stage-operations"><el-button size="small" link type="primary" @click="open(row)">编辑</el-button><el-tooltip :content="row.childStageCount ? '请先移出或删除组内子阶段' : '请先移动阶段中的工作项'" :disabled="!row.counts.total && !row.childStageCount"><span><el-button size="small" link type="danger" :disabled="!!row.counts.total || !!row.childStageCount || busy" @click="remove(row)">删除</el-button></span></el-tooltip></div></template></el-table-column> <el-table-column label="操作" width="126" fixed="right" class-name="business-operation-cell"><template #default="{ row }"><div class="stage-operations"><el-button size="small" link type="primary" :disabled="row.approvalStatus === 'PENDING' || ['COMPLETED', 'LEGACY_PASSED'].includes(row.executionStatus || '')" @click="open(row)">编辑</el-button><el-tooltip :content="row.childStageCount ? '请先移出或删除组内子阶段' : row.deliveryAttachmentCount ? '请先移除本轮交付附件' : row.purchaseBatchCount ? '请先清空采购批次范围' : '请先移动阶段中的工作项'" :disabled="!row.counts.total && !row.childStageCount && !row.deliveryAttachmentCount && !row.purchaseBatchCount"><span><el-button size="small" link type="danger" :disabled="!!row.counts.total || !!row.childStageCount || !!row.deliveryAttachmentCount || !!row.purchaseBatchCount || busy" @click="remove(row)">删除</el-button></span></el-tooltip></div></template></el-table-column>
</el-table> </el-table>
<el-alert v-if="failure" type="error" :title="failure" :closable="false" class="failure" /> <el-alert v-if="failure" type="error" :title="failure" :closable="false" class="failure" />
</div> </div>
@ -16,11 +17,13 @@
<el-form label-position="top" size="small"> <el-form label-position="top" size="small">
<el-form-item v-if="editing" label="节点类型(不可修改)"><el-tag size="small" type="info">{{ stageNodeTypeLabel(editing) }}</el-tag></el-form-item> <el-form-item v-if="editing" label="节点类型(不可修改)"><el-tag size="small" type="info">{{ stageNodeTypeLabel(editing) }}</el-tag></el-form-item>
<el-form-item label="阶段名称" required><el-input v-model="draft.name" maxlength="120" /></el-form-item> <el-form-item label="阶段名称" required><el-input v-model="draft.name" maxlength="120" /></el-form-item>
<el-form-item label="阶段负责人"><el-select v-model="draft.ownerId" clearable placeholder="未分配"><el-option v-for="member in members" :key="member.userId" :value="member.userId" :label="member.name" /></el-select></el-form-item> <el-form-item label="发起人(阶段创建人)"><span>{{ editing?.creatorName || '#' + editing?.creatorId }}</span></el-form-item>
<el-form-item label="阶段负责人" :required="editing?.nodeType !== 'PURCHASE'"><el-select v-model="draft.ownerId" clearable placeholder="未分配"><el-option v-for="member in members" :key="member.userId" :value="member.userId" :label="member.name" /></el-select></el-form-item>
<el-form-item v-if="editing?.nodeType === 'PURCHASE'" label="采购批次"><PurchaseBatchPicker v-model="purchaseIds" :project-id="projectId" :iteration-id="iterationId" :selected="purchaseBatches" :disabled="busy || !purchaseLoaded" /></el-form-item>
<el-form-item label="阶段描述"><el-input v-model="draft.description" type="textarea" :rows="3" maxlength="10000" placeholder="说明本阶段需要完成的事项" /></el-form-item> <el-form-item label="阶段描述"><el-input v-model="draft.description" type="textarea" :rows="3" maxlength="10000" placeholder="说明本阶段需要完成的事项" /></el-form-item>
</el-form> </el-form>
<el-alert v-if="editorFailure" type="error" :title="editorFailure" :closable="false" class="failure" /> <el-alert v-if="editorFailure" type="error" :title="editorFailure" :closable="false" class="failure" />
<template #footer><el-button @click="editorOpen = false">取消</el-button><el-button type="primary" :loading="busy" :disabled="!draft.name.trim()" @click="save">保存</el-button></template> <template #footer><el-button size="small" @click="editorOpen = false">取消</el-button><el-button size="small" type="primary" :loading="busy" :disabled="!draft.name.trim() || !purchaseLoaded || editing?.nodeType !== 'PURCHASE' && !draft.ownerId" @click="save">保存</el-button></template>
</el-dialog> </el-dialog>
</el-dialog> </el-dialog>
<StageStructureDialog v-if="view && iterationId" :visible="structureOpen" :project-id="projectId" :iteration-id="iterationId" :view="view" @close="structureOpen = false" @changed="emit('changed')" /> <StageStructureDialog v-if="view && iterationId" :visible="structureOpen" :project-id="projectId" :iteration-id="iterationId" :view="view" @close="structureOpen = false" @changed="emit('changed')" />
@ -30,18 +33,27 @@ import { reactive, ref, watch } from 'vue'
import { ElMessageBox } from 'element-plus' import { ElMessageBox } from 'element-plus'
import { api, errorText } from '../../../api' import { api, errorText } from '../../../api'
import StageStructureDialog from './StageStructureDialog.vue' import StageStructureDialog from './StageStructureDialog.vue'
import type { Stage, StageInput, Member, FlowView } from '../../../types' import PurchaseBatchPicker from './PurchaseBatchPicker.vue'
import type { Stage, StageInput, Member, FlowView, PurchaseBatchProgress } from '../../../types'
import { stageNodeTypeLabel } from '../../../shared/constants/stageNodeTypes' import { stageNodeTypeLabel } from '../../../shared/constants/stageNodeTypes'
const props = defineProps<{ visible: boolean; projectId: number; iterationId?: number; stages: Stage[]; members: Member[]; view?: FlowView }>() const props = defineProps<{ visible: boolean; projectId: number; iterationId?: number; stages: Stage[]; members: Member[]; view?: FlowView }>()
const emit = defineEmits<{ close: []; changed: [] }>() const emit = defineEmits<{ close: []; changed: [] }>()
const structureOpen = ref(false) const structureOpen = ref(false)
const editing = ref<Stage | null>(null), editorOpen = ref(false), busy = ref(false), failure = ref(''), editorFailure = ref('') const editing = ref<Stage | null>(null), editorOpen = ref(false), busy = ref(false), failure = ref(''), editorFailure = ref('')
const draft = reactive<StageInput>({ name: '', sortOrder: 0, ownerId: null, description: '' }) const draft = reactive<StageInput>({ name: '', sortOrder: 0, ownerId: null, description: '' })
const purchaseIds = ref<number[]>([]), purchaseBatches = ref<PurchaseBatchProgress[]>([]), purchaseLoaded = ref(true)
watch(() => props.visible, visible => { if (!visible) { editorOpen.value = false; structureOpen.value = false } failure.value = '' }) watch(() => props.visible, visible => { if (!visible) { editorOpen.value = false; structureOpen.value = false } failure.value = '' })
/** 类型仅作只读展示;编辑草稿保留原分类,改名或说明不会把既有阶段转换为其他类型。 */ /** 固定类型和创建人只读;采购范围加载失败时禁止保存,避免空草稿意外清空既有批次。 */
function open(stage: Stage) { editing.value = stage; Object.assign(draft, { name: stage.name, sortOrder: stage.sortOrder, ownerId: stage.ownerId ?? null, description: stage.description || '', stageKind: stage.stageKind || 'WORK', nodeType: stage.nodeType, version: stage.version }); editorFailure.value = ''; editorOpen.value = true } async function open(stage: Stage) {
editing.value = stage; Object.assign(draft, { name: stage.name, sortOrder: stage.sortOrder, ownerId: stage.ownerId ?? null, description: stage.description || '', stageKind: stage.stageKind || 'WORK', nodeType: stage.nodeType, version: stage.version }); editorFailure.value = ''; editorOpen.value = true
purchaseIds.value = []; purchaseBatches.value = []; purchaseLoaded.value = stage.nodeType !== 'PURCHASE'
if (stage.nodeType === 'PURCHASE' && props.iterationId) {
try { const result = await api.stageCompletion(props.projectId, props.iterationId, stage.id); if (editing.value?.id === stage.id && editorOpen.value) { purchaseBatches.value = result.delivery?.purchase?.batches || []; purchaseIds.value = purchaseBatches.value.map(row => row.batchId); purchaseLoaded.value = true } }
catch (error) { if (editing.value?.id === stage.id) editorFailure.value = errorText(error) }
}
}
/** 保存经经理鉴权与阶段版本校验的元数据,失败保留草稿。 */ /** 保存经经理鉴权与阶段版本校验的元数据,失败保留草稿。 */
async function save() { if (!editing.value) return; busy.value = true; editorFailure.value = ''; try { await api.editStage(props.projectId, editing.value.id, { ...draft }, props.iterationId); editorOpen.value = false; emit('changed') } catch (error) { editorFailure.value = errorText(error) } finally { busy.value = false } } async function save() { if (!editing.value) return; busy.value = true; editorFailure.value = ''; try { await api.editStage(props.projectId, editing.value.id, { ...draft, purchaseBatchIds: editing.value.nodeType === 'PURCHASE' ? purchaseIds.value : undefined }, props.iterationId); editorOpen.value = false; emit('changed') } catch (error) { editorFailure.value = errorText(error) } finally { busy.value = false } }
/** 经产品内确认软删除空阶段,后端仍在项目锁内重查是否为空。 */ /** 经产品内确认软删除空阶段,后端仍在项目锁内重查是否为空。 */
async function remove(stage: Stage) { try { await ElMessageBox.confirm('删除这个空阶段?历史数据将保留。', '删除阶段', { type: 'warning', closeOnClickModal: false }) } catch { return } busy.value = true; failure.value = ''; try { await api.removeStage(props.projectId, stage.id, stage.version, props.iterationId); emit('changed') } catch (error) { failure.value = errorText(error) } finally { busy.value = false } } async function remove(stage: Stage) { try { await ElMessageBox.confirm('删除这个空阶段?历史数据将保留。', '删除阶段', { type: 'warning', closeOnClickModal: false }) } catch { return } busy.value = true; failure.value = ''; try { await api.removeStage(props.projectId, stage.id, stage.version, props.iterationId); emit('changed') } catch (error) { failure.value = errorText(error) } finally { busy.value = false } }
</script> </script>

View File

@ -1,15 +1,17 @@
<template> <template>
<el-drawer :close-on-click-modal="false" :model-value="stageId !== null" :title="`${stageName} · 工作项`" size="min(820px, 100%)" append-to-body @close="emit('close')"> <el-drawer :close-on-click-modal="false" :model-value="stageId !== null" :title="`${stageName} · 阶段详情`" size="min(900px, 100%)" append-to-body @close="emit('close')">
<p v-if="stage?.description" class="stage-description">{{ stage.description }}</p> <p v-if="stage?.description" class="stage-description">{{ stage.description }}</p>
<el-tabs v-model="mode"> <el-tabs v-model="mode">
<el-tab-pane :label="`当前版本 · ${stageTotal}`" name="current"> <el-tab-pane :label="`当前版本 · ${stageTotal}`" name="current">
<div class="drawer-intro"><el-tag v-if="stage" size="small">v{{ stage.revisionNo || 1 }} · {{ stageStatusNames[stage.executionStatus || 'NOT_STARTED'] }}</el-tag><span>当前版本共 {{ stageTotal }} 个工作项,包含子任务。</span><el-button v-if="canCreate && (stageId === 0 || stage?.canCreateWorkItem)" size="small" type="primary" @click="emit('create', stageId || null)">新建工作项</el-button></div> <div class="drawer-intro"><el-tag v-if="stage" size="small">v{{ stage.revisionNo || 1 }} · {{ stageStatusNames[stage.executionStatus || 'NOT_STARTED'] }}</el-tag><span>当前版本共 {{ stageTotal }} 个工作项,包含子任务。</span><el-button v-if="canCreate && (stageId === 0 || stage?.canCreateWorkItem)" size="small" type="primary" @click="emit('create', stageId || null)">新建工作项</el-button></div>
<div v-if="stage?.stageKind === 'GROUP'" class="group-overview"><p>阶段组 · 子阶段 {{ stage.completedChildStageCount || 0 }}/{{ stage.childStageCount || 0 }} 已完成;下表按工作项去重汇总。</p><el-button v-for="child in children" :key="child.id" size="small" @click="emit('navigate', child.id)">{{ child.name }} · {{ stageStatusNames[child.executionStatus || 'NOT_STARTED'] }} · {{ child.counts.total }} 项</el-button><el-button v-if="stage.canCreateChildStage && canManage" size="small" type="primary" @click="emit('createChild', stage.id)">新建子阶段</el-button></div> <StageCompletionPanel v-if="stage && iterationId" :project-id="projectId" :iteration-id="iterationId" :stage="stage" :refresh-key="view.graphVersion" @changed="emit('changed')" @editing="emit('editing', $event)" />
<div v-if="stage?.stageKind === 'GROUP'" class="group-overview"><p>阶段组 · 子阶段 {{ stage.completedChildStageCount || 0 }}/{{ stage.childStageCount || 0 }} 已完成;下表按工作项去重汇总。</p><el-button v-for="child in children" :key="child.id" size="small" @click="emit('navigate', child.id)">{{ child.name }} · {{ stageStatusLabel(child) }} · {{ child.counts.total }} 项</el-button><el-button v-if="stage.canCreateChildStage && canManage" size="small" type="primary" @click="emit('createChild', stage.id)">新建子阶段</el-button></div>
<StageSchedulePanel v-if="stage" :project-id="projectId" :iteration-id="iterationId" :stage-id="stage.id" :schedule="stage" :completed="['COMPLETED', 'LEGACY_PASSED'].includes(stage.executionStatus || '')" :can-manage="canManage" @changed="emit('changed')" /> <StageSchedulePanel v-if="stage" :project-id="projectId" :iteration-id="iterationId" :stage-id="stage.id" :schedule="stage" :completed="['COMPLETED', 'LEGACY_PASSED'].includes(stage.executionStatus || '')" :can-manage="canManage" @changed="emit('changed')" />
<div class="drawer-filters"><el-input v-model="keyword" size="small" clearable placeholder="搜索工作项名称" /><el-select v-model="typeFilter" size="small" clearable placeholder="全部类型"><el-option v-for="(name, type) in typeNames" :key="type" :value="type" :label="name" /></el-select><el-select v-model="statusFilter" size="small" clearable placeholder="全部状态"><el-option v-for="(name, status) in statusNames" :key="status" :value="status" :label="name" /></el-select></div> <el-alert v-if="stage?.nodeType === 'PURCHASE'" title="采购阶段通过批次验收进度确认完成,不创建工作项。旧工作项如需迁移请由项目管理者调整归属。" type="info" :closable="false" />
<div v-if="stage?.nodeType !== 'PURCHASE'" class="drawer-filters"><el-input v-model="keyword" size="small" clearable placeholder="搜索工作项名称" /><el-select v-model="typeFilter" size="small" clearable placeholder="全部类型"><el-option v-for="(name, type) in typeNames" :key="type" :value="type" :label="name" /></el-select><el-select v-model="statusFilter" size="small" clearable placeholder="全部状态"><el-option v-for="(name, status) in statusNames" :key="status" :value="status" :label="name" /></el-select></div>
<p class="drawer-count">显示 {{ filteredItems.length }}/{{ iterationId ? currentTotal : currentItems.length }} 个</p> <p class="drawer-count">显示 {{ filteredItems.length }}/{{ iterationId ? currentTotal : currentItems.length }} 个</p>
<el-alert v-if="failure" :title="failure" type="error" :closable="false" /> <el-alert v-if="failure" :title="failure" type="error" :closable="false" />
<el-table v-loading="currentLoading" :data="filteredItems" size="small" max-height="calc(100vh - 290px)" empty-text="当前阶段没有符合条件的工作项"> <el-table v-if="stage?.nodeType !== 'PURCHASE' || filteredItems.length" v-loading="currentLoading" :data="filteredItems" size="small" max-height="calc(100vh - 290px)" empty-text="当前阶段没有符合条件的工作项">
<el-table-column label="工作项" min-width="230"><template #default="{ row }"><el-link @click="emit('open', row.id)">{{ row.parentTaskId ? '↳ ' : '' }}{{ row.title }}</el-link></template></el-table-column> <el-table-column label="工作项" min-width="230"><template #default="{ row }"><el-link @click="emit('open', row.id)">{{ row.parentTaskId ? '↳ ' : '' }}{{ row.title }}</el-link></template></el-table-column>
<el-table-column v-if="stage?.stageKind === 'GROUP'" label="子阶段" min-width="140"><template #default="{ row }">{{ row.stagePath }}</template></el-table-column> <el-table-column v-if="stage?.stageKind === 'GROUP'" label="子阶段" min-width="140"><template #default="{ row }">{{ row.stagePath }}</template></el-table-column>
<el-table-column label="类型" width="75"><template #default="{ row }">{{ typeNames[row.type as ItemType] }}</template></el-table-column> <el-table-column label="类型" width="75"><template #default="{ row }">{{ typeNames[row.type as ItemType] }}</template></el-table-column>
@ -26,6 +28,8 @@
<el-alert v-if="failure" :title="failure" type="error" :closable="false" class="history-message" /> <el-alert v-if="failure" :title="failure" type="error" :closable="false" class="history-message" />
<el-table v-loading="loading" :data="revisions" size="small" class="history-table"><el-table-column label="版本" width="70"><template #default="{ row }">v{{ row.revision_no }}</template></el-table-column><el-table-column label="阶段名称" prop="stage_name_snapshot" /><el-table-column label="开始" width="155"><template #default="{ row }">{{ readable(row.startedAt) }}</template></el-table-column><el-table-column label="状态" width="100" class-name="business-status-cell"><template #default="{ row }">{{ row.supersededAt ? '已被取代' : '当前版本' }}</template></el-table-column><el-table-column label="操作" width="70" class-name="business-operation-cell"><template #default="{ row }"><el-button size="small" link type="primary" @click="openRevision(row)">查看</el-button></template></el-table-column></el-table> <el-table v-loading="loading" :data="revisions" size="small" class="history-table"><el-table-column label="版本" width="70"><template #default="{ row }">v{{ row.revision_no }}</template></el-table-column><el-table-column label="阶段名称" prop="stage_name_snapshot" /><el-table-column label="开始" width="155"><template #default="{ row }">{{ readable(row.startedAt) }}</template></el-table-column><el-table-column label="状态" width="100" class-name="business-status-cell"><template #default="{ row }">{{ row.supersededAt ? '已被取代' : '当前版本' }}</template></el-table-column><el-table-column label="操作" width="70" class-name="business-operation-cell"><template #default="{ row }"><el-button size="small" link type="primary" @click="openRevision(row)">查看</el-button></template></el-table-column></el-table>
<el-pagination v-if="revisionTotal > 20" v-model:current-page="revisionPage" :page-size="20" :total="revisionTotal" layout="prev, pager, next, total" @current-change="reloadRevisions" /> <el-pagination v-if="revisionTotal > 20" v-model:current-page="revisionPage" :page-size="20" :total="revisionTotal" layout="prev, pager, next, total" @current-change="reloadRevisions" />
<StageCompletionPanel v-if="selected && stage && iterationId" :key="selected.revision.id" :project-id="projectId" :iteration-id="iterationId" :stage="stage" :revision-id="selected.revision.id" />
<el-collapse v-if="selected?.childStages?.length && iterationId"><el-collapse-item v-for="child in selected.childStages.filter(value => value.delivery)" :key="child.stageId" :title="`${child.name} · v${child.revisionNo} 当时交付`" :name="child.stageId"><StageDeliverySnapshot :snapshot="child.delivery || null" :project-id="projectId" :iteration-id="iterationId" /></el-collapse-item></el-collapse>
<template v-if="selected"><h3 v-if="selected.childStages?.length">本版本子阶段组合</h3><el-table v-if="selected.childStages?.length" :data="selected.childStages" size="small"><el-table-column label="子阶段" prop="name" /><el-table-column label="版本" width="80"><template #default="{ row }">v{{ row.revisionNo }}</template></el-table-column><el-table-column label="状态" width="100"><template #default="{ row }">{{ stageStatusNames[row.executionStatus as keyof typeof stageStatusNames] }}</template></el-table-column><el-table-column label="工作项" prop="itemCount" width="80" /><el-table-column label="当时预计结束" width="140"><template #default="{ row }">{{ plannedDate(row.plannedEndAt) }}</template></el-table-column></el-table><StageSchedulePanel :project-id="projectId" :iteration-id="iterationId" :stage-id="stageId!" :schedule="selected.revision" :historical="true" :superseded-at="selected.revision.supersededAt" /><h3>v{{ selected.revision.revision_no }} 工作项 · {{ selected.total ?? selected.items.length }} 个</h3><el-table :data="selected.items" size="small" max-height="330" empty-text="此版本没有工作项"><el-table-column label="工作项" min-width="190"><template #default="{ row }"><el-link @click="openHistorical(row.id)">{{ row.parent_task_id ? '↳ ' : '' }}{{ row.title }}</el-link></template></el-table-column><el-table-column label="状态" width="105" class-name="business-status-cell"><template #default="{ row }">{{ statusNames[row.status as Lifecycle] || row.status }}</template></el-table-column><el-table-column label="原预计结束" width="155"><template #default="{ row }">{{ plannedDate(row.plannedEndAt) }}</template></el-table-column><el-table-column label="操作" width="70" class-name="business-operation-cell"><template #default="{ row }"><el-button size="small" link type="primary" @click="openHistorical(row.id)">详情</el-button></template></el-table-column></el-table><el-pagination v-if="(selected.total || 0) > 50" v-model:current-page="detailPage" :page-size="50" :total="selected.total" layout="prev, pager, next, total" @current-change="reloadDetail" /><h3>当时的阶段连线</h3><p v-if="!selected.flowDefinition" class="history-muted">该轮次尚未开始,或迁移前未留存流程定义快照。</p><p v-else-if="!selected.flowDefinition.edges.length" class="history-muted">定义 v{{ selected.flowDefinition.revisionNo }} 没有连线。</p><div v-else class="history-edges"><el-tag v-for="edge in selected.flowDefinition.edges" :key="`${edge.predecessorStageId}-${edge.successorStageId}`" size="small">{{ edge.predecessorName }} → {{ edge.successorName }}</el-tag></div></template> <template v-if="selected"><h3 v-if="selected.childStages?.length">本版本子阶段组合</h3><el-table v-if="selected.childStages?.length" :data="selected.childStages" size="small"><el-table-column label="子阶段" prop="name" /><el-table-column label="版本" width="80"><template #default="{ row }">v{{ row.revisionNo }}</template></el-table-column><el-table-column label="状态" width="100"><template #default="{ row }">{{ stageStatusNames[row.executionStatus as keyof typeof stageStatusNames] }}</template></el-table-column><el-table-column label="工作项" prop="itemCount" width="80" /><el-table-column label="当时预计结束" width="140"><template #default="{ row }">{{ plannedDate(row.plannedEndAt) }}</template></el-table-column></el-table><StageSchedulePanel :project-id="projectId" :iteration-id="iterationId" :stage-id="stageId!" :schedule="selected.revision" :historical="true" :superseded-at="selected.revision.supersededAt" /><h3>v{{ selected.revision.revision_no }} 工作项 · {{ selected.total ?? selected.items.length }} 个</h3><el-table :data="selected.items" size="small" max-height="330" empty-text="此版本没有工作项"><el-table-column label="工作项" min-width="190"><template #default="{ row }"><el-link @click="openHistorical(row.id)">{{ row.parent_task_id ? '↳ ' : '' }}{{ row.title }}</el-link></template></el-table-column><el-table-column label="状态" width="105" class-name="business-status-cell"><template #default="{ row }">{{ statusNames[row.status as Lifecycle] || row.status }}</template></el-table-column><el-table-column label="原预计结束" width="155"><template #default="{ row }">{{ plannedDate(row.plannedEndAt) }}</template></el-table-column><el-table-column label="操作" width="70" class-name="business-operation-cell"><template #default="{ row }"><el-button size="small" link type="primary" @click="openHistorical(row.id)">详情</el-button></template></el-table-column></el-table><el-pagination v-if="(selected.total || 0) > 50" v-model:current-page="detailPage" :page-size="50" :total="selected.total" layout="prev, pager, next, total" @current-change="reloadDetail" /><h3>当时的阶段连线</h3><p v-if="!selected.flowDefinition" class="history-muted">该轮次尚未开始,或迁移前未留存流程定义快照。</p><p v-else-if="!selected.flowDefinition.edges.length" class="history-muted">定义 v{{ selected.flowDefinition.revisionNo }} 没有连线。</p><div v-else class="history-edges"><el-tag v-for="edge in selected.flowDefinition.edges" :key="`${edge.predecessorStageId}-${edge.successorStageId}`" size="small">{{ edge.predecessorName }} → {{ edge.successorName }}</el-tag></div></template>
</el-tab-pane> </el-tab-pane>
</el-tabs> </el-tabs>
@ -40,11 +44,13 @@ import { api, errorText } from '../../../api'
import { localTime, plannedDate } from '../../../shared/utils/time' import { localTime, plannedDate } from '../../../shared/utils/time'
import StageSchedulePanel from '../../schedules/components/StageSchedulePanel.vue' import StageSchedulePanel from '../../schedules/components/StageSchedulePanel.vue'
import StageSnapshotDialog from './StageSnapshotDialog.vue' import StageSnapshotDialog from './StageSnapshotDialog.vue'
import StageCompletionPanel from './StageCompletionPanel.vue'
import StageDeliverySnapshot from './StageDeliverySnapshot.vue'
import type { FlowView, Member, ItemType, Lifecycle, StageRevision, StageRevisionDetail, WorkItem } from '../../../types' import type { FlowView, Member, ItemType, Lifecycle, StageRevision, StageRevisionDetail, WorkItem } from '../../../types'
import { itemStatusLabel, stageStatusNames, statusNames, typeNames } from '../../../shared/constants/labels' import { itemStatusLabel, stageStatusNames, stageStatusLabel, statusNames, typeNames } from '../../../shared/constants/labels'
const props = defineProps<{ projectId: number; iterationId?: number; stageId: number | null; initialTab: 'current' | 'history'; view: FlowView; members: Member[]; canCreate: boolean; canManage?: boolean }>() const props = defineProps<{ projectId: number; iterationId?: number; stageId: number | null; initialTab: 'current' | 'history'; view: FlowView; members: Member[]; canCreate: boolean; canManage?: boolean }>()
const emit = defineEmits<{ close: []; open: [id: number]; create: [stageId: number | null]; changed: []; navigate: [id: number]; createChild: [id: number] }>() const emit = defineEmits<{ close: []; open: [id: number]; create: [stageId: number | null]; changed: []; navigate: [id: number]; createChild: [id: number]; editing: [value: boolean] }>()
const mode = ref<'current' | 'history'>('current'), keyword = ref(''), typeFilter = ref<ItemType | null>(null), statusFilter = ref<Lifecycle | null>(null) const mode = ref<'current' | 'history'>('current'), keyword = ref(''), typeFilter = ref<ItemType | null>(null), statusFilter = ref<Lifecycle | null>(null)
const currentRows = ref<WorkItem[]>([]), currentTotal = ref(0), currentPage = ref(1), currentLoading = ref(false), revisionPage = ref(1), revisionTotal = ref(0), detailPage = ref(1) const currentRows = ref<WorkItem[]>([]), currentTotal = ref(0), currentPage = ref(1), currentLoading = ref(false), revisionPage = ref(1), revisionTotal = ref(0), detailPage = ref(1)
const loading = ref(false), failure = ref(''), revisions = ref<StageRevision[]>([]), selected = ref<StageRevisionDetail | null>(null) const loading = ref(false), failure = ref(''), revisions = ref<StageRevision[]>([]), selected = ref<StageRevisionDetail | null>(null)

View File

@ -7,7 +7,7 @@
<div class="detail-title"><el-tag>{{ typeNames[detail.type] }}</el-tag><h2>{{ detail.title }}</h2></div> <div class="detail-title"><el-tag>{{ typeNames[detail.type] }}</el-tag><h2>{{ detail.title }}</h2></div>
<div class="detail-tags"><el-tag :type="detail.overdue ? 'danger' : 'info'">{{ itemStatusLabel(detail) }}</el-tag><el-tag v-if="detail.overdue" type="info">{{ statusNames[detail.status] }}</el-tag><el-tag v-if="detail.dependencyBlocked && !detail.historical" type="warning">实际前置条件未满足</el-tag><el-tag v-if="!detail.historical" :type="detail.scheduleConstraints.scheduleValidationStatus === 'VALID' ? 'success' : 'info'">{{ scheduleLabel }}</el-tag><el-tag v-if="detail.stageRevisionNo" type="info">阶段 v{{ detail.stageRevisionNo }}</el-tag><el-tag v-if="detail.historical" type="warning">历史只读</el-tag><el-tag type="info">工作项版本 {{ detail.version }}</el-tag></div> <div class="detail-tags"><el-tag :type="detail.overdue ? 'danger' : 'info'">{{ itemStatusLabel(detail) }}</el-tag><el-tag v-if="detail.overdue" type="info">{{ statusNames[detail.status] }}</el-tag><el-tag v-if="detail.dependencyBlocked && !detail.historical" type="warning">实际前置条件未满足</el-tag><el-tag v-if="!detail.historical" :type="detail.scheduleConstraints.scheduleValidationStatus === 'VALID' ? 'success' : 'info'">{{ scheduleLabel }}</el-tag><el-tag v-if="detail.stageRevisionNo" type="info">阶段 v{{ detail.stageRevisionNo }}</el-tag><el-tag v-if="detail.historical" type="warning">历史只读</el-tag><el-tag type="info">工作项版本 {{ detail.version }}</el-tag></div>
<el-alert v-if="detail.historical" type="info" :closable="false" title="该工作项属于已被回退取代的阶段版本;原状态、排期、评论、附件和历史仅供查看。" class="failure" /> <el-alert v-if="detail.historical" type="info" :closable="false" title="该工作项属于已被回退取代的阶段版本;原状态、排期、评论、附件和历史仅供查看。" class="failure" />
<el-alert v-else-if="stageFrozen" type="info" :closable="false" title="当前阶段已完成,工作项已冻结;如需重做,请由项目经理从流程视图回退。" class="failure" /> <el-alert v-else-if="stageFrozen" type="info" :closable="false" :title="currentStage?.approvalStatus === 'PENDING' ? '当前阶段正在审批,交付已冻结;需要修改请负责人先撤回申请,评论仍可讨论。' : '当前阶段已完成,工作项已冻结;如需重做,请由项目经理从流程视图回退。'" class="failure" />
<el-alert v-if="detail.scheduleReviewRequired" type="warning" :closable="false" :title="detail.scheduleReviewClosed ? '本轮未确认排期;参考计划未参与本轮排期和超期统计。' : '上游阶段已回退,参考计划尚未生效;请确认阶段计划后调整工作项排期。'" class="failure" /> <el-alert v-if="detail.scheduleReviewRequired" type="warning" :closable="false" :title="detail.scheduleReviewClosed ? '本轮未确认排期;参考计划未参与本轮排期和超期统计。' : '上游阶段已回退,参考计划尚未生效;请确认阶段计划后调整工作项排期。'" class="failure" />
<p v-if="detail.scheduleReviewRequired" class="muted">参考时间:{{ plannedDate(detail.referencePlannedStartAt || null) }} → {{ plannedDate(detail.referencePlannedEndAt || null) }}</p> <p v-if="detail.scheduleReviewRequired" class="muted">参考时间:{{ plannedDate(detail.referencePlannedStartAt || null) }} → {{ plannedDate(detail.referencePlannedEndAt || null) }}</p>
<el-button v-if="detail.scheduleReviewRequired && !detail.scheduleReviewClosed && writable" size="small" @click="confirmReview">确认保留原排期</el-button> <el-button v-if="detail.scheduleReviewRequired && !detail.scheduleReviewClosed && writable" size="small" @click="confirmReview">确认保留原排期</el-button>
@ -52,14 +52,14 @@
</article> </article>
<el-alert v-if="!detail.historical" type="info" :closable="false" :title="detail.scheduleConstraints.earliestPlannedStartAt ? `最早合法预计开始:${planningLimitDate(detail.scheduleConstraints.earliestPlannedStartAt, 'start', 'min')}` : '暂无参与排期计算的前置结束时间;缺少前置工作项结束时间会阻止保存后续开始时间。'" /> <el-alert v-if="!detail.historical" type="info" :closable="false" :title="detail.scheduleConstraints.earliestPlannedStartAt ? `最早合法预计开始:${planningLimitDate(detail.scheduleConstraints.earliestPlannedStartAt, 'start', 'min')}` : '暂无参与排期计算的前置结束时间;缺少前置工作项结束时间会阻止保存后续开始时间。'" />
</section> </section>
<section><h3>评论</h3><article v-for="comment in detail.comments" :key="comment.id" class="comment"><strong>{{ comment.author }}</strong><p>{{ comment.body }}</p></article><template v-if="writable"><el-input v-model="commentText" type="textarea" :rows="3" placeholder="添加评论" maxlength="10000" /><el-button class="comment-submit" :disabled="!commentText.trim() || busy" @click="comment">发送评论</el-button></template></section> <section><h3>评论</h3><article v-for="comment in detail.comments" :key="comment.id" class="comment"><strong>{{ comment.author }}</strong><p>{{ comment.body }}</p></article><template v-if="canDiscuss"><el-input v-model="commentText" type="textarea" :rows="3" placeholder="添加评论" maxlength="10000" /><el-button size="small" class="comment-submit" :disabled="!commentText.trim() || busy" @click="comment">发送评论</el-button></template></section>
<section><div class="section-heading"><h3>附件</h3><label v-if="writable" class="upload-link">上传附件(最多 10 MiB)<input type="file" :disabled="busy" @change="upload" /></label></div><div v-for="file in detail.attachments" :key="file.id" class="attachment"><el-link class="attachment-name" :title="file.name" @click="download(file.id, file.name)">{{ file.name }}</el-link><div class="attachment-actions"><span>{{ (file.size / 1024).toFixed(1) }} KB</span><el-button v-if="writable && detail.canDeleteAttachments" size="small" link type="danger" :disabled="busy || attachmentConfirmationOpen" @click="removeAttachment(file)">删除</el-button></div></div></section> <section><div class="section-heading"><h3>附件</h3><label v-if="writable" class="upload-link">上传附件(最多 10 MiB)<input type="file" :disabled="busy" @change="upload" /></label></div><div v-for="file in detail.attachments" :key="file.id" class="attachment"><el-link class="attachment-name" :title="file.name" @click="download(file.id, file.name)">{{ file.name }}</el-link><div class="attachment-actions"><span>{{ (file.size / 1024).toFixed(1) }} KB</span><el-button v-if="writable && detail.canDeleteAttachments" size="small" link type="danger" :disabled="busy || attachmentConfirmationOpen" @click="removeAttachment(file)">删除</el-button></div></div></section>
<section><h3>操作历史</h3><div v-for="entry in detail.history" :key="entry.id" class="history"><strong>{{ actionNames[entry.action] || '工作项更新' }}</strong><span>{{ members.find(m => m.userId === entry.createdBy)?.name || `用户 #${entry.createdBy}` }}</span><p>{{ historyText(entry.detail) }}</p><small class="muted">{{ displayTime(entry.createdAt) }}</small></div></section> <section><h3>操作历史</h3><div v-for="entry in detail.history" :key="entry.id" class="history"><strong>{{ actionNames[entry.action] || '工作项更新' }}</strong><span>{{ members.find(m => m.userId === entry.createdBy)?.name || `用户 #${entry.createdBy}` }}</span><p>{{ historyText(entry.detail) }}</p><small class="muted">{{ displayTime(entry.createdAt) }}</small></div></section>
</template> </template>
</div> </div>
</el-drawer> </el-drawer>
<el-dialog :close-on-click-modal="false" v-model="assignmentOpen" title="调整工作项阶段归属" width="480px" append-to-body><el-alert type="info" :closable="false" title="仅项目管理者可移动待开始根任务,子任务同步继承。阶段组不能直接承载工作项;后端复验新门禁、排期及循环依赖。" /><el-select v-model="assignmentStageId" size="small" clearable filterable placeholder="未分配阶段" style="width:100%;margin:14px 0"><el-option v-for="stage in stages.filter(value => value.stageKind !== 'GROUP')" :key="stage.id" :value="stage.id" :label="stage.stagePath || stage.name" /></el-select><el-alert v-if="assignmentFailure" :title="assignmentFailure" type="error" :closable="false" /><template #footer><el-button size="small" @click="assignmentOpen = false">取消</el-button><el-button size="small" type="primary" :loading="busy" @click="saveAssignment">保存</el-button></template></el-dialog> <el-dialog :close-on-click-modal="false" v-model="assignmentOpen" title="调整工作项阶段归属" width="480px" append-to-body><el-alert type="info" :closable="false" title="仅项目管理者可移动待开始根任务,子任务同步继承。阶段组不能直接承载工作项;后端复验新门禁、排期及循环依赖。" /><el-select v-model="assignmentStageId" size="small" clearable filterable placeholder="未分配阶段" style="width:100%;margin:14px 0"><el-option v-for="stage in stages.filter(value => value.stageKind !== 'GROUP' && value.nodeType !== 'PURCHASE')" :key="stage.id" :value="stage.id" :label="stage.stagePath || stage.name" /></el-select><el-alert v-if="assignmentFailure" :title="assignmentFailure" type="error" :closable="false" /><template #footer><el-button size="small" @click="assignmentOpen = false">取消</el-button><el-button size="small" type="primary" :loading="busy" @click="saveAssignment">保存</el-button></template></el-dialog>
<ItemScheduleDialog :item-id="scheduleOpen && writable ? id : null" @close="scheduleOpen = false" @saved="scheduleSaved" /> <ItemScheduleDialog :item-id="scheduleOpen && writable ? id : null" @close="scheduleOpen = false" @saved="scheduleSaved" />
<el-dialog :close-on-click-modal="false" v-model="depOpen" :title="editingDependency ? '编辑前置条件' : '添加前置条件'" width="600px" append-to-body> <el-dialog :close-on-click-modal="false" v-model="depOpen" :title="editingDependency ? '编辑前置条件' : '添加前置条件'" width="600px" append-to-body>
<el-form label-position="top"> <el-form label-position="top">
@ -92,8 +92,10 @@ const scheduleLabel = computed(() => detail.value?.scheduleConstraints.scheduleV
const blockedText = computed(() => detail.value?.blockedReasons.map(r => r.stageId ? `${r.sourceName}:${r.message}` : r.message || `${r.sourceName}:当前 ${lifecycleLabels[r.currentStatus || ''] || r.currentStatus},要求 ${lifecycleLabels[String(r.expectedStatus)] || r.expectedStatus}`).join(';') || '当前无法开始') const blockedText = computed(() => detail.value?.blockedReasons.map(r => r.stageId ? `${r.sourceName}:${r.message}` : r.message || `${r.sourceName}:当前 ${lifecycleLabels[r.currentStatus || ''] || r.currentStatus},要求 ${lifecycleLabels[String(r.expectedStatus)] || r.expectedStatus}`).join(';') || '当前无法开始')
// 阶段边只展示服务端完成摘要,不在前端重新判定实际 canStart。 // 阶段边只展示服务端完成摘要,不在前端重新判定实际 canStart。
const stagePredecessors = computed(() => props.stageEdges.filter(edge => edge.successorStageId === detail.value?.stageId).map(edge => props.stages.find(stage => stage.id === edge.predecessorStageId)).filter((stage): stage is Stage => !!stage)) const stagePredecessors = computed(() => props.stageEdges.filter(edge => edge.successorStageId === detail.value?.stageId).map(edge => props.stages.find(stage => stage.id === edge.predecessorStageId)).filter((stage): stage is Stage => !!stage))
const stageFrozen = computed(() => ['COMPLETED', 'LEGACY_PASSED'].includes(props.stages.find(stage => stage.id === detail.value?.stageId)?.executionStatus || '')) const currentStage = computed(() => props.stages.find(stage => stage.id === detail.value?.stageId))
const stageFrozen = computed(() => currentStage.value?.approvalStatus === 'PENDING' || ['COMPLETED', 'LEGACY_PASSED'].includes(currentStage.value?.executionStatus || ''))
const writable = computed(() => props.canWrite && !detail.value?.iterationReadOnly && !detail.value?.historical && !stageFrozen.value) const writable = computed(() => props.canWrite && !detail.value?.iterationReadOnly && !detail.value?.historical && !stageFrozen.value)
const canDiscuss = computed(() => props.canWrite && !detail.value?.iterationReadOnly && !detail.value?.historical && !['COMPLETED', 'LEGACY_PASSED'].includes(currentStage.value?.executionStatus || ''))
const editableDependencies = computed(() => writable.value && detail.value?.status === 'READY') const editableDependencies = computed(() => writable.value && detail.value?.status === 'READY')
const loadedChildren = ref<WorkItem[]>([]) const loadedChildren = ref<WorkItem[]>([])
const childItems = computed(() => detail.value?.historical ? detail.value.historicalChildren || [] : loadedChildren.value) const childItems = computed(() => detail.value?.historical ? detail.value.historicalChildren || [] : loadedChildren.value)
@ -127,8 +129,8 @@ async function load(background = false) {
/** 实际执行和审计发生时间保留北京时间及微秒,预计日期使用独立的日期展示函数。 */ /** 实际执行和审计发生时间保留北京时间及微秒,预计日期使用独立的日期展示函数。 */
function displayTime(value: string | null) { return value ? localTime(value, 'Asia/Shanghai').replace('T', ' ') : '未设置' } function displayTime(value: string | null) { return value ? localTime(value, 'Asia/Shanghai').replace('T', ' ') : '未设置' }
/** 执行业务动作并刷新受影响工作项;被拒绝时保留具体原因。 */ /** 执行业务动作并刷新受影响工作项;被拒绝时保留具体原因。 */
async function action(commit: () => Promise<unknown>) { async function action(commit: () => Promise<unknown>, discussion = false) {
if (!writable.value) return if (!(discussion ? canDiscuss.value : writable.value)) return
busy.value = true; failure.value = '' busy.value = true; failure.value = ''
try { await commit(); emit('changed'); await load() } catch (error) { failure.value = errorText(error) } finally { busy.value = false } try { await commit(); emit('changed'); await load() } catch (error) { failure.value = errorText(error) } finally { busy.value = false }
} }
@ -147,7 +149,7 @@ async function remove() {
const item = detail.value; await action(async () => { await api.remove(item.id, item.version); emit('close') }) const item = detail.value; await action(async () => { await api.remove(item.id, item.version); emit('close') })
} }
/** 评论成功才清空输入,失败时保留草稿。 */ /** 评论成功才清空输入,失败时保留草稿。 */
async function comment() { if (detail.value) await action(async () => { await api.comment(detail.value!.id, commentText.value); commentText.value = '' }) } async function comment() { if (detail.value) await action(async () => { await api.comment(detail.value!.id, commentText.value); commentText.value = '' }, true) }
/** 文件大小先提示,服务端仍独立验证身份、权限与大小。 */ /** 文件大小先提示,服务端仍独立验证身份、权限与大小。 */
async function upload(event: Event) { const input = event.target as HTMLInputElement, file = input.files?.[0]; if (!file || !detail.value) return; if (file.size > 10 * 1024 * 1024) { ElMessage.error('附件不能超过 10 MiB'); return } await action(() => api.upload(detail.value!.id, file)); input.value = '' } async function upload(event: Event) { const input = event.target as HTMLInputElement, file = input.files?.[0]; if (!file || !detail.value) return; if (file.size > 10 * 1024 * 1024) { ElMessage.error('附件不能超过 10 MiB'); return } await action(() => api.upload(detail.value!.id, file)); input.value = '' }
/** 下载失败展示权限或连接提示,不提供绕过鉴权的静态 URL。 */ /** 下载失败展示权限或连接提示,不提供绕过鉴权的静态 URL。 */

View File

@ -39,7 +39,7 @@ const busy = ref(false), failure = ref(''), invalidStart = ref(false), invalidEn
const initialConstraints = ref<Schedule | null>(null), constraintFailure = ref('') const initialConstraints = ref<Schedule | null>(null), constraintFailure = ref('')
const constraints = computed(() => props.item?.scheduleConstraints || initialConstraints.value) const constraints = computed(() => props.item?.scheduleConstraints || initialConstraints.value)
/** 阶段组只能容纳子阶段,工作项创建不得将其作为可选归属。 */ /** 阶段组只能容纳子阶段,工作项创建不得将其作为可选归属。 */
const workStages = computed(() => props.stages.filter(stage => stage.stageKind !== 'GROUP')) const workStages = computed(() => props.stages.filter(stage => stage.stageKind !== 'GROUP' && stage.nodeType !== 'PURCHASE'))
let constraintSequence = 0, constraintTimer: ReturnType<typeof setTimeout> | undefined let constraintSequence = 0, constraintTimer: ReturnType<typeof setTimeout> | undefined
let generation = 0, mounted = true let generation = 0, mounted = true
/** 子任务继承父阶段,编辑保留原归属;每次打开清空旧草稿,并要求重新明确选择邮件通知。 */ /** 子任务继承父阶段,编辑保留原归属;每次打开清空旧草稿,并要求重新明确选择邮件通知。 */

View File

@ -1,9 +1,20 @@
import type { IterationStatus, StageExecutionStatus, Lifecycle, ItemType, WorkItem } from '../../types' import type { IterationStatus, StageExecutionStatus, StageApprovalStatus, Stage, Lifecycle, ItemType, WorkItem } from '../../types'
export const iterationStatusNames: Record<IterationStatus, string> = { PLANNED: '计划中', ACTIVE: '执行中', FINISHED: '已结束', CANCELLED: '已取消' } export const iterationStatusNames: Record<IterationStatus, string> = { PLANNED: '计划中', ACTIVE: '执行中', FINISHED: '已结束', CANCELLED: '已取消' }
export const stageStatusNames: Record<StageExecutionStatus, string> = { NOT_STARTED: '未执行', IN_PROGRESS: '正在执行', COMPLETED: '已完成', LEGACY_PASSED: '历史沿用' } export const stageStatusNames: Record<StageExecutionStatus, string> = { NOT_STARTED: '未执行', IN_PROGRESS: '正在执行', COMPLETED: '已完成', LEGACY_PASSED: '历史沿用' }
export const approvalStatusNames: Record<StageApprovalStatus, string> = { NONE: '未申请', PENDING: '待审批', APPROVED: '已通过', REJECTED: '待整改', WITHDRAWN: '已撤回', INVALIDATED: '已失效', SUPERSEDED: '换版失效', TERMINATED: '已终止' }
/** 审批与执行分开存储,统一组合展示;齐备不冒充完成,已通过历史优先于源数据波动。 */
export function stageStatusLabel(stage: Pick<Stage, 'executionStatus' | 'approvalStatus' | 'nodeType' | 'deliveryReady'>): string {
if (stage.executionStatus === 'COMPLETED' || stage.executionStatus === 'LEGACY_PASSED') return stageStatusNames[stage.executionStatus]
if (stage.approvalStatus === 'PENDING') return '待审批'
if (stage.approvalStatus === 'REJECTED') return stage.nodeType === 'PURCHASE' ? '待处理' : '待整改'
if (stage.deliveryReady) return stage.nodeType === 'PURCHASE' ? '待审核完成' : '可申请完成'
return stageStatusNames[stage.executionStatus || 'NOT_STARTED']
}
export const statusNames: Record<Lifecycle, string> = { READY: '待开始', IN_PROGRESS: '进行中', COMPLETED: '已完成', CANCELLED: '已取消', CLOSED: '关闭' } export const statusNames: Record<Lifecycle, string> = { READY: '待开始', IN_PROGRESS: '进行中', COMPLETED: '已完成', CANCELLED: '已取消', CLOSED: '关闭' }
/** 展示状态仅取服务端超期判断,仍保留基础生命周期用于动作与看板分组。 */ /** 展示状态仅取服务端超期判断,仍保留基础生命周期用于动作与看板分组。 */
@ -15,4 +26,6 @@ export const typeNames: Record<ItemType, string> = { TASK: '任务', REQUIREMENT
export const priorityNames: Record<string, string> = { LOW: '低', MEDIUM: '中', HIGH: '高', URGENT: '紧急' } export const priorityNames: Record<string, string> = { LOW: '低', MEDIUM: '中', HIGH: '高', URGENT: '紧急' }
export const actionNames: Record<string, string> = { COLLABORATION_ENABLED: '启用项目协作', CHILD_CREATED: '创建子任务', CHILD_ADDED: '添加子任务', CHILD_REMOVED: '移除子任务', STAGE_CREATED: '创建阶段', STAGE_EDITED: '编辑阶段', STAGE_DELETED: '删除阶段', STAGE_EDGE_CREATED: '连接阶段', STAGE_EDGE_DELETED: '断开阶段', STAGE_STATUS_CHANGED: '阶段状态变化', STAGE_REWORKED: '阶段回退', SCHEDULE_REVIEWED: '排期已复核', ITEM_STAGE_CHANGED: '调整工作项阶段', PROJECT_CREATED: '创建项目', PROJECT_EDITED: '编辑项目', PROJECT_DELETED: '删除项目', PROJECT_CONFIGURED: '项目关联空间变更', MEMBER_REMOVED: '移除成员', MEMBER_CHANGED: '成员变更', ITEM_CREATED: '创建工作项', ITEM_EDITED: '编辑工作项', ITEM_DELETED: '删除工作项', TASK_STARTED: '开始工作项', STATUS_CHANGED: '状态变更', DEPENDENCY_SAVED: '保存前置依赖', DEPENDENCY_REMOVED: '删除前置依赖', SCHEDULE_CHANGED: '排期变更', COMMENT_ADDED: '新增评论', ATTACHMENT_ADDED: '上传附件', ATTACHMENT_DELETED: '删除附件' } export const stageActionNames: Record<string, string> = { STAGE_STARTED: '开始阶段', STAGE_DELIVERY_EDITED: '修改交付说明', STAGE_ATTACHMENT_ADDED: '上传阶段交付附件', STAGE_ATTACHMENT_DELETED: '删除阶段交付附件', STAGE_ATTACHMENT_REUSED: '沿用历史交付附件', STAGE_PURCHASE_SCOPE_CHANGED: '确认采购批次范围', STAGE_COMPLETION_SUBMITTED: '申请阶段完成', STAGE_COMPLETION_APPROVED: '阶段完成审批通过', STAGE_COMPLETION_REJECTED: '阶段完成申请驳回', STAGE_COMPLETION_WITHDRAWN: '撤回阶段完成申请', STAGE_COMPLETION_INVALIDATED: '阶段完成申请失效', STAGE_PURCHASE_READY: '采购阶段待审核完成' }
export const actionNames: Record<string, string> = { ...stageActionNames, COLLABORATION_ENABLED: '启用项目协作', CHILD_CREATED: '创建子任务', CHILD_ADDED: '添加子任务', CHILD_REMOVED: '移除子任务', STAGE_CREATED: '创建阶段', STAGE_EDITED: '编辑阶段', STAGE_DELETED: '删除阶段', STAGE_EDGE_CREATED: '连接阶段', STAGE_EDGE_DELETED: '断开阶段', STAGE_STATUS_CHANGED: '阶段状态变化', STAGE_REWORKED: '阶段回退', SCHEDULE_REVIEWED: '排期已复核', ITEM_STAGE_CHANGED: '调整工作项阶段', PROJECT_CREATED: '创建项目', PROJECT_EDITED: '编辑项目', PROJECT_DELETED: '删除项目', PROJECT_CONFIGURED: '项目关联空间变更', MEMBER_REMOVED: '移除成员', MEMBER_CHANGED: '成员变更', ITEM_CREATED: '创建工作项', ITEM_EDITED: '编辑工作项', ITEM_DELETED: '删除工作项', TASK_STARTED: '开始工作项', STATUS_CHANGED: '状态变更', DEPENDENCY_SAVED: '保存前置依赖', DEPENDENCY_REMOVED: '删除前置依赖', SCHEDULE_CHANGED: '排期变更', COMMENT_ADDED: '新增评论', ATTACHMENT_ADDED: '上传附件', ATTACHMENT_DELETED: '删除附件' }

View File

@ -3,6 +3,7 @@ export type * from './workspace'
export type * from './iteration' export type * from './iteration'
export type * from './work-item' export type * from './work-item'
export type * from './stage' export type * from './stage'
export type * from './stage-completion'
export type * from './flow' export type * from './flow'
export type * from './rework' export type * from './rework'
export type * from './schedule' export type * from './schedule'

View File

@ -51,6 +51,7 @@ export interface IterationAction {
} }
export interface IterationPreview { export interface IterationPreview {
pendingApprovals?: { stageId: number; name: string; revisionId: number }[]
iterationId: number iterationId: number
version: number version: number
graphVersion: number graphVersion: number

View File

@ -0,0 +1,54 @@
import type { Reason } from './common'
export type StageApprovalStatus = 'NONE' | 'PENDING' | 'APPROVED' | 'REJECTED' | 'WITHDRAWN' | 'INVALIDATED' | 'SUPERSEDED' | 'TERMINATED'
export interface StageDeliveryAttachment {
id: number
revisionId: number
name: string
mediaType: string
sha256: string
size: number
creatorId: number
creatorName?: string
createdAt: number
}
export interface PurchaseBatchOption { id: number; batchNo: string; batchName: string | null; lineCount: number }
export interface PurchaseAcceptanceLine {
requestId: number; requestNo: string; name: string; unit: string | null
quantity: number; acceptedQuantity: number; pendingQuantity: number; notArrivedQuantity: number
complete: boolean; cancelled: boolean; historical: boolean | number; progress: number
}
export interface PurchaseBatchProgress {
batchId: number; batchNo: string | null; batchName: string | null; available: boolean
effectiveLines: number; completedLines: number; progress: number; complete: boolean; lines: PurchaseAcceptanceLine[]
}
export interface PurchaseProgress {
sampledAt: number; complete: boolean; progress: number; effectiveLines: number; completedLines: number; batches: PurchaseBatchProgress[]
}
export interface StageDeliverySnapshot {
formatVersion: number; sampledAt: number; stageId: number; revisionId: number; nodeType: string
name: string; creatorId: number; ownerId: number | null; note: string | null; purchaseScopeConfirmed: boolean
items: { id: number; title: string; status: string; version: number }[]
attachments: StageDeliveryAttachment[]
purchase: PurchaseProgress | null
}
export interface StageApproval {
id: number; revision_id: number; submission_no: number; request_source: 'OWNER' | 'PURCHASE_CONFIRM'
submitted_by: number | null; approver_id: number; owner_id: number | null; status: StageApprovalStatus
submitterName: string | null; deciderName: string | null; submittedAt: string; decidedAt: string | null; reason: string | null
}
export interface StageCompletionCapabilities {
deliveryReady: boolean; blockedReasons: Reason[]; stageBlockedReasons: Reason[]
canEditDelivery: boolean; canEditPurchase: boolean; canStart: boolean; canSubmit: boolean; canWithdraw: boolean; canApprove: boolean; canConfirmPurchase: boolean
}
export interface StageCompletion {
revisionId: number; revisionVersion: number; historical: boolean; approvalStatus: StageApprovalStatus
completionSource: string | null; note: string | null; evidenceHash: string | null; sourceChanged: boolean
delivery: StageDeliverySnapshot | null; approvedDelivery: StageDeliverySnapshot | null; approvals: StageApproval[]; capabilities: StageCompletionCapabilities
}
export interface StageCompletionCommand {
revisionId: number; version: number; evidenceHash?: string | null; note?: string; reason?: string
idempotencyKey?: string; sendEmail?: boolean
}

View File

@ -1,5 +1,6 @@
import type { Lifecycle, Reason } from './common' import type { Lifecycle, Reason } from './common'
import type { StageSchedule } from './schedule' import type { StageSchedule } from './schedule'
import type { StageApprovalStatus, StageDeliverySnapshot } from './stage-completion'
export interface StageCounts { export interface StageCounts {
@ -45,6 +46,19 @@ export interface Stage extends StageSummary, Omit<StageSchedule, 'plannedStartAt
sortOrder: number sortOrder: number
ownerId: number | null ownerId: number | null
ownerName: string | null ownerName: string | null
creatorId?: number
creatorName?: string | null
approvalStatus?: StageApprovalStatus
completionSource?: string | null
deliveryReady?: boolean
deliveryAttachmentCount?: number
deliveryEvidenceHash?: string
canSubmitCompletion?: boolean
canEditDelivery?: boolean
canApproveCompletion?: boolean
canConfirmPurchase?: boolean
purchaseProgress?: number | null
purchaseBatchCount?: number
description: string | null description: string | null
version: number version: number
currentRevisionId?: number currentRevisionId?: number
@ -63,6 +77,7 @@ export interface Stage extends StageSummary, Omit<StageSchedule, 'plannedStartAt
} }
export interface StageInput { export interface StageInput {
purchaseBatchIds?: number[]
nodeType?: StageNodeType nodeType?: StageNodeType
stageKind?: 'WORK' | 'GROUP' stageKind?: 'WORK' | 'GROUP'
parentStageId?: number | null parentStageId?: number | null
@ -92,7 +107,7 @@ export interface StageRevision extends StageSchedule {
} }
export interface StageRevisionDetail { export interface StageRevisionDetail {
childStages?: { stageId: number; name: string; revisionId: number; revisionNo: number; executionStatus: StageExecutionStatus; itemCount: number; plannedStartAt: string | null; plannedEndAt: string | null }[] childStages?: { stageId: number; name: string; revisionId: number; revisionNo: number; executionStatus: StageExecutionStatus; itemCount: number; plannedStartAt: string | null; plannedEndAt: string | null; delivery?: StageDeliverySnapshot }[]
frozenSnapshot?: boolean frozenSnapshot?: boolean
total?: number total?: number
revision: StageRevision revision: StageRevision

View File

@ -35,6 +35,8 @@ export interface Condition extends Reason {
} }
export interface WorkItem { export interface WorkItem {
stageApprovalStatus?: import('./stage-completion').StageApprovalStatus
stageReadOnly?: boolean
stageGroupId?: number | null stageGroupId?: number | null
stagePath?: string stagePath?: string
snapshotFrozen?: boolean snapshotFrozen?: boolean

View File

@ -3,9 +3,10 @@
<section v-for="(label, state) in statusNames" :key="state" class="lane" @dragover.prevent @drop.prevent="drop(state)"> <section v-for="(label, state) in statusNames" :key="state" class="lane" @dragover.prevent @drop.prevent="drop(state)">
<header>{{ label }} <span>{{ counts?.[state] ?? items.filter(i => i.status === state).length }}</span></header> <header>{{ label }} <span>{{ counts?.[state] ?? items.filter(i => i.status === state).length }}</span></header>
<div class="lane-content" role="region" :aria-label="label + '工作项'" tabindex="0"> <div class="lane-content" role="region" :aria-label="label + '工作项'" tabindex="0">
<article v-for="item in items.filter(i => i.status === state)" :key="item.id" class="work-card" :draggable="canWrite && !busy.has(item.id)" @dragstart="dragged = item.id" @dragend="dragged = null" @click="emit('open', item.id)"> <article v-for="item in items.filter(i => i.status === state)" :key="item.id" class="work-card" :draggable="canWrite && !item.stageReadOnly && !busy.has(item.id)" @dragstart="dragged = item.id" @dragend="dragged = null" @click="emit('open', item.id)">
<div class="card-meta"><span class="card-id">{{ typeNames[item.type] }} #{{ item.id }}</span><small v-if="item.stageId" class="stage-version" :title="item.stagePath || stages.find(stage => stage.id === item.stageId)?.name">{{ item.stagePath || stages.find(stage => stage.id === item.stageId)?.name || '阶段' }} · v{{ stages.find(stage => stage.id === item.stageId)?.revisionNo || 1 }}</small><el-tag size="small" :type="item.priority === 'URGENT' ? 'danger' : 'info'">{{ priorityNames[item.priority] }}</el-tag></div> <div class="card-meta"><span class="card-id">{{ typeNames[item.type] }} #{{ item.id }}</span><small v-if="item.stageId" class="stage-version" :title="item.stagePath || stages.find(stage => stage.id === item.stageId)?.name">{{ item.stagePath || stages.find(stage => stage.id === item.stageId)?.name || '阶段' }} · v{{ stages.find(stage => stage.id === item.stageId)?.revisionNo || 1 }}</small><el-tag size="small" :type="item.priority === 'URGENT' ? 'danger' : 'info'">{{ priorityNames[item.priority] }}</el-tag></div>
<strong class="card-title" :title="item.title">{{ item.title }}</strong> <strong class="card-title" :title="item.title">{{ item.title }}</strong>
<el-tag v-if="item.stageApprovalStatus === 'PENDING' || item.stageApprovalStatus === 'REJECTED'" size="small" :type="item.stageApprovalStatus === 'PENDING' ? 'warning' : 'danger'">阶段{{ approvalStatusNames[item.stageApprovalStatus] }}</el-tag>
<div v-if="item.parentTaskId" class="card-family" :title="'父任务:' + item.parentTaskTitle">↳ 子任务 · {{ item.parentTaskTitle }}</div><div v-else-if="item.childCount" class="card-family">子任务已结束 {{ item.childTerminalCount }}/{{ item.childCount }}</div> <div v-if="item.parentTaskId" class="card-family" :title="'父任务:' + item.parentTaskTitle">↳ 子任务 · {{ item.parentTaskTitle }}</div><div v-else-if="item.childCount" class="card-family">子任务已结束 {{ item.childTerminalCount }}/{{ item.childCount }}</div>
<div class="card-footer"><div class="card-tags"><el-tag v-if="item.overdue" size="small" type="danger">超期未完成</el-tag><el-tag v-if="item.dependencyBlocked" size="small" type="warning">前置阻塞</el-tag><el-tag v-if="item.scheduleReviewRequired" size="small" type="warning">{{ item.scheduleReviewClosed ? '本轮未确认排期' : '排期待复核' }}</el-tag><el-tag v-if="item.scheduleConstraints.scheduleValidationStatus !== 'VALID'" size="small" type="info">{{ item.scheduleConstraints.scheduleValidationStatus === 'INCOMPLETE' ? '排期未完成' : '排期冲突' }}</el-tag></div><time class="card-deadline" :datetime="item.plannedEndAt || undefined">{{ item.plannedEndAt ? plannedDate(item.plannedEndAt, item.timezone) : '尚未设置预计结束' }}</time></div> <div class="card-footer"><div class="card-tags"><el-tag v-if="item.overdue" size="small" type="danger">超期未完成</el-tag><el-tag v-if="item.dependencyBlocked" size="small" type="warning">前置阻塞</el-tag><el-tag v-if="item.scheduleReviewRequired" size="small" type="warning">{{ item.scheduleReviewClosed ? '本轮未确认排期' : '排期待复核' }}</el-tag><el-tag v-if="item.scheduleConstraints.scheduleValidationStatus !== 'VALID'" size="small" type="info">{{ item.scheduleConstraints.scheduleValidationStatus === 'INCOMPLETE' ? '排期未完成' : '排期冲突' }}</el-tag></div><time class="card-deadline" :datetime="item.plannedEndAt || undefined">{{ item.plannedEndAt ? plannedDate(item.plannedEndAt, item.timezone) : '尚未设置预计结束' }}</time></div>
</article> </article>
@ -19,7 +20,7 @@
import { computed, nextTick, onBeforeUnmount, onMounted, reactive, ref } from 'vue' import { computed, nextTick, onBeforeUnmount, onMounted, reactive, ref } from 'vue'
import { ElMessage } from 'element-plus' import { ElMessage } from 'element-plus'
import type { WorkItem, Lifecycle, Stage } from '../../types' import type { WorkItem, Lifecycle, Stage } from '../../types'
import { statusNames, typeNames, priorityNames } from '../../shared/constants/labels' import { statusNames, typeNames, priorityNames, approvalStatusNames } from '../../shared/constants/labels'
import { plannedDate } from '../../shared/utils/time' import { plannedDate } from '../../shared/utils/time'
import { api, errorText } from '../../api' import { api, errorText } from '../../api'
import { moveCard } from '../../shared/utils/optimistic' import { moveCard } from '../../shared/utils/optimistic'

View File

@ -6,7 +6,7 @@
</div> </div>
<el-alert v-if="failure" type="error" :title="failure" :closable="false" class="flow-failure" /> <el-alert v-if="failure" type="error" :title="failure" :closable="false" class="flow-failure" />
<div class="flow-editor" :class="{ inactive: !active }"> <div class="flow-editor" :class="{ inactive: !active }">
<FlowNodePalette :enabled="canManage && !busy && !stageNameOpen" /> <FlowNodePalette :enabled="canManage && !busy && !stageNameOpen" @pointerdown.capture="finishCanvasGesture" />
<div ref="canvas" class="flow-canvas" @dragover.prevent @drop.prevent="dropStage"> <div ref="canvas" class="flow-canvas" @dragover.prevent @drop.prevent="dropStage">
<!-- 保持阶段组、子阶段和连线的固定层级;选中时自动提升父组会使其背景遮住内部连线。 --> <!-- 保持阶段组、子阶段和连线的固定层级;选中时自动提升父组会使其背景遮住内部连线。 -->
<VueFlow v-if="active" :id="flowId" v-model:nodes="nodes" :edges="edges" :connection-line-type="ConnectionLineType.Bezier" :delete-key-code="null" :min-zoom="0.1" :max-zoom="4" :nodes-connectable="canManage && !busy" :edges-updatable="false" :nodes-draggable="!busy" :elevate-nodes-on-select="false" @connect="connectStages" @edge-click="edgeClicked" @node-click="selectNode" @node-drag-start="dragging = true" @node-drag="nodeDragged" @node-drag-stop="dragStopped" @move-end="viewportMoved" @nodes-initialized="restoreViewport"> <VueFlow v-if="active" :id="flowId" v-model:nodes="nodes" :edges="edges" :connection-line-type="ConnectionLineType.Bezier" :delete-key-code="null" :min-zoom="0.1" :max-zoom="4" :nodes-connectable="canManage && !busy" :edges-updatable="false" :nodes-draggable="!busy" :elevate-nodes-on-select="false" @connect="connectStages" @edge-click="edgeClicked" @node-click="selectNode" @node-drag-start="dragging = true" @node-drag="nodeDragged" @node-drag-stop="dragStopped" @move-end="viewportMoved" @nodes-initialized="restoreViewport">
@ -24,7 +24,7 @@
<StageCreateDialog :visible="stageNameOpen" :project-id="projectId" :iteration-id="iterationId" :parent="createParent" :node-type="createNodeType" :members="members" @close="stageNameOpen = false" @created="stageCreated" /> <StageCreateDialog :visible="stageNameOpen" :project-id="projectId" :iteration-id="iterationId" :parent="createParent" :node-type="createNodeType" :members="members" @close="stageNameOpen = false" @created="stageCreated" />
<StageManager :visible="stageOpen" :project-id="projectId" :iteration-id="iterationId" :stages="view.stages" :members="members" :view="view" @close="stageOpen = false" @changed="emit('changed')" /> <StageManager :visible="stageOpen" :project-id="projectId" :iteration-id="iterationId" :stages="view.stages" :members="members" :view="view" @close="stageOpen = false" @changed="emit('changed')" />
<StageReworkDialog :visible="reworkSourceId !== null" :source-id="reworkSourceId" :project-id="projectId" :iteration-id="iterationId" :view="view" @close="reworkSourceId = null" @changed="emit('changed')" /> <StageReworkDialog :visible="reworkSourceId !== null" :source-id="reworkSourceId" :project-id="projectId" :iteration-id="iterationId" :view="view" @close="reworkSourceId = null" @changed="emit('changed')" />
<StageWorkItemsDrawer :stage-id="drawerStageId" :initial-tab="drawerTab" :project-id="projectId" :iteration-id="iterationId" :view="view" :members="members" :can-create="canCreate" :can-manage="canManage" @changed="emit('changed')" @close="drawerStageId = null" @open="openItem" @create="createFromDrawer" @navigate="drawerStageId = $event" @create-child="createChildFromDrawer" /> <StageWorkItemsDrawer :stage-id="drawerStageId" :initial-tab="drawerTab" :project-id="projectId" :iteration-id="iterationId" :view="view" :members="members" :can-create="canCreate" :can-manage="canManage" @changed="emit('changed')" @close="drawerStageId = null; drawerEditing = false" @open="openItem" @create="createFromDrawer" @navigate="drawerStageId = $event" @create-child="createChildFromDrawer" @editing="drawerEditing = $event" />
</section> </section>
</template> </template>
<script setup lang="ts"> <script setup lang="ts">
@ -44,6 +44,7 @@ import { buildFlowGraph, absoluteRectangle, resizeStageGroup, updateReworkRoutes
import { readFlowPreferences, writeFlowPreferences } from './utils/preferences' import { readFlowPreferences, writeFlowPreferences } from './utils/preferences'
import { stageAppearance } from './utils/stageAppearance' import { stageAppearance } from './utils/stageAppearance'
import { stageGroupAt } from './utils/stageDrop' import { stageGroupAt } from './utils/stageDrop'
import { useCanvasGestureCleanup } from './composables/useCanvasGestureCleanup'
import { isPaletteNodeType } from '../../shared/constants/stageNodeTypes' import { isPaletteNodeType } from '../../shared/constants/stageNodeTypes'
import type { FlowNodeData, FlowEdgeData } from './utils/graph' import type { FlowNodeData, FlowEdgeData } from './utils/graph'
import type { FlowView, Member, Point, StageNodeType } from '../../types' import type { FlowView, Member, Point, StageNodeType } from '../../types'
@ -60,7 +61,7 @@ const props = defineProps<{ view: FlowView; projectId: number; iterationId?: num
const emit = defineEmits<{ open: [id: number]; changed: []; create: [stageId: number | null] }>() const emit = defineEmits<{ open: [id: number]; changed: []; create: [stageId: number | null] }>()
const canvas = ref<HTMLElement | null>(null) const canvas = ref<HTMLElement | null>(null)
const flowId = 'project-flow-' + props.projectId + '-' + props.iterationId const flowId = 'project-flow-' + props.projectId + '-' + props.iterationId
const { fitView, setViewport, viewport, screenToFlowCoordinate, getNodes, updateNodeInternals } = useVueFlow(flowId) const { fitView, setViewport, viewport, screenToFlowCoordinate, getNodes, updateNodeInternals, paneDragging } = useVueFlow(flowId)
const nodes = ref<Node<FlowNodeData>[]>([]), edges = ref<Edge<FlowEdgeData>[]>([]), positions = ref<Record<string, Point>>({}) const nodes = ref<Node<FlowNodeData>[]>([]), edges = ref<Edge<FlowEdgeData>[]>([]), positions = ref<Record<string, Point>>({})
const busy = ref(false), dragging = ref(false), failure = ref(''), stageOpen = ref(false), stageNameOpen = ref(false), pendingStagePoint = ref<Point | null>(null) const busy = ref(false), dragging = ref(false), failure = ref(''), stageOpen = ref(false), stageNameOpen = ref(false), pendingStagePoint = ref<Point | null>(null)
const draftViewport = ref<(Point & { zoom: number }) | null>(null) const draftViewport = ref<(Point & { zoom: number }) | null>(null)
@ -68,8 +69,13 @@ const createParentId = ref<number | null>(null), collapsedStages = ref<number[]>
const createNodeType = ref<StageNodeType | undefined>(undefined) const createNodeType = ref<StageNodeType | undefined>(undefined)
const createParent = computed(() => props.view.stages.find(stage => stage.id === createParentId.value) || null) const createParent = computed(() => props.view.stages.find(stage => stage.id === createParentId.value) || null)
const reworkSourceId = ref<number | null>(null), drawerStageId = ref<number | null>(null), drawerTab = ref<'current' | 'history'>('current') const reworkSourceId = ref<number | null>(null), drawerStageId = ref<number | null>(null), drawerTab = ref<'current' | 'history'>('current')
// 展示坐标与视口只存在当前浏览器;抽屉工作项始终取父页面更新后的服务端快照。 const drawerEditing = ref(false)
const isEditing = computed(() => drawerStageId.value !== null || dragging.value || busy.value || stageOpen.value || stageNameOpen.value || reworkSourceId.value !== null) // 平移和节点移动期间都暂停静默同步,避免尚未释放的鼠标手势遇到画布重建;坐标仍仅保存到当前浏览器。
const isEditing = computed(() => drawerEditing.value || dragging.value || paneDragging.value || busy.value || stageOpen.value || stageNameOpen.value || reworkSourceId.value !== null)
const { finishCanvasGesture } = useCanvasGestureCleanup(
computed(() => dragging.value || paneDragging.value),
computed(() => !props.active || stageOpen.value || stageNameOpen.value || drawerStageId.value !== null || reworkSourceId.value !== null),
)
defineExpose({ isEditing }) defineExpose({ isEditing })
let loaded = false, movingProgrammatically = false let loaded = false, movingProgrammatically = false
let previousParents: Record<string, number | null> = {} let previousParents: Record<string, number | null> = {}

View File

@ -3,10 +3,10 @@
<Handle v-if="data.stage" id="in" type="target" :position="Position.Left" :connectable="!!data.canManage" :style="{ top: '42px' }" /> <Handle v-if="data.stage" id="in" type="target" :position="Position.Left" :connectable="!!data.canManage" :style="{ top: '42px' }" />
<header class="stage-drag"><span class="phase-dot"></span><span v-if="data.stage" class="stage-type">{{ stageNodeTypeLabel(data.stage) }}</span><strong :title="data.title">{{ data.title }}</strong><span v-if="data.stage?.isCurrent" class="stage-current">当前</span><button v-if="data.stage?.stageKind === 'GROUP'" class="nodrag stage-toggle" @click.stop="emit('toggle', data.stageId!)">{{ data.collapsed ? '展开' : '折叠' }}</button><span v-if="data.stage" class="stage-version">v{{ data.stage.revisionNo || 1 }}</span></header> <header class="stage-drag"><span class="phase-dot"></span><span v-if="data.stage" class="stage-type">{{ stageNodeTypeLabel(data.stage) }}</span><strong :title="data.title">{{ data.title }}</strong><span v-if="data.stage?.isCurrent" class="stage-current">当前</span><button v-if="data.stage?.stageKind === 'GROUP'" class="nodrag stage-toggle" @click.stop="emit('toggle', data.stageId!)">{{ data.collapsed ? '展开' : '折叠' }}</button><span v-if="data.stage" class="stage-version">v{{ data.stage.revisionNo || 1 }}</span></header>
<p v-if="data.stage" class="phase-description" :class="{ empty: !data.stage.description?.trim() }" :title="data.stage.description || '未填写阶段描述'">{{ data.stage.description || '未填写阶段描述' }}</p> <p v-if="data.stage" class="phase-description" :class="{ empty: !data.stage.description?.trim() }" :title="data.stage.description || '未填写阶段描述'">{{ data.stage.description || '未填写阶段描述' }}</p>
<div class="phase-body"><button class="nodrag stage-items" title="查看当前版本工作项" @click.stop="emit('view', data.stageId!)">{{ data.itemCount || 0 }} 个工作项</button><span v-if="data.stage" class="stage-status" :title="appearance.description">{{ appearance.label }}</span></div> <div class="phase-body"><button class="nodrag stage-items" :title="data.stage ? `发起人:${data.stage.creatorName || '#' + data.stage.creatorId};负责人:${data.stage.ownerName || '未设置'}。点击查看交付与审批。` : '查看工作项'" @click.stop="emit('view', data.stageId!)">{{ data.stage?.nodeType === 'PURCHASE' ? `${data.stage.purchaseBatchCount || 0} 个批次 · ${data.stage.purchaseProgress || 0}%` : `${data.itemCount || 0} 个工作项` }}</button><span v-if="data.stage" class="stage-status" :title="appearance.description">{{ appearance.label }}</span></div>
<div v-if="data.stage" class="phase-plan" :class="{ warning: data.stage.scheduleReviewRequired || data.stage.overdue }" :title="planLabel(data.stage)">{{ planLabel(data.stage) }}</div> <div v-if="data.stage" class="phase-plan" :class="{ warning: data.stage.scheduleReviewRequired || data.stage.overdue }" :title="planLabel(data.stage)">{{ planLabel(data.stage) }}</div>
<div v-if="data.stage?.stageKind === 'GROUP'" class="group-summary">子阶段 {{ data.stage.completedChildStageCount || 0 }}/{{ data.stage.childStageCount || 0 }} 已完成 · 内部排期{{ data.stage.subtreeScheduleValidationStatus === 'VALID' ? '完整' : '待完善' }}</div> <div v-if="data.stage?.stageKind === 'GROUP'" class="group-summary">子阶段 {{ data.stage.completedChildStageCount || 0 }}/{{ data.stage.childStageCount || 0 }} 已完成 · 内部排期{{ data.stage.subtreeScheduleValidationStatus === 'VALID' ? '完整' : '待完善' }}</div>
<div v-if="data.stage" class="phase-actions"><button v-if="data.canManage && data.stage.canCreateChildStage" class="nodrag stage-create" @click.stop="emit('createChild', data.stageId!)">+ 子阶段</button><button v-if="data.canWrite && data.stage.canCreateWorkItem" class="nodrag stage-create" @click.stop="emit('create', data.stageId!)">新建</button><button class="nodrag stage-history" @click.stop="emit('history', data.stageId!)">历史版本</button><button v-if="data.canManage && data.stage.canRework" class="nodrag stage-rework" @click.stop="emit('rework', data.stageId!)">回退</button></div> <div v-if="data.stage" class="phase-actions"><button v-if="data.canManage && data.stage.canCreateChildStage" class="nodrag stage-create" @click.stop="emit('createChild', data.stageId!)">+ 子阶段</button><button v-if="data.canWrite && data.stage.canCreateWorkItem" class="nodrag stage-create" @click.stop="emit('create', data.stageId!)">新建</button><button v-if="data.stage.canApproveCompletion || data.stage.canSubmitCompletion || data.stage.canConfirmPurchase" class="nodrag" @click.stop="emit('view', data.stageId!)">{{ data.stage.canApproveCompletion ? '审批' : data.stage.canConfirmPurchase ? '确认完成' : '提审' }}</button><button class="nodrag stage-history" @click.stop="emit('history', data.stageId!)">历史版本</button><button v-if="data.canManage && data.stage.canRework" class="nodrag stage-rework" @click.stop="emit('rework', data.stageId!)">回退</button></div>
<Handle v-if="data.stage" id="rework-out" type="source" :position="Position.Bottom" :connectable="false" :style="{ left: '70%', opacity: 0, pointerEvents: 'none' }" /> <Handle v-if="data.stage" id="rework-out" type="source" :position="Position.Bottom" :connectable="false" :style="{ left: '70%', opacity: 0, pointerEvents: 'none' }" />
<Handle v-if="data.stage" id="rework-in" type="target" :position="Position.Bottom" :connectable="false" :style="{ left: '30%', opacity: 0, pointerEvents: 'none' }" /> <Handle v-if="data.stage" id="rework-in" type="target" :position="Position.Bottom" :connectable="false" :style="{ left: '30%', opacity: 0, pointerEvents: 'none' }" />
<Handle v-if="data.stage" id="out" type="source" :position="Position.Right" :connectable="!!data.canManage" :style="{ top: '42px' }" /> <Handle v-if="data.stage" id="out" type="source" :position="Position.Right" :connectable="!!data.canManage" :style="{ top: '42px' }" />

View File

@ -0,0 +1,62 @@
import { onBeforeUnmount, onMounted, watch, type ComputedRef } from 'vue'
/**
* 在画布鼠标手势被窗口切换或弹窗中断时,释放 Vue Flow 的浏览器拖放拦截。
* @param gestureActive 仅当前画布的节点拖动或画布平移状态,不包含节点库的原生拖放
* @param interrupted 画布隐藏或对话框打开时为 true,停止继续接收当前画布手势
* @returns 可在再次操作节点库前调用的清理函数;不改动节点业务数据
*/
export function useCanvasGestureCleanup(gestureActive: ComputedRef<boolean>, interrupted: ComputedRef<boolean>) {
let pointer = { x: 0, y: 0 }, finishing = false, suppressInterruptedClick = false
/** 仅记录坐标,不捕获或阻止事件,使鼠标释放仍由 Vue Flow 自己处理。 */
function rememberPointer(event: PointerEvent) { pointer = { x: event.clientX, y: event.clientY } }
/** 新的按下代表新的操作意图,不能把上一次中断手势的点击保护带到这次操作。 */
function pointerStarted(event: PointerEvent) { suppressInterruptedClick = false; rememberPointer(event) }
/** 中断后迟到的鼠标释放不能误开阶段详情;新按下和键盘点击仍正常处理。 */
function discardInterruptedClick(event: MouseEvent) {
if (!suppressInterruptedClick || event.detail === 0) return
suppressInterruptedClick = false; event.preventDefault(); event.stopImmediatePropagation()
}
/**
* 使用标准 mouseup 结束当前画布手势,让 Vue Flow 同时移除其临时窗口监听和保存最终坐标。
* Vue Flow 的 D3 鼠标手势会暂时禁止原生 dragstart;失焦时浏览器可能不再向原窗口发送 mouseup。
* 不能只清除组件布尔状态,否则节点库下一次拖放仍会被拦截;也不直接访问第三方内部监听表。
* 升级 Vue Flow 后,若其已自行处理失焦和隐藏时的手势释放,可重新验证并移除此兼容处理。
*/
function finishCanvasGesture() {
if (!gestureActive.value || finishing) return
finishing = true; suppressInterruptedClick = true
try { window.dispatchEvent(new MouseEvent('mouseup', { view: window, bubbles: true, buttons: 0, clientX: pointer.x, clientY: pointer.y })) }
finally { finishing = false }
}
/** 页面转入后台时视为手势中断,恢复后应可直接开始新的拖动。 */
function visibilityChanged() { if (document.hidden) finishCanvasGesture() }
/** 在鼠标手势监听之前记录指针;不影响节点库原生拖放和其他页面的鼠标操作。 */
onMounted(() => {
window.addEventListener('pointerdown', pointerStarted, true)
window.addEventListener('pointermove', rememberPointer, true)
window.addEventListener('click', discardInterruptedClick, true)
window.addEventListener('pointercancel', finishCanvasGesture, true)
window.addEventListener('blur', finishCanvasGesture)
document.addEventListener('visibilitychange', visibilityChanged)
})
/** 在画布卸载或弹窗遮罩接管输入前结束手势,避免窗口级监听存活到下一次操作。 */
watch(interrupted, value => { if (value) finishCanvasGesture() }, { flush: 'sync' })
/** 卸载前仍由现有画布完成释放,再移除本组件注册的监听,避免污染其他页面。 */
onBeforeUnmount(() => {
finishCanvasGesture()
window.removeEventListener('pointerdown', pointerStarted, true)
window.removeEventListener('pointermove', rememberPointer, true)
window.removeEventListener('click', discardInterruptedClick, true)
window.removeEventListener('pointercancel', finishCanvasGesture, true)
window.removeEventListener('blur', finishCanvasGesture)
document.removeEventListener('visibilitychange', visibilityChanged)
})
return { finishCanvasGesture }
}

View File

@ -1,5 +1,5 @@
import type { Stage } from '../../../types' import type { Stage } from '../../../types'
import { stageStatusNames } from '../../../shared/constants/labels' import { stageStatusLabel } from '../../../shared/constants/labels'
const stageColors = { const stageColors = {
NOT_STARTED: { background: 'var(--el-fill-color)', border: 'var(--el-border-color)', accent: 'var(--el-text-color-secondary)' }, NOT_STARTED: { background: 'var(--el-fill-color)', border: 'var(--el-border-color)', accent: 'var(--el-text-color-secondary)' },
@ -7,6 +7,8 @@ const stageColors = {
COMPLETED: { background: 'var(--el-color-success-light-9)', border: 'var(--el-color-success-light-5)', accent: 'var(--el-color-success)' }, COMPLETED: { background: 'var(--el-color-success-light-9)', border: 'var(--el-color-success-light-5)', accent: 'var(--el-color-success)' },
LEGACY_PASSED: { background: 'var(--el-fill-color)', border: 'var(--el-color-warning-light-5)', accent: 'var(--el-color-warning)' }, LEGACY_PASSED: { background: 'var(--el-fill-color)', border: 'var(--el-color-warning-light-5)', accent: 'var(--el-color-warning)' },
REWORK_PENDING: { background: 'var(--el-color-warning-light-9)', border: 'var(--el-color-warning-light-5)', accent: 'var(--el-color-warning)' }, REWORK_PENDING: { background: 'var(--el-color-warning-light-9)', border: 'var(--el-color-warning-light-5)', accent: 'var(--el-color-warning)' },
PENDING_APPROVAL: { background: 'var(--el-color-warning-light-9)', border: 'var(--el-color-warning-light-5)', accent: 'var(--el-color-warning)' },
REJECTED: { background: 'var(--el-color-danger-light-9)', border: 'var(--el-color-danger-light-5)', accent: 'var(--el-color-danger)' },
} as const } as const
/** /**
@ -15,13 +17,14 @@ const stageColors = {
* @param stage 后端当前版本摘要;未分配分组没有阶段,采用中性底色 * @param stage 后端当前版本摘要;未分配分组没有阶段,采用中性底色
* @returns 展示色和状态文案;开始或完成后自动恢复普通状态配色,不修改业务状态 * @returns 展示色和状态文案;开始或完成后自动恢复普通状态配色,不修改业务状态
*/ */
export function stageAppearance(stage?: Pick<Stage, 'executionStatus' | 'reworkId'>) { export function stageAppearance(stage?: Pick<Stage, 'executionStatus' | 'reworkId' | 'approvalStatus' | 'nodeType' | 'deliveryReady'>) {
const status = stage?.executionStatus || 'NOT_STARTED' const status = stage?.executionStatus || 'NOT_STARTED'
const tone = status === 'NOT_STARTED' && stage?.reworkId != null ? 'REWORK_PENDING' : status const completed = status === 'COMPLETED' || status === 'LEGACY_PASSED'
const tone = !completed && stage?.approvalStatus === 'PENDING' ? 'PENDING_APPROVAL' : !completed && stage?.approvalStatus === 'REJECTED' ? 'REJECTED' : !completed && stage?.nodeType === 'PURCHASE' && stage?.deliveryReady ? 'PENDING_APPROVAL' : status === 'NOT_STARTED' && stage?.reworkId != null ? 'REWORK_PENDING' : status
return { return {
tone, tone,
...stageColors[tone], ...stageColors[tone],
label: tone === 'REWORK_PENDING' ? '回退待重做' : stageStatusNames[status], label: tone === 'REWORK_PENDING' ? '回退待重做' : stageStatusLabel(stage || {}),
description: tone === 'REWORK_PENDING' ? '未执行 · 当前版本由回退生成,开始执行后恢复正常状态配色' : stageStatusNames[status], description: tone === 'REWORK_PENDING' ? '未执行 · 当前版本由回退生成,开始执行后恢复正常状态配色' : stageStatusLabel(stage || {}),
} }
} }

View File

@ -9,7 +9,7 @@
<div class="item-label" :style="{ paddingLeft: (8 + (row.depth || 0) * 16) + 'px' }" :title="row.label" @click="openRow(row)"><span v-if="row.item?.dependencyBlocked" class="blocked-dot" />{{ row.stage ? '◆ ' : row.item?.stageId || row.item?.parentTaskId ? '↳ ' : '' }}{{ row.label }} <small v-if="row.stage">v{{ row.stage.revisionNo || 1 }}</small></div> <div class="item-label" :style="{ paddingLeft: (8 + (row.depth || 0) * 16) + 'px' }" :title="row.label" @click="openRow(row)"><span v-if="row.item?.dependencyBlocked" class="blocked-dot" />{{ row.stage ? '◆ ' : row.item?.stageId || row.item?.parentTaskId ? '↳ ' : '' }}{{ row.label }} <small v-if="row.stage">v{{ row.stage.revisionNo || 1 }}</small></div>
<div class="timeline" :style="{ width: days * unit + 'px' }"> <div class="timeline" :style="{ width: days * unit + 'px' }">
<div v-if="row.start && row.end" class="bar" :class="{ blocked: row.item?.dependencyBlocked, busy: pending.has(row.key), reference: row.reference, 'stage-bar': !!row.stage }" :style="barStyle(row)" @pointerdown="begin(row, $event, 'move')" @dblclick="openRow(row)"> <div v-if="row.start && row.end" class="bar" :class="{ blocked: row.item?.dependencyBlocked, busy: pending.has(row.key), reference: row.reference, 'stage-bar': !!row.stage }" :style="barStyle(row)" @pointerdown="begin(row, $event, 'move')" @dblclick="openRow(row)">
<span v-if="editable(row)" class="handle left" @pointerdown.stop="begin(row, $event, 'start')" />{{ row.reference ? (row.stage || row.item)?.scheduleReviewClosed ? '参考 · 本轮未确认' : '参考 · 待复核' : row.stage ? stageStatusNames[row.stage.executionStatus || 'NOT_STARTED'] : itemStatusLabel(row.item!) }}<span v-if="editable(row)" class="handle right" @pointerdown.stop="begin(row, $event, 'end')" /> <span v-if="editable(row)" class="handle left" @pointerdown.stop="begin(row, $event, 'start')" />{{ row.reference ? (row.stage || row.item)?.scheduleReviewClosed ? '参考 · 本轮未确认' : '参考 · 待复核' : row.stage ? stageStatusLabel(row.stage) : itemStatusLabel(row.item!) }}<span v-if="editable(row)" class="handle right" @pointerdown.stop="begin(row, $event, 'end')" />
</div> </div>
<span v-else-if="row.stage" class="no-plan" @click="openRow(row)">{{ row.stage.scheduleReviewClosed ? '本轮未确认排期' : row.stage.scheduleReviewRequired ? '排期待复核' : '阶段未排期' }} · 查看时间</span> <span v-else-if="row.stage" class="no-plan" @click="openRow(row)">{{ row.stage.scheduleReviewClosed ? '本轮未确认排期' : row.stage.scheduleReviewRequired ? '排期待复核' : '阶段未排期' }} · 查看时间</span>
</div> </div>
@ -18,7 +18,7 @@
</div> </div>
<el-empty v-if="!rows.length && !unscheduled.length" :image-size="64" :description="memberFiltered ? '所选成员在当前范围内暂无符合条件的工作项' : '当前范围内暂无符合条件的工作项'" /> <el-empty v-if="!rows.length && !unscheduled.length" :image-size="64" :description="memberFiltered ? '所选成员在当前范围内暂无符合条件的工作项' : '当前范围内暂无符合条件的工作项'" />
<el-dialog :close-on-click-modal="false" :model-value="!!selectedStage" :title="(selectedStage?.name || '') + ' · 阶段时间'" width="min(800px, 95%)" append-to-body @close="selectedStageId = null"> <el-dialog :close-on-click-modal="false" :model-value="!!selectedStage" :title="(selectedStage?.name || '') + ' · 阶段时间'" width="min(800px, 95%)" append-to-body @close="selectedStageId = null">
<StageSchedulePanel v-if="selectedStage && projectId" :project-id="projectId" :iteration-id="iterationId" :stage-id="selectedStage.id" :schedule="selectedStage" :can-manage="canManage" :completed="frozen(selectedStage.id)" @changed="emit('changed')" /> <StageSchedulePanel v-if="selectedStage && projectId" :project-id="projectId" :iteration-id="iterationId" :stage-id="selectedStage.id" :schedule="selectedStage" :can-manage="canManage && selectedStage.approvalStatus !== 'PENDING'" :completed="frozen(selectedStage.id)" @changed="emit('changed')" />
</el-dialog> </el-dialog>
</div> </div>
</template> </template>
@ -26,7 +26,7 @@
import { computed, onBeforeUnmount, reactive, ref } from 'vue' import { computed, onBeforeUnmount, reactive, ref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus' import { ElMessage, ElMessageBox } from 'element-plus'
import type { WorkItem, ScheduleChange, Stage, StageScheduleChange } from '../../types' import type { WorkItem, ScheduleChange, Stage, StageScheduleChange } from '../../types'
import { itemStatusLabel, stageStatusNames } from '../../shared/constants/labels' import { itemStatusLabel, stageStatusLabel } from '../../shared/constants/labels'
import { shiftDays, visualMillis, localTime, plannedRange, planBoundary, plannedDate } from '../../shared/utils/time' import { shiftDays, visualMillis, localTime, plannedRange, planBoundary, plannedDate } from '../../shared/utils/time'
import { api, errorText } from '../../api' import { api, errorText } from '../../api'
import { moveSchedule } from '../../shared/utils/optimistic' import { moveSchedule } from '../../shared/utils/optimistic'
@ -75,7 +75,7 @@ let disposed = false
/** 完成后的正常计划只读;缺失计划在专门的补录面板处理。 */ /** 完成后的正常计划只读;缺失计划在专门的补录面板处理。 */
function frozen(stageId?: number | null) { return ['COMPLETED', 'LEGACY_PASSED'].includes(props.stages.find(stage => stage.id === stageId)?.executionStatus || '') } function frozen(stageId?: number | null) { return ['COMPLETED', 'LEGACY_PASSED'].includes(props.stages.find(stage => stage.id === stageId)?.executionStatus || '') }
/** 参考条、只读阶段及缺少版本的条目不开放手势,最终权限仍由后端重新验证。 */ /** 参考条、只读阶段及缺少版本的条目不开放手势,最终权限仍由后端重新验证。 */
function editable(row: TimelineRow) { return !row.reference && !pending.has(row.key) && (row.stage ? !!props.canManage && !!props.projectId && !!props.iterationId && row.stage.revisionVersion !== undefined && !frozen(row.stage.id) : props.canWrite && !row.item?.historical && !frozen(row.item?.stageId)) } function editable(row: TimelineRow) { const stage = row.stage || props.stages.find(value => value.id === row.item?.stageId); return stage?.approvalStatus !== 'PENDING' && !row.reference && !pending.has(row.key) && (row.stage ? !!props.canManage && !!props.projectId && !!props.iterationId && row.stage.revisionVersion !== undefined && !frozen(row.stage.id) : props.canWrite && !row.item?.historical && !frozen(row.item?.stageId)) }
/** 点击阶段查看阶段时间,点击工作项保持原详情弹窗入口。 */ /** 点击阶段查看阶段时间,点击工作项保持原详情弹窗入口。 */
function openRow(row: TimelineRow) { if (row.stage) selectedStageId.value = row.stage.id; else if (row.item) emit('open', row.item.id) } function openRow(row: TimelineRow) { if (row.stage) selectedStageId.value = row.stage.id; else if (row.item) emit('open', row.item.id) }
/** 日期网格投影原计划;旧排期位置保持精度,主动拖动后的请求才按整日边界提交。 */ /** 日期网格投影原计划;旧排期位置保持精度,主动拖动后的请求才按整日边界提交。 */

View File

@ -67,6 +67,7 @@
v-if="row.stageId" v-if="row.stageId"
class="muted" class="muted"
> v{{ stages.find(stage => stage.id === row.stageId)?.revisionNo || 1 }}</small> > v{{ stages.find(stage => stage.id === row.stageId)?.revisionNo || 1 }}</small>
<el-tag v-if="row.stageApprovalStatus === 'PENDING' || row.stageApprovalStatus === 'REJECTED'" size="small" :type="row.stageApprovalStatus === 'PENDING' ? 'warning' : 'danger'">{{ row.stageApprovalStatus === 'PENDING' ? '阶段待审批' : '阶段待整改' }}</el-tag>
</template> </template>
</el-table-column> </el-table-column>
<el-table-column <el-table-column