diff --git a/ruoyi-project/sql/project_collaboration.sql b/ruoyi-project/sql/project_collaboration.sql index 08d1fde..e4c5eb4 100644 --- a/ruoyi-project/sql/project_collaboration.sql +++ b/ruoyi-project/sql/project_collaboration.sql @@ -573,10 +573,10 @@ CREATE TABLE pm_collab_stage_revision_member ( -- 画布分类固定于阶段身份,不随执行版本变化;历史普通阶段使用 STAGE。 ALTER TABLE pm_collab_project_stage - ADD COLUMN node_type VARCHAR(24) NOT NULL DEFAULT 'STAGE' COMMENT '固定节点类型:GROUP阶段组,REQUIREMENT需求,PROPOSAL方案,PURCHASE采购,DESIGN设计,MACHINING加工,ASSEMBLY组装,DEBUGGING调试,DEVELOPMENT研发,TESTING测试,STAGE历史普通阶段', + ADD COLUMN node_type VARCHAR(24) NOT NULL DEFAULT 'STAGE' COMMENT '固定节点类型:GROUP阶段组,REQUIREMENT需求,PROPOSAL方案,PURCHASE采购,DESIGN设计,MACHINING加工,ASSEMBLY组装,DEBUGGING调试,DEVELOPMENT研发,TESTING测试,CUSTOM自定义,STAGE历史普通阶段', ADD CONSTRAINT ck_pm_stage_node_type CHECK ( (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','CUSTOM') AND stage_kind='WORK') ); -- 阶段版本交付、人工完成审批及采购批次引用。 diff --git a/ruoyi-project/sql/upgrade/024_custom_stage_node.sql b/ruoyi-project/sql/upgrade/024_custom_stage_node.sql new file mode 100644 index 0000000..26fa51a --- /dev/null +++ b/ruoyi-project/sql/upgrade/024_custom_stage_node.sql @@ -0,0 +1,12 @@ +-- 项目协作:新增自定义工作阶段分类。023 后执行,可重复执行;不修改历史类型或执行事实。 +SET NAMES utf8mb4; +SET @pm_custom_check_exists=(SELECT COUNT(*) FROM information_schema.TABLE_CONSTRAINTS + WHERE CONSTRAINT_SCHEMA=DATABASE() AND TABLE_NAME='pm_collab_project_stage' AND CONSTRAINT_NAME='ck_pm_stage_node_type'); +-- 在同一 ALTER 内替换分类约束和补充中文注释,避免存在无类型校验的中间状态。 +SET @pm_custom_ddl=CONCAT('ALTER TABLE pm_collab_project_stage ', + IF(@pm_custom_check_exists>0,'DROP CHECK ck_pm_stage_node_type, ',''), + 'MODIFY COLUMN node_type VARCHAR(24) NOT NULL DEFAULT ''STAGE'' COMMENT ''固定节点类型:GROUP阶段组,REQUIREMENT需求,PROPOSAL方案,PURCHASE采购,DESIGN设计,MACHINING加工,ASSEMBLY组装,DEBUGGING调试,DEVELOPMENT研发,TESTING测试,CUSTOM自定义,STAGE历史普通阶段'', ', + 'ADD CONSTRAINT ck_pm_stage_node_type CHECK ((node_type=''GROUP'' AND stage_kind=''GROUP'') OR (node_type IN (''STAGE'',''REQUIREMENT'',''PROPOSAL'',''PURCHASE'',''DESIGN'',''MACHINING'',''ASSEMBLY'',''DEBUGGING'',''DEVELOPMENT'',''TESTING'',''CUSTOM'') AND stage_kind=''WORK''))'); +PREPARE pm_custom_stmt FROM @pm_custom_ddl; +EXECUTE pm_custom_stmt; +DEALLOCATE PREPARE pm_custom_stmt; diff --git a/ruoyi-project/src/main/java/com/ruoyi/project/manage/controller/PmController.java b/ruoyi-project/src/main/java/com/ruoyi/project/manage/controller/PmController.java index 325827f..4718698 100644 --- a/ruoyi-project/src/main/java/com/ruoyi/project/manage/controller/PmController.java +++ b/ruoyi-project/src/main/java/com/ruoyi/project/manage/controller/PmController.java @@ -11,6 +11,7 @@ import com.ruoyi.project.manage.dto.TransitionInput; import com.ruoyi.project.manage.dto.VersionInput; import com.ruoyi.project.manage.exception.PmException; import com.ruoyi.project.manage.service.IPmService; +import com.ruoyi.project.manage.service.support.PmAttachmentStorage; import com.ruoyi.project.manage.dto.ItemQuery; import static com.ruoyi.project.manage.util.PmValues.*; @@ -66,7 +67,7 @@ public class PmController { @PostMapping("/items/{id}/children") public Map child(@PathVariable long id,@RequestBody JsonNode body) { return ok(service.createChild(id,decode(body,ChildInput.class))); } /** 子任务列表在服务层复验项目成员权限与实时状态。 */ @GetMapping("/items/{id}/children") public Map children(@PathVariable long id) { return ok(service.children(id)); } - /** 普通编辑拒绝状态;省略 stageId 时保留归属及本次邮件选择,显式 null 才移到未分配。 */ + /** 普通编辑拒绝状态注入,省略 stageId 时保留归属;阶段迁移须走管理者专用入口,显式 null 也不能绕过。 */ @PatchMapping("/items/{id}") public Map edit(@PathVariable long id,@RequestBody JsonNode body) { ItemInput input=decode(body,ItemInput.class); if(!body.has("stageId")) input=new ItemInput(input.type(),input.title(),input.description(),input.assigneeId(),input.priority(),input.plannedStartAt(),input.plannedEndAt(),input.version(),nullableStage(service.detail(id).get("stageId")),input.collaboratorIds(),input.predecessorWorkItemIds(),input.sendEmail()); @@ -101,8 +102,8 @@ public class PmController { @GetMapping("/items/{id}/successors") public Map successors(@PathVariable long id) { return ok(service.successors(id)); } /** 工作项评论受同一数据权限保护,并原子记录历史。 */ @PostMapping("/items/{id}/comments") public Map comment(@PathVariable long id,@RequestBody JsonNode body) { service.comment(id,decode(body,CommentInput.class)); return ok(null); } - /** 文件写入 MinIO 私有对象,数据库仅保存元数据;不产生公开上传 URL。 */ - @PostMapping("/items/{id}/attachments") public Map attach(@PathVariable long id,@RequestParam("file") MultipartFile file) throws java.io.IOException { if(file.getSize()>10*1024*1024) throw PmException.bad("附件不能超过 10 MiB"); return ok(service.attach(id,file.getOriginalFilename(),file.getContentType(),file.getBytes())); } + /** 在读取字节前按统一的 50MB 上限校验,文件存入 MinIO 私有对象,不产生公开上传 URL。 */ + @PostMapping("/items/{id}/attachments") public Map attach(@PathVariable long id,@RequestParam("file") MultipartFile file) throws java.io.IOException { if(file.getSize()>PmAttachmentStorage.MAX_BYTES) throw PmException.bad("附件不能超过 "+PmAttachmentStorage.MAX_SIZE_LABEL); return ok(service.attach(id,file.getOriginalFilename(),file.getContentType(),file.getBytes())); } /** 绑定工作项与附件 ID,负责人/创建者权限及软删除事务由服务统一处理,不开放存储对象删除入口。 */ @DeleteMapping("/items/{id}/attachments/{attachmentId}") public Map removeAttachment(@PathVariable long id,@PathVariable long attachmentId) { service.removeAttachment(id,attachmentId); return ok(null); } diff --git a/ruoyi-project/src/main/java/com/ruoyi/project/manage/controller/PmStageCompletionController.java b/ruoyi-project/src/main/java/com/ruoyi/project/manage/controller/PmStageCompletionController.java index cbb30e0..9886849 100644 --- a/ruoyi-project/src/main/java/com/ruoyi/project/manage/controller/PmStageCompletionController.java +++ b/ruoyi-project/src/main/java/com/ruoyi/project/manage/controller/PmStageCompletionController.java @@ -5,6 +5,7 @@ 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 com.ruoyi.project.manage.service.support.PmAttachmentStorage; import java.nio.charset.StandardCharsets; import java.util.Map; import org.springframework.http.*; @@ -52,10 +53,10 @@ public class PmStageCompletionController { /** 确认本轮采购范围,不修改源采购批次及验收事实。 */ @PutMapping("/stages/{stageId}/purchase-batches") public Map 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);} - /** 文件大小在读取字节之前校验;服务再次检查当前轮次、身份及实际内容长度。 */ + /** 读取字节前按统一的 50MB 上限校验;服务再次检查当前轮次、身份及实际内容长度。 */ @PostMapping("/stages/{stageId}/revisions/{revisionId}/attachments") public Map 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"); + if(file.getSize()>PmAttachmentStorage.MAX_BYTES)throw PmException.bad("附件不能超过"+PmAttachmentStorage.MAX_SIZE_LABEL); return ok(service.attach(projectId,iterationId,stageId,revisionId,file.getOriginalFilename(),file.getContentType(),file.getBytes())); } /** 人员显式确认沿用旧版交付,复制新对象且不继承审批通过。 */ diff --git a/ruoyi-project/src/main/java/com/ruoyi/project/manage/controller/PmStageController.java b/ruoyi-project/src/main/java/com/ruoyi/project/manage/controller/PmStageController.java index 104641b..60a88fa 100644 --- a/ruoyi-project/src/main/java/com/ruoyi/project/manage/controller/PmStageController.java +++ b/ruoyi-project/src/main/java/com/ruoyi/project/manage/controller/PmStageController.java @@ -2,6 +2,7 @@ package com.ruoyi.project.manage.controller; import com.ruoyi.project.manage.dto.StageAssignment; import com.ruoyi.project.manage.dto.StageInput; +import com.ruoyi.project.manage.dto.StageNameInput; import com.ruoyi.project.manage.dto.StageEdgeInput; import com.ruoyi.project.manage.dto.VersionInput; import com.ruoyi.project.manage.exception.PmException; @@ -38,6 +39,9 @@ public class PmStageController { /** 阶段版本与所属迭代状态均在统一项目锁内检查。 */ @PatchMapping("/projects/{id}/iterations/{iterationId}/stages/{stageId}") public Map iterationEdit(@PathVariable long id,@PathVariable long iterationId,@PathVariable long stageId,@RequestBody JsonNode body) { service.editStage(id,iterationId,stageId,decode(body,StageInput.class)); return ok(null); } + /** 快捷改名严格只接受名称和版本;身份、归属、生命周期与冻结状态仍在服务事务中复查。 */ + @PatchMapping("/projects/{id}/iterations/{iterationId}/stages/{stageId}/name") + public Map iterationRename(@PathVariable long id,@PathVariable long iterationId,@PathVariable long stageId,@RequestBody JsonNode body) { service.renameStage(id,iterationId,stageId,decode(body,StageNameInput.class)); return ok(null); } /** 仅当前迭代的空阶段可软删除,保留原版本记录。 */ @DeleteMapping("/projects/{id}/iterations/{iterationId}/stages/{stageId}") public Map iterationDelete(@PathVariable long id,@PathVariable long iterationId,@PathVariable long stageId,@RequestBody JsonNode body) { service.deleteStage(id,iterationId,stageId,decode(body,VersionInput.class)); return ok(null); } diff --git a/ruoyi-project/src/main/java/com/ruoyi/project/manage/domain/StageNodeType.java b/ruoyi-project/src/main/java/com/ruoyi/project/manage/domain/StageNodeType.java index 62d1999..4302faf 100644 --- a/ruoyi-project/src/main/java/com/ruoyi/project/manage/domain/StageNodeType.java +++ b/ruoyi-project/src/main/java/com/ruoyi/project/manage/domain/StageNodeType.java @@ -4,7 +4,7 @@ import com.ruoyi.project.manage.exception.PmException; /** 画布节点的固定业务类型;仅 GROUP 承载子阶段,其余类型共用工作阶段的执行规则。 */ public enum StageNodeType { - GROUP, REQUIREMENT, PROPOSAL, PURCHASE, DESIGN, MACHINING, ASSEMBLY, DEBUGGING, DEVELOPMENT, TESTING, STAGE; + GROUP, REQUIREMENT, PROPOSAL, PURCHASE, DESIGN, MACHINING, ASSEMBLY, DEBUGGING, DEVELOPMENT, TESTING, CUSTOM, STAGE; /** 将分类映射为既有结构类型,返回 GROUP 容器或 WORK 工作阶段,不改变执行和排期规则。 */ public String kind() { return this == GROUP ? "GROUP" : "WORK"; } diff --git a/ruoyi-project/src/main/java/com/ruoyi/project/manage/dto/StageNameInput.java b/ruoyi-project/src/main/java/com/ruoyi/project/manage/dto/StageNameInput.java new file mode 100644 index 0000000..a4ee972 --- /dev/null +++ b/ruoyi-project/src/main/java/com/ruoyi/project/manage/dto/StageNameInput.java @@ -0,0 +1,4 @@ +package com.ruoyi.project.manage.dto; + +/** 画布快捷改名白名单;不接收类型、负责人、采购范围或排期,防止改名覆盖其他业务信息。 */ +public record StageNameInput(String name, Integer version) { } diff --git a/ruoyi-project/src/main/java/com/ruoyi/project/manage/mapper/PmDependencyMapper.java b/ruoyi-project/src/main/java/com/ruoyi/project/manage/mapper/PmDependencyMapper.java index 386f7d5..fde4055 100644 --- a/ruoyi-project/src/main/java/com/ruoyi/project/manage/mapper/PmDependencyMapper.java +++ b/ruoyi-project/src/main/java/com/ruoyi/project/manage/mapper/PmDependencyMapper.java @@ -22,7 +22,13 @@ public interface PmDependencyMapper { /** 版本不匹配必须拒绝覆盖;业务服务持有项目锁并在同一事务内记录历史。 */ default void updateDependency(long id,int version,Map values) { PmMapperWrite.requireUpdated(updateDependencyRow(id,version,values)); } - /** 加载任务前置边,供开始条件、排期及无环检查共用。 */ + /** + * 加载当前有效后续项的前置边,供开始条件、排期、无环检查及阶段回退共用。 + * 只排除已删除或历史轮次的后续项;已删除前置项的边仍需保留,以阻止有效后续项误判条件满足。 + * @param projectId 已鉴权的协作项目 ID + * @param iterationId 当前校验的明确迭代 ID + * @return 当前图依赖;不删除原始依赖行,历史详情通过独立查询读取 + */ List> selectGraphDependencies(@Param("projectId") long projectId,@Param("iterationId") long iterationId); /** 历史工作项详情读取原始依赖行,不把旧边加载进当前执行图。 */ diff --git a/ruoyi-project/src/main/java/com/ruoyi/project/manage/rule/PmRules.java b/ruoyi-project/src/main/java/com/ruoyi/project/manage/rule/PmRules.java index 1cec624..2db1fed 100644 --- a/ruoyi-project/src/main/java/com/ruoyi/project/manage/rule/PmRules.java +++ b/ruoyi-project/src/main/java/com/ruoyi/project/manage/rule/PmRules.java @@ -55,7 +55,13 @@ public final class PmRules { return conditions(graph,taskId,zone).stream().filter(c -> !Boolean.TRUE.equals(c.get("satisfied"))).toList(); } - /** 合并工作项前置、父任务和阶段边界;缺失阶段计划只标记不完整,已知边界必须满足。 */ + /** + * 合并工作项前置、父任务和阶段边界,计算最早开始、最晚结束及具体冲突。 + * @param graph 已鉴权迭代的完整候选图,批量改期时包含整批最终时间 + * @param item 待检查的当前工作项;允许暂缺一个日期,但已填写端点仍须落在父任务已知范围内 + * @param zone 输出时间的展示时区,比较使用 UTC 微秒 + * @return 排期摘要;缺失阶段计划标记为不完整,实际越界标记为冲突,不写入数据库 + */ public static Map schedule(Graph graph,Item item,String zone) { Long earliest = null; Long latest = null; @@ -67,7 +73,11 @@ public final class PmRules { if(parent!=null) { earliest=parent.start(); sources.add(map("sourceId",parent.id(),"sourceName",parent.title(),"plannedStartAt",PmTime.format(parent.start(),zone),"plannedEndAt",PmTime.format(parent.end(),zone),"kind","PARENT_RANGE")); - if(item.start()!=null&&(parent.start()==null||item.start()parent.end())) { + // 子任务可以暂缺一个端点,但剩余端点仍必须同时遵守父任务的上下界。 + // 仅比较开始对开始、结束对结束,会让单填结束落在父开始之前,或单填开始落在父结束之后。 + boolean startOutside=item.start()!=null&&(parent.start()==null||item.start()parent.end()); + boolean endOutside=item.end()!=null&&(parent.end()==null||item.end()>parent.end()||parent.start()!=null&&item.end()副作用:按阶段版本修改组织元数据并原子保存历史/outbox。

*/ void editStage(long projectId,long iterationId,long id,StageInput input); + /** 仅按版本更新当前有效阶段名称;沿用经理权限、迭代只读及审批冻结门禁,不覆盖交付和历史快照。 */ + void renameStage(long projectId,long iterationId,long id,StageNameInput input); /** 旧编辑入口缺少迭代边界时拒绝执行。 */ default void editStage(long projectId,long id,StageInput input) { throw requiredIteration(); } diff --git a/ruoyi-project/src/main/java/com/ruoyi/project/manage/service/impl/PmServiceImpl.java b/ruoyi-project/src/main/java/com/ruoyi/project/manage/service/impl/PmServiceImpl.java index b20200a..a7c3384 100644 --- a/ruoyi-project/src/main/java/com/ruoyi/project/manage/service/impl/PmServiceImpl.java +++ b/ruoyi-project/src/main/java/com/ruoyi/project/manage/service/impl/PmServiceImpl.java @@ -428,7 +428,7 @@ public class PmServiceImpl implements IPmService { } /** - * 工作项写鉴权后保存私有 MinIO 对象及数据库元信息,限制为 10 MiB,不写本地目录或新二进制字段。 + * 工作项写鉴权后保存私有 MinIO 对象及数据库元信息,限制为 50MB,不写本地目录或新二进制字段。 * @param id 当前可写工作项,历史版本不能追加附件 * @param name 原文件名,仅保留文件名部分,不作为对象路径使用 * @param mediaType 浏览器提交的媒体类型,需满足 HTTP 媒体类型格式 @@ -437,7 +437,7 @@ public class PmServiceImpl implements IPmService { */ public long attach(long id,String name,String mediaType,byte[] content) { long projectId=projectOf(id),iterationId=iterationOf(id); locked(projectId,iterationId,"write"); writableItem(graphService.load(projectId,iterationId),id); - if(content==null||content.length==0||content.length>com.ruoyi.project.manage.service.support.PmAttachmentStorage.MAX_BYTES) throw PmException.bad("附件需为 1 字节至 10 MiB"); + if(content==null||content.length==0||content.length>com.ruoyi.project.manage.service.support.PmAttachmentStorage.MAX_BYTES) throw PmException.bad("附件需为 1 字节至 "+com.ruoyi.project.manage.service.support.PmAttachmentStorage.MAX_SIZE_LABEL); String safeName=required(name==null?"附件":name.replace('\\','/').substring(name.replace('\\','/').lastIndexOf('/')+1),255,"附件名称"); String safeType=mediaType==null?"application/octet-stream":required(mediaType,120,"文件类型"); try { org.springframework.http.MediaType.parseMediaType(safeType); } catch(IllegalArgumentException invalid) { throw PmException.bad("文件类型格式无效"); } diff --git a/ruoyi-project/src/main/java/com/ruoyi/project/manage/service/impl/PmStageCompletionServiceImpl.java b/ruoyi-project/src/main/java/com/ruoyi/project/manage/service/impl/PmStageCompletionServiceImpl.java index 88ffab5..58cbf21 100644 --- a/ruoyi-project/src/main/java/com/ruoyi/project/manage/service/impl/PmStageCompletionServiceImpl.java +++ b/ruoyi-project/src/main/java/com/ruoyi/project/manage/service/impl/PmStageCompletionServiceImpl.java @@ -191,10 +191,10 @@ public class PmStageCompletionServiceImpl implements IPmStageCompletionService { record(stage,"STAGE_PURCHASE_SCOPE_CHANGED",map("batchIds",ids,"message","确认本轮采购批次范围"),List.of(),false); } - /** 当前交付维护人上传真实MinIO附件,空文件、超限和不合法媒体类型均拒绝。 */ + /** 当前交付维护人上传真实 MinIO 附件,按统一的 50MB 上限拒绝超限内容,同时校验空文件和媒体类型。 */ 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"); + if(content==null||content.length==0||content.length>PmAttachmentStorage.MAX_BYTES)throw PmException.bad("附件需为1字节至"+PmAttachmentStorage.MAX_SIZE_LABEL); 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,"文件类型"); diff --git a/ruoyi-project/src/main/java/com/ruoyi/project/manage/service/impl/PmStageServiceImpl.java b/ruoyi-project/src/main/java/com/ruoyi/project/manage/service/impl/PmStageServiceImpl.java index d38fe25..5f73e4b 100644 --- a/ruoyi-project/src/main/java/com/ruoyi/project/manage/service/impl/PmStageServiceImpl.java +++ b/ruoyi-project/src/main/java/com/ruoyi/project/manage/service/impl/PmStageServiceImpl.java @@ -3,6 +3,7 @@ package com.ruoyi.project.manage.service.impl; import com.ruoyi.project.manage.dto.StageAssignment; import com.ruoyi.project.manage.dto.StageEdgeInput; import com.ruoyi.project.manage.dto.StageInput; +import com.ruoyi.project.manage.dto.StageNameInput; import com.ruoyi.project.manage.dto.VersionInput; import com.ruoyi.project.manage.exception.PmException; import com.ruoyi.project.manage.domain.Graph; @@ -179,6 +180,26 @@ public class PmStageServiceImpl implements IPmStageService { auditService.record(projectId,iterationId,null,"STAGE_EDITED",map("stageId",id,"name",input.name().trim()),access.actor()); } + /** + * 仅更新当前阶段名称,兼容历史未设置负责人的节点;不借快捷入口改动交付或固定类型。 + * @param projectId 阶段所属协作项目,管理权限在项目锁前后复查 + * @param iterationId 明确的可写迭代范围 + * @param id 当前有效阶段标识 + * @param input 名称及预期阶段版本;空名称、过期版本和已冻结版本均拒绝 + * 注意:项目锁覆盖版本检查、名称写入及定义快照/审计;历史执行快照不随改名重写。 + */ + public void renameStage(long projectId,long iterationId,long id,StageNameInput input) { + locked(projectId,iterationId,"admin"); + Map existing=stage(projectId,iterationId,id); + if(input==null||input.name()==null||input.name().isBlank()||input.name().trim().length()>120) throw PmException.bad("阶段名称需为 1—120 个字符"); + version(input.version(),(int)number(existing,"version")); + PmStageRules.requireDeliveryMutable(graphService.load(projectId,iterationId),id); + stageMapper.updateStage(id,(int)number(existing,"version"),map("name",input.name().trim())); + groups.bind(projectId,iterationId); + snapshotDefinition(projectId,iterationId); + auditService.record(projectId,iterationId,null,"STAGE_EDITED",map("stageId",id,"name",input.name().trim()),access.actor()); + } + /** 非空阶段拒绝删除;空阶段的连线先移除,再软删阶段并原子保存历史与事件。 */ public void deleteStage(long projectId,long iterationId,long id,VersionInput input) { locked(projectId,iterationId,"admin"); Map existing=stage(projectId,iterationId,id); version(input.version(),(int)number(existing,"version")); diff --git a/ruoyi-project/src/main/java/com/ruoyi/project/manage/service/support/PmAttachmentStorage.java b/ruoyi-project/src/main/java/com/ruoyi/project/manage/service/support/PmAttachmentStorage.java index ca1c472..88bef4a 100644 --- a/ruoyi-project/src/main/java/com/ruoyi/project/manage/service/support/PmAttachmentStorage.java +++ b/ruoyi-project/src/main/java/com/ruoyi/project/manage/service/support/PmAttachmentStorage.java @@ -15,7 +15,9 @@ import org.springframework.transaction.support.TransactionSynchronizationManager /** 协作附件只写 MinIO 私有对象;对象键、校验和及下载鉴权由服务端控制,不暴露桶地址。 */ @Component public class PmAttachmentStorage { - public static final int MAX_BYTES=10*1024*1024; + // 上传校验与 MinIO 受限读取共用 50MB 上限,避免上传成功的大附件在下载时被旧上限拒绝。 + public static final int MAX_BYTES=50*1024*1024; + public static final String MAX_SIZE_LABEL=(MAX_BYTES/(1024*1024))+"MB"; private final BusinessFileStorage storage; /** 复用系统存储配置和环境隔离,传入空本地路径,禁止未启用 MinIO 时落入文件目录。 */ diff --git a/ruoyi-project/src/main/resources/mapper/project/manage/PmDependencyMapper.xml b/ruoyi-project/src/main/resources/mapper/project/manage/PmDependencyMapper.xml index 132d12c..4bf3331 100644 --- a/ruoyi-project/src/main/resources/mapper/project/manage/PmDependencyMapper.xml +++ b/ruoyi-project/src/main/resources/mapper/project/manage/PmDependencyMapper.xml @@ -54,6 +54,8 @@ JOIN pm_collab_work_item successor ON successor.id=d.successor_task_id LEFT JOIN pm_collab_project_stage ss ON ss.project_id=successor.project_id AND ss.id=successor.stage_id WHERE d.project_id=#{projectId} AND d.iteration_id=#{iterationId} AND d.condition_type IN ('TASK_COMPLETED','WORK_ITEM_COMPLETED') + + AND successor.deleted=false AND (successor.stage_id IS NULL OR successor.stage_revision_id=ss.current_revision_id) ORDER BY d.id diff --git a/ruoyi-ui-vue3/src/views/project/manage/README.md b/ruoyi-ui-vue3/src/views/project/manage/README.md index 31871eb..b7c263a 100644 --- a/ruoyi-ui-vue3/src/views/project/manage/README.md +++ b/ruoyi-ui-vue3/src/views/project/manage/README.md @@ -57,14 +57,22 @@ manage/ ## 工作项分工与前置条件 - 阶段节点展示已有描述的两行摘要,完整说明在阶段抽屉查看;拖入新阶段时可填写描述。 -- 流程画布左侧节点库提供阶段组、需求、方案、采购、设计、加工、组装、调试、研发和测试,支持搜索与拖放。普通类型拖入组内(包括子节点上方)自动归属,组本身仍只支持根画布;未执行及历史保护规则保持不变。 +- 流程画布左侧节点库提供阶段组、需求、方案、采购、设计、加工、组装、调试、研发、测试和自定义,支持搜索与拖放。普通类型拖入组内(包括子节点上方)自动归属,组本身仍只支持根画布;未执行及历史保护规则保持不变。自定义类型按普通工作阶段要求交付齐备后提审,不支持承载子阶段。 - 节点分类创建后固定,名称、负责人和说明可编辑;只有阶段组承载子阶段,其余分类沿用工作阶段规则。组内快捷创建可在提交前选择工作分类;复制迭代保留来源分类,回退换版沿用同一节点身份。 - 已有数据库上线前执行 `ruoyi-project/sql/upgrade/022_stage_node_types.sql`;脚本可重复执行,已有工作阶段标为普通阶段,已有组标为阶段组,不改动排期、执行版本或工作项。新安装结构已包含分类字段和组合约束。 +- 已完成 023 的数据库执行 `ruoyi-project/sql/upgrade/024_custom_stage_node.sql` 开放自定义类型;该升级只扩展类型约束及中文字段注释,不转换历史节点分类。 +- 项目管理者可通过节点名称后的编辑图标快捷改名,接口只接收名称和阶段版本;审批中或已完成版本仍只读。节点右上角删除图标与阶段管理表共用保护条件,已有执行历史、工作项、子阶段、交付附件或采购批次时禁用并说明原因,后端仍持锁复验后软删除。 - 新建和编辑工作项可从项目成员中多选协作人,负责人仍为单选。协作分工不改变项目角色或访问权限,历史版本保留原分工;回退复制仅继承仍有效的成员,并在预览中说明移除项。 - 新建工作项可选多个同迭代前置工作项,需求、任务、缺陷均可作为依赖两端。所有前置已完成或已关闭才满足条件,取消不满足;编辑依赖仍使用详情中的专用入口。 - 依赖、工作项和协作分工在同一项目锁事务中保存,继续共用实际开始、排期及混合执行图环检测。新建表单排期提示由后端约束预览计算,提交时重新验证。 - 已有数据库先完成 `ruoyi-project/sql/upgrade/016_work_item_collaboration.sql` 增量升级;该文件新增协作人关联表并兼容新旧依赖标识,保留已有工作项与排期。全新环境使用 `ruoyi-project/sql/project_collaboration.sql`。 +## 迭代操作 + +- 项目管理者在迭代工具栏直接编辑、开始、结束或删除当前迭代,更多操作使用点击菜单;普通成员不能管理迭代。归档及终态迭代的编辑入口禁用,可先取消归档或重新打开。 +- 筹备迭代由管理者手动开始并记录实际开始时间;执行中由管理者预览、确认结束并记录实际结束时间,不根据预计日期自动切换状态。待开始或进行中的工作项阻止结束,取消工作项或未审批阶段须逐条确认异常并说明原因后才能带异常结束。 +- 删除仅适用于从未执行且没有任何工作项或执行历史的筹备迭代,后端软删除并保留审计;已执行迭代通过结束、取消、归档保留历史。 + ## 甘特成员筛选 - 甘特排期的成员下拉支持多选当前项目成员;清空表示全部,多选按负责人或协作人任一匹配取并集,同一工作项只显示一次。 diff --git a/ruoyi-ui-vue3/src/views/project/manage/api/stages.ts b/ruoyi-ui-vue3/src/views/project/manage/api/stages.ts index dea16ef..cc8c2a4 100644 --- a/ruoyi-ui-vue3/src/views/project/manage/api/stages.ts +++ b/ruoyi-ui-vue3/src/views/project/manage/api/stages.ts @@ -30,6 +30,8 @@ export const stageApi = { removeStageEdge: (id: number, edgeId: number, version: number, iterationId?: number) => request('delete', iterationPath(id, iterationId, `stage-edges/${edgeId}`), { version }), /** 阶段元数据独立版本更新,不调整任务状态或排期。 */ editStage: (id: number, stageId: number, input: StageInput, iterationId?: number) => request('patch', iterationPath(id, iterationId, `stages/${stageId}`), input), + /** 画布快捷改名只传名称及当前版本,不能借此改动交付数据或固定类型。 */ + renameStage: (id: number, stageId: number, name: string, version: number, iterationId?: number) => request('patch', iterationPath(id, iterationId, `stages/${stageId}/name`), { name, version }), /** 非空阶段由后端拒绝;空阶段软删除保留历史。 */ removeStage: (id: number, stageId: number, version: number, iterationId?: number) => request('delete', iterationPath(id, iterationId, `stages/${stageId}`), { version }), } diff --git a/ruoyi-ui-vue3/src/views/project/manage/composables/useProjectCollaboration.ts b/ruoyi-ui-vue3/src/views/project/manage/composables/useProjectCollaboration.ts index ce791bb..18623a6 100644 --- a/ruoyi-ui-vue3/src/views/project/manage/composables/useProjectCollaboration.ts +++ b/ruoyi-ui-vue3/src/views/project/manage/composables/useProjectCollaboration.ts @@ -4,6 +4,7 @@ import { ElMessage, ElMessageBox } from 'element-plus' import useUserStore from '@/store/modules/user' import { api, errorText, isAccessFailure } from '../api' import { plannedDate, planBoundary } from '../shared/utils/time' +import { typeNames } from '../shared/constants/labels' import { reconcileRows, retainSnapshot } from '../shared/utils/snapshot' import type { Project, Member, WorkItem, ItemType, Lifecycle, FlowView, Iteration, ItemQuery } from '../types' import { iterationReadOnly, iterationCanExecute } from '../features/iterations/utils/scope' @@ -100,6 +101,8 @@ export function useProjectCollaboration() { const statCards = computed(() => [{ label: '全部工作项', value: statistics.value.total || 0 }, { label: '进行中', value: statistics.value.inProgress || 0 }, { label: '已完成', value: statistics.value.completed || 0 }, { label: '关闭', value: statistics.value.closed || 0 }, { label: '超期未完成', value: statistics.value.overdue || 0 }, { label: '实际前置阻塞', value: statistics.value.blocked || 0 }, { label: '排期未完成', value: statistics.value.scheduleIncomplete || 0 }]) let refreshSequence = 0, workspaceSequence = 0, navigationSequence = 0, iterationSequence = 0, initializationSequence = 0 + // 批量写入绑定业务范围,不能使用会随详情深链接变化的 navigationSequence。 + let scopeSequence = 0 let timer: ReturnType | undefined let active = true, initialized = false, initializing = false, restoringRoute = false let polling = false, applyingBackgroundMembers = false @@ -167,6 +170,17 @@ export function useProjectCollaboration() { return { view, page: page.value, pageSize, keyword: keyword.value, type: typeFilter.value, blockedOnly: blockedOnly.value, stageId: stageFilter.value, ...(view === 'gantt' ? { from: ganttFrom.value, to: ganttTo.value, memberIds: [...ganttMemberIds.value] } : {}) } } + /** 导出沿用甘特的完整服务端筛选,但独立从第一页读取,翻页不改变导出范围。 */ + const ganttExportQuery = computed(() => ({ ...query('gantt'), page: 1, pageSize: 200 })) + /** 文件中记录本次筛选含义,成员多选仍按负责人或协作人命中任一成员计算。 */ + const ganttExportFilters = computed(() => [ + keyword.value.trim() ? `标题:${keyword.value.trim()}` : '', + typeFilter.value ? `类型:${typeNames[typeFilter.value]}` : '全部类型', + blockedOnly.value ? '仅看依赖阻塞' : '', + stageFilter.value == null ? '全部阶段' : stageFilter.value === 0 ? '未分配阶段' : `阶段:${flowView.value?.stages.find(stage => stage.id === stageFilter.value)?.stagePath || flowView.value?.stages.find(stage => stage.id === stageFilter.value)?.name || stageFilter.value}`, + ganttMemberIds.value.length ? `成员:${ganttMemberIds.value.map(id => members.value.find(member => member.userId === id)?.name || `用户 #${id}`).join('、')}` : '全部成员', + ].filter(Boolean).join(';')) + /** 用户主动刷新或业务操作完成时显示加载状态;独立包装避免分页事件的页码被当作后台标志。 */ async function refresh() { await refreshData(false) @@ -257,6 +271,7 @@ export function useProjectCollaboration() { /** 清空旧范围数据与所有未提交输入,切回原迭代也不能恢复旧请求。 */ function clearScope() { + scopeSequence++ refreshSequence++ navigationSequence++ iterationSequence++ @@ -377,11 +392,12 @@ export function useProjectCollaboration() { editorOpen.value = true } - /** 保存后打开同迭代最新详情。 */ + /** 保存后只在原导航范围打开详情;刷新期间切换迭代或离页后不恢复旧工作项。 */ async function saved(id: number) { + const navigation = navigationSequence editorOpen.value = false await refresh() - detailId.value = id + if (active && navigation === navigationSequence && current.value) detailId.value = id } /** 预计时间仅展示北京时间日期,模型保留既有时间精度。 */ @@ -402,15 +418,19 @@ export function useProjectCollaboration() { } finally { busy.value = false } } - /** 逐项开始明确报告部分成功,整批提交期间暂停轮询,范围切换后停止继续提交。 */ + /** + * 逐项开始并报告部分成功,提交期间暂停轮询;项目或迭代范围变化即停止后续提交。 + * 不能仅比较迭代 ID:切到其他迭代再返回时,旧批次也已失效,不应恢复后台写入。 + * 同迭代内仅打开或关闭详情不会改变业务范围,仍应完成本次已选批次并报告结果。 + */ async function startSelection() { if (!canExecute.value || busy.value) return busy.value = true - const iteration = iterationId.value, errors: string[] = [] + const scope = scopeSequence, errors: string[] = [] let succeeded = 0 try { for (const item of [...selection.value]) { - if (iteration !== iterationId.value || !canExecute.value) break + if (!active || scope !== scopeSequence || !canExecute.value) break try { await api.start(item.id, item.version) succeeded++ @@ -418,7 +438,9 @@ export function useProjectCollaboration() { errors.push(`${item.title}:${errorText(error)}`) } } + if (!active || scope !== scopeSequence) return await refresh() + if (!active || scope !== scopeSequence) return ElMessage({ type: errors.length ? 'warning' : 'success', message: `已开始 ${succeeded} 项${errors.length ? `\n${errors.join('\n')}` : ''}`, duration: 10000 }) } finally { busy.value = false } } @@ -570,6 +592,7 @@ export function useProjectCollaboration() { onDeactivated(() => { active = false + scopeSequence++ if (timer) clearInterval(timer) timer = undefined refreshSequence++ @@ -588,6 +611,7 @@ export function useProjectCollaboration() { onBeforeUnmount(() => { active = false + scopeSequence++ if (timer) clearInterval(timer) refreshSequence++ workspaceSequence++ @@ -601,7 +625,7 @@ export function useProjectCollaboration() { items, members, flowView, current, selectedIteration, zone, canWrite, canCreate, canExecute, loading, failure, tab, keyword, typeFilter, blockedOnly, stageFilter, detailId, refreshKey, selection, editing, editorOpen, creatingParent, defaultStageId, page, pageSize, total, boardCounts, - ganttFrom, ganttTo, ganttMemberIds, membersOpen, inviteUser, inviteRole, userCandidates, batchOpen, + ganttFrom, ganttTo, ganttMemberIds, ganttExportQuery, ganttExportFilters, membersOpen, inviteUser, inviteRole, userCandidates, batchOpen, notifications, statCards, userStore, refreshWorkspace, refresh, loadBoardMore, moveGanttWindow, changeIteration, iterationsChanged, archiveFilterChanged, openNotice, diff --git a/ruoyi-ui-vue3/src/views/project/manage/features/iterations/components/IterationControls.vue b/ruoyi-ui-vue3/src/views/project/manage/features/iterations/components/IterationControls.vue index 7acfe82..dec3bc4 100644 --- a/ruoyi-ui-vue3/src/views/project/manage/features/iterations/components/IterationControls.vue +++ b/ruoyi-ui-vue3/src/views/project/manage/features/iterations/components/IterationControls.vue @@ -5,15 +5,17 @@ {{ iterationStatusNames[selected.status] }}{{ selected.archivedAt ? ' · 已归档' : '' }} {{ selected.finishResult === 'COMPLETED' ? '正常完成' : '带异常结束' }} 新建迭代 - 迭代操作 @@ -71,7 +71,7 @@ + diff --git a/ruoyi-ui-vue3/src/views/project/manage/views/flow/components/FlowSectionNode.vue b/ruoyi-ui-vue3/src/views/project/manage/views/flow/components/FlowSectionNode.vue new file mode 100644 index 0000000..714132a --- /dev/null +++ b/ruoyi-ui-vue3/src/views/project/manage/views/flow/components/FlowSectionNode.vue @@ -0,0 +1,33 @@ + + + diff --git a/ruoyi-ui-vue3/src/views/project/manage/views/flow/components/FlowStageNode.vue b/ruoyi-ui-vue3/src/views/project/manage/views/flow/components/FlowStageNode.vue index 7601d69..207fc3f 100644 --- a/ruoyi-ui-vue3/src/views/project/manage/views/flow/components/FlowStageNode.vue +++ b/ruoyi-ui-vue3/src/views/project/manage/views/flow/components/FlowStageNode.vue @@ -1,7 +1,7 @@ diff --git a/ruoyi-ui-vue3/src/views/project/manage/views/gantt/composables/useGanttViewport.ts b/ruoyi-ui-vue3/src/views/project/manage/views/gantt/composables/useGanttViewport.ts new file mode 100644 index 0000000..9288d8f --- /dev/null +++ b/ruoyi-ui-vue3/src/views/project/manage/views/gantt/composables/useGanttViewport.ts @@ -0,0 +1,85 @@ +import { nextTick, onActivated, onBeforeUnmount, onDeactivated, onMounted, ref, type Ref } from 'vue' + +/** + * 根据滚动区真实位置分配高度,避免顶部换行、页面缩放和系统页签高度变化遮住横向滚动条。 + * @param element 甘特唯一的双向滚动容器 + * @returns 最大可用高度;内容较少时仍自然收缩,不改变滚动位置 + * 只监听当前工作区,尺寸回调通过一帧合并;卸载时释放全部监听及观察器。 + */ +export function useGanttViewport(element: Ref) { + const maxHeight = ref(320) + let observer: ResizeObserver | undefined, mutations: MutationObserver | undefined, frame = 0, disposed = false, active = true + let host: HTMLElement | null = null + + /** 统一使用可视坐标,CSS 缩放时转换回布局像素;分页、容器边距与系统页脚均留在滚动区外。 */ + function measure() { + frame = 0 + const scroll = element.value + if (!scroll || disposed || !active) return + const rect = scroll.getBoundingClientRect() + if (!rect.width || !scroll.offsetWidth) return + const scale = rect.width / scroll.offsetWidth + const viewport = window.visualViewport + let bottom = viewport ? viewport.offsetTop + viewport.height : window.innerHeight + if (host) { + const bounds = host.getBoundingClientRect(), style = getComputedStyle(host) + bottom = Math.min(bottom, bounds.top + host.clientHeight * scale - (parseFloat(style.paddingBottom) || 0) * scale) + } + const surface = scroll.closest('.work-surface') + const pagination = surface?.querySelector('.work-pagination') + const footer = pagination ? pagination.getBoundingClientRect().height / scale + (parseFloat(getComputedStyle(pagination).marginTop) || 0) : 0 + const height = Math.max(80, Math.floor((bottom - Math.max(0, rect.top)) / scale - footer - 20)) + if (height !== maxHeight.value) maxHeight.value = height + } + + /** 尺寸及外层滚动事件可能同帧触发多次,只安排一次测量,避免 ResizeObserver 内同步写布局。 */ + function scheduleMeasure() { + if (active && !disposed && !frame) frame = window.requestAnimationFrame(measure) + } + + /** + * 页面有 min-height 时,筛选换行可能只挤占留白,整页尺寸不变;因此也观察前置兄弟和甘特提示区。 + * 直接子节点增删后重建目标集合,避免错误提示或分页新出现时继续沿用旧位置。 + */ + function observeLayout() { + const scroll = element.value, workspace = scroll?.closest('.pm-app') + if (!observer || !scroll) return + observer.disconnect() + for (const target of new Set([host, workspace, scroll.parentElement, ...(workspace?.children || [])])) { + if (target) observer.observe(target) + } + scheduleMeasure() + } + + onMounted(() => { + host = element.value?.closest('.app-main') || null + void nextTick(scheduleMeasure) + window.addEventListener('resize', scheduleMeasure) + host?.addEventListener('scroll', scheduleMeasure, { passive: true }) + window.visualViewport?.addEventListener('resize', scheduleMeasure) + window.visualViewport?.addEventListener('scroll', scheduleMeasure) + if (typeof ResizeObserver !== 'undefined' && element.value) { + observer = new ResizeObserver(scheduleMeasure) + observeLayout() + const workspace = element.value.closest('.pm-app') + if (workspace && typeof MutationObserver !== 'undefined') { + mutations = new MutationObserver(observeLayout) + mutations.observe(workspace, { childList: true }) + } + } + }) + // KeepAlive 停用期间不计算脱离页面的尺寸;返回后即使外层尺寸未变化也重新测量。 + onActivated(() => { active = true; void nextTick(scheduleMeasure) }) + onDeactivated(() => { active = false; window.cancelAnimationFrame(frame); frame = 0 }) + onBeforeUnmount(() => { + disposed = true + observer?.disconnect() + mutations?.disconnect() + window.cancelAnimationFrame(frame) + window.removeEventListener('resize', scheduleMeasure) + host?.removeEventListener('scroll', scheduleMeasure) + window.visualViewport?.removeEventListener('resize', scheduleMeasure) + window.visualViewport?.removeEventListener('scroll', scheduleMeasure) + }) + return maxHeight +} diff --git a/ruoyi-ui-vue3/src/views/project/manage/views/gantt/utils/exportData.ts b/ruoyi-ui-vue3/src/views/project/manage/views/gantt/utils/exportData.ts new file mode 100644 index 0000000..98a6fc2 --- /dev/null +++ b/ruoyi-ui-vue3/src/views/project/manage/views/gantt/utils/exportData.ts @@ -0,0 +1,41 @@ +import { api } from '../../../api' +import type { ItemQuery, WorkItem } from '../../../types' + +/** + * 读取当前筛选的全部分页,不把页面当前页误当作完整甘特图。 + * @param projectId 已选协作项目,所有请求继续经过原鉴权接口 + * @param iterationId 已选迭代,不跨迭代汇总 + * @param query 本次点击时的筛选快照,页码由导出独立管理 + * @param isCurrent 页面、迭代或筛选变化后返回 false,停止续页及文件生成 + * @returns 图版本一致的阶段与工作项;读取失败或版本变化时整次失败,不交付部分结果 + */ +export async function collectGanttData(projectId: number, iterationId: number, query: ItemQuery, isCurrent: () => boolean) { + const filter = { ...query, memberIds: [...(query.memberIds || [])], view: 'gantt' as const } + checkScope() + const graph = await api.flowView(projectId, iterationId) + checkScope() + const items: WorkItem[] = [], ids = new Set() + let total = 0 + for (let page = 1; ; page++) { + checkScope() + const result = await api.items(projectId, iterationId, { ...filter, page, pageSize: 200 }) + checkScope() + if (result.graphVersion !== graph.graphVersion || page > 1 && result.total !== total) throw new Error('导出期间排期数据发生变化,请重新导出') + total = result.total + if (total > 10000) throw new Error('匹配工作项超过 10000 项,请缩小时间或筛选范围后导出') + for (const item of result.rows) { + if (ids.has(item.id)) throw new Error('导出期间分页数据发生变化,请重新导出') + ids.add(item.id); items.push(item) + } + if (items.length === total) break + if (!result.rows.length || items.length > total) throw new Error('导出数据不完整,请刷新后重试') + } + // 最后一页完成后再走一次鉴权与图版本检查;不把两次修改前后的分页拼成一张图。 + const latest = await api.items(projectId, iterationId, { ...filter, page: 1, pageSize: 1 }) + checkScope() + if (latest.graphVersion !== graph.graphVersion || latest.total !== total) throw new Error('导出期间排期数据发生变化,请重新导出') + return { items, stages: graph.stages } + + /** 即使切走后又返回相同迭代,调用方的代次检查也会使旧导出失效。 */ + function checkScope() { if (!isCurrent()) throw new Error('导出范围已切换') } +} diff --git a/ruoyi-ui-vue3/src/views/project/manage/views/gantt/utils/exportImage.ts b/ruoyi-ui-vue3/src/views/project/manage/views/gantt/utils/exportImage.ts new file mode 100644 index 0000000..3704155 --- /dev/null +++ b/ruoyi-ui-vue3/src/views/project/manage/views/gantt/utils/exportImage.ts @@ -0,0 +1,135 @@ +import { itemStatusLabel, stageStatusLabel, typeNames } from '../../../shared/constants/labels' +import { plannedDate, visualMillis } from '../../../shared/utils/time' +import type { TimelineRow } from './timeline' + +export type GanttExportFormat = 'png' | 'svg' +export interface GanttImage { svg: string; width: number; height: number } +interface ImageInput { + rows: TimelineRow[] + minimum: number + days: number + zone: string + projectName: string + iterationName: string + filters: string +} + +/** 用户名称仅作为 SVG 文本,移除 XML 禁止字符并转义标记,不能产生脚本、链接或外部资源引用。 */ +function xml(value: string): string { + return value.replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f\ufffe\uffff]/g, '').replace(/[&<>"']/g, char => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[char]!) +} + +/** 按中英文近似字宽拆行,不省略长名称;行高随拆行增长,导出不依赖屏幕上的省略号或裁切。 */ +function wrap(value: string, units: number): string[] { + const lines: string[] = [] + let line = '', length = 0 + for (const char of value.replace(/\s+/g, ' ')) { + const size = char.charCodeAt(0) > 255 ? 2 : 1 + if (length + size > units && line) { lines.push(line); line = ''; length = 0 } + line += char; length += size + } + lines.push(line) + return lines +} + +/** SVG 基础文本保持固定字体和浅色底,导出不受用户暗黑主题影响;所有可变内容先转义。 */ +function text(x: number, y: number, value: string, size = 12, color = '#334155', weight = 400): string { + return `${xml(value)}` +} + +/** + * 从完整业务行生成独立矢量甘特,不截取 DOM,因此屏幕滚动、分页与设备像素比不会截断文件。 + * @param input 导出瞬间固定的标题、筛选、日期轴和完整行,预计日期仍按业务时区显示 + * @returns 不依赖外部字体、样式和图片的 SVG 及逻辑尺寸;参考计划仅作虚线标识 + */ +export function createGanttImage(input: ImageInput): GanttImage { + const { rows, minimum, days, zone } = input + const unit = 34, dayMs = 86400000, padding = 16, labelWidth = 370, statusWidth = 130 + const timelineX = padding + labelWidth + statusWidth, timelineWidth = days * unit, width = timelineX + timelineWidth + padding + const titleLines = wrap(`${input.projectName} / ${input.iterationName} · 甘特排期`, Math.floor((width - 32) / 11)) + const filters = wrap(`筛选:${input.filters || '全部'};工作项 ${rows.filter(row => row.item).length} 项`, Math.floor((width - 32) / 7)) + const layout = rows.map(row => { + const prefix = row.stage ? `${row.stage.stageKind === 'GROUP' ? '阶段组' : '阶段'} · ` : `${row.item?.parentTaskId ? '子任务' : typeNames[row.item!.type]} #${row.item!.id} · ` + const name = prefix + row.label + (row.stage ? ` · v${row.stage.revisionNo || 1}` : '') + const indent = Math.min(row.depth || 0, 8) * 16 + const lines = wrap(name, Math.floor((labelWidth - indent - 20) / 7)) + return { row, name, indent, lines, height: Math.max(74, lines.length * 18 + 50) } + }) + const headerTop = 78 + titleLines.length * 26 + filters.length * 18 + const bodyTop = headerTop + 34, height = bodyTop + layout.reduce((sum, row) => sum + row.height, 0) + 24 + const output = [`${xml(`${input.projectName} / ${input.iterationName} 甘特排期`)}`] + titleLines.forEach((line, i) => output.push(text(padding, 30 + i * 26, line, 20, '#0f172a', 600))) + let y = 38 + titleLines.length * 26 + output.push(text(padding, y, `日期:${plannedDate(new Date(minimum).toISOString(), zone)} — ${plannedDate(new Date(minimum + days * dayMs - 1).toISOString(), zone)}`)) + filters.forEach((line, i) => output.push(text(padding, y + 22 + i * 18, line))) + output.push(text(padding, headerTop - 12, '蓝色:有效计划 橙色:前置阻塞 虚线:参考计划(未生效)', 11, '#64748b')) + output.push(``, text(padding + 8, headerTop + 22, '阶段 / 工作项 · 日期 · 负责人', 12, '#334155', 600), text(padding + labelWidth + 8, headerTop + 22, '状态', 12, '#334155', 600)) + for (let day = 0; day < days; day++) output.push(text(timelineX + day * unit + 2, headerTop + 22, plannedDate(new Date(minimum + day * dayMs).toISOString(), zone).slice(5), 10)) + y = bodyTop + for (const entry of layout) { + const { row, height: rowHeight, indent, lines, name } = entry + const source = (row.stage || row.item)!, reference = row.reference && !!row.start && !!row.end + const date = reference ? `参考:${plannedDate(row.start, zone)} → ${plannedDate(row.end, zone)}` : `${plannedDate(source.plannedStartAt, zone)} → ${plannedDate(source.plannedEndAt, zone)}` + output.push(`${xml(name)}`) + lines.forEach((line, index) => output.push(text(padding + 8 + indent, y + 19 + index * 18, line, 12, '#0f172a', row.stage ? 600 : 400))) + output.push(text(padding + 8 + indent, y + lines.length * 18 + 19, date, 11, reference ? '#b45309' : '#64748b')) + output.push(text(padding + 8 + indent, y + lines.length * 18 + 35, `负责人:${row.stage?.ownerName || row.item?.assigneeName || '未分配'}`, 11, '#64748b')) + const status = row.stage ? stageStatusLabel(row.stage) : itemStatusLabel(row.item!) + wrap(status, 16).forEach((line, index) => output.push(text(padding + labelWidth + 8, y + 23 + index * 18, line))) + if (reference) output.push(text(padding + labelWidth + 8, y + 46, source.scheduleReviewClosed ? '本轮未确认' : '排期待复核', 11, '#b45309')) + else if (!row.start || !row.end) output.push(text(padding + labelWidth + 8, y + 46, '排期未完成', 11, '#b45309')) + output.push(``) + if (row.start && row.end) { + // 只裁切时间条到当前日期窗口;左侧日期保持完整,不能改写或截断源排期。 + const startAt = visualMillis(row.start), endAt = visualMillis(row.end) + if (endAt >= minimum && startAt < minimum + days * dayMs && endAt >= startAt) { + const start = Math.min(timelineWidth - 1, Math.max(0, (startAt - minimum) / dayMs * unit)) + const end = Math.min(timelineWidth, (endAt - minimum) / dayMs * unit) + // 既有计划允许起止相等或相差不足毫秒;这些窗口内区间仍有标记,不能被当作窗口外计划丢弃。 + output.push(``) + } + } + output.push(``) + y += rowHeight + } + output.push('') + return { svg: output.join(''), width, height } +} + +/** PNG 尽量使用双倍像素;超过保守画布边长或总像素限制时明确拒绝,避免下载空白图或浏览器耗尽内存。 */ +export function pngScale(width: number, height: number): number { + const scale = Math.min(2, 8192 / width, 16384 / height, Math.sqrt(24_000_000 / (width * height))) + if (!Number.isFinite(scale) || scale < 1) throw new Error('当前甘特图过大,请选择 SVG 矢量图,或缩小时间和筛选范围后导出 PNG') + return scale +} + +/** + * SVG 直接下载;PNG 将同一份无外链 SVG 绘制到画布,确保两种格式具有相同内容。 + * @param image 已完成排版的独立图像 + * @param format 用户选择的图片格式 + * @returns 可下载文件;浏览器解码或编码失败时抛错,临时 URL 和画布像素始终释放 + */ +export async function ganttImageBlob(image: GanttImage, format: GanttExportFormat): Promise { + const svg = new Blob([image.svg], { type: 'image/svg+xml;charset=utf-8' }) + if (format === 'svg') return svg + const scale = pngScale(image.width, image.height), url = URL.createObjectURL(svg), canvas = document.createElement('canvas') + try { + const bitmap = new Image() + await new Promise((resolve, reject) => { bitmap.onload = () => resolve(); bitmap.onerror = () => reject(new Error('图片生成失败,请尝试 SVG 格式')); bitmap.src = url }) + canvas.width = Math.ceil(image.width * scale); canvas.height = Math.ceil(image.height * scale) + const context = canvas.getContext('2d') + if (!context) throw new Error('浏览器无法生成 PNG,请选择 SVG 格式') + context.drawImage(bitmap, 0, 0, canvas.width, canvas.height) + return await new Promise((resolve, reject) => canvas.toBlob(blob => blob ? resolve(blob) : reject(new Error('PNG 编码失败,请选择 SVG 格式')), 'image/png')) + } finally { URL.revokeObjectURL(url); canvas.width = 0; canvas.height = 0 } +} + +/** 文件名不携带路径或控制字符;点击后延迟释放 URL,给浏览器下载进程保留读取时间。 */ +export function downloadGanttImage(blob: Blob, name: string, format: GanttExportFormat): void { + const url = URL.createObjectURL(blob), anchor = document.createElement('a') + anchor.href = url + anchor.download = `${name.replace(/[<>:"/\\|?*\u0000-\u001f]/g, '_').slice(0, 140) || '甘特排期'}.${format}` + document.body.append(anchor) + try { anchor.click() } + finally { anchor.remove(); window.setTimeout(() => URL.revokeObjectURL(url), 10000) } +} diff --git a/ruoyi-ui-vue3/src/views/project/manage/views/gantt/utils/timeline.ts b/ruoyi-ui-vue3/src/views/project/manage/views/gantt/utils/timeline.ts new file mode 100644 index 0000000..a4a5ce6 --- /dev/null +++ b/ruoyi-ui-vue3/src/views/project/manage/views/gantt/utils/timeline.ts @@ -0,0 +1,57 @@ +import type { Stage, WorkItem } from '../../../types' + +export interface TimelineRow { + key: string + label: string + depth?: number + item?: WorkItem + stage?: Stage + start: string | null + end: string | null + reference: boolean +} + +/** 有效时间优先,参考时间必须作为整对使用;不把有效端点与参考端点拼成看似有效的计划。 */ +function timelineRow(key: string, label: string, source: Stage | WorkItem, stage: boolean): TimelineRow { + const normal = !!source.plannedStartAt && !!source.plannedEndAt + return { key, label, stage: stage ? source as Stage : undefined, item: stage ? undefined : source as WorkItem, start: normal ? source.plannedStartAt : source.referencePlannedStartAt || null, end: normal ? source.plannedEndAt : source.referencePlannedEndAt || null, reference: !normal } +} + +/** 不完整任务在界面顶部保留入口;只有完整有效或参考区间才绘制时间条。 */ +function hasRange(item: WorkItem) { + return !!(item.plannedStartAt && item.plannedEndAt || item.referencePlannedStartAt && item.referencePlannedEndAt) +} + +/** + * 屏幕与导出共用阶段层级和工作项顺序,成员筛选保留所属阶段的父路径。 + * @param items 已由服务端按当前筛选和权限过滤的工作项,不在此扩大查询范围 + * @param stages 当前迭代阶段摘要,组计划采用自身计划,不用子阶段包络代替 + * @param memberFiltered 是否只展示匹配成员所在的阶段 + * @param stageFilter 指定阶段或阶段组,0 表示未分配阶段 + * @param includeUnscheduled 导出时将未排期项纳入对应阶段,界面仍使用顶部未排期入口 + * @returns 不修改源数据的有序行,每个工作项最多出现一次 + */ +export function buildTimelineRows(items: WorkItem[], stages: Stage[], memberFiltered = false, stageFilter?: number | null, includeUnscheduled = false): TimelineRow[] { + const result: TimelineRow[] = [], known = new Set(stages.map(stage => stage.id)) + const visible = new Set(items.map(item => item.stageId).filter((id): id is number => !!id)) + if (stageFilter && !memberFiltered) { + visible.add(stageFilter) + for (const child of stages.filter(stage => stage.parentStageId === stageFilter)) visible.add(child.id) + } + for (const stage of stages) if (visible.has(stage.id) && stage.parentStageId) visible.add(stage.parentStageId) + for (const root of stages.filter(stage => !stage.parentStageId)) append(root, 0) + for (const item of items.filter(item => !item.stageId || !known.has(item.stageId))) { + if (includeUnscheduled || hasRange(item)) result.push(timelineRow('i:' + item.id, item.title, item, false)) + } + return result + + /** 父级先于子级展示,层级仅用于显示,不改变后端阶段门禁或改期入口。 */ + function append(stage: Stage, depth: number) { + if ((memberFiltered || stageFilter != null) && !visible.has(stage.id)) return + result.push({ ...timelineRow('s:' + stage.id, stage.name, stage, true), depth }) + for (const child of stages.filter(candidate => candidate.parentStageId === stage.id)) append(child, depth + 1) + for (const item of items.filter(item => item.stageId === stage.id)) { + if (includeUnscheduled || hasRange(item)) result.push({ ...timelineRow('i:' + item.id, item.title, item, false), depth: depth + 1 + (item.parentTaskId ? 1 : 0) }) + } + } +} diff --git a/ruoyi-ui-vue3/src/views/project/manage/views/workspace/ProjectWorkspace.vue b/ruoyi-ui-vue3/src/views/project/manage/views/workspace/ProjectWorkspace.vue index eba65a2..5457726 100644 --- a/ruoyi-ui-vue3/src/views/project/manage/views/workspace/ProjectWorkspace.vue +++ b/ruoyi-ui-vue3/src/views/project/manage/views/workspace/ProjectWorkspace.vue @@ -178,6 +178,11 @@ :to="ganttTo" :member-filtered="ganttMemberIds.length > 0" :stage-filter="stageFilter" + :export-query="ganttExportQuery" + :export-filters="ganttExportFilters" + :project-name="current.name" + :iteration-name="selectedIteration.name" + :loading="loading" :can-write="canWrite" :can-manage="canWrite && current.canManage" :project-id="current.id" @@ -299,7 +304,7 @@ const { items, members, flowView, current, selectedIteration, zone, canWrite, canCreate, canExecute, loading, failure, tab, keyword, typeFilter, blockedOnly, stageFilter, detailId, refreshKey, selection, editing, editorOpen, creatingParent, defaultStageId, page, pageSize, total, boardCounts, - ganttFrom, ganttTo, ganttMemberIds, membersOpen, inviteUser, inviteRole, userCandidates, batchOpen, + ganttFrom, ganttTo, ganttMemberIds, ganttExportQuery, ganttExportFilters, membersOpen, inviteUser, inviteRole, userCandidates, batchOpen, notifications, statCards, userStore, refreshWorkspace, refresh, loadBoardMore, moveGanttWindow, changeIteration, iterationsChanged, archiveFilterChanged, openNotice,