Merge remote-tracking branch 'origin/project' into project

This commit is contained in:
lixiaolong 2026-10-29 09:59:20 +08:00
commit b66157a291
45 changed files with 1312 additions and 165 deletions

View File

@ -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')
);
-- 阶段版本交付、人工完成审批及采购批次引用。

View File

@ -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;

View File

@ -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<String,Object> child(@PathVariable long id,@RequestBody JsonNode body) { return ok(service.createChild(id,decode(body,ChildInput.class))); }
/** 子任务列表在服务层复验项目成员权限与实时状态。 */
@GetMapping("/items/{id}/children") public Map<String,Object> children(@PathVariable long id) { return ok(service.children(id)); }
/** 普通编辑拒绝状态;省略 stageId 时保留归属及本次邮件选择,显式 null 才移到未分配。 */
/** 普通编辑拒绝状态注入,省略 stageId 时保留归属;阶段迁移须走管理者专用入口,显式 null 也不能绕过。 */
@PatchMapping("/items/{id}") public Map<String,Object> 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<String,Object> successors(@PathVariable long id) { return ok(service.successors(id)); }
/** 工作项评论受同一数据权限保护,并原子记录历史。 */
@PostMapping("/items/{id}/comments") public Map<String,Object> 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<String,Object> 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<String,Object> 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<String,Object> removeAttachment(@PathVariable long id,@PathVariable long attachmentId) { service.removeAttachment(id,attachmentId); return ok(null); }

View File

@ -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<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);}
/** 文件大小在读取字节之前校验;服务再次检查当前轮次、身份及实际内容长度。 */
/** 读取字节前按统一的 50MB 上限校验;服务再次检查当前轮次、身份及实际内容长度。 */
@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");
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()));
}
/** 人员显式确认沿用旧版交付,复制新对象且不继承审批通过。 */

View File

@ -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<String,Object> 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<String,Object> 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<String,Object> 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); }

View File

@ -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"; }

View File

@ -0,0 +1,4 @@
package com.ruoyi.project.manage.dto;
/** 画布快捷改名白名单;不接收类型、负责人、采购范围或排期,防止改名覆盖其他业务信息。 */
public record StageNameInput(String name, Integer version) { }

View File

@ -22,7 +22,13 @@ public interface PmDependencyMapper {
/** 版本不匹配必须拒绝覆盖;业务服务持有项目锁并在同一事务内记录历史。 */
default void updateDependency(long id,int version,Map<String,Object> values) { PmMapperWrite.requireUpdated(updateDependencyRow(id,version,values)); }
/** 加载任务前置边,供开始条件、排期及无环检查共用。 */
/**
* 加载当前有效后续项的前置边,供开始条件、排期、无环检查及阶段回退共用。
* 只排除已删除或历史轮次的后续项;已删除前置项的边仍需保留,以阻止有效后续项误判条件满足。
* @param projectId 已鉴权的协作项目 ID
* @param iterationId 当前校验的明确迭代 ID
* @return 当前图依赖;不删除原始依赖行,历史详情通过独立查询读取
*/
List<Map<String,Object>> selectGraphDependencies(@Param("projectId") long projectId,@Param("iterationId") long iterationId);
/** 历史工作项详情读取原始依赖行,不把旧边加载进当前执行图。 */

View File

@ -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<String,Object> 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.start()) || item.end()!=null&&(parent.end()==null||item.end()>parent.end())) {
// 子任务可以暂缺一个端点,但剩余端点仍必须同时遵守父任务的上下界。
// 仅比较开始对开始、结束对结束,会让单填结束落在父开始之前,或单填开始落在父结束之后。
boolean startOutside=item.start()!=null&&(parent.start()==null||item.start()<parent.start()||parent.end()!=null&&item.start()>parent.end());
boolean endOutside=item.end()!=null&&(parent.end()==null||item.end()>parent.end()||parent.start()!=null&&item.end()<parent.start());
if(startOutside||endOutside) {
conflict=true; reasons.add(map("code","PARENT_SCHEDULE_CONFLICT","sourceId",parent.id(),"sourceName",parent.title(),"message","子任务时间必须在父任务范围内,且对应父时间不能为空","plannedStartAt",PmTime.format(parent.start(),zone),"plannedEndAt",PmTime.format(parent.end(),zone)));
}
}

View File

@ -195,7 +195,7 @@ public interface IPmService {
void comment(long id,CommentInput input);
/**
* 附件存入 MinIO 私有对象,数据库仅保存元数据;限制为 10 MiB,业务回滚时补偿新对象。
* 附件存入 MinIO 私有对象,数据库仅保存元数据;限制为 50MB,业务回滚时补偿新对象。
*
* @param id 路径中的目标对象 ID;服务按当前身份校验维护或查看权限
* @param name 附件原始文件名,服务会校验和净化

View File

@ -3,6 +3,7 @@ package com.ruoyi.project.manage.service;
import com.ruoyi.project.manage.exception.PmException;
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;
@ -43,6 +44,8 @@ public interface IPmStageService {
* <p>副作用:按阶段版本修改组织元数据并原子保存历史/outbox。</p>
*/
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(); }

View File

@ -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("文件类型格式无效"); }

View File

@ -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,"文件类型");

View File

@ -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<String,Object> 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<String,Object> existing=stage(projectId,iterationId,id); version(input.version(),(int)number(existing,"version"));

View File

@ -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 时落入文件目录。 */

View File

@ -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
</select>

View File

@ -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`。
## 迭代操作
- 项目管理者在迭代工具栏直接编辑、开始、结束或删除当前迭代,更多操作使用点击菜单;普通成员不能管理迭代。归档及终态迭代的编辑入口禁用,可先取消归档或重新打开。
- 筹备迭代由管理者手动开始并记录实际开始时间;执行中由管理者预览、确认结束并记录实际结束时间,不根据预计日期自动切换状态。待开始或进行中的工作项阻止结束,取消工作项或未审批阶段须逐条确认异常并说明原因后才能带异常结束。
- 删除仅适用于从未执行且没有任何工作项或执行历史的筹备迭代,后端软删除并保留审计;已执行迭代通过结束、取消、归档保留历史。
## 甘特成员筛选
- 甘特排期的成员下拉支持多选当前项目成员;清空表示全部,多选按负责人或协作人任一匹配取并集,同一工作项只显示一次。

View File

@ -30,6 +30,8 @@ export const stageApi = {
removeStageEdge: (id: number, edgeId: number, version: number, iterationId?: number) => request<void>('delete', iterationPath(id, iterationId, `stage-edges/${edgeId}`), { version }),
/** 阶段元数据独立版本更新,不调整任务状态或排期。 */
editStage: (id: number, stageId: number, input: StageInput, iterationId?: number) => request<void>('patch', iterationPath(id, iterationId, `stages/${stageId}`), input),
/** 画布快捷改名只传名称及当前版本,不能借此改动交付数据或固定类型。 */
renameStage: (id: number, stageId: number, name: string, version: number, iterationId?: number) => request<void>('patch', iterationPath(id, iterationId, `stages/${stageId}/name`), { name, version }),
/** 非空阶段由后端拒绝;空阶段软删除保留历史。 */
removeStage: (id: number, stageId: number, version: number, iterationId?: number) => request<void>('delete', iterationPath(id, iterationId, `stages/${stageId}`), { version }),
}

View File

@ -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<typeof setInterval> | 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,

View File

@ -5,15 +5,17 @@
<el-tag v-if="selected" :type="readOnly ? 'info' : 'success'">{{ iterationStatusNames[selected.status] }}{{ selected.archivedAt ? ' · 已归档' : '' }}</el-tag>
<span v-if="selected?.finishResult" class="iteration-note">{{ selected.finishResult === 'COMPLETED' ? '正常完成' : '带异常结束' }}</span>
<el-button v-if="canManage" @click="openEditor()">新建迭代</el-button>
<el-dropdown v-if="selected && canManage"><el-button>迭代操作</el-button><template #dropdown><el-dropdown-menu>
<el-dropdown-item v-if="!readOnly" @click="openEditor(selected)">编辑迭代</el-dropdown-item>
<el-dropdown-item v-if="!selected.archivedAt && selected.status === 'PLANNED'" @click="simpleAction('activate')">开始迭代</el-dropdown-item>
<el-dropdown-item v-if="!selected.archivedAt && selected.status === 'ACTIVE'" @click="openPreview('finish')">结束迭代</el-dropdown-item>
<template v-if="selected && canManage">
<el-button :disabled="readOnly || busy" :title="readOnly ? '当前迭代只读;请先取消归档或重新打开,再编辑。' : '修改迭代名称、目标和计划日期'" @click="openEditor(selected)">编辑迭代</el-button>
<el-button v-if="!selected.archivedAt && selected.status === 'PLANNED'" type="primary" plain :disabled="busy" @click="simpleAction('activate')">开始迭代</el-button>
<el-button v-if="!selected.archivedAt && selected.status === 'ACTIVE'" type="primary" plain :disabled="busy" @click="openPreview('finish')">结束迭代</el-button>
<el-button type="danger" plain :disabled="!!deleteDisabledReason || busy" :title="deleteDisabledReason || '仅可删除没有工作项或执行历史的筹备迭代;阶段配置会保留在软删除记录中。'" @click="remove">删除迭代</el-button>
</template>
<el-dropdown v-if="selected && canManage" trigger="click"><el-button :disabled="busy">更多迭代操作 <el-icon><ArrowDown /></el-icon></el-button><template #dropdown><el-dropdown-menu>
<el-dropdown-item v-if="!readOnly" @click="openPreview('cancel')">取消迭代</el-dropdown-item>
<el-dropdown-item v-if="!selected.archivedAt && ['FINISHED', 'CANCELLED'].includes(selected.status)" @click="simpleAction('reopen')">重新打开</el-dropdown-item>
<el-dropdown-item v-if="!selected.archivedAt && ['FINISHED', 'CANCELLED'].includes(selected.status)" @click="simpleAction('archive')">归档</el-dropdown-item>
<el-dropdown-item v-if="selected.archivedAt" @click="simpleAction('unarchive')">取消归档</el-dropdown-item>
<el-dropdown-item v-if="selected.status === 'PLANNED' && !selected.archivedAt" @click="remove">删除空迭代</el-dropdown-item>
</el-dropdown-menu></template></el-dropdown>
<span v-if="readOnly && selected" class="iteration-note">当前迭代只读,可查看详情、历史与下载附件。</span>
<el-dialog :close-on-click-modal="false" v-model="editorOpen" :title="editing ? '编辑迭代' : '新建迭代'" width="min(600px, 95%)" append-to-body>
@ -39,6 +41,7 @@
<script setup lang="ts">
import { computed, reactive, ref, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ArrowDown } from '@element-plus/icons-vue'
import { api, errorText } from '../../../api'
import type { Iteration, IterationInput, IterationAction, IterationPreview, Lifecycle } from '../../../types'
import { iterationStatusNames, statusNames } from '../../../shared/constants/labels'
@ -49,6 +52,8 @@ import { createIdempotencyKey } from '../../../shared/utils/idempotency'
const props = defineProps<{ projectId: number; iterationId: number | null; iterations: Iteration[]; canManage: boolean; includeArchived: boolean }>()
const emit = defineEmits<{ select: [id: number]; changed: [id?: number]; 'archive-filter': [include: boolean] }>()
const selected = computed(() => props.iterations.find(row => row.id === props.iterationId)), readOnly = computed(() => iterationReadOnly(selected.value))
// 状态不允许删除时保留入口并解释原因;工作项和历史是否为空仍由后端事务内核验。
const deleteDisabledReason = computed(() => selected.value?.archivedAt ? '归档迭代不能删除,请先取消归档。' : selected.value?.status !== 'PLANNED' ? '仅从未执行的筹备迭代可以删除;已执行迭代请结束或归档保留历史。' : '')
const editorOpen = ref(false), editing = ref<Iteration | null>(null), busy = ref(false), failure = ref(''), invalidStart = ref(false), invalidEnd = ref(false)
const draft = reactive<IterationInput>({ code: '', name: '', goal: '', plannedStartAt: null, plannedEndAt: null, sortOrder: 0, sourceIterationId: null })
const previewOpen = ref(false), previewAction = ref<'finish' | 'cancel'>('finish'), preview = ref<IterationPreview | null>(null), accepted = ref<string[]>([]), reason = ref(''), requestKey = ref('')
@ -62,21 +67,22 @@ function openEditor(row?: Iteration) { editing.value = row || null; Object.assig
async function save() { const token = sequence; busy.value = true; failure.value = ''; try { const input = { ...draft, ...(editing.value ? editedPlannedRange(draft.plannedStartAt, draft.plannedEndAt, editing.value.plannedStartAt, editing.value.plannedEndAt) : plannedRange(draft.plannedStartAt, draft.plannedEndAt)), idempotencyKey: requestKey.value }; if (input.sourceIterationId) input.sourceGraphVersion = (await api.iteration(props.projectId, input.sourceIterationId)).graphVersion; const result = editing.value ? await api.editIteration(props.projectId, editing.value.id, input) : await api.createIteration(props.projectId, input); if (token === sequence) { if (result.copyWarnings?.length) ElMessage.warning(result.copyWarnings.map(warning => warning.message).join('\n')); editorOpen.value = false; emit('changed', result.id) } } catch (error) { if (token === sequence) failure.value = errorText(error) } finally { busy.value = false } }
/** 所有动作包含元数据及图版本和兼容 HTTP 的幂等键,拒绝时不修改本地生命周期。 */
function actionInput(row: Iteration): IterationAction { return { version: row.version, graphVersion: row.graphVersion, idempotencyKey: createIdempotencyKey() } }
/** 开始、重开和归档展示具体确认,确认后以服务端状态刷新。 */
async function simpleAction(action: 'activate' | 'reopen' | 'archive' | 'unarchive') { const row = selected.value; if (!row) return; const token = sequence, projectId = props.projectId; const labels = { activate: '开始迭代', reopen: '重新打开迭代', archive: '归档迭代', unarchive: '取消归档' }; try { await ElMessageBox.confirm(`${labels[action]}“${row.name}”?`, labels[action], { closeOnClickModal: false }); const latest = await api.iteration(projectId, row.id); if (token !== sequence) return; await api.iterationAction(projectId, row.id, action, { ...actionInput(row), graphVersion: latest.graphVersion }); if (token === sequence) emit('changed', row.id) } catch (error) { if (error !== 'cancel' && error !== 'close') ElMessage.error(errorText(error)) } }
/** 开始、重开和归档须明确确认;确认期间暂停同步及重复操作,切换迭代后忽略旧请求回调。 */
async function simpleAction(action: 'activate' | 'reopen' | 'archive' | 'unarchive') { const row = selected.value; if (!row || busy.value) return; const token = sequence, projectId = props.projectId; const labels = { activate: '开始迭代', reopen: '重新打开迭代', archive: '归档迭代', unarchive: '取消归档' }; busy.value = true; try { await ElMessageBox.confirm(`${labels[action]}“${row.name}”?`, labels[action], { closeOnClickModal: false }); if (token !== sequence) return; const latest = await api.iteration(projectId, row.id); if (token !== sequence) return; await api.iterationAction(projectId, row.id, action, { ...actionInput(row), graphVersion: latest.graphVersion }); if (token === sequence) emit('changed', row.id) } catch (error) { if (token === sequence && error !== 'cancel' && error !== 'close') ElMessage.error(errorText(error)) } finally { busy.value = false } }
/** 结束和取消先生成兼容 HTTP 的预览请求键并取得完整影响清单,预览与提交沿用同一键。 */
async function openPreview(action: 'finish' | 'cancel') { const row = selected.value; if (!row) return; const token = sequence; busy.value = true; failure.value = ''; preview.value = null; accepted.value = []; reason.value = ''; previewAction.value = action; requestKey.value = createIdempotencyKey(); previewOpen.value = true; try { const result = await api.previewIteration(props.projectId, row.id, action, { ...actionInput(row), idempotencyKey: requestKey.value }); if (token === sequence) preview.value = result } catch (error) { if (token === sequence) failure.value = errorText(error) } finally { busy.value = false } }
/** 异常必须逐条显式确认,取消勾选会立即阻止带异常结束。 */
function toggleException(key: string, checked: boolean) { accepted.value = checked ? [...new Set([...accepted.value, key])] : accepted.value.filter(value => value !== key) }
/** 提交与预览一致的版本和确认清单;取消清单在服务端同事务重新比对。 */
async function commitPreview() { const row = selected.value, result = preview.value; if (!row || !result || !canCommit.value) return; const token = sequence; busy.value = true; failure.value = ''; try { await api.iterationAction(props.projectId, row.id, previewAction.value, { version: result.version, graphVersion: result.graphVersion, idempotencyKey: requestKey.value, reason: reason.value, acceptedExceptionIds: accepted.value, acceptedItemIds: previewAction.value === 'cancel' ? result.itemsToCancel.map(item => item.id) : [] }); if (token === sequence) { previewOpen.value = false; emit('changed', row.id) } } catch (error) { if (token === sequence) { failure.value = errorText(error); preview.value = null } } finally { busy.value = false } }
/** 删除仅允许空迭代并由后端核验;软删除保留审计记录。 */
async function remove() { const row = selected.value; if (!row) return; try { await ElMessageBox.confirm(`删除空迭代“${row.name}”?存在工作项或执行历史时将拒绝。`, '删除空迭代', { type: 'warning', closeOnClickModal: false }); await api.deleteIteration(props.projectId, row.id, actionInput(row)); emit('changed') } catch (error) { if (error !== 'cancel' && error !== 'close') ElMessage.error(errorText(error)) } }
/** 删除空筹备迭代由后端核验并软删除;确认期间暂停同步,切换范围后不发旧请求或刷新新迭代。 */
async function remove() { const row = selected.value; if (!row || deleteDisabledReason.value || busy.value) return; const token = sequence, projectId = props.projectId; busy.value = true; try { await ElMessageBox.confirm(`删除筹备迭代“${row.name}”?存在工作项或执行历史时将拒绝;通过后软删除并保留记录。`, '删除迭代', { type: 'warning', closeOnClickModal: false }); if (token !== sequence) return; await api.deleteIteration(projectId, row.id, actionInput(row)); if (token === sequence) emit('changed') } catch (error) { if (token === sequence && error !== 'cancel' && error !== 'close') ElMessage.error(errorText(error)) } finally { busy.value = false } }
defineExpose({ isEditing: computed(() => editorOpen.value || previewOpen.value || busy.value) })
</script>
<style scoped>.iteration-controls{display:flex;gap:8px;align-items:center;flex-wrap:wrap;margin-bottom:10px}
/* 组件 DOM 和状态类由运行时生成;按 class token 匹配保持原选择器的含义和优先级,避免 IDE 静态模板匹配误报。 */
.iteration-controls>[class~="el-select"]{width:250px}.iteration-note{font-size:12px;color:var(--el-text-color-secondary)}
.iteration-controls :deep(.el-button+.el-button){margin-left:0}
.el-form [class~="el-select"]{width:100%}
.el-dialog [class~="el-checkbox"]{display:block;height:auto;white-space:normal;margin:10px 0}
[class~="el-textarea"]{margin-top:12px}</style>

View File

@ -12,7 +12,7 @@
<el-input v-if="canManage" v-model="reason" size="small" class="batch-reason" maxlength="2000" placeholder="调整说明(已开始阶段改期必填)" />
</el-tab-pane>
<el-tab-pane :label="`工作项排期 · ${itemRows.length}`" name="items">
<p class="note">已载入 {{ itemRows.length }} 个可编辑工作项;单次最多处理 500 个对象。已完成阶段的工作项只读。</p>
<p class="note">已载入 {{ itemRows.length }} 个可编辑工作项;单次最多处理 500 个对象。待审批或已完成阶段的工作项只读。</p>
<el-table v-loading="loading" :data="itemRows" size="small" max-height="420">
<el-table-column label="工作项" min-width="200" class-name="business-control-cell"><template #default="{ row }">{{ row.name }}<el-tag v-if="row.pending" size="small" type="warning">待复核</el-tag><el-checkbox v-if="row.pending" v-model="row.confirm" size="small">确认参考计划</el-checkbox></template></el-table-column>
<el-table-column label="预计开始" min-width="180"><template #default="{ row }"><TimeField boundary="start" v-model="row.plannedStartAt" zone="Asia/Shanghai" /></template></el-table-column>
@ -53,8 +53,11 @@ watch(() => [props.visible, props.projectId, props.iterationId], async () => {
} catch (error) { if (request === sequence) failure.value = errorText(error) }
finally { if (request === sequence) loading.value = false }
}, { immediate: true })
/** 只有当前未完成阶段允许改期,补录必须使用专门入口。 */
function frozen(stageId?: number | null) { return ['COMPLETED', 'LEGACY_PASSED'].includes(stages.value.find(stage => stage.id === stageId)?.executionStatus || '') }
/** 待审批交付与已完成阶段均冻结排期,避免让用户编辑后整批才被后端拒绝;补录仍使用专门入口。 */
function frozen(stageId?: number | null) {
const stage = stages.value.find(stage => stage.id === stageId)
return stage?.approvalStatus === 'PENDING' || ['COMPLETED', 'LEGACY_PASSED'].includes(stage?.executionStatus || '')
}
/** 参考只作为输入初值;未修改也未勾选的复核行绝不会被隐式确认。 */
function draft(id: number, version: number, name: string, source: Pick<WorkItem, 'plannedStartAt' | 'plannedEndAt' | 'referencePlannedStartAt' | 'referencePlannedEndAt' | 'scheduleReviewRequired'>): Draft {
const start = source.plannedStartAt ?? source.referencePlannedStartAt ?? null, end = source.plannedEndAt ?? source.referencePlannedEndAt ?? null
@ -66,7 +69,7 @@ async function loadMore() {
try {
const result = await api.items(props.projectId, props.iterationId, { view: 'flat', page: nextPage, pageSize: 100 })
if (request !== sequence) return
itemRows.value.push(...result.rows.filter(item => !item.historical && !item.scheduleReviewClosed && !frozen(item.stageId)).map(item => draft(item.id, item.version, item.title, item)))
itemRows.value.push(...result.rows.filter(item => !item.historical && !item.stageReadOnly && !item.scheduleReviewClosed && !frozen(item.stageId)).map(item => draft(item.id, item.version, item.title, item)))
loadedCount.value += result.rows.length; itemTotal.value = result.total; page = nextPage
} catch (error) { if (request === sequence) failure.value = errorText(error) }
finally { if (request === sequence) loading.value = false }

View File

@ -16,7 +16,7 @@
<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>
<span class="muted">MinIO私有存储,单个文件最多{{ ATTACHMENT_MAX_SIZE_LABEL }}</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>
@ -62,6 +62,7 @@ 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 { ATTACHMENT_MAX_BYTES, ATTACHMENT_MAX_SIZE_LABEL } from '../../../shared/constants/attachments'
import type { Stage, StageApproval, StageApprovalStatus, StageCompletion, StageCompletionCommand, StageDeliveryAttachment, StageDeliverySnapshot as DeliverySnapshot } from '../../../types'
import PurchaseBatchPicker from './PurchaseBatchPicker.vue'
import StageDeliverySnapshot from './StageDeliverySnapshot.vue'
@ -124,11 +125,11 @@ async function refresh() {
if (dirty.value) { try { await ElMessageBox.confirm('刷新将放弃尚未保存的交付说明或采购范围,是否继续?', '刷新阶段交付', { closeOnClickModal: false, type: 'warning' }) } catch { return } }
await load(true)
}
/** 原生文件输入只交给模块客户端,不能生成公开MinIO地址或本地路径。 */
/** 按协作统一的 50MB 上限检查文件后交给模块客户端,不生成公开 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 }
if (!file.size || file.size > ATTACHMENT_MAX_BYTES) { failure.value = `附件需为1字节至${ATTACHMENT_MAX_SIZE_LABEL}`; return }
void mutate(() => api.uploadStageAttachment(props.projectId, props.iterationId, props.stage.id, input().revisionId, file))
}
/** 软删确认不会销毁历史对象,取消确认不触发后端操作。 */

View File

@ -37,6 +37,7 @@ import PurchaseBatchPicker from './PurchaseBatchPicker.vue'
import type { Stage, StageInput, Member, FlowView, PurchaseBatchProgress } from '../../../types'
import { stageNodeTypeLabel } from '../../../shared/constants/stageNodeTypes'
import { stageStatusLabel } from '../../../shared/constants/labels'
import { stageDeleteBlockedReason } from '../utils/actions'
const props = defineProps<{ visible: boolean; projectId: number; iterationId?: number; stages: Stage[]; members: Member[]; view?: FlowView }>()
const emit = defineEmits<{ close: []; changed: [] }>()
const structureOpen = ref(false)
@ -55,29 +56,13 @@ async function open(stage: Stage) {
}
/** 保存经经理鉴权与阶段版本校验的元数据,失败保留草稿。 */
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 } }
/**
* 根据服务端的历史与当前执行状态判断是否曾执行,不把回退后的新版本误当作全新阶段。
* @param stage 已鉴权阶段摘要,历史标记兼容旧接口返回的 0/1
* @returns 是否必须保留执行历史对应的阶段结构
*/
function hasExecutionHistory(stage: Stage): boolean { return !!stage.executionHistory || !!stage.executionStatus && stage.executionStatus !== 'NOT_STARTED' }
/**
* 为删除按钮提供与已有后端保护一致的原因,空工作项不代表阶段从未执行。
* @param stage 当前行阶段,父组保护从同一份项目阶段摘要读取
* @returns 不可删除的具体原因;空字符串允许发起确认,最终仍由后端持锁复验
*/
function deleteBlockedReason(stage: Stage): string {
if (hasExecutionHistory(stage)) return '该阶段已有执行历史,不能删除;清空工作项或回退换版不会清除执行历史。'
const parent = props.stages.find(value => value.id === stage.parentStageId)
if (parent && hasExecutionHistory(parent)) return '所属阶段组已有执行历史,不能删除其中的子阶段。'
if (stage.approvalStatus === 'PENDING') return '阶段正在审批,不能删除。'
if (stage.canEditStructure === false || parent?.canEditStructure === false) return '当前阶段或所属阶段组的结构不可编辑,不能删除。'
if (stage.childStageCount) return '请先移出或删除组内子阶段。'
if (stage.counts.total) return '请先移动阶段中的工作项。'
if (stage.deliveryAttachmentCount) return '请先移除本轮交付附件。'
if (stage.purchaseBatchCount) return '请先清空采购批次范围。'
return ''
return stageDeleteBlockedReason(stage, props.stages)
}
/** 发起确认前重新检查当前摘要,只对可删除空阶段提交;后端继续在项目锁内验证历史与版本。 */
async function remove(stage: Stage) { const blocked = deleteBlockedReason(stage); if (blocked) { failure.value = blocked; return } 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 } }

View File

@ -0,0 +1,43 @@
<template>
<el-dialog :model-value="!!stage" :close-on-click-modal="false" title="修改阶段名称" width="min(440px, 94vw)" append-to-body @close="emit('close')">
<el-form size="small" label-position="top" @submit.prevent="save">
<el-form-item label="阶段名称" required><el-input v-model="name" maxlength="120" show-word-limit autofocus :disabled="busy" /></el-form-item>
<p class="rename-hint">仅修改名称,节点类型和其他阶段信息保持原值。</p>
</el-form>
<el-alert v-if="failure" :title="failure" type="error" :closable="false" />
<template #footer><el-button size="small" :disabled="busy" @click="emit('close')">取消</el-button><el-button size="small" type="primary" :loading="busy" :disabled="!name.trim()" @click="save">保存</el-button></template>
</el-dialog>
</template>
<script setup lang="ts">
import { onBeforeUnmount, ref, watch } from 'vue'
import { api, errorText } from '../../../api'
import type { Stage } from '../../../types'
import { stageRenameBlockedReason } from '../utils/actions'
const props = defineProps<{ stage: Stage | null; projectId: number; iterationId?: number }>()
const emit = defineEmits<{ close: []; changed: [] }>()
const name = ref(''), busy = ref(false), failure = ref('')
let generation = 0
/** 切换节点时建立独立名称草稿;不把当前输入绑定到共享阶段摘要。 */
watch(() => props.stage, stage => { generation++; name.value = stage?.name || ''; failure.value = '' }, { immediate: true })
/** 关闭或离开迭代后忽略旧请求回调,防止关闭另一节点的编辑框。 */
onBeforeUnmount(() => { generation++ })
/**
* 使用只接受名称和阶段版本的接口,避免快捷改名覆盖负责人、描述、采购范围或日期。
* 空值、冻结状态和重复提交在前端拦截;权限和并发版本仍由后端持锁复验。
*/
async function save() {
const stage = props.stage
if (!stage || busy.value || !name.value.trim()) return
const blocked = stageRenameBlockedReason(stage)
if (blocked) { failure.value = blocked; return }
if (name.value.trim() === stage.name) { emit('close'); return }
const token = generation; busy.value = true; failure.value = ''
try {
await api.renameStage(props.projectId, stage.id, name.value.trim(), stage.version, props.iterationId)
if (token === generation) { emit('changed'); emit('close') }
} catch (error) { if (token === generation) failure.value = errorText(error) }
finally { busy.value = false }
}
</script>
<style scoped>.rename-hint{font-size:12px;color:var(--el-text-color-secondary)}</style>

View File

@ -0,0 +1,32 @@
import type { Stage } from '../../../types'
/** 当前版本改名遵循交付冻结规则;历史名称快照保持只读,不随改名覆盖。 */
export function stageRenameBlockedReason(stage: Stage): string {
if (stage.approvalStatus === 'PENDING') return '阶段正在审批,请先撤回申请后修改名称。'
if (['COMPLETED', 'LEGACY_PASSED'].includes(stage.executionStatus || '')) return '阶段已完成,当前版本只读。'
return ''
}
/** 根据全版本历史识别执行过的阶段,不能把回退后的空版本当作全新节点。 */
function hasExecutionHistory(stage: Stage): boolean {
return !!stage.executionHistory || !!stage.executionStatus && stage.executionStatus !== 'NOT_STARTED'
}
/**
* 为画布及管理表统一提供删除受限原因,后端仍在项目锁内复验历史、内容与版本。
* @param stage 当前阶段;未分配虚拟节点不调用此方法
* @param stages 当前迭代全部阶段,用于校验父组的历史保护
* @returns 空字符串表示可请求删除确认,其他值用于禁用提示
*/
export function stageDeleteBlockedReason(stage: Stage, stages: readonly Stage[]): string {
if (hasExecutionHistory(stage)) return '该阶段已有执行历史,不能删除;清空工作项或回退换版不会清除执行历史。'
const parent = stages.find(value => value.id === stage.parentStageId)
if (parent && hasExecutionHistory(parent)) return '所属阶段组已有执行历史,不能删除其中的子阶段。'
if (stage.approvalStatus === 'PENDING') return '阶段正在审批,不能删除。'
if (stage.canEditStructure === false || parent?.canEditStructure === false) return '当前阶段或所属阶段组的结构不可编辑,不能删除。'
if (stage.childStageCount) return '请先移出或删除组内子阶段。'
if (stage.counts.total) return '请先移动阶段中的工作项。'
if (stage.deliveryAttachmentCount) return '请先移除本轮交付附件。'
if (stage.purchaseBatchCount) return '请先清空采购批次范围。'
return ''
}

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-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-else-if="stageFrozen" type="info" :closable="false" :title="currentStage?.approvalStatus === 'PENDING' ? '当前阶段正在审批,交付已冻结;需要修改请负责人先撤回申请,评论仍可讨论。' : '当前阶段已完成,工作项已冻结;如需重做,请由项目经理从流程视图回退。'" class="failure" />
<el-alert v-else-if="stageFrozen" type="info" :closable="false" :title="stagePending ? '当前阶段正在审批,交付已冻结;需要修改请负责人先撤回申请,评论仍可讨论。' : '当前阶段已完成,工作项已冻结;如需重做,请由项目经理从流程视图回退。'" 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>
<el-button v-if="detail.scheduleReviewRequired && !detail.scheduleReviewClosed && writable" size="small" @click="confirmReview">确认保留原排期</el-button>
@ -53,7 +53,7 @@
<el-alert v-if="!detail.historical" type="info" :closable="false" :title="detail.scheduleConstraints.earliestPlannedStartAt ? `最早合法预计开始:${planningLimitDate(detail.scheduleConstraints.earliestPlannedStartAt, 'start', 'min')}` : '暂无参与排期计算的前置结束时间;缺少前置工作项结束时间会阻止保存后续开始时间。'" />
</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">上传附件(最多 {{ ATTACHMENT_MAX_SIZE_LABEL }})<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>
</template>
</div>
@ -71,7 +71,7 @@
</el-dialog>
</template>
<script setup lang="ts">
import { computed, ref, watch } from 'vue'
import { computed, onBeforeUnmount, ref, watch } from 'vue'
import { ElMessage, ElMessageBox, vLoading } from 'element-plus'
import { api, errorText, isAccessFailure, downloadAttachment } from '../../../api'
import { reconcileRows, retainSnapshot } from '../../../shared/utils/snapshot'
@ -80,38 +80,75 @@ import ItemScheduleDialog from '../../schedules/components/ItemScheduleDialog.vu
import PredecessorPicker from './PredecessorPicker.vue'
import type { WorkItem, Member, Condition, Lifecycle, StageEdge, Stage, PredecessorOption } from '../../../types'
import { typeNames, priorityNames, statusNames, actionNames, itemStatusLabel } from '../../../shared/constants/labels'
import { ATTACHMENT_MAX_BYTES, ATTACHMENT_MAX_SIZE_LABEL } from '../../../shared/constants/attachments'
const lifecycleLabels: Record<string, string> = statusNames
const props = withDefaults(defineProps<{ projectId?: number; iterationId?: number; canExecute?: boolean; id: number | null; refreshKey: number; items: WorkItem[]; members: Member[]; canWrite: boolean; canManage?: boolean; stages?: Stage[]; stageEdges?: StageEdge[] }>(), { stages: () => [], stageEdges: () => [], canExecute: true })
const emit = defineEmits<{ close: []; changed: []; open: [id: number]; edit: [item: WorkItem]; 'create-child': [parent: WorkItem] }>()
const detail = ref<WorkItem | null>(null), loading = ref(false), busy = ref(false), failure = ref(''), commentText = ref('')
const attachmentConfirmationOpen = ref(false)
let loadSequence = 0
const deleteConfirmationOpen = ref(false)
let loadSequence = 0, scopeSequence = 0
const scheduleOpen = ref(false), assignmentOpen = ref(false), assignmentStageId = ref<number | null>(null), assignmentFailure = ref('')
const scheduleLabel = computed(() => detail.value?.scheduleConstraints.scheduleValidationStatus === 'VALID' ? '排期合法' : detail.value?.scheduleConstraints.scheduleValidationStatus === 'CONFLICT' ? '排期冲突' : '排期未完成')
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。
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 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 stagePending = computed(() => detail.value?.stageApprovalStatus === 'PENDING' || currentStage.value?.approvalStatus === 'PENDING')
const stageCompleted = computed(() =>
(!!detail.value?.stageReadOnly && detail.value.stageApprovalStatus !== 'PENDING')
|| ['COMPLETED', 'LEGACY_PASSED'].includes(currentStage.value?.executionStatus || '')
)
const stageFrozen = computed(() => stagePending.value || stageCompleted.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 canDiscuss = computed(() => props.canWrite && !detail.value?.iterationReadOnly && !detail.value?.historical && !stageCompleted.value)
const editableDependencies = computed(() => writable.value && detail.value?.status === 'READY')
const loadedChildren = ref<WorkItem[]>([])
const childItems = computed(() => detail.value?.historical ? detail.value.historicalChildren || [] : loadedChildren.value)
/** 阶段归属使用独立的经理入口,普通编辑不能清空阶段绕过门禁。 */
function openAssignment() { if (!detail.value || !props.canManage) return; assignmentStageId.value = detail.value.stageId ?? null; assignmentFailure.value = ''; assignmentOpen.value = true }
/** 失败保留选择并显示业务冲突,成功重新读取详情和共享阶段摘要。 */
async function saveAssignment() { if (!detail.value || !props.canManage || busy.value) return; busy.value = true; assignmentFailure.value = ''; try { await api.assignStage(detail.value, assignmentStageId.value || null); assignmentOpen.value = false; await load(); emit('changed') } catch (error) { assignmentFailure.value = errorText(error) } finally { busy.value = false } }
watch(() => [props.id, props.projectId, props.iterationId], () => { detail.value = null; commentText.value = ''; scheduleOpen.value = false; assignmentOpen.value = false; depOpen.value = false; sourceId.value = null; loadedChildren.value = []; failure.value = ''; void load() })
/** 阶段归属提交绑定当前详情;切换对象后不关闭新表单,也不显示旧请求错误。 */
async function saveAssignment() {
if (!detail.value || !props.canManage || !writable.value || busy.value || loading.value) return
const sequence = scopeSequence, item = detail.value, stageId = assignmentStageId.value
busy.value = true; assignmentFailure.value = ''; loadSequence++
try {
await api.assignStage(item, stageId)
if (sequence !== scopeSequence) return
assignmentOpen.value = false; emit('changed'); await load()
} catch (error) { if (sequence === scopeSequence) assignmentFailure.value = errorText(error) }
finally { if (sequence === scopeSequence) busy.value = false }
}
// 详情请求和写请求分别计次:刷新不能取消本次提交,换对象(包括离开再返回)必须使旧提交回调失效。
watch(() => [props.id, props.projectId, props.iterationId], () => {
scopeSequence++
busy.value = false
deleteConfirmationOpen.value = false
attachmentConfirmationOpen.value = false
detail.value = null
commentText.value = ''
scheduleOpen.value = false
assignmentOpen.value = false
depOpen.value = false
sourceId.value = null
loadedChildren.value = []
failure.value = ''
assignmentFailure.value = ''
depFailure.value = ''
void load()
}, { flush: 'sync' })
watch(() => props.refreshKey, () => { void load() })
/** 卸载后所有在途回调作废,防止离页后弹出旧错误或刷新另一工作区。 */
onBeforeUnmount(() => { scopeSequence++; loadSequence++ })
/**
* 加载详情和子任务后校验范围与请求代次;后台相同内容保留引用,短暂失败保留已有详情。
* @param background 为 true 时不显示加载遮罩;请求途中开始编辑则丢弃结果,访问失效仍清理。
*/
async function load(background = false) {
const sequence = ++loadSequence, id = props.id
if (id === null) { detail.value = null; return }
if (id === null) { detail.value = null; loading.value = false; return }
if (!background) loading.value = true
try {
const result = await api.detail(id)
@ -128,11 +165,23 @@ async function load(background = false) {
}
/** 实际执行和审计发生时间保留北京时间及微秒,预计日期使用独立的日期展示函数。 */
function displayTime(value: string | null) { return value ? localTime(value, 'Asia/Shanghai').replace('T', ' ') : '未设置' }
/** 执行业务动作并刷新受影响工作项;被拒绝时保留具体原因。 */
async function action(commit: () => Promise<unknown>, discussion = false) {
if (!(discussion ? canDiscuss.value : writable.value)) return
busy.value = true; failure.value = ''
try { await commit(); emit('changed'); await load() } catch (error) { failure.value = errorText(error) } finally { busy.value = false }
/**
* 串行提交当前工作项动作,仅在用户仍停留于本次详情时应用成功或失败回调。
* 前台重读期间不提交旧版本;只使在途后台读失效,避免前台加载状态失去对应的结束回调。
* @param commit 已捕获工作项 ID 和版本的请求,不能在等待之后重新读取当前详情作为写入目标。
* @param discussion 评论允许在待审批阶段发送,其余写入仍受交付冻结限制。
* @param onSuccess 本次详情内的成功处理,例如清理已发送草稿或关闭已删除对象。
*/
async function action(commit: () => Promise<unknown>, discussion = false, onSuccess?: () => void) {
if (!detail.value || busy.value || loading.value || !(discussion ? canDiscuss.value : writable.value)) return
const sequence = scopeSequence
busy.value = true; failure.value = ''; loadSequence++
try {
await commit()
if (sequence !== scopeSequence) return
onSuccess?.(); emit('changed'); await load()
} catch (error) { if (sequence === scopeSequence) failure.value = errorText(error) }
finally { if (sequence === scopeSequence) busy.value = false }
}
/** 开始只调用统一后端方法,传递详情版本防止过期点击。 */
async function start() { if (props.canExecute && writable.value && detail.value) { const item = detail.value; await action(() => api.start(item.id, item.version)) } }
@ -142,18 +191,40 @@ async function confirmReview() { if (detail.value?.scheduleReviewRequired) { con
async function scheduleSaved() { scheduleOpen.value = false; emit('changed'); await load() }
/** 回退、完成、取消及关闭/重开由后端状态机和子任务门禁判断,不在前端强制写状态。 */
async function transition(status: Lifecycle) { if (detail.value) { const item = detail.value; await action(() => api.transition(item.id, status, item.version)) } }
/** 删除经产品交互确认后调用受保护软删除,后续已开始时服务端拒绝。 */
/** 确认绑定打开时的工作项及版本,换对象或关闭后作废;后端继续复验软删除条件。 */
async function remove() {
if (!detail.value) return
try { await ElMessageBox.confirm('删除此工作项?操作历史会保留,存在已开始的后续任务时将拒绝删除。', '删除工作项', { type: 'warning', closeOnClickModal: false }) } catch { return }
const item = detail.value; await action(async () => { await api.remove(item.id, item.version); emit('close') })
if (!detail.value || !writable.value || busy.value || loading.value || deleteConfirmationOpen.value) return
const item = detail.value, sequence = scopeSequence
deleteConfirmationOpen.value = true
try { await ElMessageBox.confirm(`删除工作项“${item.title}”?操作历史会保留,存在已开始的后续任务时将拒绝删除。`, '删除工作项', { type: 'warning', closeOnClickModal: false }) }
catch { return }
finally { if (sequence === scopeSequence) deleteConfirmationOpen.value = false }
if (sequence !== scopeSequence) return
await action(() => api.remove(item.id, item.version), false, () => emit('close'))
}
/** 评论使用提交时的文本;只有未继续编辑的同一份草稿才在成功后清空。 */
async function comment() {
if (!detail.value || !commentText.value.trim()) return
const itemId = detail.value.id, body = commentText.value
await action(() => api.comment(itemId, body), true, () => { if (commentText.value === body) commentText.value = '' })
}
/** 选择文件时固定所属工作项,按协作统一的 50MB 上限检查后上传;清空 input 以允许重试同一文件。 */
async function upload(event: Event) {
const input = event.target as HTMLInputElement, file = input.files?.[0]
if (!file || !detail.value) return
const itemId = detail.value.id
if (file.size > ATTACHMENT_MAX_BYTES) {
ElMessage.error(`附件不能超过 ${ATTACHMENT_MAX_SIZE_LABEL}`); input.value = ''; return
}
await action(() => api.upload(itemId, file))
input.value = ''
}
/** 鉴权下载失败仅反馈到发起下载的详情,不把旧错误展示在另一工作项中。 */
async function download(id: number, name: string) {
const sequence = scopeSequence
try { await downloadAttachment(id, name) }
catch (error) { if (sequence === scopeSequence) failure.value = errorText(error) }
}
/** 评论成功才清空输入,失败时保留草稿。 */
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 = '' }
/** 下载失败展示权限或连接提示,不提供绕过鉴权的静态 URL。 */
async function download(id: number, name: string) { try { await downloadAttachment(id, name) } catch (error) { failure.value = errorText(error) } }
/**
* 先确认附件删除,再提交详情所属工作项与附件 ID;失败沿用统一错误展示并保留列表。
@ -161,19 +232,19 @@ async function download(id: number, name: string) { try { await downloadAttachme
* 确认期间暂停后台同步;切换详情后放弃旧确认,避免在另一个工作项中执行旧操作。
*/
async function removeAttachment(file: { id: number; name: string }) {
if (!detail.value?.canDeleteAttachments || !writable.value || busy.value || attachmentConfirmationOpen.value) return
const itemId = detail.value.id
if (!detail.value?.canDeleteAttachments || !writable.value || busy.value || loading.value || attachmentConfirmationOpen.value) return
const itemId = detail.value.id, sequence = scopeSequence
attachmentConfirmationOpen.value = true
try {
await ElMessageBox.confirm(`删除附件“${file.name}”?删除后将无法下载。`, '删除附件', { type: 'warning', closeOnClickModal: false, confirmButtonText: '删除', cancelButtonText: '取消' })
} catch { return } finally { attachmentConfirmationOpen.value = false }
if (props.id !== itemId || detail.value?.id !== itemId || !detail.value.canDeleteAttachments) return
} catch { return } finally { if (sequence === scopeSequence) attachmentConfirmationOpen.value = false }
if (sequence !== scopeSequence || props.id !== itemId || detail.value?.id !== itemId || !detail.value.canDeleteAttachments) return
await action(() => api.removeAttachment(itemId, file.id))
}
const depOpen = ref(false), editingDependency = ref<Condition | null>(null), sourceId = ref<number | null>(null), depFailure = ref('')
// 删除确认属于未提交的用户操作,静默同步不能在确认期间替换当前详情。
const isEditing = computed(() => busy.value || loading.value || attachmentConfirmationOpen.value || scheduleOpen.value || assignmentOpen.value || depOpen.value || !!commentText.value.trim())
const isEditing = computed(() => busy.value || loading.value || deleteConfirmationOpen.value || attachmentConfirmationOpen.value || scheduleOpen.value || assignmentOpen.value || depOpen.value || !!commentText.value.trim())
/** 工作区轮询只静默更新空闲详情,评论、依赖和排期草稿均保留到用户完成操作。 */
async function synchronize() { if (!isEditing.value) await load(true) }
defineExpose({ isEditing, synchronize })
@ -184,12 +255,17 @@ watch(editableDependencies, allowed => { if (!allowed) { depOpen.value = false;
void load()
/** 依赖编辑仅针对当前待开始工作项,候选组件覆盖当前迭代全部工作项类型。 */
function openDependency(condition?: Condition) { editingDependency.value = condition || null; depFailure.value = ''; sourceId.value = condition?.sourceId || null; depOpen.value = true }
/** 保存依赖使用两个版本;环或排期失败时保留表单并显示服务端路径/冲突。 */
/** 保存依赖绑定本次详情及双版本;同次请求防重,切换后的旧结果不关闭新表单。 */
async function saveDependency() {
if (!detail.value || !editableDependencies.value) return
busy.value = true; depFailure.value = ''
try { await api.dependency(detail.value.id, { conditionType: 'WORK_ITEM_COMPLETED', predecessorTaskId: sourceId.value, expectedStatus: 'COMPLETED', version: editingDependency.value?.version ?? null, taskVersion: detail.value.version }, editingDependency.value?.id); depOpen.value = false; emit('changed'); await load() }
catch (error) { depFailure.value = errorText(error) } finally { busy.value = false }
if (!detail.value || !editableDependencies.value || busy.value || loading.value) return
const sequence = scopeSequence, item = detail.value
busy.value = true; depFailure.value = ''; loadSequence++
try {
await api.dependency(item.id, { conditionType: 'WORK_ITEM_COMPLETED', predecessorTaskId: sourceId.value, expectedStatus: 'COMPLETED', version: editingDependency.value?.version ?? null, taskVersion: item.version }, editingDependency.value?.id)
if (sequence !== scopeSequence) return
depOpen.value = false; emit('changed'); await load()
} catch (error) { if (sequence === scopeSequence) depFailure.value = errorText(error) }
finally { if (sequence === scopeSequence) busy.value = false }
}
/** 删除依赖仍提交任务与依赖版本,失败不从页面移除条件。 */
async function deleteDependency(condition: Condition) { if (detail.value) { const item = detail.value; await action(() => api.removeDependency(item.id, condition.id, item.version, condition.version)) } }

View File

@ -0,0 +1,4 @@
// 与后端及 Spring multipart 的 50MB 上限一致,按 1024 进位;两个上传入口共用,避免提示与校验不一致。
const ATTACHMENT_MAX_MB = 50
export const ATTACHMENT_MAX_BYTES = ATTACHMENT_MAX_MB * 1024 * 1024
export const ATTACHMENT_MAX_SIZE_LABEL = `${ATTACHMENT_MAX_MB}MB`

View File

@ -12,6 +12,7 @@ export const STAGE_NODE_TYPES = [
{ value: 'DEBUGGING', label: '调试', symbol: '调', description: '开展设备或系统调试' },
{ value: 'DEVELOPMENT', label: '研发', symbol: '研', description: '实施研发与功能开发' },
{ value: 'TESTING', label: '测试', symbol: '测', description: '执行测试和验证工作' },
{ value: 'CUSTOM', label: '自定义', symbol: '自', description: '自定名称和事项,按普通阶段提审完成' },
] as const satisfies readonly { value: StageNodeType; label: string; symbol: string; description: string }[]
export const WORK_STAGE_NODE_TYPES = STAGE_NODE_TYPES.filter(type => type.value !== 'GROUP')

View File

@ -27,7 +27,7 @@ export interface StageSummary {
export type StageExecutionStatus = 'NOT_STARTED' | 'IN_PROGRESS' | 'COMPLETED' | 'LEGACY_PASSED'
/** 节点分类创建后固定;STAGE 只用于兼容历史普通阶段。 */
export type StageNodeType = 'GROUP' | 'REQUIREMENT' | 'PROPOSAL' | 'PURCHASE' | 'DESIGN' | 'MACHINING' | 'ASSEMBLY' | 'DEBUGGING' | 'DEVELOPMENT' | 'TESTING' | 'STAGE'
export type StageNodeType = 'GROUP' | 'REQUIREMENT' | 'PROPOSAL' | 'PURCHASE' | 'DESIGN' | 'MACHINING' | 'ASSEMBLY' | 'DEBUGGING' | 'DEVELOPMENT' | 'TESTING' | 'CUSTOM' | 'STAGE'
export interface Stage extends StageSummary, Omit<StageSchedule, 'plannedStartAt' | 'plannedEndAt'> {
stageKind?: 'WORK' | 'GROUP'

View File

@ -1,17 +1,17 @@
<template>
<div ref="board" class="board" :style="{ height: boardHeight + 'px' }">
<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] ?? itemsByStatus[state].length }}</span></header>
<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 && !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>
<article v-for="item in itemsByStatus[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 || stagesById.get(item.stageId)?.name">{{ item.stagePath || stagesById.get(item.stageId)?.name || '阶段' }} · v{{ stagesById.get(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>
<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 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>
<el-button v-if="(counts?.[state] || 0) > items.filter(i => i.status === state).length" size="small" text @click="emit('load-more', state)">加载更多({{ items.filter(i => i.status === state).length }}/{{ counts?.[state] }})</el-button>
<div v-if="!items.some(i => i.status === state)" class="empty-lane">暂无工作项</div>
<el-button v-if="(counts?.[state] || 0) > itemsByStatus[state].length" size="small" text @click="emit('load-more', state)">加载更多({{ itemsByStatus[state].length }}/{{ counts?.[state] }})</el-button>
<div v-if="!itemsByStatus[state].length" class="empty-lane">暂无工作项</div>
</div>
</section>
</div>
@ -27,6 +27,14 @@ import { moveCard } from '../../shared/utils/optimistic'
const props = withDefaults(defineProps<{ items: WorkItem[]; stages?: Stage[]; canWrite: boolean; canExecute?: boolean; counts?: Partial<Record<Lifecycle, number>> }>(), { stages: () => [], canExecute: true })
const emit = defineEmits<{ open: [id: number]; changed: []; 'load-more': [state: Lifecycle] }>()
const dragged = ref<number | null>(null); const busy = reactive(new Set<number>())
/** 一次遍历按状态分列并保持接口顺序;乐观移动和失败恢复会自动重算,避免每列重复扫描全部工作项。 */
const itemsByStatus = computed(() => {
const result: Record<Lifecycle, WorkItem[]> = { READY: [], IN_PROGRESS: [], COMPLETED: [], CANCELLED: [], CLOSED: [] }
for (const item of props.items) result[item.status]?.push(item)
return result
})
/** 阶段名称和版本按 ID 索引,卡片较多时不为每个字段重复线性查找阶段。 */
const stagesById = computed(() => new Map(props.stages.map(stage => [stage.id, stage])))
// 拖动和提交期间暂停工作区静默同步,避免状态列被在途旧快照覆盖。
defineExpose({ isEditing: computed(() => dragged.value !== null || busy.size > 0) })
const board = ref<HTMLElement | null>(null), boardHeight = ref(480)

View File

@ -1,35 +1,53 @@
<template>
<section class="flow-view">
<div class="flow-toolbar">
<div class="flow-tools"><el-button size="small" @click="autoLayout" :disabled="busy">自动布局</el-button><el-button size="small" @click="fitAll">适应画布</el-button></div>
<div class="flow-tools"><span class="flow-help">点击阶段查看当前及历史工作项;画布位置只保存在当前浏览器</span><el-button v-if="canManage" size="small" @click="stageOpen = true">管理阶段</el-button></div>
<div class="flow-tools">
<el-button size="small" @click="autoLayout" :disabled="busy || canvasInteracting">自动布局</el-button><el-button size="small" @click="fitAll">适应画布</el-button>
<el-button size="small" :type="canvasMode === 'select' ? 'primary' : 'default'" :disabled="busy" @click="canvasMode = canvasMode === 'select' ? 'pan' : 'select'">框选</el-button>
<el-button size="small" :type="canvasMode === 'section' ? 'primary' : 'default'" :disabled="busy || sections.length >= 200" @click="canvasMode = canvasMode === 'section' ? 'pan' : 'section'">分区</el-button>
<el-checkbox v-model="guidesEnabled" size="small" :disabled="busy">对齐与间距辅助</el-checkbox>
<el-dropdown size="small" trigger="click" :disabled="busy || selectedNodes.length < 2 || !sameScope" @command="applyArrangement">
<el-button size="small" :disabled="busy || selectedNodes.length < 2 || !sameScope" :title="sameScope ? '以选区边界对齐' : '请选择同一画布层级的节点'">对齐 / 等距 ▾</el-button>
<template #dropdown><el-dropdown-menu>
<el-dropdown-item command="left">左对齐</el-dropdown-item><el-dropdown-item command="center-x">水平居中(中心竖线对齐)</el-dropdown-item><el-dropdown-item command="right">右对齐</el-dropdown-item>
<el-dropdown-item command="top" divided>顶部对齐</el-dropdown-item><el-dropdown-item command="center-y">垂直居中(中心横线对齐)</el-dropdown-item><el-dropdown-item command="bottom">底部对齐</el-dropdown-item>
<el-dropdown-item command="distribute-x" divided :disabled="selectedNodes.length < 3">水平等间距</el-dropdown-item><el-dropdown-item command="distribute-y" :disabled="selectedNodes.length < 3">垂直等间距</el-dropdown-item>
</el-dropdown-menu></template>
</el-dropdown>
<el-button v-if="selectedNodes.length" size="small" :disabled="busy || selectedNodes.some(node => !!node.parentNode) || sections.length >= 200" @click="createSelectionSection">选区设为分区</el-button>
<span v-if="selectedNodes.length" class="flow-help">已选 {{ selectedNodes.length }} 个节点{{ sameScope ? '' : '(不同层级)' }}</span>
</div>
<div class="flow-tools"><span class="flow-help">{{ canvasMode === 'section' ? '在空白处拖框创建分区;拖动分区标题栏可整体移动' : canvasMode === 'select' ? '拖框或点击选择节点;Ctrl / ⌘ 可加选;空格可平移' : '拖动平移;Shift 拖框 / Ctrl 或 ⌘ 点击多选;布局仅存当前浏览器' }}</span><el-button v-if="canManage" size="small" @click="stageOpen = true">管理阶段</el-button></div>
</div>
<el-alert v-if="failure" type="error" :title="failure" :closable="false" class="flow-failure" />
<div class="flow-editor" :class="{ inactive: !active }">
<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" :class="{ 'drawing-section': canvasMode === 'section' }" @pointerdown.capture="canvasTools.drawSection" @keydown.capture="canvasTools.moveWithKeyboard" @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 && canvasMode !== 'section'" :edges-updatable="false" :nodes-draggable="!busy && canvasMode !== 'section'" :selection-key-code="canvasMode === 'select' ? true : 'Shift'" :multi-selection-key-code="['Control', 'Meta']" :selection-mode="SelectionMode.Full" :pan-on-drag="canvasMode === 'pan' ? true : [1, 2]" :node-drag-threshold="3" :elevate-nodes-on-select="false" @connect="connectStages" @edge-click="edgeClicked" @node-click="selectNode" @node-drag-start="dragStarted" @node-drag="nodeDragged" @node-drag-stop="dragStopped" @move-end="viewportMoved" @nodes-initialized="restoreViewport" @selection-start="selecting = true" @selection-end="selecting = false">
<Background :gap="22" :size="1" pattern-color="var(--el-border-color)" />
<MiniMap pannable zoomable :node-color="minimapColor" node-stroke-color="var(--el-color-primary-light-3)" mask-color="var(--el-mask-color-extra-light)" />
<Controls :show-interactive="false" />
<template #edge-rework="edgeProps"><FlowReworkEdge v-bind="edgeProps" /></template>
<template #node-stage="{ data }"><FlowStageNode :data="data" @view="openDrawer($event, 'current')" @create="createInStage" @rework="openRework" @history="openDrawer($event, 'history')" /></template>
<template #node-group="{ data }"><FlowStageNode :data="data" @view="openDrawer($event, 'current')" @create-child="createChildStage" @toggle="toggleGroup" @rework="openRework" @history="openDrawer($event, 'history')" /></template>
<template #node-section="{ data }"><FlowSectionNode v-if="data.section" :section="data.section" :disabled="busy" @rename="canvasTools.renameSection" @remove="canvasTools.removeSection" @resize="canvasTools.resizeSection" /></template>
<template #node-stage="{ data }"><FlowStageNode :data="{ ...data, busy }" @view="openDrawer($event, 'current')" @create="createInStage" @rework="openRework" @history="openDrawer($event, 'history')" @rename="renameStage" @remove="removeStage" /></template>
<template #node-group="{ data }"><FlowStageNode :data="{ ...data, busy }" @view="openDrawer($event, 'current')" @create-child="createChildStage" @toggle="toggleGroup" @rework="openRework" @history="openDrawer($event, 'history')" @rename="renameStage" @remove="removeStage" /></template>
</VueFlow>
<FlowCanvasGuides :guides="guides" :draft="sectionDraft" :viewport="viewport" />
<div v-if="!view.unassigned?.counts?.total && !view.stages.length" class="canvas-empty">{{ canManage ? '从左侧拖入节点,然后连接阶段执行顺序。' : '暂无阶段和工作项。' }}</div>
<div class="canvas-legend"><span class="legend-line"></span>未执行 <span class="legend-line green"></span>已完成 <span class="legend-line legacy"></span>历史沿用 <span class="legend-line rework" :style="{ borderColor: FLOW_REWORK_COLOR }"></span>回退记录 · 多条入边须全部满足</div>
</div>
</div>
<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')" />
<StageRenameDialog :stage="renamingStage" :project-id="projectId" :iteration-id="iterationId" @close="renamingStage = 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; drawerEditing = false" @open="openItem" @create="createFromDrawer" @navigate="drawerStageId = $event" @create-child="createChildFromDrawer" @editing="drawerEditing = $event" />
</section>
</template>
<script setup lang="ts">
import { computed, nextTick, ref, watch } from 'vue'
import { ConnectionLineType, VueFlow, useVueFlow } from '@vue-flow/core'
import { ConnectionLineType, SelectionMode, VueFlow, useVueFlow } from '@vue-flow/core'
import type { Node, Edge, NodeMouseEvent, NodeDragEvent, GraphNode, Connection } from '@vue-flow/core'
import { ElMessageBox } from 'element-plus'
import { Background } from '@vue-flow/background'
@ -45,14 +63,20 @@ import { readFlowPreferences, writeFlowPreferences } from './utils/preferences'
import { stageAppearance } from './utils/stageAppearance'
import { stageGroupAt } from './utils/stageDrop'
import { useCanvasGestureCleanup } from './composables/useCanvasGestureCleanup'
import { useCanvasTools } from './composables/useCanvasTools'
import type { ArrangeAction } from './utils/canvasGeometry'
import { isPaletteNodeType } from '../../shared/constants/stageNodeTypes'
import type { FlowNodeData, FlowEdgeData } from './utils/graph'
import type { FlowView, Member, Point, StageNodeType } from '../../types'
import type { FlowView, Member, Point, Stage, StageNodeType } from '../../types'
import StageManager from '../../features/stages/components/StageManager.vue'
import StageCreateDialog from '../../features/stages/components/StageCreateDialog.vue'
import StageRenameDialog from '../../features/stages/components/StageRenameDialog.vue'
import { stageDeleteBlockedReason, stageRenameBlockedReason } from '../../features/stages/utils/actions'
import FlowStageNode from './components/FlowStageNode.vue'
import FlowNodePalette from './components/FlowNodePalette.vue'
import FlowReworkEdge from './components/FlowReworkEdge.vue'
import FlowSectionNode from './components/FlowSectionNode.vue'
import FlowCanvasGuides from './components/FlowCanvasGuides.vue'
import { FLOW_REWORK_COLOR } from './constants/theme'
import StageReworkDialog from '../../features/stages/components/StageReworkDialog.vue'
import StageWorkItemsDrawer from '../../features/stages/components/StageWorkItemsDrawer.vue'
@ -61,7 +85,7 @@ const props = defineProps<{ view: FlowView; projectId: number; iterationId?: num
const emit = defineEmits<{ open: [id: number]; changed: []; create: [stageId: number | null] }>()
const canvas = ref<HTMLElement | null>(null)
const flowId = 'project-flow-' + props.projectId + '-' + props.iterationId
const { fitView, setViewport, viewport, screenToFlowCoordinate, getNodes, updateNodeInternals, paneDragging } = useVueFlow(flowId)
const { fitView, setViewport, viewport, screenToFlowCoordinate, getNodes, updateNodeInternals, paneDragging, userSelectionActive, userSelectionRect, nodesSelectionActive } = useVueFlow(flowId)
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 draftViewport = ref<(Point & { zoom: number }) | null>(null)
@ -70,11 +94,16 @@ const createNodeType = ref<StageNodeType | undefined>(undefined)
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 drawerEditing = ref(false)
const renamingStage = ref<Stage | null>(null)
const selecting = ref(false)
const canvasTools = useCanvasTools({ nodes: getNodes, viewport, enabled: computed(() => props.active && !busy.value && !stageOpen.value && !stageNameOpen.value && !renamingStage.value && drawerStageId.value === null && reworkSourceId.value === null), toFlow: screenToFlowCoordinate, changed: persistCanvasLayout })
const { sections, guidesEnabled, guides, mode: canvasMode, draft: sectionDraft, interacting: canvasInteracting, selected: selectedNodes, sameScope } = canvasTools
// 平移和节点移动期间都暂停静默同步,避免尚未释放的鼠标手势遇到画布重建;坐标仍仅保存到当前浏览器。
const isEditing = computed(() => drawerEditing.value || dragging.value || paneDragging.value || busy.value || stageOpen.value || stageNameOpen.value || reworkSourceId.value !== null)
const isEditing = computed(() => drawerEditing.value || dragging.value || selecting.value || canvasInteracting.value || paneDragging.value || busy.value || stageOpen.value || stageNameOpen.value || renamingStage.value !== null || reworkSourceId.value !== null)
const { finishCanvasGesture } = useCanvasGestureCleanup(
computed(() => dragging.value || paneDragging.value),
computed(() => !props.active || stageOpen.value || stageNameOpen.value || drawerStageId.value !== null || reworkSourceId.value !== null),
computed(() => !props.active || stageOpen.value || stageNameOpen.value || renamingStage.value !== null || drawerStageId.value !== null || reworkSourceId.value !== null),
cancelCanvasSelection,
)
defineExpose({ isEditing })
let loaded = false, movingProgrammatically = false
@ -86,6 +115,8 @@ watch(() => props.view, () => {
positions.value = Object.fromEntries(Object.entries(preference?.positions || {}).filter(([id]) => id.startsWith('s:') && (preference?.parents?.[id] ?? null) === (props.view.stages.find(stage => 's:' + stage.id === id)?.parentStageId ?? null)))
draftViewport.value = preference?.viewport || null
collapsedStages.value = preference?.collapsedStages || []
sections.value = preference?.sections || []
guidesEnabled.value = preference?.guidesEnabled !== false
loaded = true
}
// 迁入或迁出阶段组后坐标原点已变化;只清除该节点的旧坐标,避免把根画布绝对位置当成子画布相对位置。
@ -96,25 +127,49 @@ watch(() => props.view, () => {
}, { immediate: true })
watch(() => [props.canCreate, props.canManage], rebuild)
/** 生命周期或权限变成只读时关闭写对话框,避免已打开的入口继续提交。 */
watch(() => props.canManage, allowed => { if (!allowed) { stageOpen.value = false; stageNameOpen.value = false; reworkSourceId.value = null } })
watch(() => props.canManage, allowed => { if (!allowed) { stageOpen.value = false; stageNameOpen.value = false; renamingStage.value = null; reworkSourceId.value = null } })
watch(() => props.active, async active => { if (active) { await nextTick(); await restoreViewport() } else if (loaded) { draftViewport.value = { ...viewport.value }; savePreference() } })
/** 按子画布和外框实际尺寸重建阶段摘要,折叠只隐藏内部节点,不改变共享业务图。 */
function rebuild() {
if (dragging.value) return
const selected = new Set(getNodes.value.filter(node => node.selected).map(node => node.id))
const graph = buildFlowGraph(props.view, positions.value, collapsedStages.value)
for (const node of graph.nodes) if (node.data) { node.data.canWrite = props.canCreate; node.data.canManage = props.canManage; node.connectable = !!node.data.stage && props.canManage }
for (const node of graph.nodes) if (node.data) { node.data.canWrite = props.canCreate; node.data.canManage = props.canManage; node.data.deleteBlockedReason = node.data.stage ? stageDeleteBlockedReason(node.data.stage, props.view.stages) : ''; node.connectable = !!node.data.stage && props.canManage }
for (const edge of graph.edges) edge.selectable = props.canManage && edge.data?.kind !== 'rework'
nodes.value = graph.nodes; edges.value = graph.edges
nodes.value = [...canvasTools.sectionNodes(), ...graph.nodes].map(node => ({ ...node, selected: selected.has(node.id) })); edges.value = graph.edges
}
/** 本地偏好保存阶段坐标、分区和辅助开关;均不进入业务接口,旧工作项坐标不再写回。 */
function savePreference() { writeFlowPreferences(props.userId, props.projectId, { positions: positions.value, parents: previousParents, collapsedStages: collapsedStages.value, viewport: draftViewport.value, sections: sections.value, guidesEnabled: guidesEnabled.value }, props.iterationId) }
/** 批量排版后先调整组边界及连线,再一次保存补偿后的相对坐标,避免刷新后子节点漂移。 */
function persistCanvasLayout() {
const current = getNodes.value
const groups = current.filter(node => node.type === 'group').map(node => node.id)
for (const id of groups) resizeStageGroup(current, id, edges.value)
updateReworkRoutes(current, edges.value)
positions.value = { ...positions.value, ...Object.fromEntries(current.filter(node => node.id.startsWith('s:')).map(node => [node.id, { ...node.position }])) }
savePreference(); rebuild()
if (groups.length) void nextTick(() => updateNodeInternals(groups))
}
/** 多选排版的失败原因保留在画布上,不对已选节点进行部分修改。 */
function applyArrangement(action: ArrangeAction) { failure.value = canvasTools.arrange(action) }
/** 分区由完整根节点的包围框生成;只选择子阶段时提示使用其阶段组。 */
function createSelectionSection() { failure.value = canvasTools.sectionFromSelection() }
/** 拖动起点记录分区包含的根节点,避免拖动途中将路过的节点吸入分区。 */
function dragStarted(event: NodeDragEvent) { dragging.value = true; canvasTools.startDrag(event) }
/** 框选使用原生指针捕获;失焦、隐藏或弹窗接管时解除展示状态,避免静默同步一直被暂停。 */
function cancelCanvasSelection() {
if (!selecting.value) return
selecting.value = false; userSelectionActive.value = false; userSelectionRect.value = null
nodesSelectionActive.value = getNodes.value.some(node => node.selected)
}
/** 本地偏好只保存阶段坐标和视口;旧工作项坐标不再写回浏览器。 */
function savePreference() { writeFlowPreferences(props.userId, props.projectId, { positions: positions.value, parents: previousParents, collapsedStages: collapsedStages.value, viewport: draftViewport.value }, props.iterationId) }
/**
* 拖动中只调整受影响的父框和回退路径,保留 Vue Flow 的拖拽锚点及其他阶段位置。
* @param event 当前拖动节点集合,支持同时选中多个子阶段
* @remarks 尺寸写入 DOM 后刷新父框连接点,避免执行线仍连接旧宽高。
*/
function nodeDragged(event: NodeDragEvent) {
canvasTools.drag(event)
const groups = [...new Set(event.nodes.map(node => node.parentNode).filter((id): id is string => !!id))]
for (const id of groups) resizeStageGroup(getNodes.value, id, edges.value)
updateReworkRoutes(getNodes.value, edges.value)
@ -124,7 +179,7 @@ function nodeDragged(event: NodeDragEvent) {
* 松开时保存补偿后的父子坐标;重新进入页面可恢复相同外框,不调用业务写接口。
* @param event 拖动最终节点集合,用于保存前完成最后一次边界计算
*/
function dragStopped(event: NodeDragEvent) { nodeDragged(event); positions.value = { ...positions.value, ...Object.fromEntries(getNodes.value.map(node => [node.id, { ...node.position }])) }; dragging.value = false; savePreference(); rebuild() }
function dragStopped(event: NodeDragEvent) { nodeDragged(event); canvasTools.finishDrag(); dragging.value = false; persistCanvasLayout() }
/** 删除旧手动阶段坐标后按显式阶段图重新布局。 */
async function autoLayout() { positions.value = {}; savePreference(); rebuild(); await nextTick(); await fitAll() }
/** 缩放和平移只影响当前浏览器的展示偏好。 */
@ -147,8 +202,12 @@ async function fitAll() {
draftViewport.value = { ...viewport.value }; savePreference()
} finally { movingProgrammatically = false }
}
/** 点击阶段打开当前工作项;按钮事件会停止冒泡以保留历史、创建和回退动作。 */
function selectNode(event: NodeMouseEvent) { if (event.node.type === 'stage' || event.node.type === 'group') openDrawer(Number(event.node.id.slice(2)), 'current') }
/** 框选模式及修饰键点击只选节点,避免多选时误开抽屉;普通单击仍打开阶段详情。 */
function selectNode(event: NodeMouseEvent) {
const mouse = event.event as MouseEvent
if (canvasMode.value !== 'pan' || mouse.ctrlKey || mouse.metaKey || mouse.shiftKey) return
if (event.node.type === 'stage' || event.node.type === 'group') openDrawer(Number(event.node.id.slice(2)), 'current')
}
/** 当前或历史版本共用同一阶段抽屉,零号虚拟节点只展示未分配当前工作项。 */
function openDrawer(stageId: number, tab: 'current' | 'history') { if (stageId !== 0 && !props.view.stages.some(stage => stage.id === stageId)) return; drawerTab.value = stageId === 0 ? 'current' : tab; drawerStageId.value = stageId }
/** 工作项详情沿用项目级详情抽屉;先关闭阶段列表,避免两个遮罩层争夺焦点。 */
@ -161,8 +220,34 @@ function createChildFromDrawer(id: number) { drawerStageId.value = null; createC
function createInStage(stageId: number) { if (!props.canCreate || stageId !== 0 && !props.view.stages.some(stage => stage.id === stageId)) return; emit('create', stageId || null) }
/** 回退入口使用后端当前阶段能力,待开始阶段也可进入;提交仍须通过项目锁内复验。 */
function openRework(stageId: number) { if (props.canManage && props.view.stages.some(stage => stage.id === stageId && stage.canRework)) reworkSourceId.value = stageId }
/** 快捷改名先检查当前能力;以独立草稿打开,避免画布原始名称被未保存输入改写。 */
function renameStage(stageId: number) {
const stage = props.view.stages.find(row => row.id === stageId)
if (!stage || !props.canManage || busy.value) return
const blocked = stageRenameBlockedReason(stage)
if (blocked) { failure.value = blocked; return }
renamingStage.value = { ...stage }
}
/**
* 删除真实空阶段前展示明确确认,取消不发请求;历史、子阶段和交付保护与管理表共用。
* 确认期间暂停同步,提交仍携带原阶段版本;失败保留服务端节点并刷新最新原因。
*/
async function removeStage(stageId: number) {
const stage = props.view.stages.find(row => row.id === stageId)
if (!stage || !props.canManage || busy.value) return
const blocked = stageDeleteBlockedReason(stage, props.view.stages)
if (blocked) { failure.value = blocked; return }
busy.value = true; failure.value = ''
try {
await ElMessageBox.confirm(`删除空阶段“${stage.name}”?关联执行连线将断开,历史记录保留。`, '删除阶段', { type: 'warning', closeOnClickModal: false })
if (!props.canManage) return
await api.removeStage(props.projectId, stage.id, stage.version, props.iterationId)
emit('changed')
} catch (error) { if (error !== 'cancel' && error !== 'close') { failure.value = errorText(error); emit('changed') } }
finally { busy.value = false }
}
/** 小地图复用当前版本的状态色,便于缩小时定位回退待重做阶段;主题切换由 CSS 变量即时响应。 */
function minimapColor(node: GraphNode<FlowNodeData>) { return stageAppearance(node.data?.stage).accent }
function minimapColor(node: GraphNode<FlowNodeData>) { return node.type === 'section' ? 'var(--el-color-primary-light-8)' : stageAppearance(node.data?.stage).accent }
/**
* 将素材分类和画布落点转为创建草稿,命中子节点或组背景均自动归入同一组。
* @param event 浏览器拖放事件,坐标须按当前缩放和平移转换,不能用 DOM 层级推测归属
@ -219,4 +304,8 @@ async function edgeClicked(event: { edge: Edge<FlowEdgeData> }) {
.flow-canvas :deep([class~="vue-flow__controls-button"]){background:var(--el-bg-color-overlay);color:var(--el-text-color-primary);fill:currentColor;border-bottom-color:var(--el-border-color-light)}
.flow-canvas :deep([class~="vue-flow__controls-button"]:hover){background:var(--el-fill-color)}
.flow-canvas :deep([class~="vue-flow__minimap"]){background:var(--el-bg-color-overlay);border:1px solid var(--el-border-color-light);box-shadow:var(--el-box-shadow-lighter)}
.flow-canvas :deep([class~="vue-flow__node-section"]){padding:0;border:0;background:transparent;pointer-events:none}
.flow-canvas :deep([class~="vue-flow__node-stage"].selected .phase-group),.flow-canvas :deep([class~="vue-flow__node-group"].selected .phase-group),.flow-canvas :deep([class~="vue-flow__node-section"].selected .canvas-section){outline:2px solid var(--el-color-primary);outline-offset:3px}
.flow-canvas :deep([class~="vue-flow__selection"]),.flow-canvas :deep([class~="vue-flow__nodesselection-rect"]){background:color-mix(in srgb,var(--el-color-primary) 8%,transparent);border:1px solid var(--el-color-primary)}
.drawing-section :deep([class~="vue-flow__pane"]){cursor:crosshair}
</style>

View File

@ -0,0 +1,22 @@
<template>
<svg class="canvas-guides" aria-hidden="true">
<g :transform="`translate(${viewport.x},${viewport.y}) scale(${viewport.zoom})`">
<rect v-if="draft" :x="draft.x" :y="draft.y" :width="draft.width" :height="draft.height" class="section-draft" vector-effect="non-scaling-stroke" />
<g v-for="(line,index) in guides" :key="index" :class="line.kind">
<line :x1="line.x1" :y1="line.y1" :x2="line.x2" :y2="line.y2" vector-effect="non-scaling-stroke" />
<template v-if="line.label">
<line v-for="end in [1,2] as const" :key="end" :x1="(end===1?line.x1:line.x2)-(line.y1===line.y2?0:4/viewport.zoom)" :x2="(end===1?line.x1:line.x2)+(line.y1===line.y2?0:4/viewport.zoom)" :y1="(end===1?line.y1:line.y2)-(line.y1===line.y2?4/viewport.zoom:0)" :y2="(end===1?line.y1:line.y2)+(line.y1===line.y2?4/viewport.zoom:0)" vector-effect="non-scaling-stroke" />
<rect :x="(line.x1+line.x2)/2-(line.label.length*3.5+5)/viewport.zoom" :y="(line.y1+line.y2)/2-8/viewport.zoom" :width="(line.label.length*7+10)/viewport.zoom" :height="16/viewport.zoom" :rx="3/viewport.zoom" class="distance-label" />
<text :x="(line.x1+line.x2)/2" :y="(line.y1+line.y2)/2" :font-size="11/viewport.zoom" text-anchor="middle" dominant-baseline="central">{{ line.label }}</text>
</template>
</g>
</g>
</svg>
</template>
<script setup lang="ts">
import type { CanvasBox, CanvasGuide } from '../utils/canvasGeometry'
defineProps<{ guides: CanvasGuide[]; draft: CanvasBox | null; viewport: { x: number; y: number; zoom: number } }>()
</script>
<style scoped>
.canvas-guides{position:absolute;inset:0;width:100%;height:100%;z-index:30;pointer-events:none;overflow:hidden}.alignment line{stroke:var(--el-color-danger);stroke-width:1;stroke-dasharray:4 3}.distance line{stroke:var(--el-color-primary);stroke-width:1}.distance text{fill:var(--el-color-primary)}.distance-label{fill:var(--el-bg-color-overlay);stroke:var(--el-color-primary-light-5);stroke-width:0.5;vector-effect:non-scaling-stroke}.section-draft{fill:var(--el-color-primary-light-9);fill-opacity:0.4;stroke:var(--el-color-primary);stroke-width:1;stroke-dasharray:6 4}
</style>

View File

@ -0,0 +1,33 @@
<template>
<div class="canvas-section" :aria-label="`分区:${section.name}`">
<header class="section-drag">
<el-input v-if="editing" ref="input" v-model="name" size="small" maxlength="100" class="nodrag nopan" aria-label="分区名称" @pointerdown.stop @mousedown.stop @keydown.enter.prevent="submit" @keydown.esc.prevent.stop="cancel" @blur="submit" />
<button v-else class="section-name" type="button" :title="section.name + ';双击修改名称'" @dblclick.stop="edit">{{ section.name }}</button>
<button type="button" class="nodrag nopan section-action" aria-label="修改分区名称" :disabled="disabled" @pointerdown.stop @mousedown.stop @click.stop="edit"><EditPen /></button>
<button type="button" class="nodrag nopan section-action remove" aria-label="删除分区,保留阶段" title="删除分区,保留阶段" :disabled="disabled" @pointerdown.stop @mousedown.stop @click.stop="emit('remove', section.id)"><Delete /></button>
<span class="section-grip" title="拖动分区及其内部节点">⠿</span>
</header>
<button type="button" class="section-resize nodrag nopan" aria-label="调整分区大小" :disabled="disabled" @pointerdown.stop.prevent="emit('resize', section.id, $event)"></button>
</div>
</template>
<script setup lang="ts">
import { nextTick, ref } from 'vue'
import { EditPen, Delete } from '@element-plus/icons-vue'
import type { InputInstance } from 'element-plus'
import type { CanvasSection } from '../utils/canvasGeometry'
const props = defineProps<{ section: CanvasSection; disabled: boolean }>()
const emit = defineEmits<{ rename: [id: string, name: string]; remove: [id: string]; resize: [id: string, event: PointerEvent] }>()
const editing = ref(false), name = ref(''), input = ref<InputInstance>()
/** 使用独立草稿编辑分区标题,避免尚未确认的输入污染浏览器偏好。 */
async function edit() { if (props.disabled) return; name.value = props.section.name; editing.value = true; await nextTick(); input.value?.focus(); input.value?.select() }
/** 非空标题在 Enter 或失焦时提交;空值保留原名,不删除分区。 */
function submit() { if (!editing.value) return; editing.value = false; if (name.value.trim()) emit('rename', props.section.id, name.value) }
/** Escape 放弃本次标题草稿,随后到达的 blur 不能再次提交。 */
function cancel() { editing.value = false }
</script>
<style scoped>
.canvas-section{height:100%;width:100%;box-sizing:border-box;border:1px dashed var(--el-color-primary-light-3);border-radius:12px;background:color-mix(in srgb,var(--el-color-primary) 5%,transparent);position:relative;pointer-events:none}
.section-drag{height:34px;display:flex;align-items:center;gap:5px;padding:0 10px;box-sizing:border-box;pointer-events:auto;cursor:grab;background:color-mix(in srgb,var(--el-color-primary) 10%,var(--el-bg-color));border-radius:11px 11px 0 0;color:var(--el-text-color-primary)}
.section-name{min-width:0;flex:0 1 auto;text-align:left;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;border:0;background:transparent;color:inherit;font-size:12px;font-weight:600;padding:0;cursor:text}.section-action{width:20px;height:22px;flex:none;display:inline-flex;align-items:center;justify-content:center;border:0;border-radius:3px;background:transparent;color:var(--el-color-primary);cursor:pointer;padding:3px}.section-action svg{width:14px;height:14px}.section-action.remove{color:var(--el-color-danger)}.section-action:hover{background:var(--el-fill-color)}.section-grip{margin-left:auto;color:var(--el-text-color-secondary)}
.section-resize{position:absolute;right:0;bottom:0;width:20px;height:20px;pointer-events:auto;border:0;background:linear-gradient(135deg,transparent 55%,var(--el-color-primary) 56%,var(--el-color-primary) 62%,transparent 63%,transparent 72%,var(--el-color-primary) 73%,var(--el-color-primary) 79%,transparent 80%);cursor:nwse-resize}
</style>

View File

@ -1,7 +1,7 @@
<template>
<div class="phase-group" :class="{ 'is-current': data.stage?.isCurrent, 'is-container': data.stage?.stageKind === 'GROUP' && !data.collapsed }" :data-stage="data.stageId" :data-state="appearance.tone" :style="{ '--phase-background': appearance.background, '--phase-border': appearance.border, '--phase-accent': appearance.accent }">
<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><span class="stage-title"><strong :title="data.title">{{ data.title }}</strong><button v-if="data.stage && data.canManage" type="button" class="nodrag nopan node-action" aria-label="修改阶段名称" :title="renameBlockedReason || '修改阶段名称'" :disabled="!!renameBlockedReason || !!data.busy" @pointerdown.stop @mousedown.stop @click.stop="emit('rename', data.stageId!)"><EditPen /></button></span><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><button v-if="data.stage && data.canManage" type="button" class="nodrag nopan node-action node-delete" aria-label="删除阶段" :title="String(data.deleteBlockedReason || '删除空阶段')" :disabled="!!data.deleteBlockedReason || !!data.busy" @pointerdown.stop @mousedown.stop @click.stop="emit('remove', data.stageId!)"><Delete /></button></header>
<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="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>
@ -14,16 +14,19 @@
</template>
<script setup lang="ts">
import { computed } from 'vue'
import { EditPen, Delete } from '@element-plus/icons-vue'
import { Handle, Position } from '@vue-flow/core'
import type { FlowNodeData } from '../utils/graph'
import { stageAppearance } from '../utils/stageAppearance'
import { stageNodeTypeLabel } from '../../../shared/constants/stageNodeTypes'
import type { Stage } from '../../../types'
import { plannedDate } from '../../../shared/utils/time'
import { stageRenameBlockedReason } from '../../../features/stages/utils/actions'
const props = defineProps<{ data: FlowNodeData }>()
// 配色仅反映当前版本快照,后台静默同步状态后无需重载画布即可更新。
const appearance = computed(() => stageAppearance(props.data.stage))
const emit = defineEmits<{ view: [id: number]; create: [id: number]; rework: [id: number]; history: [id: number]; createChild: [id: number]; toggle: [id: number] }>()
const renameBlockedReason = computed(() => props.data.stage ? stageRenameBlockedReason(props.data.stage) : '')
const emit = defineEmits<{ view: [id: number]; create: [id: number]; rework: [id: number]; history: [id: number]; createChild: [id: number]; toggle: [id: number]; rename: [id: number]; remove: [id: number] }>()
/** 节点仅展示阶段自身的预计日期;参考时间留在抽屉,避免混作本轮有效排期。 */
function planLabel(stage: Stage): string {
if (stage.scheduleReviewRequired) return stage.scheduleReviewClosed ? '本轮未确认排期' : '排期待复核'
@ -33,8 +36,9 @@ function planLabel(stage: Stage): string {
</script>
<style scoped>
.stage-type{flex:none;white-space:nowrap;font-size:10px;line-height:16px;padding:0 4px;border-radius:3px;color:var(--phase-accent);background:color-mix(in srgb,var(--phase-accent) 12%,var(--el-bg-color-overlay))}
.stage-title{display:flex;align-items:center;gap:3px;min-width:0;flex:1}.stage-title strong{flex:0 1 auto}.node-action{display:inline-flex;align-items:center;justify-content:center;width:17px;height:20px;flex:none;padding:1px;border:0;border-radius:3px;background:transparent;color:var(--el-color-primary);cursor:pointer}.node-action svg{width:13px;height:13px}.node-action:hover:not(:disabled){background:var(--el-fill-color)}.node-action:disabled{color:var(--el-text-color-disabled);cursor:not-allowed}.node-delete{color:var(--el-color-danger)}
.phase-group[class~="is-current"]{border-color:var(--el-color-primary)}.stage-current{font-size:10px;color:var(--el-color-primary);background:var(--el-color-primary-light-9);border-radius:3px;padding:1px 4px;white-space:nowrap;flex:none}
.phase-group{width:100%;height:100%;background:var(--phase-background);border:1px solid var(--phase-border);border-radius:11px;color:var(--el-text-color-primary);cursor:pointer;box-sizing:border-box}.stage-drag{display:flex;align-items:center;gap:8px;padding:13px 14px 4px;cursor:grab}.stage-drag strong{font-size:13px;flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.stage-version{font-size:11px;color:var(--el-text-color-secondary)}.phase-dot{width:8px;height:8px;border-radius:50%;background:var(--phase-accent);flex:none}
.phase-group{width:100%;height:100%;background:var(--phase-background);border:1px solid var(--phase-border);border-radius:11px;color:var(--el-text-color-primary);cursor:pointer;box-sizing:border-box}.stage-drag{display:flex;align-items:center;gap:8px;padding:13px 14px 4px;cursor:grab}.stage-drag strong{font-size:13px;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.stage-version{font-size:11px;color:var(--el-text-color-secondary)}.phase-dot{width:8px;height:8px;border-radius:50%;background:var(--phase-accent);flex:none}
.phase-body{display:flex;align-items:center;justify-content:space-between;gap:6px;padding:1px 14px 0}.stage-items{font-size:12px;font-weight:600;color:var(--el-color-primary)}.stage-status{font-size:11px;color:var(--el-text-color-regular);white-space:nowrap}.phase-actions{display:flex;align-items:center;gap:11px;padding:5px 14px}.stage-items,.phase-actions button{border:0;background:transparent;padding:0;cursor:pointer}.phase-actions button{color:var(--el-color-primary);font-size:11px;white-space:nowrap}
.phase-plan{font-size:10px;padding:3px 14px 0;color:var(--el-text-color-secondary);overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.phase-plan.warning{color:var(--el-color-warning)}
.phase-description{display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical;overflow:hidden;white-space:pre-wrap;overflow-wrap:anywhere;font-size:11px;line-height:16px;height:32px;margin:3px 14px 6px;color:var(--el-text-color-regular)}.phase-description.empty{color:var(--el-text-color-placeholder)}

View File

@ -4,9 +4,10 @@ import { onBeforeUnmount, onMounted, watch, type ComputedRef } from 'vue'
* 在画布鼠标手势被窗口切换或弹窗中断时,释放 Vue Flow 的浏览器拖放拦截。
* @param gestureActive 仅当前画布的节点拖动或画布平移状态,不包含节点库的原生拖放
* @param interrupted 画布隐藏或对话框打开时为 true,停止继续接收当前画布手势
* @param cancelSelection 可选的框选清理;Vue Flow 的指针框选不会触发 D3 的 mouseup,需要另行复位
* @returns 可在再次操作节点库前调用的清理函数;不改动节点业务数据
*/
export function useCanvasGestureCleanup(gestureActive: ComputedRef<boolean>, interrupted: ComputedRef<boolean>) {
export function useCanvasGestureCleanup(gestureActive: ComputedRef<boolean>, interrupted: ComputedRef<boolean>, cancelSelection?: () => void) {
let pointer = { x: 0, y: 0 }, finishing = false, suppressInterruptedClick = false
/** 仅记录坐标,不捕获或阻止事件,使鼠标释放仍由 Vue Flow 自己处理。 */
@ -28,6 +29,7 @@ export function useCanvasGestureCleanup(gestureActive: ComputedRef<boolean>, int
* 升级 Vue Flow 后,若其已自行处理失焦和隐藏时的手势释放,可重新验证并移除此兼容处理。
*/
function finishCanvasGesture() {
cancelSelection?.()
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 })) }

View File

@ -0,0 +1,244 @@
import { computed, onBeforeUnmount, onMounted, ref, watch, type Ref } from 'vue'
import type { GraphNode, Node, NodeDragEvent } from '@vue-flow/core'
import type { Point } from '../../../types'
import { createIdempotencyKey } from '../../../shared/utils/idempotency'
import { absoluteRectangle, type FlowNodeData } from '../utils/graph'
import { arrangeBoxes, containsBox, selectionRoots, snapBox, type ArrangeAction, type CanvasBox, type CanvasGuide, type CanvasSection } from '../utils/canvasGeometry'
interface CanvasToolsOptions {
nodes: Readonly<Ref<GraphNode<FlowNodeData>[]>>
viewport: Readonly<Ref<Point & { zoom: number }>>
enabled: Readonly<Ref<boolean>>
toFlow: (point: Point) => Point
changed: () => void
}
/**
* 管理纯展示的分区、框选排版和拖动辅助,不调用业务接口或改变阶段父子关系。
* @param options 当前 Vue Flow 实例、坐标转换及本地保存回调;不得传入其他项目画布的节点
* @returns 工具状态与事件处理器;浏览器手势监听在结束、失焦、页签隐藏和卸载时释放
*/
export function useCanvasTools(options: CanvasToolsOptions) {
const sections = ref<CanvasSection[]>([]), guidesEnabled = ref(true), guides = ref<CanvasGuide[]>([])
const mode = ref<'pan' | 'select' | 'section'>('pan'), draft = ref<CanvasBox | null>(null), resizing = ref(false)
const selected = computed(() => selectionRoots(options.nodes.value.filter(node => node.selected && node.type !== 'section').map(localBox)))
const sameScope = computed(() => new Set(selected.value.map(node => node.parentNode || '')).size <= 1)
let pointerCleanup: ((commit: boolean) => void) | null = null
let dragActive = false
let carried: { id: string; sectionId: string; position: Point; origin: Point }[] = []
const carriedChildren = new Map<string, Point>()
/** 同层排版用相对矩形;辅助线另取绝对坐标,不能混用这两个坐标空间。 */
function localBox(node: Node<FlowNodeData>): CanvasBox {
const rect = absoluteRectangle(node, [])
return { ...rect, id: node.id, parentNode: node.parentNode }
}
/** 根选区整体与兄弟节点比较,父节点已选中时排除其子节点,避免吸附到自己的内容。 */
function dragBoxes(event: NodeDragEvent): CanvasBox[] {
return selectionRoots(event.nodes.filter(node => !carriedChildren.has(node.id)).map(node => ({ ...absoluteRectangle(node, options.nodes.value), id: node.id, parentNode: node.parentNode })))
}
/** 拖动分区时在起点确定内部根节点,整个手势不重新收集,防止途经节点被意外带走。 */
function startDrag(event: NodeDragEvent) {
dragActive = true
captureSectionContents(event.nodes)
}
/** 鼠标和键盘共用起点包含关系;已在本次移动集合中的根节点由调用方移动,不能重复携带。 */
function captureSectionContents(moving: GraphNode<FlowNodeData>[]) {
carried = []; carriedChildren.clear()
const moved = new Set(moving.map(node => node.id)), captured = new Set<string>()
for (const sectionNode of moving.filter(node => node.type === 'section')) {
const area = { ...absoluteRectangle(sectionNode, options.nodes.value), id: sectionNode.id }
for (const node of options.nodes.value) {
if (node.type === 'section' || moved.has(node.id) || captured.has(node.id) || !containsBox(area, { ...absoluteRectangle(node, options.nodes.value), id: node.id, parentNode: node.parentNode })) continue
carried.push({ id: node.id, sectionId: sectionNode.id, position: { ...node.position }, origin: { ...sectionNode.position } }); captured.add(node.id)
}
}
// 选区包含分区及其组内子阶段时,组会被分区整体携带;子阶段必须保留起点相对坐标,不能再直接位移。
for (const node of moving) if (node.parentNode && captured.has(node.parentNode)) carriedChildren.set(node.id, { ...node.position })
}
/** 每次鼠标移动按当前缩放吸附整个选区,再按分区起点补偿内部节点;松手时须再调用一次。 */
function drag(event: NodeDragEvent) {
restoreCarriedChildren()
const roots = dragBoxes(event), ids = new Set(roots.map(box => box.id))
const movingNodes = event.nodes.filter(node => ids.has(node.id))
guides.value = []
const carriedIds = new Set(carried.map(item => item.id))
if (guidesEnabled.value && roots.length && new Set(roots.map(box => box.parentNode || '')).size === 1) {
const x = Math.min(...roots.map(box => box.x)), y = Math.min(...roots.map(box => box.y))
const area = { id: event.node.id, parentNode: roots[0].parentNode, x, y, width: Math.max(...roots.map(box => box.x + box.width)) - x, height: Math.max(...roots.map(box => box.y + box.height)) - y }
const sectionsOnly = roots.every(box => box.id.startsWith('section:'))
const peers = options.nodes.value.filter(node => !ids.has(node.id) && !ids.has(node.parentNode || '') && !carriedIds.has(node.id) && (node.type === 'section') === sectionsOnly).map(node => ({ ...absoluteRectangle(node, options.nodes.value), id: node.id, parentNode: node.parentNode }))
const result = snapBox(area, peers, 6 / options.viewport.value.zoom)
for (const node of movingNodes) node.position = { x: node.position.x + result.delta.x, y: node.position.y + result.delta.y }
guides.value = result.guides
}
moveSectionContents()
}
/** 按分区整体位移补偿内部节点,阶段组的子节点由 Vue Flow 自然继承父坐标。 */
function moveSectionContents() {
for (const item of carried) {
const node = options.nodes.value.find(node => node.id === item.id), section = options.nodes.value.find(node => node.id === item.sectionId)
if (node && section) node.position = { x: item.position.x + section.position.x - item.origin.x, y: item.position.y + section.position.y - item.origin.y }
}
restoreCarriedChildren()
}
/** Vue Flow 会先应用全部显式选中节点的拖动;将被携带组内的选中子阶段恢复为起点相对坐标。 */
function restoreCarriedChildren() {
for (const [id, position] of carriedChildren) {
const child = options.nodes.value.find(node => node.id === id)
if (child) child.position = { ...position }
}
}
/** 分区几何与 Vue Flow 节点分开存储;只记录展示矩形,不持久化节点快照或任何业务能力。 */
function syncSections() {
sections.value = sections.value.map(section => {
const node = options.nodes.value.find(item => item.id === section.id)
return node ? { ...section, ...absoluteRectangle(node, []), id: section.id } : section
})
}
/** 辅助线随手势结束清空;本地分区位置由调用方与阶段坐标在一次保存中写入。 */
function finishDrag() { syncSections(); carried = []; carriedChildren.clear(); dragActive = false; guides.value = [] }
/**
* 接管画布方向键微调,避免 Vue Flow 默认移动绕过分区携带、组边界和本地保存。
* @param event 仅当前画布冒泡的键盘事件;文本输入和按钮自身的键盘操作不移动节点
* @remarks 方向键每次移动 1 个画布单位,Shift 为 10;精确微调不吸附,父子选中只移动父级。
*/
function moveWithKeyboard(event: KeyboardEvent) {
const vectors: Record<string, Point> = { ArrowLeft: { x: -1, y: 0 }, ArrowRight: { x: 1, y: 0 }, ArrowUp: { x: 0, y: -1 }, ArrowDown: { x: 0, y: 1 } }
const vector = vectors[event.key], target = event.target as Element
if (!vector || target.closest('input,textarea,select,[contenteditable="true"]')) return
event.stopPropagation()
// 鼠标手势持有起点快照或尺寸闭包时不能用键盘重建画布,否则后续移动会写入已被替换的节点对象。
if (dragActive || pointerCleanup) { event.preventDefault(); return }
if (target.closest('button') || event.ctrlKey || event.metaKey || event.altKey || !options.enabled.value || mode.value === 'section') return
const selectedIds = new Set(selectionRoots(options.nodes.value.filter(node => node.selected).map(localBox)).map(box => box.id))
const moving = options.nodes.value.filter(node => selectedIds.has(node.id))
if (!moving.length) return
event.preventDefault(); captureSectionContents(moving)
const step = event.shiftKey ? 10 : 1
for (const node of moving) if (!carriedChildren.has(node.id)) node.position = { x: node.position.x + vector.x * step, y: node.position.y + vector.y * step }
moveSectionContents(); finishDrag(); options.changed()
}
/** 对齐只作用于同一父画布的阶段,均分空间不足时返回可展示的原因,不做部分变更。 */
function arrange(action: ArrangeAction): string {
if (!options.enabled.value) return '画布正在处理其他操作,请稍后重试。'
const result = arrangeBoxes(selected.value, action)
if (!result) return !sameScope.value ? '请选择同一画布层级的节点进行对齐。' : action.startsWith('distribute-') ? '等间距需要至少三个节点,且首尾之间有足够空间。' : '请至少选择两个节点。'
for (const node of options.nodes.value) if (result[node.id]) node.position = result[node.id]
options.changed()
return ''
}
/** 创建分区仅保存标题与几何值;不将阶段挂到分区下,因此已有执行边和组约束保持独立。 */
function addSection(box: Omit<CanvasBox, 'id'>) {
if (sections.value.length >= 200) return
sections.value.push({ ...box, id: 'section:' + createIdempotencyKey(), name: '分区 ' + (sections.value.length + 1), width: Math.max(180, box.width), height: Math.max(120, box.height) })
mode.value = 'pan'; options.changed()
}
/** 以选中根阶段或完整阶段组的边界创建分区;子阶段仍由业务阶段组管理,不能被展示分区拆出。 */
function sectionFromSelection(): string {
if (!selected.value.length || selected.value.some(box => box.parentNode)) return '请选择根画布节点;组内子阶段请选中其完整阶段组。'
if (sections.value.length >= 200) return '当前画布最多支持 200 个分区。'
const x = Math.min(...selected.value.map(box => box.x)) - 24, y = Math.min(...selected.value.map(box => box.y)) - 48
const width = Math.max(...selected.value.map(box => box.x + box.width)) - x + 24, height = Math.max(...selected.value.map(box => box.y + box.height)) - y + 24
if (width > 20000 || height > 20000) return '所选节点跨度过大,请分为多个分区(分区边长最多 20000)。'
addSection({ x, y, width, height })
return ''
}
/** 改名仅接受有限长度的非空文本;节点组件提交草稿后才同步到浏览器偏好。 */
function renameSection(id: string, name: string) {
const section = sections.value.find(item => item.id === id), normalized = name.trim().slice(0, 100)
if (!options.enabled.value || !section || !normalized) return
section.name = normalized; options.changed()
}
/** 删除的是展示分区,内部阶段、连线和历史记录不受影响。 */
function removeSection(id: string) {
if (!options.enabled.value) return
sections.value = sections.value.filter(section => section.id !== id); options.changed()
}
/**
* 在空白画布按下后绘制分区,使用屏幕到画布的转换处理缩放和平移。
* @param event 左键指针事件;阻止兼容鼠标事件,避免 Vue Flow 同时平移或框选
* @remarks 取消、失焦、隐藏和卸载只清理草稿;小于 20 像素的误触不创建分区。
*/
function drawSection(event: PointerEvent) {
if (!options.enabled.value || mode.value !== 'section' || event.button !== 0 || sections.value.length >= 200) return
const target = event.target as Element
if (target.closest('.vue-flow__node, .vue-flow__controls, .vue-flow__minimap')) return
event.preventDefault(); event.stopPropagation()
const start = options.toFlow({ x: event.clientX, y: event.clientY })
draft.value = { id: 'draft', ...start, width: 0, height: 0 }
/** 反向拖框同样使用最小坐标,分区尺寸始终非负。 */
const move = (pointer: PointerEvent) => {
const end = options.toFlow({ x: pointer.clientX, y: pointer.clientY })
draft.value = { id: 'draft', x: Math.min(start.x, end.x), y: Math.min(start.y, end.y), width: Math.min(20000, Math.abs(end.x - start.x)), height: Math.min(20000, Math.abs(end.y - start.y)) }
}
listenPointer(move, commit => {
const box = draft.value; draft.value = null
if (commit && box && box.width >= 20 && box.height >= 20) addSection(box)
})
}
/** 右下角调整分区尺寸,按缩放换算并限制在可持久化范围;取消时恢复原尺寸。 */
function resizeSection(id: string, event: PointerEvent) {
if (!options.enabled.value || event.button !== 0) return
const node = options.nodes.value.find(item => item.id === id)
if (!node) return
const original = absoluteRectangle(node, []), start = options.toFlow({ x: event.clientX, y: event.clientY })
resizing.value = true
listenPointer(pointer => {
const end = options.toFlow({ x: pointer.clientX, y: pointer.clientY })
node.style = { width: Math.min(20000, Math.max(180, original.width + end.x - start.x)) + 'px', height: Math.min(20000, Math.max(120, original.height + end.y - start.y)) + 'px' }
}, commit => {
if (!commit) node.style = { width: original.width + 'px', height: original.height + 'px' }
resizing.value = false; syncSections(); options.changed()
})
}
/** 单个指针手势独占临时监听;先释放监听再执行保存,避免回调重建画布时仍有旧监听写入。 */
function listenPointer(move: (event: PointerEvent) => void, finish: (commit: boolean) => void) {
pointerCleanup?.(false)
/** 正常抬起提交;取消和窗口失焦撤销当前草稿。 */
const up = () => cleanup(true), cancel = () => cleanup(false)
/** 事件清理可重复调用,隐藏与卸载的连续回调不会二次提交。 */
function cleanup(commit: boolean) {
if (pointerCleanup !== cleanup) return
pointerCleanup = null
window.removeEventListener('pointermove', move); window.removeEventListener('pointerup', up)
window.removeEventListener('pointercancel', cancel); window.removeEventListener('blur', cancel)
finish(commit)
}
pointerCleanup = cleanup
window.addEventListener('pointermove', move); window.addEventListener('pointerup', up)
window.addEventListener('pointercancel', cancel); window.addEventListener('blur', cancel)
}
/** 组装纯展示节点,不提供执行连接点,也不设置业务 parentNode。 */
function sectionNodes(): Node<FlowNodeData>[] {
return sections.value.map(section => ({ id: section.id, type: 'section', position: { x: section.x, y: section.y }, style: { width: section.width + 'px', height: section.height + 'px' }, zIndex: -10, connectable: false, deletable: false, dragHandle: '.section-drag', data: { section } }))
}
watch(guidesEnabled, () => { guides.value = []; options.changed() })
watch(options.enabled, enabled => { if (!enabled) { pointerCleanup?.(false); guides.value = [] } })
/** 浏览器切后台未必触发窗口 blur;隐藏时同样撤销未结束的分区草稿。 */
function visibilityChanged() { if (document.hidden) pointerCleanup?.(false) }
onMounted(() => document.addEventListener('visibilitychange', visibilityChanged))
onBeforeUnmount(() => { pointerCleanup?.(false); carried = []; document.removeEventListener('visibilitychange', visibilityChanged) })
return { sections, guidesEnabled, guides, mode, draft, resizing, selected, sameScope,
interacting: computed(() => !!draft.value || resizing.value), startDrag, drag, finishDrag, moveWithKeyboard, arrange, drawSection, resizeSection,
renameSection, removeSection, sectionFromSelection, sectionNodes }
}

View File

@ -0,0 +1,133 @@
import type { Point } from '../../../types'
export interface CanvasBox extends Point { id: string; width: number; height: number; parentNode?: string }
export interface CanvasSection extends CanvasBox { name: string }
export interface CanvasGuide { x1: number; y1: number; x2: number; y2: number; kind: 'alignment' | 'distance'; label?: string }
export type ArrangeAction = 'left' | 'center-x' | 'right' | 'top' | 'center-y' | 'bottom' | 'distribute-x' | 'distribute-y'
/** 同时选择父子时只操作最外层,防止阶段组平移后子节点又被重复移动。 */
export function selectionRoots<T extends CanvasBox>(boxes: T[]): T[] {
const ids = new Set(boxes.map(box => box.id))
return boxes.filter(box => !box.parentNode || !ids.has(box.parentNode))
}
/**
* 在同一父画布内计算六种对齐或边缘间距均分,不修改阶段归属。
* @param input 选中节点的本层矩形;对齐以选区包围框为基准,均分固定首尾
* @param action 工具栏动作;center-x 表示横坐标中心相同,center-y 表示纵坐标中心相同
* @returns 节点的新本层坐标;跨父级、数量不足或均分空间不足返回 null,避免制造重叠
*/
export function arrangeBoxes(input: CanvasBox[], action: ArrangeAction): Record<string, Point> | null {
const boxes = selectionRoots(input)
if (boxes.length < 2 || new Set(boxes.map(box => box.parentNode || '')).size !== 1) return null
const horizontal = ['left', 'center-x', 'right', 'distribute-x'].includes(action)
const axis = horizontal ? 'x' : 'y', size = horizontal ? 'width' : 'height'
const start = Math.min(...boxes.map(box => box[axis])), end = Math.max(...boxes.map(box => box[axis] + box[size]))
if (action.startsWith('distribute-')) {
if (boxes.length < 3) return null
const sorted = [...boxes].sort((a, b) => a[axis] - b[axis] || a.id.localeCompare(b.id))
// 排序末节点可能小于中间的大阶段组;以首尾节点本身界定跨度,不能借外包围框把尾节点推远。
const last = sorted[sorted.length - 1], span = last[axis] + last[size] - sorted[0][axis]
const gap = (span - sorted.reduce((sum, box) => sum + box[size], 0)) / (boxes.length - 1)
if (gap < 0) return null
let offset = start
return Object.fromEntries(sorted.map(box => { const position = { x: box.x, y: box.y, [axis]: offset }; offset += box[size] + gap; return [box.id, position] }))
}
return Object.fromEntries(boxes.map(box => [box.id, { x: box.x, y: box.y,
[axis]: action.startsWith('center-') ? (start + end - box[size]) / 2 : ['right', 'bottom'].includes(action) ? end - box[size] : start }]))
}
/** 判断整块根节点是否位于分区内部;阶段组按整体矩形计入,组内子阶段不单独归属。 */
export function containsBox(section: CanvasBox, box: CanvasBox): boolean {
return !box.parentNode && box.x >= section.x && box.y >= section.y && box.x + box.width <= section.x + section.width && box.y + box.height <= section.y + section.height
}
/** 两矩形在指定轴上的投影相交,只有同排或同列才比较间距,避免远处节点干扰吸附。 */
function overlaps(a: CanvasBox, b: CanvasBox, axis: 'x' | 'y'): boolean {
const size = axis === 'x' ? 'width' : 'height'
return a[axis] < b[axis] + b[size] && a[axis] + a[size] > b[axis]
}
/** 生成可缩放的距离标记,数值采用画布坐标像素,与缩放比例无关。 */
function distanceGuide(a: CanvasBox, b: CanvasBox, axis: 'x' | 'y'): CanvasGuide {
if (axis === 'x') {
const y = Math.max(a.y, b.y) - 12
return { x1: a.x + a.width, y1: y, x2: b.x, y2: y, kind: 'distance', label: String(Math.round(b.x - a.x - a.width)) }
}
const x = Math.max(a.x, b.x) - 12
return { x1: x, y1: a.y + a.height, x2: x, y2: b.y, kind: 'distance', label: String(Math.round(b.y - a.y - a.height)) }
}
/**
* 拖动时计算边缘/中心与等间距吸附,并返回非交互的辅助线。
* @param moving 当前拖动选区的绝对包围框,多选时作为整体处理
* @param input 未拖动的同层节点;调用方排除已选父节点的子孙
* @param threshold 画布坐标阈值,调用方使用 6 / zoom 保持屏幕上吸附距离一致
* @returns 修正偏移及吸附后的辅助线;每轴只选择最接近目标,不做全图自动布局
*/
export function snapBox(moving: CanvasBox, input: CanvasBox[], threshold: number): { delta: Point; guides: CanvasGuide[] } {
const peers = input.filter(box => box.id !== moving.id && (box.parentNode || '') === (moving.parentNode || ''))
const delta: Point = { x: 0, y: 0 }, references: CanvasGuide[] = []
for (const axis of ['x', 'y'] as const) {
const size = axis === 'x' ? 'width' : 'height', other = axis === 'x' ? 'y' : 'x'
let best = threshold + 0.001, correction = 0, reference: CanvasGuide | undefined
// 一轴最多吸附一次;均分候选只用同排/列相邻节点,排序后线性扫描,避免逐帧 O(N²) 配对。
for (const peer of peers) for (const from of [0, 0.5, 1]) for (const to of [0, 0.5, 1]) {
const value = peer[axis] + peer[size] * to - moving[axis] - moving[size] * from
if (Math.abs(value) < best) { best = Math.abs(value); correction = value; reference = undefined }
}
const row = peers.filter(peer => overlaps(moving, peer, other)).sort((a, b) => a[axis] - b[axis])
for (let i = 1; i < row.length; i++) {
const a = row[i - 1], b = row[i], gap = b[axis] - a[axis] - a[size]
if (gap < 0) continue
const targets = [a[axis] - gap - moving[size], b[axis] + b[size] + gap]
if (gap >= moving[size]) targets.push((a[axis] + a[size] + b[axis] - moving[size]) / 2)
for (const target of targets) {
const value = target - moving[axis]
if (Math.abs(value) < best) { best = Math.abs(value); correction = value; reference = distanceGuide(a, b, axis) }
}
}
delta[axis] = correction
if (reference) references.push(reference)
}
const snapped = { ...moving, x: moving.x + delta.x, y: moving.y + delta.y }, guides: CanvasGuide[] = [...references]
for (const axis of ['x', 'y'] as const) {
const size = axis === 'x' ? 'width' : 'height', other = axis === 'x' ? 'y' : 'x', otherSize = axis === 'x' ? 'height' : 'width'
for (const peer of peers) for (const from of [0, 0.5, 1]) for (const to of [0, 0.5, 1]) {
const at = snapped[axis] + snapped[size] * from
if (Math.abs(at - peer[axis] - peer[size] * to) > 0.01) continue
const low = Math.min(snapped[other], peer[other]) - 12, high = Math.max(snapped[other] + snapped[otherSize], peer[other] + peer[otherSize]) + 12
guides.push(axis === 'x' ? { x1: at, x2: at, y1: low, y2: high, kind: 'alignment' } : { y1: at, y2: at, x1: low, x2: high, kind: 'alignment' })
}
const row = peers.filter(peer => overlaps(snapped, peer, other))
const before = row.filter(peer => peer[axis] + peer[size] <= snapped[axis]).sort((a, b) => b[axis] + b[size] - a[axis] - a[size])[0]
const after = row.filter(peer => peer[axis] >= snapped[axis] + snapped[size]).sort((a, b) => a[axis] - b[axis])[0]
if (before) guides.push(distanceGuide(before, snapped, axis))
if (after) guides.push(distanceGuide(snapped, after, axis))
}
// 同列/同行可能有大量节点;合并共线标记后,SVG 数量只与选区锚点数量相关,避免逐帧堆积 DOM。
const merged = new Map<string, CanvasGuide>()
for (const guide of guides) {
const vertical = guide.x1 === guide.x2
const key = guide.kind === 'alignment' ? (vertical ? 'x:' + guide.x1 : 'y:' + guide.y1) : JSON.stringify(guide)
const previous = merged.get(key)
if (previous && guide.kind === 'alignment') {
if (vertical) { previous.y1 = Math.min(previous.y1, guide.y1); previous.y2 = Math.max(previous.y2, guide.y2) }
else { previous.x1 = Math.min(previous.x1, guide.x1); previous.x2 = Math.max(previous.x2, guide.x2) }
} else merged.set(key, { ...guide })
}
return { delta, guides: [...merged.values()] }
}
/** 验证浏览器分区草稿并复制有限几何值,过滤损坏、重复或过大对象;不接受任何阶段父级字段。 */
export function sanitizeSections(value: unknown): CanvasSection[] {
if (!Array.isArray(value)) return []
const ids = new Set<string>(), result: CanvasSection[] = []
for (const entry of value.slice(0, 200)) {
if (!entry || typeof entry !== 'object' || typeof entry.id !== 'string' || !/^section:[\w-]{1,100}$/.test(entry.id) || ids.has(entry.id)) continue
if (typeof entry.name !== 'string' || !entry.name.trim() || !['x', 'y', 'width', 'height'].every(key => typeof entry[key] === 'number' && Number.isFinite(entry[key]))) continue
if (Math.abs(entry.x) > 1e7 || Math.abs(entry.y) > 1e7 || entry.width < 180 || entry.height < 120 || entry.width > 20000 || entry.height > 20000) continue
result.push({ id: entry.id, name: entry.name.trim().slice(0, 100), x: entry.x, y: entry.y, width: entry.width, height: entry.height }); ids.add(entry.id)
}
return result
}

View File

@ -2,8 +2,9 @@ import type { Node, Edge } from '@vue-flow/core'
import { ConnectionLineType, MarkerType } from '@vue-flow/core'
import { FLOW_REWORK_COLOR } from '../constants/theme'
import type { FlowView, Point, Stage, WorkItem } from '../../../types'
import type { CanvasSection } from './canvasGeometry'
export interface FlowNodeData { item?: WorkItem; children?: WorkItem[]; stage?: Stage; stageId?: number; title?: string; itemCount?: number; collapsed?: boolean; [key: string]: unknown }
export interface FlowNodeData { section?: CanvasSection; item?: WorkItem; children?: WorkItem[]; stage?: Stage; stageId?: number; title?: string; itemCount?: number; collapsed?: boolean; [key: string]: unknown }
export interface FlowEdgeData { kind?: 'execution' | 'rework'; linkId?: number; version?: number; reworkCount?: number; latestReworkAt?: string; laneY?: number; sourceEscapeX?: number; targetEscapeX?: number; [key: string]: unknown }
interface Rectangle extends Point { width: number; height: number }
export const FLOW_ITEM_WIDTH = 260
@ -50,7 +51,7 @@ export function buildFlowGraph(view: FlowView, positions: Record<string, Point>,
}
if (!stages.length || view.unassigned?.counts.total) {
const rootRects = stages.filter(stage => !stage.parentStageId).map(stage => rectangles.get(stage.id)!)
const position = freePosition({ x: 30, y: 40 }, FLOW_STAGE_WIDTH, FLOW_STAGE_HEIGHT, rootRects, 48)
const position = positions['s:0'] || freePosition({ x: 30, y: 40 }, FLOW_STAGE_WIDTH, FLOW_STAGE_HEIGHT, rootRects, 48)
nodes.push({ id: 's:0', type: 'stage', position, style: { width: FLOW_STAGE_WIDTH + 'px', height: FLOW_STAGE_HEIGHT + 'px' }, data: { stageId: 0, title: '未分配', itemCount: view.unassigned?.counts.total || 0 }, connectable: false, dragHandle: '.stage-drag' })
}
const visible = new Set(nodes.map(node => node.id))
@ -92,7 +93,8 @@ export function buildFlowGraph(view: FlowView, positions: Record<string, Point>,
const level = levels.get(stage.id)!, size = rectangles.get(stage.id) || { width: FLOW_STAGE_WIDTH, height: FLOW_STAGE_HEIGHT }, saved = positions['s:' + stage.id]
const shift = groupOffsets.get(stage.id)
const preferred = saved ? { x: saved.x + (shift?.x || 0), y: saved.y + (shift?.y || 0) } : { x: columns.get(level)!, y: nextY.get(level) || top }
const point = freePosition(preferred, size.width, size.height, occupied, 48), rect = { ...point, width: size.width, height: size.height }
// 自动避让只用于新节点;手动吸附、对齐和均分的坐标必须原样恢复,否则松手后会被二次排版。
const point = saved ? preferred : freePosition(preferred, size.width, size.height, occupied, 48), rect = { ...point, width: size.width, height: size.height }
rectangles.set(stage.id, rect); occupied.push(rect); nextY.set(level, point.y + size.height + 56)
}
}
@ -152,12 +154,12 @@ export function updateReworkRoutes(nodes: Node<FlowNodeData>[], edges: Edge<Flow
/** 将相对子节点转为绝对矩形,用于适应画布和回退通道,避免硬编码阶段组尺寸。 */
export function absoluteRectangle(node: Node<FlowNodeData>, nodes: Node<FlowNodeData>[]): Rectangle {
const parent = nodes.find(candidate => candidate.id === node.parentNode), origin = parent ? absoluteRectangle(parent, nodes) : { x: 0, y: 0 }
const parent = node.parentNode ? nodes.find(candidate => candidate.id === node.parentNode) : undefined, origin = parent ? absoluteRectangle(parent, nodes) : { x: 0, y: 0 }
const style = typeof node.style === 'object' ? node.style : {}
return { x: origin.x + node.position.x, y: origin.y + node.position.y, width: Number.parseFloat(String(style?.width || FLOW_STAGE_WIDTH)), height: Number.parseFloat(String(style?.height || FLOW_STAGE_HEIGHT)) }
}
/** 在当前作用域内按实际矩形向下避让,兼容浏览器中相互覆盖的旧坐标。 */
/** 仅对未保存坐标的新节点在当前作用域内向下避让,避免覆盖已有的手动排列。 */
function freePosition(candidate: Point, width: number, height: number, occupied: Rectangle[], gap: number): Point {
const point = { ...candidate }; let conflicts: Rectangle[]
do { conflicts = occupied.filter(rect => point.x < rect.x + rect.width + gap && point.x + width + gap > rect.x && point.y < rect.y + rect.height + gap && point.y + height + gap > rect.y); if (conflicts.length) point.y = Math.max(...conflicts.map(rect => rect.y + rect.height + gap)) } while (conflicts.length)

View File

@ -1,6 +1,9 @@
import type { Point } from '../../../types'
import { sanitizeSections, type CanvasSection } from './canvasGeometry'
export interface FlowPreferences {
sections?: CanvasSection[]
guidesEnabled?: boolean
parents?: Record<string, number | null>
collapsedStages: number[]
positions: Record<string, Point>
@ -13,7 +16,7 @@ const VERSION = 2
/** 按登录用户、项目和迭代分隔浏览器偏好,避免同设备或同项目串用画布状态。 */
function key(userId: number | string, projectId: number, iterationId?: number): string { return `pm-flow-view:${userId}:${projectId}${iterationId ? `:${iterationId}` : ""}` }
/** 仅恢复当前格式的展示坐标;本地内容不参与阶段、工作项或权限判断。 */
/** 兼容旧格式坐标并校验新增分区和辅助开关;本地内容不参与阶段、工作项或权限判断。 */
export function readFlowPreferences(userId: number | string, projectId: number, iterationId?: number): FlowPreferences | null {
try {
const raw = localStorage.getItem(key(userId, projectId, iterationId))
@ -26,7 +29,7 @@ export function readFlowPreferences(userId: number | string, projectId: number,
const positions = Object.fromEntries(Object.entries(source.positions).filter(([id, point]) => /^(s|w):\d+$/.test(id) && Number.isFinite(point?.x) && Number.isFinite(point?.y)).map(([id, point]) => [id, { x: point.x, y: point.y }]))
const viewport = source.viewport && Number.isFinite(source.viewport.x) && Number.isFinite(source.viewport.y) && Number.isFinite(source.viewport.zoom) && source.viewport.zoom > 0 ? { x: source.viewport.x, y: source.viewport.y, zoom: source.viewport.zoom } : null
const parents = Object.fromEntries(Object.entries(source.parents || {}).filter(([id, parent]) => /^s:\d+$/.test(id) && (parent === null || Number.isSafeInteger(parent) && parent > 0)))
return { collapsedStages, positions, viewport, parents }
return { collapsedStages, positions, viewport, parents, sections: sanitizeSections(source.sections), guidesEnabled: source.guidesEnabled !== false }
} catch { return null }
}

View File

@ -1,8 +1,16 @@
<template>
<div class="gantt-wrap">
<div class="gantt-note">阶段与工作项共用时间轴;拖动时间条或端点调整计划,失败恢复原排期。虚线为失效参考计划,仅供查看。</div>
<div class="gantt-toolbar">
<div class="gantt-note">阶段与工作项共用时间轴;拖动时间条或端点调整计划,失败恢复原排期。虚线为失效参考计划,仅供查看。</div>
<div class="export-actions">
<el-select v-model="exportFormat" size="small" aria-label="甘特导出格式" :disabled="exporting" class="export-format">
<el-option label="PNG 图片" value="png" /><el-option label="SVG 矢量图" value="svg" />
</el-select>
<el-button size="small" :loading="exporting" :disabled="loading || !!gesture || pending.size > 0 || !projectId || !iterationId" title="导出当前筛选及时间范围的全部记录,包含其他分页" @click="exportImage">导出甘特图</el-button>
</div>
</div>
<div v-if="unscheduled.length" class="unscheduled">排期未完成:<el-link v-for="item in unscheduled" :key="item.id" @click="emit('open', item.id)">{{ item.title }}{{ item.scheduleReviewRequired ? item.scheduleReviewClosed ? '(本轮未确认)' : '(待复核)' : '' }}&nbsp;</el-link></div>
<div class="gantt-scroll">
<div ref="scrollElement" class="gantt-scroll" :style="{ maxHeight: scrollHeight + 'px' }" role="region" aria-label="甘特排期,可横向及纵向滚动" tabindex="0">
<div class="gantt-table" :style="{ width: (labelWidth + days * unit) + 'px' }">
<div class="gantt-head"><div class="item-label">阶段 / 工作项</div><div v-for="day in days" :key="day" class="day" :style="{ width: unit + 'px' }">{{ dayLabel(day - 1) }}</div></div>
<div v-for="row in rows" :key="row.key" class="gantt-row" :class="{ 'stage-row': !!row.stage }">
@ -23,55 +31,64 @@
</div>
</template>
<script setup lang="ts">
import { computed, onBeforeUnmount, reactive, ref } from 'vue'
import { computed, onBeforeUnmount, onDeactivated, reactive, ref, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { WorkItem, ScheduleChange, Stage, StageScheduleChange } from '../../types'
import type { WorkItem, ScheduleChange, Stage, StageScheduleChange, ItemQuery } from '../../types'
import { itemStatusLabel, stageStatusLabel } from '../../shared/constants/labels'
import { shiftDays, visualMillis, localTime, plannedRange, planBoundary, plannedDate } from '../../shared/utils/time'
import { api, errorText } from '../../api'
import { moveSchedule } from '../../shared/utils/optimistic'
import StageSchedulePanel from '../../features/schedules/components/StageSchedulePanel.vue'
import { buildTimelineRows, type TimelineRow } from './utils/timeline'
import { useGanttViewport } from './composables/useGanttViewport'
import { collectGanttData } from './utils/exportData'
import { createGanttImage, ganttImageBlob, downloadGanttImage, type GanttExportFormat } from './utils/exportImage'
interface TimelineRow { key: string; label: string; depth?: number; item?: WorkItem; stage?: Stage; start: string | null; end: string | null; reference: boolean }
const props = withDefaults(defineProps<{ items: WorkItem[]; stages?: Stage[]; zone: string; canWrite: boolean; canManage?: boolean; projectId?: number; iterationId?: number; from?: string; to?: string; memberFiltered?: boolean; stageFilter?: number | null }>(), { stages: () => [], memberFiltered: false })
const props = withDefaults(defineProps<{ items: WorkItem[]; stages?: Stage[]; zone: string; canWrite: boolean; canManage?: boolean; projectId?: number; iterationId?: number; from?: string; to?: string; memberFiltered?: boolean; stageFilter?: number | null; loading?: boolean; projectName?: string; iterationName?: string; exportQuery?: ItemQuery; exportFilters?: string }>(), { stages: () => [], memberFiltered: false })
const emit = defineEmits<{ open: [id: number]; changed: [] }>()
const unit = 34, labelWidth = 220, dayMs = 86400000
const pending = reactive(new Set<string>()), selectedStageId = ref<number | null>(null)
const scrollElement = ref<HTMLElement | null>(null), scrollHeight = useGanttViewport(scrollElement)
const exporting = ref(false), exportFormat = ref<GanttExportFormat>('png')
let exportSequence = 0
// 筛选切走再切回也要作废旧导出;普通轮询替换同值摘要不改变本次导出范围。
watch(() => JSON.stringify([props.projectId, props.iterationId, props.from, props.to, props.stageFilter, props.memberFiltered, props.exportQuery]), () => { exportSequence++ }, { flush: 'sync' })
// 系统菜单由 KeepAlive 缓存,离页不会卸载;停用同样要取消旧导出,返回也不能继续下载。
onDeactivated(() => { exportSequence++ })
const selectedStage = computed(() => props.stages.find(stage => stage.id === selectedStageId.value))
const unscheduled = computed(() => props.items.filter(item => !item.plannedStartAt || !item.plannedEndAt))
/** 父组、子阶段及工作项逐层展示;成员筛选保留完整父路径,各工作项只进入所属工作阶段一次。 */
const rows = computed(() => {
const result: TimelineRow[] = [], known = new Set(props.stages.map(stage => stage.id))
const visible = new Set(props.items.map(item => item.stageId).filter((id): id is number => !!id))
if (props.stageFilter && !props.memberFiltered) {
visible.add(props.stageFilter)
for (const child of props.stages.filter(stage => stage.parentStageId === props.stageFilter)) visible.add(child.id)
}
for (const stage of props.stages) if (visible.has(stage.id) && stage.parentStageId) visible.add(stage.parentStageId)
for (const root of props.stages.filter(stage => !stage.parentStageId)) append(root, 0)
for (const item of props.items.filter(item => !item.stageId || !known.has(item.stageId))) if (hasRange(item)) result.push(timelineRow('i:' + item.id, item.title, item, false))
return result
/** 父级先展示,引用实际阶段计划而非子计划包络;层级只是显示,不改变原子改期入口。 */
function append(stage: Stage, depth: number) {
if ((props.memberFiltered || props.stageFilter != null) && !visible.has(stage.id)) return
result.push({ ...timelineRow('s:' + stage.id, stage.name, stage, true), depth })
for (const child of props.stages.filter(candidate => candidate.parentStageId === stage.id)) append(child, depth + 1)
for (const item of props.items.filter(item => item.stageId === stage.id)) if (hasRange(item)) result.push({ ...timelineRow('i:' + item.id, item.title, item, false), depth: depth + 1 + (item.parentTaskId ? 1 : 0) })
}
})
/** 有效时间优先;只有完整参考区间才画参考条,不拼接两种语义的端点。 */
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 }
const rows = computed(() => buildTimelineRows(props.items, props.stages, props.memberFiltered, props.stageFilter))
// 网格从北京时间零点开始,避免当前时分秒使日期刻度与整日计划错位。
const minimum = computed(() => visualMillis(planBoundary(plannedDate(props.from || new Date(Math.min(...rows.value.filter(row => row.start).map(row => visualMillis(row.start!)), Date.now()) - dayMs).toISOString(), props.zone), 'start', props.zone)!))
const maximum = computed(() => props.to ? visualMillis(props.to) : Math.max(...rows.value.filter(row => row.end).map(row => visualMillis(row.end!)), minimum.value + 14 * dayMs) + dayMs)
const days = computed(() => Math.min(730, Math.max(1, Math.ceil((maximum.value - minimum.value) / dayMs))))
const gesture = ref<{ row: TimelineRow; x: number; kind: 'move' | 'start' | 'end'; delta: number } | null>(null)
let disposed = false
/**
* 固定点击时的筛选、标题和日期轴,读取全部匹配页后生成文件;期间暂停静默同步和改期手势。
* 页面或筛选变化立即使旧结果失效,失败不下载部分数据,也不影响当前甘特的滚动与排期。
*/
async function exportImage() {
if (exporting.value || props.loading || gesture.value || pending.size || !props.projectId || !props.iterationId) return
const sequence = exportSequence, format = exportFormat.value
const query = { ...props.exportQuery, from: props.from, to: props.to, stageId: props.stageFilter, memberIds: [...(props.exportQuery?.memberIds || [])] }
const input = { minimum: minimum.value, days: days.value, zone: props.zone, projectName: props.projectName || '项目协作', iterationName: props.iterationName || '当前迭代', filters: props.exportFilters || '全部' }
const current = () => !disposed && sequence === exportSequence
exporting.value = true
try {
const data = await collectGanttData(props.projectId, props.iterationId, query, current)
if (!current()) return
const exportRows = buildTimelineRows(data.items, data.stages, props.memberFiltered, props.stageFilter, true)
if (!exportRows.length) { ElMessage.info('当前筛选范围没有可导出的排期'); return }
const image = createGanttImage({ ...input, rows: exportRows })
const blob = await ganttImageBlob(image, format)
if (!current()) return
downloadGanttImage(blob, `${input.projectName}_${input.iterationName}_甘特排期_${plannedDate(new Date().toISOString(), props.zone)}`, format)
ElMessage.success('甘特图已导出')
} catch (error) { if (current()) ElMessage({ type: 'error', message: errorText(error), duration: 8000 }) }
finally { exporting.value = false }
}
/** 完成后的正常计划只读;缺失计划在专门的补录面板处理。 */
function frozen(stageId?: number | null) { return ['COMPLETED', 'LEGACY_PASSED'].includes(props.stages.find(stage => stage.id === stageId)?.executionStatus || '') }
/** 参考条、只读阶段及缺少版本的条目不开放手势,最终权限仍由后端重新验证。 */
@ -88,7 +105,7 @@ function barStyle(row: TimelineRow) {
function dayLabel(day: number) { return localTime(new Date(minimum.value + day * dayMs).toISOString(), props.zone).slice(5, 10) }
/** 手势只累计位移,松开前不修改原对象或发送请求。 */
function begin(row: TimelineRow, event: PointerEvent, kind: 'move' | 'start' | 'end') {
if (!editable(row)) return
if (exporting.value || !editable(row)) return
event.preventDefault(); cleanup(); gesture.value = { row, x: event.clientX, kind, delta: 0 }
window.addEventListener('pointermove', track); window.addEventListener('pointerup', end, { once: true })
}
@ -125,8 +142,24 @@ async function end() {
/** 退出时释放监听,打开的原因对话框也不能继续向已离开的迭代写入。 */
function cleanup() { window.removeEventListener('pointermove', track); window.removeEventListener('pointerup', end); gesture.value = null }
onBeforeUnmount(() => { disposed = true; cleanup() })
defineExpose({ isEditing: computed(() => !!gesture.value || pending.size > 0 || selectedStageId.value !== null) })
defineExpose({ isEditing: computed(() => exporting.value || !!gesture.value || pending.size > 0 || selectedStageId.value !== null) })
</script>
<style scoped>
.gantt-note{font-size:12px;color:var(--el-text-color-secondary);margin:0 0 10px}.unscheduled{padding:8px;background:var(--el-color-warning-light-9);margin-bottom:10px;border-radius:6px;font-size:12px}.gantt-scroll{overflow:auto;max-height:calc(100vh - 320px);border:1px solid var(--el-border-color-light);border-radius:6px}.gantt-head,.gantt-row{display:flex;height:38px;align-items:center;border-bottom:1px solid var(--el-border-color-lighter)}.gantt-head{background:var(--el-fill-color-light);position:sticky;top:0;z-index:3}.item-label{width:220px;flex-shrink:0;position:sticky;left:0;background:var(--el-bg-color-overlay);z-index:2;padding:8px;font-size:12px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;cursor:pointer}.stage-row .item-label{font-weight:600;background:var(--el-fill-color-light)}.day{flex-shrink:0;text-align:center;color:var(--el-text-color-secondary);font-size:10px}.timeline{overflow:hidden;position:relative;height:100%;background:repeating-linear-gradient(to right,transparent 0,transparent 33px,var(--el-border-color-lighter) 33px,var(--el-border-color-lighter) 34px)}.bar{position:absolute;top:7px;height:24px;border-radius:4px;background:var(--el-color-primary-light-8);color:var(--el-text-color-primary);font-size:11px;min-width:20px;text-align:center;line-height:24px;cursor:grab;user-select:none;touch-action:none}.bar.stage-bar{background:var(--el-color-primary-light-5);font-weight:600}.bar.blocked{background:var(--el-color-warning-light-8)}.bar.busy{opacity:.55}.bar.reference{border:1px dashed var(--el-color-warning);background:var(--el-color-warning-light-9);color:var(--el-color-warning);cursor:pointer;line-height:22px}.handle{position:absolute;width:7px;top:0;height:100%;cursor:ew-resize;background:var(--el-color-primary-light-5)}.handle.left{left:0}.handle.right{right:0}.blocked-dot{display:inline-block;width:6px;height:6px;border-radius:50%;background:var(--el-color-warning);margin-right:5px}.no-plan{font-size:12px;color:var(--el-text-color-secondary);padding:10px;display:inline-block;cursor:pointer}
.gantt-note{font-size:12px;color:var(--el-text-color-secondary);margin:0 0 10px}.unscheduled{padding:8px;background:var(--el-color-warning-light-9);margin-bottom:10px;border-radius:6px;font-size:12px}.gantt-scroll{overflow:auto;border:1px solid var(--el-border-color-light);border-radius:6px}.gantt-head,.gantt-row{display:flex;height:38px;align-items:center;border-bottom:1px solid var(--el-border-color-lighter)}.gantt-head{background:var(--el-fill-color-light);position:sticky;top:0;z-index:3}.item-label{width:220px;flex-shrink:0;position:sticky;left:0;background:var(--el-bg-color-overlay);z-index:2;padding:8px;font-size:12px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;cursor:pointer}.stage-row .item-label{font-weight:600;background:var(--el-fill-color-light)}.day{flex-shrink:0;text-align:center;color:var(--el-text-color-secondary);font-size:10px}.timeline{overflow:hidden;position:relative;height:100%;background:repeating-linear-gradient(to right,transparent 0,transparent 33px,var(--el-border-color-lighter) 33px,var(--el-border-color-lighter) 34px)}.bar{position:absolute;top:7px;height:24px;border-radius:4px;background:var(--el-color-primary-light-8);color:var(--el-text-color-primary);font-size:11px;min-width:20px;text-align:center;line-height:24px;cursor:grab;user-select:none;touch-action:none}.bar.stage-bar{background:var(--el-color-primary-light-5);font-weight:600}.bar.blocked{background:var(--el-color-warning-light-8)}.bar.busy{opacity:.55}.bar.reference{border:1px dashed var(--el-color-warning);background:var(--el-color-warning-light-9);color:var(--el-color-warning);cursor:pointer;line-height:22px}.handle{position:absolute;width:7px;top:0;height:100%;cursor:ew-resize;background:var(--el-color-primary-light-5)}.handle.left{left:0}.handle.right{right:0}.blocked-dot{display:inline-block;width:6px;height:6px;border-radius:50%;background:var(--el-color-warning);margin-right:5px}.no-plan{font-size:12px;color:var(--el-text-color-secondary);padding:10px;display:inline-block;cursor:pointer}
/* 高度按实际可用区域计算;长时间轴不能撑开父容器,否则横向滚动条会跑到页面之外。 */
.gantt-wrap{min-width:0;width:100%;max-width:100%}
.gantt-toolbar{display:flex;align-items:center;justify-content:space-between;flex-wrap:wrap;gap:8px;margin-bottom:8px}
.gantt-toolbar .gantt-note{flex:1 1 280px;margin:0;line-height:18px}
.export-actions{display:flex;align-items:center;gap:8px;flex:none;margin-left:auto}
.export-format{width:132px}
.unscheduled{max-height:76px;overflow:auto;line-height:22px;overflow-wrap:anywhere}
.gantt-scroll{width:100%;max-width:100%;min-height:80px;box-sizing:border-box;scrollbar-gutter:stable;scrollbar-width:auto;scrollbar-color:var(--el-text-color-placeholder) var(--el-fill-color-light)}
.gantt-scroll:focus-visible{outline:2px solid var(--el-color-primary);outline-offset:2px}
.gantt-scroll::-webkit-scrollbar{width:10px;height:10px}
.gantt-scroll::-webkit-scrollbar-track{background:var(--el-fill-color-light)}
.gantt-scroll::-webkit-scrollbar-thumb{background:var(--el-text-color-placeholder);border-radius:5px;border:2px solid var(--el-fill-color-light)}
.gantt-scroll::-webkit-scrollbar-corner{background:var(--el-fill-color-light)}
.gantt-table{min-width:100%}
.item-label{box-sizing:border-box}
.timeline{flex-shrink:0}
</style>

View File

@ -0,0 +1,85 @@
import { nextTick, onActivated, onBeforeUnmount, onDeactivated, onMounted, ref, type Ref } from 'vue'
/**
* 根据滚动区真实位置分配高度,避免顶部换行、页面缩放和系统页签高度变化遮住横向滚动条。
* @param element 甘特唯一的双向滚动容器
* @returns 最大可用高度;内容较少时仍自然收缩,不改变滚动位置
* 只监听当前工作区,尺寸回调通过一帧合并;卸载时释放全部监听及观察器。
*/
export function useGanttViewport(element: Ref<HTMLElement | null>) {
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<HTMLElement>('.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<HTMLElement>('.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
}

View File

@ -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<number>()
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('导出范围已切换') }
}

View File

@ -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 => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&apos;' })[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 `<text x="${x}" y="${y}" font-size="${size}" fill="${color}" font-weight="${weight}">${xml(value)}</text>`
}
/**
* 从完整业务行生成独立矢量甘特,不截取 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 = [`<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${height}" viewBox="0 0 ${width} ${height}" role="img"><title>${xml(`${input.projectName} / ${input.iterationName} 甘特排期`)}</title><defs><pattern id="day-grid" x="${timelineX}" width="${unit}" height="1" patternUnits="userSpaceOnUse"><path d="M0 0V1" stroke="#e2e8f0" stroke-width="1"/></pattern></defs><rect width="100%" height="100%" fill="#fff"/><g font-family="Microsoft YaHei, PingFang SC, Arial, sans-serif">`]
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(`<rect x="${padding}" y="${headerTop}" width="${width - padding * 2}" height="34" fill="#f1f5f9"/>`, 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(`<g><title>${xml(name)}</title><rect x="${padding}" y="${y}" width="${width - padding * 2}" height="${rowHeight}" fill="${row.stage ? '#f8fafc' : '#fff'}"/>`)
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(`<rect x="${timelineX}" y="${y}" width="${timelineWidth}" height="${rowHeight}" fill="url(#day-grid)"/>`)
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(`<rect x="${timelineX + start}" y="${y + 16}" width="${Math.min(timelineWidth - start, Math.max(1, end - start))}" height="24" rx="4" fill="${reference ? '#fffbeb' : row.item?.dependencyBlocked ? '#fed7aa' : row.stage ? '#93c5fd' : '#bfdbfe'}"${reference ? ' stroke="#d97706" stroke-dasharray="5 3"' : ''}/>`)
}
}
output.push(`<path d="M${padding} ${y + rowHeight}H${width - padding}" stroke="#e2e8f0"/></g>`)
y += rowHeight
}
output.push('</g></svg>')
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<Blob> {
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<void>((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<Blob>((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) }
}

View File

@ -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) })
}
}
}

View File

@ -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,