Merge remote-tracking branch 'origin/project' into project
This commit is contained in:
commit
3a1580077f
@ -527,3 +527,40 @@ WHERE NOT EXISTS(SELECT 1 FROM sys_menu WHERE menu_id=2601);
|
||||
INSERT INTO sys_menu(menu_id,menu_name,parent_id,order_num,path,is_frame,is_cache,menu_type,visible,status,perms,create_by,create_time)
|
||||
SELECT 2602,'项目协作配置',2600,2,'#',1,0,'F','0','0','project:manage:admin','admin',CURRENT_TIMESTAMP
|
||||
WHERE NOT EXISTS(SELECT 1 FROM sys_menu WHERE menu_id=2602);
|
||||
|
||||
-- 阶段组、同层执行图及父级历史组合
|
||||
ALTER TABLE pm_collab_project_stage
|
||||
ADD COLUMN stage_kind VARCHAR(8) NOT NULL DEFAULT 'WORK' COMMENT '阶段类型:WORK工作阶段,GROUP阶段组',
|
||||
ADD COLUMN parent_stage_id BIGINT NULL COMMENT '所属阶段组ID;空值表示迭代根画布',
|
||||
ADD KEY idx_pm_stage_parent(project_id,iteration_id,parent_stage_id,deleted,id),
|
||||
ADD CONSTRAINT fk_pm_stage_parent FOREIGN KEY(project_id,iteration_id,parent_stage_id) REFERENCES pm_collab_project_stage(project_id,iteration_id,id),
|
||||
ADD CONSTRAINT ck_pm_stage_kind CHECK(stage_kind IN ('WORK','GROUP')),
|
||||
ADD CONSTRAINT ck_pm_stage_parent CHECK(stage_kind<>'GROUP' OR parent_stage_id IS NULL);
|
||||
ALTER TABLE pm_collab_stage_edge
|
||||
ADD COLUMN parent_stage_id BIGINT NULL COMMENT '执行连线所属阶段组;空值表示迭代根画布',
|
||||
ADD KEY idx_pm_edge_canvas(project_id,iteration_id,parent_stage_id,id),
|
||||
ADD CONSTRAINT fk_pm_edge_canvas FOREIGN KEY(project_id,iteration_id,parent_stage_id) REFERENCES pm_collab_project_stage(project_id,iteration_id,id);
|
||||
ALTER TABLE pm_collab_stage_revision
|
||||
ADD COLUMN stage_kind_snapshot VARCHAR(8) NOT NULL DEFAULT 'WORK' COMMENT '本版本阶段类型快照',
|
||||
ADD COLUMN parent_stage_snapshot_id BIGINT NULL COMMENT '本版本所属阶段组ID快照',
|
||||
ADD COLUMN stage_description_snapshot TEXT NULL COMMENT '本版本阶段说明快照',
|
||||
ADD COLUMN revision_reason VARCHAR(16) NOT NULL DEFAULT 'INITIAL' COMMENT '产生原因:INITIAL初建,REWORK整体重做,CHILD_REWORK子阶段换版汇总';
|
||||
CREATE TABLE pm_collab_stage_revision_member (
|
||||
id BIGINT NOT NULL AUTO_INCREMENT COMMENT '主键ID',
|
||||
project_id BIGINT NOT NULL COMMENT '协作项目ID',
|
||||
iteration_id BIGINT NOT NULL COMMENT '所属迭代ID',
|
||||
parent_stage_id BIGINT NOT NULL COMMENT '所属阶段组ID',
|
||||
parent_revision_id BIGINT NOT NULL COMMENT '父级汇总版本ID',
|
||||
child_stage_id BIGINT NOT NULL COMMENT '子阶段ID',
|
||||
child_revision_id BIGINT NOT NULL COMMENT '该汇总版本绑定的子执行版本ID',
|
||||
snapshot_json LONGTEXT NULL COMMENT '冻结时的子阶段和工作项只读快照;不包含附件二进制及公开存储地址',
|
||||
snapshot_format_version INT NOT NULL DEFAULT 1 COMMENT '历史快照数据格式版本',
|
||||
frozen_at BIGINT NULL COMMENT '快照冻结时间(UTC微秒);空值表示当前实时组合',
|
||||
PRIMARY KEY(id),
|
||||
UNIQUE KEY uk_pm_group_revision_child(parent_revision_id,child_stage_id),
|
||||
KEY idx_pm_group_child_revision(child_revision_id,parent_revision_id),
|
||||
CONSTRAINT fk_pm_group_parent_revision FOREIGN KEY(project_id,iteration_id,parent_stage_id,parent_revision_id) REFERENCES pm_collab_stage_revision(project_id,iteration_id,stage_id,id),
|
||||
CONSTRAINT fk_pm_group_child_revision FOREIGN KEY(project_id,iteration_id,child_stage_id,child_revision_id) REFERENCES pm_collab_stage_revision(project_id,iteration_id,stage_id,id),
|
||||
CONSTRAINT ck_pm_group_snapshot CHECK((snapshot_json IS NULL AND frozen_at IS NULL) OR (snapshot_json IS NOT NULL AND frozen_at IS NOT NULL AND JSON_VALID(snapshot_json))),
|
||||
CONSTRAINT ck_pm_group_self CHECK(parent_stage_id<>child_stage_id)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='项目协作:阶段组版本成员及冻结历史';
|
||||
|
||||
38
ruoyi-project/sql/upgrade/019_stage_groups.sql
Normal file
38
ruoyi-project/sql/upgrade/019_stage_groups.sql
Normal file
@ -0,0 +1,38 @@
|
||||
-- 项目协作:两层阶段树、同层画布和阶段组历史快照。先备份,018 后执行一次。
|
||||
-- 保留已有阶段、工作项、版本及精确排期;旧阶段全部为根工作阶段。
|
||||
SET NAMES utf8mb4;
|
||||
ALTER TABLE pm_collab_project_stage
|
||||
ADD COLUMN stage_kind VARCHAR(8) NOT NULL DEFAULT 'WORK' COMMENT '阶段类型:WORK工作阶段,GROUP阶段组',
|
||||
ADD COLUMN parent_stage_id BIGINT NULL COMMENT '所属阶段组ID;空值表示迭代根画布',
|
||||
ADD KEY idx_pm_stage_parent(project_id,iteration_id,parent_stage_id,deleted,id),
|
||||
ADD CONSTRAINT fk_pm_stage_parent FOREIGN KEY(project_id,iteration_id,parent_stage_id) REFERENCES pm_collab_project_stage(project_id,iteration_id,id),
|
||||
ADD CONSTRAINT ck_pm_stage_kind CHECK(stage_kind IN ('WORK','GROUP')),
|
||||
ADD CONSTRAINT ck_pm_stage_parent CHECK(stage_kind<>'GROUP' OR parent_stage_id IS NULL);
|
||||
ALTER TABLE pm_collab_stage_edge
|
||||
ADD COLUMN parent_stage_id BIGINT NULL COMMENT '执行连线所属阶段组;空值表示迭代根画布',
|
||||
ADD KEY idx_pm_edge_canvas(project_id,iteration_id,parent_stage_id,id),
|
||||
ADD CONSTRAINT fk_pm_edge_canvas FOREIGN KEY(project_id,iteration_id,parent_stage_id) REFERENCES pm_collab_project_stage(project_id,iteration_id,id);
|
||||
ALTER TABLE pm_collab_stage_revision
|
||||
ADD COLUMN stage_kind_snapshot VARCHAR(8) NOT NULL DEFAULT 'WORK' COMMENT '本版本阶段类型快照',
|
||||
ADD COLUMN parent_stage_snapshot_id BIGINT NULL COMMENT '本版本所属阶段组ID快照',
|
||||
ADD COLUMN stage_description_snapshot TEXT NULL COMMENT '本版本阶段说明快照',
|
||||
ADD COLUMN revision_reason VARCHAR(16) NOT NULL DEFAULT 'INITIAL' COMMENT '产生原因:INITIAL初建,REWORK整体重做,CHILD_REWORK子阶段换版汇总';
|
||||
CREATE TABLE pm_collab_stage_revision_member (
|
||||
id BIGINT NOT NULL AUTO_INCREMENT COMMENT '主键ID',
|
||||
project_id BIGINT NOT NULL COMMENT '协作项目ID',
|
||||
iteration_id BIGINT NOT NULL COMMENT '所属迭代ID',
|
||||
parent_stage_id BIGINT NOT NULL COMMENT '所属阶段组ID',
|
||||
parent_revision_id BIGINT NOT NULL COMMENT '父级汇总版本ID',
|
||||
child_stage_id BIGINT NOT NULL COMMENT '子阶段ID',
|
||||
child_revision_id BIGINT NOT NULL COMMENT '该汇总版本绑定的子执行版本ID',
|
||||
snapshot_json LONGTEXT NULL COMMENT '冻结时的子阶段和工作项只读快照;不包含附件二进制及公开存储地址',
|
||||
snapshot_format_version INT NOT NULL DEFAULT 1 COMMENT '历史快照数据格式版本',
|
||||
frozen_at BIGINT NULL COMMENT '快照冻结时间(UTC微秒);空值表示当前实时组合',
|
||||
PRIMARY KEY(id),
|
||||
UNIQUE KEY uk_pm_group_revision_child(parent_revision_id,child_stage_id),
|
||||
KEY idx_pm_group_child_revision(child_revision_id,parent_revision_id),
|
||||
CONSTRAINT fk_pm_group_parent_revision FOREIGN KEY(project_id,iteration_id,parent_stage_id,parent_revision_id) REFERENCES pm_collab_stage_revision(project_id,iteration_id,stage_id,id),
|
||||
CONSTRAINT fk_pm_group_child_revision FOREIGN KEY(project_id,iteration_id,child_stage_id,child_revision_id) REFERENCES pm_collab_stage_revision(project_id,iteration_id,stage_id,id),
|
||||
CONSTRAINT ck_pm_group_snapshot CHECK((snapshot_json IS NULL AND frozen_at IS NULL) OR (snapshot_json IS NOT NULL AND frozen_at IS NOT NULL AND JSON_VALID(snapshot_json))),
|
||||
CONSTRAINT ck_pm_group_self CHECK(parent_stage_id<>child_stage_id)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='项目协作:阶段组版本成员及冻结历史';
|
||||
@ -32,9 +32,12 @@ public class PmReworkController {
|
||||
/** 阶段历史列表分页且先检查项目、迭代和阶段的完整归属。 */
|
||||
@GetMapping("/projects/{id}/iterations/{iterationId}/stages/{stageId}/revisions")
|
||||
public Map<String,Object> iterationRevisions(@PathVariable long id,@PathVariable long iterationId,@PathVariable long stageId,@RequestParam(defaultValue="1") int page,@RequestParam(defaultValue="50") int pageSize) { return ok(service.revisionPage(id,iterationId,stageId,page,pageSize)); }
|
||||
/** 历史工作项按选定版本分页,可通过原工作项详情 ID 查看只读记录。 */
|
||||
/** 历史工作项按选定版本分页;阶段组详情需继续携带父级版本,防止读取保留分支的后续变化。 */
|
||||
@GetMapping("/projects/{id}/iterations/{iterationId}/stages/{stageId}/revisions/{revisionId}")
|
||||
public Map<String,Object> iterationRevision(@PathVariable long id,@PathVariable long iterationId,@PathVariable long stageId,@PathVariable long revisionId,@RequestParam(defaultValue="1") int page,@RequestParam(defaultValue="50") int pageSize) { return ok(service.revisionItemsPage(id,iterationId,stageId,revisionId,page,pageSize)); }
|
||||
/** 历史父级组合的工作项详情不追随仍活跃的并行分支,权限仍按当前项目成员核验。 */
|
||||
@GetMapping("/projects/{id}/iterations/{iterationId}/stages/{stageId}/revisions/{revisionId}/items/{itemId}")
|
||||
public Map<String,Object> snapshot(@PathVariable long id,@PathVariable long iterationId,@PathVariable long stageId,@PathVariable long revisionId,@PathVariable long itemId) { return ok(service.itemSnapshot(id,iterationId,stageId,revisionId,itemId)); }
|
||||
/** 当前项目阶段轮次列表,旧轮次不混入普通流程图。 */
|
||||
@GetMapping("/projects/{id}/stages/{stageId}/revisions") public Map<String,Object> revisions(@PathVariable long id,@PathVariable long stageId) { return ok(service.revisions(id,stageId)); }
|
||||
/** 轮次的只读工作项快照。 */
|
||||
|
||||
@ -17,6 +17,12 @@ import org.springframework.web.bind.annotation.*;
|
||||
@RestController
|
||||
@RequestMapping("/project/manage")
|
||||
public class PmStageController {
|
||||
/** 结构预览不写成功记录;接口仍复验项目管理者和迭代状态。 */
|
||||
@PostMapping("/projects/{id}/iterations/{iterationId}/stage-structure/preview")
|
||||
public Map<String,Object> structurePreview(@PathVariable long id,@PathVariable long iterationId,@RequestBody JsonNode body) { return ok(service.structure(id,iterationId,decode(body,com.ruoyi.project.manage.dto.StageStructureInput.class),false)); }
|
||||
/** 提交显式最终结构并复算预览图版本,不开放跨层自动迁移。 */
|
||||
@PostMapping("/projects/{id}/iterations/{iterationId}/stage-structure")
|
||||
public Map<String,Object> structureCommit(@PathVariable long id,@PathVariable long iterationId,@RequestBody JsonNode body) { return ok(service.structure(id,iterationId,decode(body,com.ruoyi.project.manage.dto.StageStructureInput.class),true)); }
|
||||
private final IPmStageService service;
|
||||
private final ObjectMapper strict;
|
||||
/** 复用项目动作鉴权服务,独立解码器同时校验所有嵌套展示字段白名单。 */
|
||||
|
||||
@ -3,7 +3,11 @@ package com.ruoyi.project.manage.domain;
|
||||
import java.util.*;
|
||||
|
||||
/** 事务内可替换的最终依赖图,用于统一排期、实际状态和循环校验。 */
|
||||
public record Graph(Map<Long,Item> items,List<Dependency> dependencies,Map<Long,String> stageNames,List<StageLink> stageLinks,Map<Long,StageRevision> stageRevisions,IterationScope iteration) {
|
||||
public record Graph(Map<Long,Item> items,List<Dependency> dependencies,Map<Long,String> stageNames,List<StageLink> stageLinks,Map<Long,StageRevision> stageRevisions,IterationScope iteration,Map<Long,StageInfo> hierarchy) {
|
||||
/** 兼容原平级调用,缺省组织信息明确解释为根工作阶段,不补造父级。 */
|
||||
public Graph(Map<Long,Item> items,List<Dependency> dependencies,Map<Long,String> stageNames,List<StageLink> stageLinks,Map<Long,StageRevision> stageRevisions,IterationScope iteration) { this(items,dependencies,stageNames,stageLinks,stageRevisions,iteration,new LinkedHashMap<>()); }
|
||||
/** 候选图替换组织结构用于最终态校验,不修改原事务快照。 */
|
||||
public Graph withHierarchy(Map<Long,StageInfo> values) { return new Graph(items,dependencies,stageNames,stageLinks,stageRevisions,iteration,new LinkedHashMap<>(values)); }
|
||||
/** 纯规则和历史快照可省略迭代上下文;生产当前图始终显式携带数据库迭代。 */
|
||||
public Graph(Map<Long,Item> items,List<Dependency> dependencies,Map<Long,String> stageNames,List<StageLink> stageLinks,Map<Long,StageRevision> stageRevisions) { this(items,dependencies,stageNames,stageLinks,stageRevisions,null); }
|
||||
/** 旧的纯任务规则测试无需构造阶段;生产图始终由数据库加载有效阶段。 */
|
||||
@ -13,5 +17,5 @@ public record Graph(Map<Long,Item> items,List<Dependency> dependencies,Map<Long,
|
||||
public Graph(Map<Long,Item> items,List<Dependency> dependencies,Map<Long,String> stageNames,List<StageLink> stageLinks) { this(items,dependencies,stageNames,stageLinks,new LinkedHashMap<>()); }
|
||||
|
||||
/** 为事务内最终态验证创建独立容器,不修改已读取的原始快照。 */
|
||||
public Graph copy() { return new Graph(new LinkedHashMap<>(items),new ArrayList<>(dependencies),new LinkedHashMap<>(stageNames),new ArrayList<>(stageLinks),new LinkedHashMap<>(stageRevisions),iteration); }
|
||||
public Graph copy() { return new Graph(new LinkedHashMap<>(items),new ArrayList<>(dependencies),new LinkedHashMap<>(stageNames),new ArrayList<>(stageLinks),new LinkedHashMap<>(stageRevisions),iteration,new LinkedHashMap<>(hierarchy)); }
|
||||
}
|
||||
|
||||
@ -0,0 +1,7 @@
|
||||
package com.ruoyi.project.manage.domain;
|
||||
|
||||
/** 阶段组织身份与执行版本分离;父级表达包含关系,执行先后仍由显式边决定。 */
|
||||
public record StageInfo(long id,String kind,Long parentId,String description) {
|
||||
/** 容器只承载子阶段,不能接受工作项,避免完成规则出现两种来源。 */
|
||||
public boolean group() { return "GROUP".equals(kind); }
|
||||
}
|
||||
@ -1,4 +1,7 @@
|
||||
package com.ruoyi.project.manage.dto;
|
||||
|
||||
/** 阶段组织元数据,不承载执行流程或节点状态。 */
|
||||
public record StageInput(String name,Integer sortOrder,Long ownerId,String description,Integer version) { }
|
||||
/** 阶段创建同时提交组织身份和整日计划;编辑不允许通过元数据接口偷偷迁移父级。 */
|
||||
public record StageInput(String name,Integer sortOrder,Long ownerId,String description,Integer version,String stageKind,Long parentStageId,String plannedStartAt,String plannedEndAt) {
|
||||
/** 原内部元数据调用省略结构字段;创建入口仍要求显式有效计划。 */
|
||||
public StageInput(String name,Integer sortOrder,Long ownerId,String description,Integer version) { this(name,sortOrder,ownerId,description,version,null,null,null,null); }
|
||||
}
|
||||
|
||||
@ -0,0 +1,9 @@
|
||||
package com.ruoyi.project.manage.dto;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/** 结构预览与提交使用同一明确最终态:只移动列出的阶段,执行边列表完整替换,不自动猜测跨层连接。 */
|
||||
public record StageStructureInput(Long graphVersion,List<Move> stages,List<StageEdgeInput> edges) {
|
||||
/** 未执行工作阶段的明确父级变更;空父级表示回到外层画布。 */
|
||||
public record Move(long id,Integer version,Long parentStageId) { }
|
||||
}
|
||||
@ -0,0 +1,21 @@
|
||||
package com.ruoyi.project.manage.mapper;
|
||||
|
||||
import java.util.*;
|
||||
import org.apache.ibatis.annotations.*;
|
||||
|
||||
/** 阶段组当前版本组合与冻结历史的唯一存储入口;写入由统一项目锁事务保护。 */
|
||||
@Mapper
|
||||
public interface PmGroupMapper {
|
||||
/** 冻结时批量读取当前分工名称,避免负责人改名或离开成员清单后历史显示成未分配。 */
|
||||
java.util.List<java.util.Map<String,Object>> selectItemOwners(@Param("projectId") long projectId,@Param("iterationId") long iterationId);
|
||||
/** 查询指定汇总版本的成员,历史读取不能改用子阶段的最新指针。 */
|
||||
List<Map<String,Object>> selectMembers(@Param("revisionId") long revisionId);
|
||||
/** 当前组合在首次执行前可补齐成员;已冻结快照不能覆盖。 */
|
||||
int bindMember(@Param("projectId") long projectId,@Param("iterationId") long iterationId,@Param("parentId") long parentId,@Param("revisionId") long revisionId,@Param("childId") long childId,@Param("childRevisionId") long childRevisionId);
|
||||
/** 清理未执行阶段结构调整留下的旧成员;冻结数据永久保留。 */
|
||||
int deleteDraftMembers(@Param("revisionId") long revisionId);
|
||||
/** 冻结一次成员视图,后续执行不能改变旧版本的工作项、评论及附件元数据。 */
|
||||
int freezeMember(@Param("id") long id,@Param("snapshot") String snapshot,@Param("at") long at);
|
||||
/** 精确写入汇总时间,局部回退的新组合不能沿用错误的 COALESCE 旧开始时间。 */
|
||||
int updateGroupState(@Param("revisionId") long revisionId,@Param("start") Long start,@Param("end") Long end);
|
||||
}
|
||||
@ -9,6 +9,10 @@ import org.apache.ibatis.annotations.Param;
|
||||
/** 项目协作对象访问接口;固定 SQL 位于同名 XML,服务层负责权限、事务与规则。 */
|
||||
@Mapper
|
||||
public interface PmStageMapper {
|
||||
/** 未执行版本随显式结构调整更新身份,已启动快照保持原值用于追溯。 */
|
||||
int refreshDraftRevisionIdentity(@Param("revisionId") long revisionId,@Param("kind") String kind,@Param("parentId") Long parentId,@Param("description") String description);
|
||||
/** 结构提交在完整最终态校验后替换本迭代全部执行边,历史定义快照保留原边。 */
|
||||
int deleteIterationEdges(@Param("projectId") long projectId,@Param("iterationId") long iterationId);
|
||||
/** 移除成员前检查其是否负责有效阶段。 */
|
||||
Map<String,Object> selectOwnedStage(@Param("projectId") long projectId, @Param("userId") Long userId);
|
||||
|
||||
|
||||
@ -11,19 +11,23 @@ import static com.ruoyi.project.manage.util.PmValues.*;
|
||||
/** 在业务提交前固定通知内容及分工,实际投递由 outbox 调度,不在持锁事务内连接邮件服务器。 */
|
||||
@Service
|
||||
public class PmNotificationPlanner {
|
||||
// 操作历史与个人站内消息是两条链路;评论和附件也必须进入此白名单,才能随 outbox 投递给业务分工人员。
|
||||
private static final Map<String,String> ITEM_ACTIONS=Map.ofEntries(
|
||||
Map.entry("ITEM_CREATED","工作项已创建"),Map.entry("CHILD_CREATED","子任务已创建"),
|
||||
Map.entry("ITEM_EDITED","工作项已修改"),Map.entry("ITEM_STAGE_CHANGED","工作项所属阶段已修改"),
|
||||
Map.entry("STATUS_CHANGED","工作项状态已修改"),Map.entry("TASK_STARTED","工作项已开始"),
|
||||
Map.entry("SCHEDULE_CHANGED","工作项排期已修改"),Map.entry("SCHEDULE_REVIEWED","工作项排期已确认"),
|
||||
Map.entry("DEPENDENCY_SAVED","工作项前置依赖已修改"),Map.entry("DEPENDENCY_REMOVED","工作项前置依赖已移除"));
|
||||
Map.entry("DEPENDENCY_SAVED","工作项前置依赖已修改"),Map.entry("DEPENDENCY_REMOVED","工作项前置依赖已移除"),
|
||||
Map.entry("COMMENT_ADDED","工作项新增评论"),Map.entry("ATTACHMENT_ADDED","工作项新增附件"),
|
||||
Map.entry("ATTACHMENT_DELETED","工作项附件已删除"));
|
||||
private final PmNotificationMapper mapper;
|
||||
|
||||
/** 注入本模块的受控读取入口;通知内容不接受客户端提交的收件地址或模板。 */
|
||||
public PmNotificationPlanner(PmNotificationMapper mapper) { this.mapper=mapper; }
|
||||
|
||||
/**
|
||||
* 为创建、修改和回退生成一个通知计划,阶段回退对整个新版本取人员并集,不为复制出的每项生成邮件。
|
||||
* 为工作项创建、修改、评论、附件变更及回退生成通知计划,收件人为去重后的负责人和协作人。
|
||||
* 阶段回退对整个新版本取人员并集;评论和附件入口沿用未勾选邮件时仅发站内消息的默认规则。
|
||||
* @param projectId 调用方已鉴权并锁定的协作项目
|
||||
* @param iterationId 业务事件所属迭代,项目级其他操作不产生个人提醒
|
||||
* @param itemId 普通工作项事件的真实 ID;阶段回退为空
|
||||
|
||||
@ -133,6 +133,7 @@ public final class PmRules {
|
||||
|
||||
/** 用 DFS 三色法检查各类型工作项、父子和阶段执行图;阶段进入/完成拆点,才能检测跨阶段执行死锁。 */
|
||||
public static void validateAcyclic(Graph graph) {
|
||||
PmStageHierarchyRules.validate(graph);
|
||||
Map<String,Set<String>> edges = new LinkedHashMap<>();
|
||||
for (Dependency d : graph.dependencies()) edge(edges,"T"+d.taskId(),"T"+d.successorId());
|
||||
// 父完成等待所有子任务结束,因此子完成→父完成也是执行图中的边。
|
||||
@ -141,6 +142,11 @@ public final class PmRules {
|
||||
// 进入阶段后才可启动工作项;阶段所有工作项完成后才可进入下游。
|
||||
// 空阶段仍有进入→完成边,使纯阶段环及混合任务环使用同一检测算法。
|
||||
for(Long stageId:graph.stageNames().keySet()) edge(edges,"I"+stageId,"O"+stageId);
|
||||
// 父级进入只代表准入;父级完成等待每个子阶段,独立分支也不能漏掉。
|
||||
for(Long stageId:graph.stageNames().keySet()) {
|
||||
Long parent=PmStageHierarchyRules.info(graph,stageId).parentId();
|
||||
if(parent!=null) { edge(edges,"I"+parent,"I"+stageId); edge(edges,"O"+stageId,"O"+parent); }
|
||||
}
|
||||
for(Item item:graph.items().values()) if(!item.deleted()&&item.stageId()!=null&&graph.stageNames().containsKey(item.stageId())) {
|
||||
edge(edges,"I"+item.stageId(),"T"+item.id()); edge(edges,"T"+item.id(),"O"+item.stageId());
|
||||
}
|
||||
|
||||
@ -18,9 +18,15 @@ public final class PmScheduleReviewRules {
|
||||
* @return 稳定顺序的复核集合及可理解的阻塞原因;不修改原图
|
||||
*/
|
||||
public static Impact affected(Graph graph,Set<Long> replaced) {
|
||||
return affected(graph,replaced,Set.of());
|
||||
}
|
||||
|
||||
/** 汇总换版保留有效父计划;只有正式计划被清空的执行阶段才传播排期复核,版本号变化本身不使后继计划失效。 */
|
||||
public static Impact affected(Graph graph,Set<Long> replaced,Set<Long> aggregates) {
|
||||
Set<Long> changed=new HashSet<>(replaced); changed.addAll(aggregates);
|
||||
Set<Long> stages=new TreeSet<>();
|
||||
for(Long id:graph.stageNames().keySet()) if(!replaced.contains(id)&&PmStageRules.ancestors(graph,id).stream().anyMatch(replaced::contains)) stages.add(id);
|
||||
return closure(graph,replaced,stages,Set.of());
|
||||
for(Long id:graph.stageNames().keySet()) if(!changed.contains(id)&&PmStageRules.ancestors(graph,id).stream().anyMatch(replaced::contains)) stages.add(id);
|
||||
return closure(graph,changed,stages,Set.of());
|
||||
}
|
||||
|
||||
/**
|
||||
@ -40,6 +46,8 @@ public final class PmScheduleReviewRules {
|
||||
do {
|
||||
int before=stages.size()+items.size();
|
||||
for(Long stage:graph.stageNames().keySet()) if(!replaced.contains(stage)&&PmStageRules.ancestors(graph,stage).stream().anyMatch(stages::contains)) stages.add(stage);
|
||||
// 只有父级正式计划也失效时才传播到全部子级;汇总版本本身保留计划时不扩大无关分支。
|
||||
for(Long stage:List.copyOf(stages)) for(Long child:PmStageHierarchyRules.children(graph,stage)) if(!replaced.contains(child)) stages.add(child);
|
||||
for(Item item:graph.items().values()) if(!item.deleted()&&(item.stageId()==null||!replaced.contains(item.stageId()))) {
|
||||
if(item.stageId()!=null&&stages.contains(item.stageId())||items.contains(item.id())||item.parentTaskId()!=null&&items.contains(item.parentTaskId())) {
|
||||
items.add(item.id()); if(item.stageId()!=null) stages.add(item.stageId());
|
||||
|
||||
@ -0,0 +1,58 @@
|
||||
package com.ruoyi.project.manage.rule;
|
||||
|
||||
import com.ruoyi.project.manage.domain.*;
|
||||
import com.ruoyi.project.manage.exception.PmException;
|
||||
import java.util.*;
|
||||
import static com.ruoyi.project.manage.util.PmValues.*;
|
||||
|
||||
/** 包含树与执行图分开验证;首版只允许根阶段组包含工作阶段,不能通过跨层连线制造隐式准入。 */
|
||||
public final class PmStageHierarchyRules {
|
||||
/** 纯规则没有数据库或全局可变状态。 */
|
||||
private PmStageHierarchyRules() { }
|
||||
|
||||
/** 旧平级快照按根工作阶段兼容,生产加载始终提供真实组织身份。 */
|
||||
public static StageInfo info(Graph graph,long id) { return graph.hierarchy().getOrDefault(id,new StageInfo(id,"WORK",null,null)); }
|
||||
|
||||
/** 返回有效直接子阶段的稳定顺序,空容器返回空列表而非自动完成。 */
|
||||
public static List<Long> children(Graph graph,long id) { return graph.stageNames().keySet().stream().filter(child->Objects.equals(info(graph,child).parentId(),id)).sorted().toList(); }
|
||||
|
||||
/** 所属父级链不包含阶段自身;损坏的历史组织关系明确拒绝,不能无限递归。 */
|
||||
public static List<Long> parents(Graph graph,long id) {
|
||||
List<Long> result=new ArrayList<>(); Set<Long> seen=new HashSet<>(); seen.add(id);
|
||||
Long next=info(graph,id).parentId();
|
||||
while(next!=null) {
|
||||
if(!seen.add(next)||!graph.stageNames().containsKey(next)) throw PmException.conflict("STAGE_HIERARCHY_INVALID","阶段父级无效或形成包含循环");
|
||||
result.add(next); next=info(graph,next).parentId();
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/** 用于组筛选和汇总的阶段集合包含自身;不从展示筛选结果推导执行范围。 */
|
||||
public static Set<Long> subtree(Graph graph,long id) {
|
||||
Set<Long> result=new LinkedHashSet<>(); result.add(id);
|
||||
for(Long child:graph.stageNames().keySet()) if(parents(graph,child).contains(id)) result.add(child);
|
||||
return result;
|
||||
}
|
||||
|
||||
/** 验证层级、同层边及工作项归属;调用者在项目锁内传入整批最终图。 */
|
||||
public static void validate(Graph graph) {
|
||||
for(Long id:graph.stageNames().keySet()) {
|
||||
StageInfo stage=info(graph,id); List<Long> parents=parents(graph,id);
|
||||
if(!Set.of("WORK","GROUP").contains(stage.kind())||parents.size()>1||stage.group()&&!parents.isEmpty()
|
||||
||!parents.isEmpty()&&!info(graph,parents.get(0)).group())
|
||||
throw new PmException(409,"STAGE_HIERARCHY_INVALID","仅支持外层阶段组包含工作阶段",map("stageId",id));
|
||||
}
|
||||
for(StageLink edge:graph.stageLinks()) if(!graph.stageNames().containsKey(edge.predecessorStageId())||!graph.stageNames().containsKey(edge.successorStageId())
|
||||
||!Objects.equals(info(graph,edge.predecessorStageId()).parentId(),info(graph,edge.successorStageId()).parentId()))
|
||||
throw PmException.conflict("STAGE_EDGE_SCOPE_CONFLICT","执行连线两端必须位于同一画布");
|
||||
for(Item item:graph.items().values()) if(!item.deleted()&&item.stageId()!=null&&(!graph.stageNames().containsKey(item.stageId())||info(graph,item.stageId()).group()))
|
||||
throw new PmException(409,"WORK_ITEM_STAGE_INVALID","工作项只能归入有效工作阶段",map("taskId",item.id()));
|
||||
}
|
||||
|
||||
/** 完整阶段路径供列表、看板及错误提示共用,旧根阶段仍只显示自身名称。 */
|
||||
public static String path(Graph graph,long id) {
|
||||
var names=new ArrayList<String>(); var parents=new ArrayList<>(parents(graph,id)); Collections.reverse(parents);
|
||||
for(Long parent:parents) names.add(graph.stageNames().get(parent)); names.add(graph.stageNames().get(id));
|
||||
return String.join(" / ",names);
|
||||
}
|
||||
}
|
||||
@ -25,10 +25,16 @@ public final class PmStageRules {
|
||||
return blockedStage(graph,item.stageId());
|
||||
}
|
||||
|
||||
/** 当前版至少有一项有效工作项且全部完成或关闭,才可视为完成;历史兼容事实单独展示。 */
|
||||
/** 工作阶段按当前工作项、阶段组按全部子阶段汇总;空节点不自动放行,迁移事实保持只读兼容。 */
|
||||
public static String executionStatus(Graph graph,long stageId) {
|
||||
var revision=graph.stageRevisions().get(stageId);
|
||||
if(revision!=null&&revision.legacyPassedAt()!=null) return "LEGACY_PASSED";
|
||||
if(PmStageHierarchyRules.info(graph,stageId).group()) {
|
||||
List<Long> children=PmStageHierarchyRules.children(graph,stageId);
|
||||
if(!children.isEmpty()&&children.stream().allMatch(id->Set.of("COMPLETED","LEGACY_PASSED").contains(executionStatus(graph,id)))) return "COMPLETED";
|
||||
if(children.stream().anyMatch(id->!"NOT_STARTED".equals(executionStatus(graph,id)))) return "IN_PROGRESS";
|
||||
return "NOT_STARTED";
|
||||
}
|
||||
List<Item> items=graph.items().values().stream().filter(i->!i.deleted()&&Objects.equals(i.stageId(),stageId)).toList();
|
||||
if(!items.isEmpty()&&items.stream().allMatch(PmRules::completed)) return "COMPLETED";
|
||||
if(revision!=null&&revision.startedAt()!=null || items.stream().anyMatch(i->Set.of("IN_PROGRESS","COMPLETED","CLOSED").contains(i.status()))) return "IN_PROGRESS";
|
||||
@ -62,17 +68,19 @@ public final class PmStageRules {
|
||||
return List.of();
|
||||
}
|
||||
|
||||
/** 阶段的全部直接和间接前置都要完成;空新阶段不能放行后继。 */
|
||||
/** 阶段及父级的准入前置均需完成;不等待父级完成,避免父子相互等待。 */
|
||||
public static List<Map<String,Object>> blockedStage(Graph graph,long stageId) {
|
||||
Map<Long,List<Long>> incoming=new HashMap<>();
|
||||
for(StageLink link:graph.stageLinks()) incoming.computeIfAbsent(link.successorStageId(),unused->new ArrayList<>()).add(link.predecessorStageId());
|
||||
List<Map<String,Object>> reasons=new ArrayList<>();
|
||||
Set<Long> visited=new HashSet<>(); Deque<Long> queue=new ArrayDeque<>(incoming.getOrDefault(stageId,List.of()));
|
||||
for(Long parent:PmStageHierarchyRules.parents(graph,stageId)) queue.addAll(incoming.getOrDefault(parent,List.of()));
|
||||
while(!queue.isEmpty()) {
|
||||
long predecessorId=queue.removeFirst(); if(!visited.add(predecessorId)) continue;
|
||||
List<Item> unfinished=graph.items().values().stream().filter(candidate->!candidate.deleted()&&Objects.equals(candidate.stageId(),predecessorId)&&!PmRules.completed(candidate)).toList();
|
||||
Set<Long> scope=PmStageHierarchyRules.subtree(graph,predecessorId);
|
||||
List<Item> unfinished=graph.items().values().stream().filter(candidate->!candidate.deleted()&&scope.contains(candidate.stageId())&&!PmRules.completed(candidate)).toList();
|
||||
String status=executionStatus(graph,predecessorId);
|
||||
if(!Set.of("COMPLETED","LEGACY_PASSED").contains(status)) reasons.add(map("code","PREDECESSOR_STAGE_INCOMPLETE","stageId",predecessorId,"sourceName",graph.stageNames().get(predecessorId),"currentStatus",status,"expectedStatus","COMPLETED","message",unfinished.isEmpty()?"前置阶段尚无已完成的当前工作项":"前置阶段还有未完成工作项","unfinishedCount",unfinished.size(),"unfinishedItemIds",unfinished.stream().map(Item::id).toList()));
|
||||
if(!Set.of("COMPLETED","LEGACY_PASSED").contains(status)) reasons.add(map("code","PREDECESSOR_STAGE_INCOMPLETE","stageId",predecessorId,"sourceName",PmStageHierarchyRules.path(graph,predecessorId),"currentStatus",status,"expectedStatus","COMPLETED","message","前置阶段或其子阶段尚未完成","unfinishedCount",unfinished.size(),"unfinishedItemIds",unfinished.stream().map(Item::id).toList()));
|
||||
queue.addAll(incoming.getOrDefault(predecessorId,List.of()));
|
||||
}
|
||||
return reasons;
|
||||
@ -104,7 +112,10 @@ public final class PmStageRules {
|
||||
List<Long> changed=new ArrayList<>();
|
||||
for(Long stageId:before.stageNames().keySet()) {
|
||||
if("NOT_STARTED".equals(executionStatus(before,stageId))) continue;
|
||||
if(!ancestors(before,stageId).equals(ancestors(after,stageId))) changed.add(stageId);
|
||||
if(!after.stageNames().containsKey(stageId)||!ancestors(before,stageId).equals(ancestors(after,stageId))
|
||||
||!Objects.equals(PmStageHierarchyRules.info(before,stageId).parentId(),PmStageHierarchyRules.info(after,stageId).parentId())
|
||||
||!PmStageHierarchyRules.info(before,stageId).kind().equals(PmStageHierarchyRules.info(after,stageId).kind())
|
||||
||!PmStageHierarchyRules.children(before,stageId).equals(PmStageHierarchyRules.children(after,stageId))) changed.add(stageId);
|
||||
}
|
||||
if(!changed.isEmpty()) throw new PmException(409,"STAGE_TOPOLOGY_LOCKED","已执行阶段的前置关系不能改写;请先回退或只编辑未开始的后续流程",map("stageIds",changed));
|
||||
}
|
||||
|
||||
@ -21,6 +21,18 @@ public final class PmStageScheduleRules {
|
||||
StageRevision r=graph.stageRevisions().get(stageId);
|
||||
List<Map<String,Object>> sources=new ArrayList<>(),missing=new ArrayList<>(),conflicts=new ArrayList<>();
|
||||
Long earliest=null;
|
||||
Long parentId=PmStageHierarchyRules.info(graph,stageId).parentId();
|
||||
if(parentId!=null) {
|
||||
StageRevision parent=graph.stageRevisions().get(parentId);
|
||||
if(parent==null||parent.plannedStart()==null||parent.plannedEnd()==null||parent.scheduleReviewReworkId()!=null)
|
||||
missing.add(map("code","PARENT_STAGE_UNSCHEDULED","stageId",parentId,"message","请先确认父阶段组计划,或同批调整父子计划"));
|
||||
else {
|
||||
earliest=parent.plannedStart();
|
||||
sources.add(map("kind","PARENT_RANGE","stageId",parentId,"sourceName",graph.stageNames().get(parentId),"plannedStartAt",time(parent.plannedStart()),"plannedEndAt",time(parent.plannedEnd())));
|
||||
if(r!=null&&(r.plannedStart()!=null&&r.plannedStart()<parent.plannedStart()||r.plannedEnd()!=null&&r.plannedEnd()>parent.plannedEnd()))
|
||||
conflicts.add(map("code","CHILD_STAGE_OUTSIDE_PARENT","stageId",parentId,"sourceName",graph.stageNames().get(parentId),"message","子阶段预计日期超出父阶段组范围"));
|
||||
}
|
||||
}
|
||||
for(StageLink edge:graph.stageLinks()) if(edge.successorStageId()==stageId) {
|
||||
StageRevision p=graph.stageRevisions().get(edge.predecessorStageId());
|
||||
Map<String,Object> source=map("stageId",edge.predecessorStageId(),"sourceName",graph.stageNames().get(edge.predecessorStageId()),
|
||||
@ -43,10 +55,23 @@ public final class PmStageScheduleRules {
|
||||
boolean finished=Set.of("COMPLETED","LEGACY_PASSED").contains(PmStageRules.executionStatus(graph,stageId));
|
||||
String status=!conflicts.isEmpty()?"CONFLICT":r==null||r.plannedStart()==null||!missing.isEmpty()||review?"INCOMPLETE":"VALID";
|
||||
Map<String,Object> result=times(r);
|
||||
result.putAll(map("earliestPlannedStartAt",missing.isEmpty()?time(earliest):null,"sources",sources,"unresolvedSources",missing,
|
||||
StageRevision parentRevision=parentId==null?null:graph.stageRevisions().get(parentId);
|
||||
result.putAll(map("earliestPlannedStartAt",missing.isEmpty()?time(earliest):null,"latestPlannedEndAt",parentRevision==null?null:time(parentRevision.plannedEnd()),"sources",sources,"unresolvedSources",missing,
|
||||
"conflicts",conflicts,"scheduleBlockedReasons",concat(missing,conflicts),"scheduleValidationStatus",status,
|
||||
"scheduleReviewRequired",review,"scheduleReviewClosed",review&&finished,
|
||||
"overdue",r!=null&&!finished&&!review&&r.plannedEnd()!=null&&PmTime.now()>=r.plannedEnd()));
|
||||
String subtreeStatus=status;
|
||||
for(Long child:PmStageHierarchyRules.children(graph,stageId)) {
|
||||
String childStatus=(String)summary(graph,child).get("subtreeScheduleValidationStatus");
|
||||
if("CONFLICT".equals(childStatus)) subtreeStatus="CONFLICT";
|
||||
else if(!"VALID".equals(childStatus)&&!"CONFLICT".equals(subtreeStatus)) subtreeStatus="INCOMPLETE";
|
||||
}
|
||||
for(Item item:graph.items().values()) if(!item.deleted()&&Objects.equals(item.stageId(),stageId)) {
|
||||
String itemStatus=(String)PmRules.schedule(graph,item,"Asia/Shanghai").get("scheduleValidationStatus");
|
||||
if("CONFLICT".equals(itemStatus)) subtreeStatus="CONFLICT";
|
||||
else if(!"VALID".equals(itemStatus)&&!"CONFLICT".equals(subtreeStatus)) subtreeStatus="INCOMPLETE";
|
||||
}
|
||||
result.put("subtreeScheduleValidationStatus",subtreeStatus);
|
||||
return result;
|
||||
}
|
||||
|
||||
|
||||
@ -20,7 +20,7 @@ public interface IPmReworkService {
|
||||
List<Map<String,Object>> revisions(long projectId,long iterationId,long stageId);
|
||||
/** 旧历史列表入口要求明确迭代,不能只凭阶段 ID 绕过范围校验。 */
|
||||
default List<Map<String,Object>> revisions(long projectId,long stageId) { throw new PmException(400,"ITERATION_REQUIRED","请明确选择迭代",Map.of()); }
|
||||
/** 历史轮次与工作项只读返回,评论和操作记录由旧工作项详情提供。 */
|
||||
/** 历史轮次只读返回;叶阶段使用旧工作项详情,阶段组使用带父级版本上下文的冻结详情。 */
|
||||
Map<String,Object> revision(long projectId,long iterationId,long stageId,long revisionId);
|
||||
/** 旧历史详情入口缺少迭代边界时拒绝。 */
|
||||
default Map<String,Object> revision(long projectId,long stageId,long revisionId) { throw new PmException(400,"ITERATION_REQUIRED","请明确选择迭代",Map.of()); }
|
||||
@ -30,4 +30,6 @@ public interface IPmReworkService {
|
||||
Map<String,Object> revisionPage(long projectId,long iterationId,long stageId,int page,int pageSize);
|
||||
/** 分页读取指定历史轮次的工作项,返回总数与只读版本元数据。 */
|
||||
Map<String,Object> revisionItemsPage(long projectId,long iterationId,long stageId,long revisionId,int page,int pageSize);
|
||||
/** 在父级版本上下文读取冻结的工作项详情,不能将实时详情作为旧父级的内容。 */
|
||||
Map<String,Object> itemSnapshot(long projectId,long iterationId,long stageId,long revisionId,long itemId);
|
||||
}
|
||||
|
||||
@ -10,6 +10,8 @@ import java.util.*;
|
||||
|
||||
/** 显式阶段执行图与展示布局契约;不恢复已停用的流程节点依赖。 */
|
||||
public interface IPmStageService {
|
||||
/** 项目管理者预览或提交明确阶段层级及全部连线最终态,预览不产生成功历史。 */
|
||||
Map<String,Object> structure(long projectId,long iterationId,com.ruoyi.project.manage.dto.StageStructureInput input,boolean commit);
|
||||
/**
|
||||
* 在项目锁内读取单迭代阶段、显式阶段边和工作项计数;画布不返回完整工作项。
|
||||
*
|
||||
|
||||
@ -39,10 +39,12 @@ public class PmIterationServiceImpl implements IPmIterationService {
|
||||
private final IPmService business;
|
||||
private final PmJson codec;
|
||||
private final ObjectMapper json;
|
||||
private final com.ruoyi.project.manage.service.support.PmGroupVersionService groups;
|
||||
|
||||
/** 所有依赖共享上层事务连接;取消复用现有最终图校验,避免直接批量改状态。 */
|
||||
public PmIterationServiceImpl(PmIterationMapper mapper,PmWorkspaceMapper workspace,PmAccess access,PmIterationAccess iterations,
|
||||
PmGraphService graphs,PmAuditService audit,IPmService business,PmJson codec,ObjectMapper json) {
|
||||
PmGraphService graphs,PmAuditService audit,IPmService business,PmJson codec,ObjectMapper json,com.ruoyi.project.manage.service.support.PmGroupVersionService groups) {
|
||||
this.groups=groups;
|
||||
this.mapper=mapper; this.workspace=workspace; this.access=access; this.iterations=iterations;
|
||||
this.graphs=graphs; this.audit=audit; this.business=business; this.codec=codec; this.json=json;
|
||||
}
|
||||
@ -229,7 +231,9 @@ public class PmIterationServiceImpl implements IPmIterationService {
|
||||
warnings.add(map("sourceStageId",number(stage,"id"),"sourceStageName",text(stage,"name"),"ownerId",owner,"message","阶段“"+text(stage,"name")+"”的原负责人已不可分配,新阶段负责人已清空"));
|
||||
owner=null;
|
||||
}
|
||||
Map<String,Object> values=map("project_id",projectId,"iteration_id",target,"name",stage.get("name"),"sort_order",stage.get("sort_order"),"owner_id",owner,"description",stage.get("description"),"created_by",actor,"created_at",now);
|
||||
Long oldParent=nullable(stage,"parent_stage_id"),parent=oldParent==null?null:ids.get(oldParent);
|
||||
if(oldParent!=null&&parent==null) throw new IllegalStateException("复制来源的父阶段组缺失");
|
||||
Map<String,Object> values=map("project_id",projectId,"iteration_id",target,"name",stage.get("name"),"sort_order",stage.get("sort_order"),"owner_id",owner,"description",stage.get("description"),"stage_kind",stage.get("stage_kind"),"parent_stage_id",parent,"created_by",actor,"created_at",now);
|
||||
long id=mapper.insertCopiedStage(values); ids.put(number(stage,"id"),id);
|
||||
values.put("stage_id",id); values.remove("id");
|
||||
long revision=mapper.insertCopiedRevision(values);
|
||||
@ -241,6 +245,7 @@ public class PmIterationServiceImpl implements IPmIterationService {
|
||||
mapper.insertCopiedEdge(map("project_id",projectId,"iteration_id",target,"predecessor_stage_id",predecessor,"successor_stage_id",successor,"created_by",actor,"created_at",now));
|
||||
}
|
||||
mapper.insertCopiedDefinition(map("project_id",projectId,"iteration_id",target,"graph_json",codec.encode(map("stages",mapper.selectCopyStages(projectId,target),"stageEdges",mapper.selectCopyEdges(projectId,target))),"created_by",actor,"created_at",now));
|
||||
groups.bind(projectId,target);
|
||||
return warnings;
|
||||
}
|
||||
|
||||
|
||||
@ -17,6 +17,8 @@ import com.ruoyi.project.manage.mapper.PmWorkItemMapper;
|
||||
import com.ruoyi.project.manage.mapper.PmWorkspaceMapper;
|
||||
import com.ruoyi.project.manage.rule.PmRules;
|
||||
import com.ruoyi.project.manage.rule.PmStageRules;
|
||||
import com.ruoyi.project.manage.rule.PmStageHierarchyRules;
|
||||
import com.ruoyi.project.manage.service.support.PmGroupVersionService;
|
||||
import com.ruoyi.project.manage.security.PmAccess;
|
||||
import com.ruoyi.project.manage.security.PmIterationAccess;
|
||||
import com.ruoyi.project.manage.service.IPmReworkService;
|
||||
@ -48,18 +50,20 @@ public class PmReworkServiceImpl implements IPmReworkService {
|
||||
private final PmJson json;
|
||||
private final ObjectMapper decoder;
|
||||
private final PmParticipantService participants;
|
||||
private final PmGroupVersionService groups;
|
||||
|
||||
/** 只注入本模块 Mapper 和统一鉴权,事务失败时版本、工作项与 outbox 一同回滚。 */
|
||||
public PmReworkServiceImpl(PmWorkspaceMapper workspace,PmStageMapper stages,PmWorkItemMapper workItems,
|
||||
PmDependencyMapper dependencies,PmRevisionMapper revisions,PmGraphService graphs,
|
||||
PmAuditService audit,PmAccess access,PmJson json,ObjectMapper decoder,PmIterationAccess iterationAccess,com.ruoyi.project.manage.mapper.PmScheduleMapper schedules,com.ruoyi.project.manage.service.IPmScheduleService scheduleService,PmParticipantService participants) {
|
||||
PmAuditService audit,PmAccess access,PmJson json,ObjectMapper decoder,PmIterationAccess iterationAccess,com.ruoyi.project.manage.mapper.PmScheduleMapper schedules,com.ruoyi.project.manage.service.IPmScheduleService scheduleService,PmParticipantService participants,PmGroupVersionService groups) {
|
||||
this.groups=groups;
|
||||
this.participants=participants;
|
||||
this.schedules=schedules; this.scheduleService=scheduleService;
|
||||
this.iterationAccess=iterationAccess; this.workspace=workspace; this.stages=stages; this.workItems=workItems; this.dependencies=dependencies;
|
||||
this.revisions=revisions; this.graphs=graphs; this.audit=audit; this.access=access; this.json=json; this.decoder=decoder;
|
||||
}
|
||||
|
||||
private record Plan(Graph graph,List<Long> affected,List<Item> copies,List<Map<String,Object>> excluded,
|
||||
private record Plan(Graph graph,List<Long> affected,List<Long> aggregates,List<Item> copies,List<Map<String,Object>> excluded,
|
||||
List<Map<String,Object>> missingAssignees,List<Map<String,Object>> missingCollaborators,List<Map<String,Object>> blockers,List<Long> reviewStages,List<Long> reviewItems,
|
||||
Set<Long> members) { }
|
||||
|
||||
@ -94,18 +98,27 @@ public class PmReworkServiceImpl implements IPmReworkService {
|
||||
|
||||
long at=PmTime.now(),actor=access.actor();
|
||||
Map<String,Object> saved=map("projectId",projectId,"iterationId",iterationId,"sourceStageId",input.sourceStageId(),"targetStageId",input.targetStageId(),
|
||||
"graphVersion",version+1,"affectedStageIds",plan.affected(),"itemMapping",new LinkedHashMap<Long,Long>(),
|
||||
"graphVersion",version+1,"affectedStageIds",plan.affected(),"aggregateStageIds",plan.aggregates(),"itemMapping",new LinkedHashMap<Long,Long>(),
|
||||
"requestAdditionsJson",additionsJson(input),"sendEmail",Boolean.TRUE.equals(input.sendEmail()));
|
||||
long reworkId=revisions.insertRework(map("project_id",projectId,"iteration_id",iterationId,"source_stage_id",input.sourceStageId(),"target_stage_id",input.targetStageId(),
|
||||
"reason",input.reason().trim(),"idempotency_key",input.idempotencyKey(),"preview_graph_version",version,
|
||||
"impact_json","{}","created_by",actor,"created_at",at));
|
||||
Map<Long,Long> nextRevisions=new LinkedHashMap<>();
|
||||
for(Long stageId:plan.affected()) {
|
||||
Set<Long> versioned=new LinkedHashSet<>(plan.affected()); versioned.addAll(plan.aggregates());
|
||||
// 必须先冻结旧父级组合,再切换任何子指针。并行保留分支继续执行后也不能改变旧父版本。
|
||||
for(Long stageId:versioned) if(PmStageHierarchyRules.info(before,stageId).group()) groups.freeze(before,stageId);
|
||||
for(Long stageId:versioned) {
|
||||
var old=before.stageRevisions().get(stageId);
|
||||
Map<String,Object> stage=stages.selectActiveStage(stageId,projectId,iterationId);
|
||||
boolean aggregate=plan.aggregates().contains(stageId);
|
||||
long next=revisions.insertRevision(map("project_id",projectId,"iteration_id",iterationId,"stage_id",stageId,"revision_no",old.revisionNo()+1,
|
||||
"rework_id",reworkId,"previous_revision_id",old.id(),"flow_definition_revision_id",null,
|
||||
"stage_name_snapshot",text(stage,"name"),"stage_owner_snapshot",nullable(stage,"owner_id"),"created_by",actor,"created_at",at));
|
||||
"stage_name_snapshot",text(stage,"name"),"stage_owner_snapshot",nullable(stage,"owner_id"),
|
||||
"stage_kind_snapshot",text(stage,"stage_kind"),"parent_stage_snapshot_id",nullable(stage,"parent_stage_id"),"stage_description_snapshot",text(stage,"description"),
|
||||
"revision_reason",aggregate?"CHILD_REWORK":"REWORK","planned_start_at",aggregate?old.plannedStart():null,"planned_end_at",aggregate?old.plannedEnd():null,"plan_source",aggregate?old.planSource():null,"plan_recorded_at",aggregate?old.planRecordedAt():null,
|
||||
"reference_planned_start_at",aggregate?old.referenceStart():old.plannedStart()==null?old.referenceStart():old.plannedStart(),
|
||||
"reference_planned_end_at",aggregate?old.referenceEnd():old.plannedEnd()==null?old.referenceEnd():old.plannedEnd(),
|
||||
"schedule_review_rework_id",aggregate?old.scheduleReviewReworkId():Long.valueOf(reworkId),"created_by",actor,"created_at",at));
|
||||
nextRevisions.put(stageId,next);
|
||||
}
|
||||
Map<Long,Long> mapped=new LinkedHashMap<>();
|
||||
@ -116,6 +129,7 @@ public class PmReworkServiceImpl implements IPmReworkService {
|
||||
long next=workItems.insertWorkItem(map("project_id",projectId,"iteration_id",iterationId,"type",old.type(),"title",old.title(),"description",old.description(),
|
||||
"assignee_id",old.assigneeId()!=null&&plan.members().contains(old.assigneeId())?old.assigneeId():null,
|
||||
"priority",old.priority(),"status","READY","planned_start_at",null,"planned_end_at",null,"actual_start_at",null,"actual_end_at",null,
|
||||
"schedule_review_rework_id",reworkId,"reference_planned_start_at",old.start()==null?old.referenceStart():old.start(),"reference_planned_end_at",old.end()==null?old.referenceEnd():old.end(),
|
||||
"stage_id",old.stageId(),"stage_revision_id",nextRevisions.get(old.stageId()),"parent_task_id",parent,
|
||||
"origin_work_item_id",old.id(),"created_by",actor,"created_at",at));
|
||||
mapped.put(old.id(),next);
|
||||
@ -134,13 +148,14 @@ public class PmReworkServiceImpl implements IPmReworkService {
|
||||
dependencies.insertDependency(map("project_id",projectId,"iteration_id",iterationId,"successor_task_id",mapped.get(dependency.successorId()),
|
||||
"condition_type","WORK_ITEM_COMPLETED","predecessor_task_id",predecessor,"expected_status","COMPLETED","created_by",actor,"created_at",at));
|
||||
}
|
||||
for(Long stageId:plan.affected()) {
|
||||
for(Long stageId:versioned) {
|
||||
long old=before.stageRevisions().get(stageId).id();
|
||||
if(revisions.supersedeRevision(old,at)!=1||revisions.switchCurrentRevision(projectId,stageId,old,nextRevisions.get(stageId))!=1)
|
||||
throw PmException.conflict("GRAPH_VERSION_CONFLICT","阶段版本已变化,请重新预览");
|
||||
}
|
||||
for(Long stageId:plan.reviewStages()) if(schedules.markStageReview(before.stageRevisions().get(stageId).id(),reworkId)!=1) throw PmException.conflict("VERSION_CONFLICT","阶段计划已变化");
|
||||
for(Long itemId:plan.reviewItems()) if(revisions.markScheduleReview(itemId,reworkId)!=1) throw PmException.conflict("VERSION_CONFLICT","工作项计划已变化");
|
||||
groups.bind(projectId,iterationId); groups.sync(projectId,iterationId);
|
||||
Graph after=graphs.load(projectId,iterationId);
|
||||
for(Dependency dependency:after.dependencies()) if(!after.items().containsKey(dependency.taskId())) throw PmException.conflict("REWORK_DEPENDENCY_CONFLICT","当前工作项不能引用历史前置工作项");
|
||||
PmRules.validateAcyclic(after); PmRules.validateSchedules(after,"Asia/Shanghai"); PmRules.validateActual(after,"Asia/Shanghai");
|
||||
@ -159,20 +174,30 @@ public class PmReworkServiceImpl implements IPmReworkService {
|
||||
return rows;
|
||||
}
|
||||
|
||||
/** 只读历史轮次及其中工作项;详情 ID 仍可打开评论、附件和原审计。 */
|
||||
/** 叶阶段保留原工作项详情;阶段组必须读取绑定子版本的冻结组合,不能用保留分支的实时详情替代历史。 */
|
||||
public Map<String,Object> revision(long projectId,long iterationId,long stageId,long revisionId) {
|
||||
locked(projectId,iterationId,"read"); stage(projectId,iterationId,stageId);
|
||||
Map<String,Object> row=revisions.selectRevision(projectId,iterationId,stageId,revisionId); if(row==null) throw PmAccess.denied();
|
||||
revisionTimes(row);
|
||||
List<Map<String,Object>> items=revisions.selectRevisionItems(revisionId);
|
||||
boolean group="GROUP".equals(text(row,"stage_kind_snapshot"));
|
||||
List<Map<String,Object>> items=group?groups.versionItems(projectId,iterationId,stageId,revisionId):revisions.selectRevisionItems(revisionId);
|
||||
for(Map<String,Object> item:items) {
|
||||
if(group) continue;
|
||||
item.put("plannedStartAt",PmTime.format(nullable(item,"planned_start_at"),"Asia/Shanghai"));
|
||||
item.put("plannedEndAt",PmTime.format(nullable(item,"planned_end_at"),"Asia/Shanghai"));
|
||||
item.put("actualStartAt",PmTime.format(nullable(item,"actual_start_at"),"Asia/Shanghai"));
|
||||
item.put("actualEndAt",PmTime.format(nullable(item,"actual_end_at"),"Asia/Shanghai"));
|
||||
item.put("historical",true); item.put("referencePlannedStartAt",PmTime.format(nullable(item,"reference_planned_start_at"),"Asia/Shanghai")); item.put("referencePlannedEndAt",PmTime.format(nullable(item,"reference_planned_end_at"),"Asia/Shanghai"));
|
||||
}
|
||||
return map("revision",row,"items",items,"flowDefinition",definitionSnapshot(projectId,iterationId,row),"readOnly",true);
|
||||
return map("revision",row,"items",items,"frozenSnapshot",group,"childStages",group?groups.versionStages(projectId,iterationId,stageId,revisionId):List.of(),"flowDefinition",definitionSnapshot(projectId,iterationId,row),"readOnly",true);
|
||||
}
|
||||
|
||||
/** 父级历史详情从指定组合的冻结内容读取,禁止用仍在执行的子项实时数据替代历史。 */
|
||||
public Map<String,Object> itemSnapshot(long projectId,long iterationId,long stageId,long revisionId,long itemId) {
|
||||
locked(projectId,iterationId,"read"); stage(projectId,iterationId,stageId);
|
||||
var revision=revisions.selectRevision(projectId,iterationId,stageId,revisionId);
|
||||
if(revision==null||!"GROUP".equals(text(revision,"stage_kind_snapshot"))) throw PmAccess.denied();
|
||||
return groups.itemSnapshot(projectId,iterationId,stageId,revisionId,itemId);
|
||||
}
|
||||
|
||||
/** 列表与详情统一输出版本自身的 ISO 时间,避免历史抽屉误用数据库微秒列或当前阶段计划。 */
|
||||
@ -240,6 +265,7 @@ public class PmReworkServiceImpl implements IPmReworkService {
|
||||
private Plan plan(long projectId,long iterationId,ReworkInput input,Graph graph) {
|
||||
if(input==null||input.sourceStageId()==null||input.targetStageId()==null) throw PmException.bad("来源和目标阶段不能为空");
|
||||
long source=input.sourceStageId(),target=input.targetStageId(); stage(projectId,iterationId,source); stage(projectId,iterationId,target);
|
||||
if(!Objects.equals(PmStageHierarchyRules.info(graph,source).parentId(),PmStageHierarchyRules.info(graph,target).parentId())) throw PmException.conflict("REWORK_SCOPE_INVALID","只能回退到同一画布的严格上游阶段");
|
||||
List<Map<String,Object>> sourceBlocked=PmStageRules.reworkBlocked(graph,source);
|
||||
if(!sourceBlocked.isEmpty()) throw new PmException(409,text(sourceBlocked.get(0),"code"),text(sourceBlocked.get(0),"message"),map("blockedReasons",sourceBlocked));
|
||||
if(!PmStageRules.ancestors(graph,source).contains(target)) throw PmException.conflict("REWORK_TARGET_INVALID","只能回退到当前阶段的上游阶段,不能选择自身");
|
||||
@ -249,8 +275,12 @@ public class PmReworkServiceImpl implements IPmReworkService {
|
||||
boolean changed;
|
||||
do {
|
||||
changed=false;
|
||||
for(Long id:List.copyOf(affected)) if(PmStageHierarchyRules.info(graph,id).group()) changed|=affected.addAll(PmStageHierarchyRules.subtree(graph,id));
|
||||
Set<Long> invalidated=new HashSet<>(affected);
|
||||
for(Long id:affected) invalidated.addAll(PmStageHierarchyRules.parents(graph,id));
|
||||
for(Long id:graph.stageNames().keySet()) if(!affected.contains(id)&&!"NOT_STARTED".equals(PmStageRules.executionStatus(graph,id))
|
||||
&&affected.stream().anyMatch(ancestor->sourceEqualsOrDescends(graph,ancestor,id))) changed|=affected.add(id);
|
||||
&&invalidated.stream().anyMatch(ancestor->PmStageRules.ancestors(graph,id).contains(ancestor)
|
||||
||PmStageHierarchyRules.parents(graph,id).stream().anyMatch(parent->PmStageRules.ancestors(graph,parent).contains(ancestor)))) changed|=affected.add(id);
|
||||
for(Dependency dependency:graph.dependencies()) {
|
||||
Item predecessor=graph.items().get(dependency.taskId()),successor=graph.items().get(dependency.successorId());
|
||||
if(predecessor==null||successor==null) { blockers.add(map("code","HISTORICAL_DEPENDENCY","message","当前依赖引用了历史或无效工作项","dependencyId",dependency.id())); continue; }
|
||||
@ -272,27 +302,30 @@ public class PmReworkServiceImpl implements IPmReworkService {
|
||||
if(predecessor==null||predecessor.stageId()!=null&&affected.contains(predecessor.stageId())&&!copiedIds.contains(predecessor.id()))
|
||||
blockers.add(map("code","REWORK_DEPENDENCY_CONFLICT","dependencyId",dependency.id(),"message","前置工作项已取消或不属于当前版本,需要先处理依赖"));
|
||||
}
|
||||
for(Long id:additions(input).keySet()) if(!affected.contains(id)) blockers.add(map("code","ADDITION_STAGE_INVALID","stageId",id,"message","补录工作项只能归入受影响阶段"));
|
||||
for(Long id:additions(input).keySet()) if(!affected.contains(id)||PmStageHierarchyRules.info(graph,id).group()) blockers.add(map("code","ADDITION_STAGE_INVALID","stageId",id,"message","补录工作项只能归入受影响的工作阶段,阶段组不能直接放工作项"));
|
||||
for(var entry:additions(input).entrySet()) for(ReworkItemInput added:entry.getValue()) validateAddition(projectId,added);
|
||||
for(Long id:affected) if(copies.stream().noneMatch(i->Objects.equals(i.stageId(),id))&&additions(input).getOrDefault(id,List.of()).isEmpty())
|
||||
blockers.add(map("code","REWORK_STAGE_EMPTY","stageId",id,"sourceName",graph.stageNames().get(id),"message","该阶段无可复制工作项,请至少补录一项"));
|
||||
// 空版本仍是未执行且阻塞后继,允许先回退再补工作项,不能强制生成虚假任务。
|
||||
Set<Long> aggregates=new TreeSet<>();
|
||||
for(Long id:affected) aggregates.addAll(PmStageHierarchyRules.parents(graph,id));
|
||||
aggregates.removeAll(affected);
|
||||
Set<Long> members=new HashSet<>(); for(Map<String,Object> row:workspace.selectMembers(projectId)) members.add(number(row,"userId"));
|
||||
List<Map<String,Object>> missingAssignees=copies.stream().filter(i->i.assigneeId()!=null&&!members.contains(i.assigneeId()))
|
||||
.map(i->map("taskId",i.id(),"taskName",i.title(),"assigneeId",i.assigneeId(),"message","负责人已不是项目成员,新版将不分配负责人")).toList();
|
||||
List<Map<String,Object>> missingCollaborators=new ArrayList<>();
|
||||
for(Item item:copies)for(var collaborator:item.collaborators())if(!members.contains(collaborator.userId()))missingCollaborators.add(map("taskId",item.id(),"taskName",item.title(),"userId",collaborator.userId(),"name",collaborator.name(),"message","协作人已不是有效项目成员,新版不再关联,旧版本保留原分工"));
|
||||
var review=com.ruoyi.project.manage.rule.PmScheduleReviewRules.affected(graph,affected);
|
||||
var review=com.ruoyi.project.manage.rule.PmScheduleReviewRules.affected(graph,affected,aggregates);
|
||||
blockers.addAll(review.blockers());
|
||||
return new Plan(graph,List.copyOf(affected),copies,excluded,missingAssignees,missingCollaborators,blockers,review.stageIds(),review.itemIds(),members);
|
||||
return new Plan(graph,List.copyOf(affected),List.copyOf(aggregates),copies,excluded,missingAssignees,missingCollaborators,blockers,review.stageIds(),review.itemIds(),members);
|
||||
}
|
||||
|
||||
/** 预览完整解释版本替换、排期失效和不能提交的原因,不把警告当作成功。 */
|
||||
private Map<String,Object> previewValue(long projectId,long iterationId,ReworkInput input,Plan plan,long graphVersion) {
|
||||
List<Map<String,Object>> stages=plan.affected().stream().map(id->map("stageId",id,"name",plan.graph().stageNames().get(id),
|
||||
"stageKind",PmStageHierarchyRules.info(plan.graph(),id).kind(),"stagePath",PmStageHierarchyRules.path(plan.graph(),id),
|
||||
"revisionNo",plan.graph().stageRevisions().get(id).revisionNo(),"copyCount",plan.copies().stream().filter(i->Objects.equals(i.stageId(),id)).count(),
|
||||
"additionalCount",additions(input).getOrDefault(id,List.of()).size())).toList();
|
||||
return map("projectId",projectId,"iterationId",iterationId,"sourceStageId",input.sourceStageId(),"targetStageId",input.targetStageId(),"graphVersion",graphVersion,
|
||||
"affectedStageIds",plan.affected(),"affectedStages",stages,"excludedItems",plan.excluded(),"missingAssignees",plan.missingAssignees(),"missingCollaborators",plan.missingCollaborators(),
|
||||
"affectedStageIds",plan.affected(),"affectedStages",stages,"aggregateStageIds",plan.aggregates(),"excludedItems",plan.excluded(),"missingAssignees",plan.missingAssignees(),"missingCollaborators",plan.missingCollaborators(),
|
||||
"scheduleReviewStageIds",plan.reviewStages(),"scheduleReviewItemIds",plan.reviewItems(),"blockedReasons",plan.blockers(),"canCommit",plan.blockers().isEmpty(),
|
||||
"message","旧版工作项和历史保持只读,新版工作项重新开始且需要重新排期");
|
||||
}
|
||||
|
||||
@ -59,9 +59,11 @@ public class PmServiceImpl implements IPmService {
|
||||
private final PmJson jsonCodec;
|
||||
private final com.ruoyi.project.manage.service.IPmScheduleService schedules;
|
||||
private final com.ruoyi.project.manage.service.support.PmAttachmentStorage attachmentStorage;
|
||||
private final com.ruoyi.project.manage.service.support.PmGroupVersionService groups;
|
||||
|
||||
/** 注入对象 Mapper、统一权限和事务支持,不允许 Controller 直接持有存储或实现。 */
|
||||
public PmServiceImpl(PmWorkspaceMapper workspaceMapper,PmWorkItemMapper workItemMapper,PmDependencyMapper dependencyMapper,PmStageMapper stageMapper,PmActivityMapper activityMapper,PmEventMapper eventMapper,PmRevisionMapper revisionMapper,PmUserMapper userMapper,PmGraphService graphService,PmAuditService auditService,PmAccess access,PmJson jsonCodec,PmIterationAccess iterationAccess,com.ruoyi.project.manage.service.IPmScheduleService schedules,PmParticipantService participants,com.ruoyi.project.manage.service.support.PmAttachmentStorage attachmentStorage) {
|
||||
public PmServiceImpl(PmWorkspaceMapper workspaceMapper,PmWorkItemMapper workItemMapper,PmDependencyMapper dependencyMapper,PmStageMapper stageMapper,PmActivityMapper activityMapper,PmEventMapper eventMapper,PmRevisionMapper revisionMapper,PmUserMapper userMapper,PmGraphService graphService,PmAuditService auditService,PmAccess access,PmJson jsonCodec,PmIterationAccess iterationAccess,com.ruoyi.project.manage.service.IPmScheduleService schedules,PmParticipantService participants,com.ruoyi.project.manage.service.support.PmAttachmentStorage attachmentStorage,com.ruoyi.project.manage.service.support.PmGroupVersionService groups) {
|
||||
this.groups=groups;
|
||||
this.attachmentStorage=attachmentStorage;
|
||||
this.participants=participants;
|
||||
this.schedules=schedules;
|
||||
@ -229,6 +231,7 @@ public class PmServiceImpl implements IPmService {
|
||||
/** 普通编辑原子更新分工、字段及本次通知选择;省略协作人则保留,邮件选择省略则不发。 */
|
||||
public void edit(long id,ItemInput input) {
|
||||
long projectId=projectOf(id),iterationId=iterationOf(id); locked(projectId,iterationId,"write"); Graph graph=graphService.load(projectId,iterationId); Item existing=writableItem(graph,id); version(input.version(),existing.version()); validateFields(projectId,iterationId,input); requireStageMutable(graph,input.stageId());
|
||||
if(!Objects.equals(existing.stageId(),input.stageId())) throw PmException.bad("请通过项目管理者的阶段归属入口移动工作项");
|
||||
if(input.predecessorWorkItemIds()!=null) throw PmException.bad("编辑前置条件请使用依赖管理入口");
|
||||
List<Long> collaboratorIds=participants.validate(projectId,input.collaboratorIds());
|
||||
if(!existing.type().equals(input.type())) throw PmException.bad("工作项类型创建后不可直接变更");
|
||||
@ -248,12 +251,15 @@ public class PmServiceImpl implements IPmService {
|
||||
|
||||
/**
|
||||
* 所有阶段调整共用父子继承校验,版本、归属和历史在同一项目锁事务中提交。
|
||||
* 仅项目管理者可以移动待开始项,普通编辑不能清空阶段来绕过执行门禁。
|
||||
* @param id 当前有效工作项 ID;子任务不能脱离父阶段
|
||||
* @param input 目标同项目阶段及工作项版本,null 阶段代表未分配
|
||||
* 注意:先校验父子整体排期是否落在目标阶段内,再同步版本和审计;相同阶段不重复更新。
|
||||
*/
|
||||
public void assignStage(long id,StageAssignment input) {
|
||||
long projectId=projectOf(id),iterationId=iterationOf(id); locked(projectId,iterationId,"write"); Graph graph=graphService.load(projectId,iterationId); Item existing=writableItem(graph,id); version(input.version(),existing.version());
|
||||
access.project(projectId,"admin");
|
||||
if(!"READY".equals(existing.status())) throw PmException.conflict("ITEM_STAGE_LOCKED","只有待开始工作项可以调整阶段");
|
||||
if(input.stageId()!=null&&stageMapper.selectActiveStageId(input.stageId(),projectId,iterationId)==null) throw PmAccess.denied();
|
||||
requireStageMutable(graph,input.stageId()); validateInheritedStage(graph,existing,input.stageId()); if(Objects.equals(existing.stageId(),input.stageId())) return;
|
||||
Graph before=graph.copy(); simulateStage(graph,existing,input.stageId());
|
||||
@ -513,7 +519,7 @@ public class PmServiceImpl implements IPmService {
|
||||
(keyword.isEmpty()||text(row,"title").toLowerCase(Locale.ROOT).contains(keyword))
|
||||
&&(query.type()==null||query.type().isBlank()||query.type().equals(row.get("type")))
|
||||
&&(!Boolean.TRUE.equals(query.blockedOnly())||Boolean.TRUE.equals(row.get("dependencyBlocked")))
|
||||
&&(query.stageId()==null||(query.stageId()==0?row.get("stageId")==null:query.stageId().equals(nullable(row,"stageId"))))
|
||||
&&(query.stageId()==null||(query.stageId()==0?row.get("stageId")==null:query.stageId().equals(nullable(row,"stageId"))||query.stageId().equals(nullable(row,"stageGroupId"))))
|
||||
&&matchesMembers(row,memberIds)
|
||||
&&(!"gantt".equals(mode)||overlaps(row,from,to))).toList();
|
||||
Map<String,Object> counts=new LinkedHashMap<>();
|
||||
@ -605,6 +611,8 @@ public class PmServiceImpl implements IPmService {
|
||||
private Map<String,Object> view(Graph graph,Item item,String zone,boolean writable) {
|
||||
Map<String,Object> response=map("id",item.id(),"projectId",item.projectId(),"type",item.type(),"title",item.title(),"description",item.description(),"assigneeId",item.assigneeId(),"priority",item.priority(),"status",item.status(),"version",item.version(),"timezone",zone,"plannedStartAt",PmTime.format(item.start(),zone),"plannedEndAt",PmTime.format(item.end(),zone),"actualStartAt",PmTime.format(item.actualStart(),zone),"actualEndAt",PmTime.format(item.actualEnd(),zone));
|
||||
response.put("collaboratorIds",item.collaborators().stream().map(c->c.userId()).toList());
|
||||
response.put("stagePath",item.stageId()==null?"未分配":com.ruoyi.project.manage.rule.PmStageHierarchyRules.path(graph,item.stageId()));
|
||||
response.put("stageGroupId",item.stageId()==null?null:com.ruoyi.project.manage.rule.PmStageHierarchyRules.info(graph,item.stageId()).parentId());
|
||||
response.put("collaborators",item.collaborators());
|
||||
boolean mutable=graph.iteration()!=null&&graph.iteration().mutable();
|
||||
response.putAll(map("iterationId",graph.iteration()==null?null:graph.iteration().id(),"iterationStatus",graph.iteration()==null?null:graph.iteration().status(),"iterationReadOnly",!mutable));
|
||||
@ -657,6 +665,7 @@ public class PmServiceImpl implements IPmService {
|
||||
/** 已完成或迁移放行阶段不可增减和改写工作项,重做必须走经理回退入口。 */
|
||||
private static void requireStageMutable(Graph graph,Long stageId) {
|
||||
if(stageId==null) return;
|
||||
if(com.ruoyi.project.manage.rule.PmStageHierarchyRules.info(graph,stageId).group()) throw PmException.bad("阶段组承载子阶段,请选择具体工作阶段");
|
||||
String status=PmStageRules.executionStatus(graph,stageId);
|
||||
if(Set.of("COMPLETED","LEGACY_PASSED").contains(status)) throw PmException.conflict("STAGE_REVISION_FROZEN","阶段已完成,需由项目经理创建回退版本后重做");
|
||||
}
|
||||
@ -678,7 +687,8 @@ public class PmServiceImpl implements IPmService {
|
||||
private void syncStage(long projectId,long iterationId,Long stageId,String previousStatus) {
|
||||
if(stageId==null) return;
|
||||
Graph after=graphService.load(projectId,iterationId); String status=PmStageRules.executionStatus(after,stageId);
|
||||
if(status.equals(previousStatus)) return;
|
||||
if(com.ruoyi.project.manage.rule.PmStageHierarchyRules.info(after,stageId).group()) { groups.sync(projectId,iterationId); return; }
|
||||
if(status.equals(previousStatus)) { groups.sync(projectId,iterationId); return; }
|
||||
var revision=after.stageRevisions().get(stageId); if(revision==null) return;
|
||||
Long now=PmTime.now();
|
||||
revisionMapper.updateRevisionState(revision.id(),"IN_PROGRESS".equals(status)||"COMPLETED".equals(status)?now:null,"COMPLETED".equals(status)?now:null);
|
||||
@ -692,6 +702,7 @@ public class PmServiceImpl implements IPmService {
|
||||
} else revisionMapper.bindStartedDefinition(revision.id(),number(latest,"id"));
|
||||
}
|
||||
auditService.record(projectId,iterationId,null,"STAGE_STATUS_CHANGED",map("stageId",stageId,"from",previousStatus,"to",status,"revisionId",revision.id()),access.actor());
|
||||
groups.sync(projectId,iterationId);
|
||||
}
|
||||
|
||||
/** 仅取路由所需项目 ID,所有标题和业务内容在项目鉴权之后加载。 */
|
||||
|
||||
@ -43,9 +43,11 @@ public class PmStageServiceImpl implements IPmStageService {
|
||||
private final PmAccess access;
|
||||
private final PmIterationAccess iterationAccess;
|
||||
private final IPmService business;
|
||||
private final com.ruoyi.project.manage.service.support.PmGroupVersionService groups;
|
||||
|
||||
/** 注入当前阶段业务需要的 Mapper 和规则,浏览器布局不再依赖数据库 Mapper。 */
|
||||
public PmStageServiceImpl(PmWorkspaceMapper workspaceMapper,PmWorkItemMapper workItemMapper,PmStageMapper stageMapper,PmRevisionMapper revisionMapper,PmGraphService graphService,PmAuditService auditService,PmJson jsonCodec,PmAccess access,IPmService business,PmIterationAccess iterationAccess,com.ruoyi.project.manage.mapper.PmScheduleMapper schedules) {
|
||||
public PmStageServiceImpl(PmWorkspaceMapper workspaceMapper,PmWorkItemMapper workItemMapper,PmStageMapper stageMapper,PmRevisionMapper revisionMapper,PmGraphService graphService,PmAuditService auditService,PmJson jsonCodec,PmAccess access,IPmService business,PmIterationAccess iterationAccess,com.ruoyi.project.manage.mapper.PmScheduleMapper schedules,com.ruoyi.project.manage.service.support.PmGroupVersionService groups) {
|
||||
this.groups=groups;
|
||||
this.schedules=schedules;
|
||||
this.iterationAccess=iterationAccess;
|
||||
this.workspaceMapper=workspaceMapper;
|
||||
@ -77,12 +79,17 @@ public class PmStageServiceImpl implements IPmStageService {
|
||||
try { access.project(projectId,"admin"); }
|
||||
catch(PmException error) { if(error.getHttpStatus()!=403) throw error; canManage=false; }
|
||||
}
|
||||
boolean canWrite=graph.iteration()!=null&&graph.iteration().mutable()&&access.canWrite(projectId);
|
||||
for(Map<String,Object> stage:stages) {
|
||||
long stageId=number(stage,"id"); stage.putAll(summary(items,stageId));
|
||||
long stageId=number(stage,"id"); stage.putAll(summary(items,stageId,graph));
|
||||
String executionStatus=PmStageRules.executionStatus(graph,stageId);
|
||||
stage.put("executionStatus",executionStatus);
|
||||
stage.putAll(com.ruoyi.project.manage.rule.PmStageScheduleRules.summary(graph,stageId));
|
||||
stage.put("complete","COMPLETED".equals(executionStatus));
|
||||
var children=com.ruoyi.project.manage.rule.PmStageHierarchyRules.children(graph,stageId);
|
||||
boolean group=com.ruoyi.project.manage.rule.PmStageHierarchyRules.info(graph,stageId).group();
|
||||
boolean topologyMutable=canManage&&"NOT_STARTED".equals(executionStatus)&&!flag(stage,"executionHistory");
|
||||
stage.putAll(map("childStageCount",children.size(),"completedChildStageCount",children.stream().filter(child->Set.of("COMPLETED","LEGACY_PASSED").contains(PmStageRules.executionStatus(graph,child))).count(),"stagePath",com.ruoyi.project.manage.rule.PmStageHierarchyRules.path(graph,stageId),"canCreateWorkItem",canWrite&&!group&&!Set.of("COMPLETED","LEGACY_PASSED").contains(executionStatus),"canCreateChildStage",topologyMutable&&group,"canEditStructure",topologyMutable));
|
||||
stage.put("blockedReasons",PmStageRules.blockedStage(graph,stageId));
|
||||
List<Map<String,Object>> reworkBlocked=PmStageRules.reworkBlocked(graph,stageId);
|
||||
stage.put("isCurrent",PmStageRules.isCurrent(graph,stageId));
|
||||
@ -95,16 +102,29 @@ public class PmStageServiceImpl implements IPmStageService {
|
||||
}).toList();
|
||||
List<Map<String,Object>> reworkEdges=schedules.selectReworkEdges(projectId,iterationId);
|
||||
for(Map<String,Object> edge:reworkEdges) edge.put("latestReworkAt",PmTime.format(nullable(edge,"latestReworkAt"),"Asia/Shanghai"));
|
||||
return map("reworkEdges",reworkEdges,"iterationId",iterationId,"graphVersion",number(revisionMapper.selectGraphVersion(projectId,iterationId),"graph_version"),"stages",stages,"stageEdges",stageEdges,"unassigned",summary(items,null),"items",List.of(),"dependencies",List.of());
|
||||
return map("reworkEdges",reworkEdges,"iterationId",iterationId,"graphVersion",number(revisionMapper.selectGraphVersion(projectId,iterationId),"graph_version"),"stages",stages,"stageEdges",stageEdges,"unassigned",summary(items,null,graph),"items",List.of(),"dependencies",List.of());
|
||||
}
|
||||
|
||||
/** 阶段经理维护入口;名称和展示顺序不隐式产生连线,执行顺序只由显式边决定。 */
|
||||
/** 创建空阶段时原子保存首版计划和父级组合;手工创建必须填写日期,系统换版使用独立内部入口。 */
|
||||
public long createStage(long projectId,long iterationId,StageInput input) {
|
||||
locked(projectId,iterationId,"admin"); validateStage(projectId,input);
|
||||
String kind=input.stageKind()==null?"WORK":input.stageKind();
|
||||
if(!Set.of("WORK","GROUP").contains(kind)) throw PmException.bad("阶段类型无效");
|
||||
if("GROUP".equals(kind)&&input.parentStageId()!=null) throw PmException.conflict("STAGE_HIERARCHY_INVALID","阶段组只能创建在根画布,不支持第三层阶段");
|
||||
var plan=PmTime.planned(input.plannedStartAt(),input.plannedEndAt());
|
||||
if(plan.start()==null||plan.end()==null||plan.end()<plan.start()) throw PmException.bad("新建阶段必须填写有效的预计开始和结束日期");
|
||||
Graph before=graphService.load(projectId,iterationId);
|
||||
if(input.parentStageId()!=null) {
|
||||
stage(projectId,iterationId,input.parentStageId());
|
||||
if(!com.ruoyi.project.manage.rule.PmStageHierarchyRules.info(before,input.parentStageId()).group()||!"NOT_STARTED".equals(PmStageRules.executionStatus(before,input.parentStageId()))) throw PmException.conflict("STAGE_TOPOLOGY_LOCKED","只能向未执行的阶段组添加子阶段");
|
||||
requireNoExecutionHistory(projectId,iterationId,input.parentStageId());
|
||||
}
|
||||
long id=stageMapper.insertStage(map("project_id",projectId,"iteration_id",iterationId,"name",input.name().trim(),"sort_order",input.sortOrder()==null?0:input.sortOrder(),
|
||||
"owner_id",input.ownerId(),"description",input.description(),"created_by",access.actor(),"created_at",PmTime.now()));
|
||||
long revision=revisionMapper.insertRevision(map("project_id",projectId,"iteration_id",iterationId,"stage_id",id,"revision_no",1,"rework_id",null,"previous_revision_id",null,"flow_definition_revision_id",null,"stage_name_snapshot",input.name().trim(),"stage_owner_snapshot",input.ownerId(),"created_by",access.actor(),"created_at",PmTime.now()));
|
||||
"stage_kind",kind,"parent_stage_id",input.parentStageId(),"owner_id",input.ownerId(),"description",input.description(),"created_by",access.actor(),"created_at",PmTime.now()));
|
||||
long revision=revisionMapper.insertRevision(map("project_id",projectId,"iteration_id",iterationId,"stage_id",id,"revision_no",1,"stage_name_snapshot",input.name().trim(),"stage_owner_snapshot",input.ownerId(),"stage_kind_snapshot",kind,"parent_stage_snapshot_id",input.parentStageId(),"stage_description_snapshot",input.description(),"planned_start_at",plan.start(),"planned_end_at",plan.end(),"plan_source","NORMAL","plan_recorded_at",PmTime.now(),"created_by",access.actor(),"created_at",PmTime.now()));
|
||||
if(revisionMapper.initializeCurrentRevision(projectId,id,revision)!=1) throw PmException.conflict("VERSION_CONFLICT","阶段初始版本建立失败");
|
||||
groups.bind(projectId,iterationId); Graph after=graphService.load(projectId,iterationId);
|
||||
PmRules.validateAcyclic(after); PmRules.validateSchedules(after,"Asia/Shanghai"); PmStageRules.validateRegression(before,after);
|
||||
snapshotDefinition(projectId,iterationId);
|
||||
auditService.record(projectId,iterationId,null,"STAGE_CREATED",map("stageId",id,"name",input.name().trim()),access.actor()); return id;
|
||||
}
|
||||
@ -112,20 +132,35 @@ public class PmStageServiceImpl implements IPmStageService {
|
||||
/** 在统一项目锁下版本更新阶段元数据,不改变工作项状态、预计时间或有效依赖。 */
|
||||
public void editStage(long projectId,long iterationId,long id,StageInput input) {
|
||||
locked(projectId,iterationId,"admin"); Map<String,Object> existing=stage(projectId,iterationId,id); version(input.version(),(int)number(existing,"version")); validateStage(projectId,input);
|
||||
stageMapper.updateStage(id,(int)number(existing,"version"),map("name",input.name().trim(),"sort_order",input.sortOrder()==null?0:input.sortOrder(),"owner_id",input.ownerId(),"description",input.description()));
|
||||
snapshotDefinition(projectId,iterationId);
|
||||
Graph before=graphService.load(projectId,iterationId),after=before.copy();
|
||||
String kind=input.stageKind()==null?text(existing,"stage_kind"):input.stageKind();
|
||||
if(!Set.of("WORK","GROUP").contains(kind)) throw PmException.bad("阶段类型无效");
|
||||
if(input.parentStageId()!=null&&!Objects.equals(input.parentStageId(),nullable(existing,"parent_stage_id"))) throw PmException.bad("请使用结构调整入口修改父级");
|
||||
if(!kind.equals(text(existing,"stage_kind"))&&(workItemMapper.selectItemInStage(projectId,id)!=null||!com.ruoyi.project.manage.rule.PmStageHierarchyRules.children(before,id).isEmpty()||!"NOT_STARTED".equals(PmStageRules.executionStatus(before,id)))) throw PmException.conflict("STAGE_KIND_LOCKED","仅未执行的空阶段可以转换类型");
|
||||
if(!kind.equals(text(existing,"stage_kind"))&&revisionMapper.selectStageRevisions(projectId,iterationId,id).stream().anyMatch(row->nullable(row,"started_at")!=null)) throw PmException.conflict("STAGE_KIND_LOCKED","曾执行的阶段不能转换类型");
|
||||
if(input.plannedStartAt()!=null||input.plannedEndAt()!=null) throw PmException.bad("阶段改期请使用版本排期入口");
|
||||
after.hierarchy().put(id,new com.ruoyi.project.manage.domain.StageInfo(id,kind,nullable(existing,"parent_stage_id"),input.description()));
|
||||
PmRules.validateAcyclic(after); PmStageRules.validateExecutedAncestors(before,after);
|
||||
stageMapper.updateStage(id,(int)number(existing,"version"),map("stage_kind",kind,"name",input.name().trim(),"sort_order",input.sortOrder()==null?0:input.sortOrder(),"owner_id",input.ownerId(),"description",input.description()));
|
||||
stageMapper.refreshDraftRevisionIdentity(number(existing,"current_revision_id"),kind,nullable(existing,"parent_stage_id"),input.description());
|
||||
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"));
|
||||
if(!com.ruoyi.project.manage.rule.PmStageHierarchyRules.children(graphService.load(projectId,iterationId),id).isEmpty()) throw PmException.conflict("STAGE_NOT_EMPTY","阶段组仍有子阶段,不能删除");
|
||||
if(workItemMapper.selectItemInStage(projectId,id)!=null) throw PmException.conflict("STAGE_NOT_EMPTY","阶段仍有未删除工作项,请先调整这些工作项的阶段");
|
||||
Graph before=graphService.load(projectId,iterationId),after=before.copy();
|
||||
after.stageNames().remove(id); after.stageLinks().removeIf(link->link.predecessorStageId()==id||link.successorStageId()==id);
|
||||
requireNoExecutionHistory(projectId,iterationId,id);
|
||||
Long parent=com.ruoyi.project.manage.rule.PmStageHierarchyRules.info(before,id).parentId();
|
||||
if(parent!=null) requireNoExecutionHistory(projectId,iterationId,parent);
|
||||
after.stageNames().remove(id); after.hierarchy().remove(id); after.stageLinks().removeIf(link->link.predecessorStageId()==id||link.successorStageId()==id);
|
||||
PmStageRules.validateExecutedAncestors(before,after);
|
||||
stageMapper.deleteEdgesForStage(projectId,id);
|
||||
stageMapper.updateStage(id,(int)number(existing,"version"),map("deleted",true));
|
||||
groups.bind(projectId,iterationId);
|
||||
snapshotDefinition(projectId,iterationId);
|
||||
auditService.record(projectId,iterationId,null,"STAGE_DELETED",map("stageId",id,"name",text(existing,"name")),access.actor());
|
||||
}
|
||||
@ -169,6 +204,48 @@ public class PmStageServiceImpl implements IPmStageService {
|
||||
business.assignStage(id,input);
|
||||
}
|
||||
|
||||
/** 预览/提交明确的结构最终态;只迁移未执行阶段,全部边由管理者明确提供,不自动重写跨层语义。 */
|
||||
public Map<String,Object> structure(long projectId,long iterationId,com.ruoyi.project.manage.dto.StageStructureInput input,boolean commit) {
|
||||
locked(projectId,iterationId,"read"); access.project(projectId,"admin"); iterationAccess.require(projectId,iterationId,"admin");
|
||||
long graphVersion=number(revisionMapper.selectGraphVersion(projectId,iterationId),"graph_version");
|
||||
if(input==null||input.graphVersion()==null||input.graphVersion()!=graphVersion) throw PmException.conflict("GRAPH_VERSION_CONFLICT","流程已变化,请刷新结构后重新预览");
|
||||
if(input.stages()==null||input.edges()==null||input.stages().size()>200||input.edges().size()>1000) throw PmException.bad("请提交阶段移动和完整连线列表");
|
||||
Graph before=graphService.load(projectId,iterationId),after=before.copy(); Set<Long> seen=new HashSet<>();
|
||||
for(var move:input.stages()) {
|
||||
if(move==null||!seen.add(move.id())) throw PmException.bad("阶段移动为空或重复");
|
||||
Map<String,Object> row=stage(projectId,iterationId,move.id()); version(move.version(),(int)number(row,"version"));
|
||||
if(!"NOT_STARTED".equals(PmStageRules.executionStatus(before,move.id()))||revisionMapper.selectStageRevisions(projectId,iterationId,move.id()).stream().anyMatch(r->nullable(r,"started_at")!=null)) throw PmException.conflict("STAGE_TOPOLOGY_LOCKED","已有执行历史的阶段不能迁移层级");
|
||||
if(move.parentStageId()!=null) stage(projectId,iterationId,move.parentStageId());
|
||||
var old=com.ruoyi.project.manage.rule.PmStageHierarchyRules.info(before,move.id());
|
||||
if(old.parentId()!=null) requireNoExecutionHistory(projectId,iterationId,old.parentId());
|
||||
if(move.parentStageId()!=null) requireNoExecutionHistory(projectId,iterationId,move.parentStageId());
|
||||
after.hierarchy().put(move.id(),new com.ruoyi.project.manage.domain.StageInfo(move.id(),old.kind(),move.parentStageId(),old.description()));
|
||||
}
|
||||
after.stageLinks().clear(); Set<String> edges=new HashSet<>(); long temporary=-1;
|
||||
for(var edge:input.edges()) {
|
||||
if(edge==null||edge.predecessorStageId()==null||edge.successorStageId()==null||edge.predecessorStageId().equals(edge.successorStageId())||!edges.add(edge.predecessorStageId()+":"+edge.successorStageId())) throw PmException.bad("执行边无效或重复");
|
||||
after.stageLinks().add(new StageLink(temporary--,projectId,edge.predecessorStageId(),edge.successorStageId(),0));
|
||||
}
|
||||
PmRules.validateAcyclic(after); PmRules.validateSchedules(after,"Asia/Shanghai"); PmStageRules.validateRegression(before,after); PmStageRules.validateExecutedAncestors(before,after);
|
||||
if(commit) {
|
||||
for(var move:input.stages()) {
|
||||
stageMapper.updateStage(move.id(),move.version(),map("parent_stage_id",move.parentStageId()));
|
||||
var info=after.hierarchy().get(move.id());
|
||||
stageMapper.refreshDraftRevisionIdentity(after.stageRevisions().get(move.id()).id(),info.kind(),info.parentId(),info.description());
|
||||
}
|
||||
stageMapper.deleteIterationEdges(projectId,iterationId);
|
||||
for(StageLink edge:after.stageLinks()) stageMapper.insertStageEdge(map("project_id",projectId,"iteration_id",iterationId,"predecessor_stage_id",edge.predecessorStageId(),"successor_stage_id",edge.successorStageId(),"created_by",access.actor(),"created_at",PmTime.now()));
|
||||
groups.bind(projectId,iterationId); revisionMapper.advanceGraphVersion(projectId,iterationId); snapshotDefinition(projectId,iterationId);
|
||||
auditService.record(projectId,iterationId,null,"STAGE_STRUCTURE_CHANGED",map("moves",input.stages(),"edges",input.edges()),access.actor());
|
||||
}
|
||||
return map("canCommit",true,"graphVersion",graphVersion,"moves",input.stages(),"edges",input.edges(),"committed",commit);
|
||||
}
|
||||
|
||||
/** 回退产生待开始新版本也不能解冻已有的阶段组结构,避免换版后绕过旧执行事实。 */
|
||||
private void requireNoExecutionHistory(long projectId,long iterationId,long stageId) {
|
||||
if(revisionMapper.selectStageRevisions(projectId,iterationId,stageId).stream().anyMatch(row->nullable(row,"started_at")!=null||nullable(row,"legacy_passed_at")!=null)) throw PmException.conflict("STAGE_TOPOLOGY_LOCKED","曾执行的阶段及阶段组不能调整层级或增减子阶段");
|
||||
}
|
||||
|
||||
/** 读取阶段元数据和负责人昵称,时间统一为带偏移 ISO;调用方已取得项目锁并校验数据权限。 */
|
||||
private List<Map<String,Object>> stageRows(long projectId,long iterationId) {
|
||||
List<Map<String,Object>> rows=stageMapper.selectVisibleStages(projectId,iterationId);
|
||||
@ -177,8 +254,9 @@ public class PmStageServiceImpl implements IPmStageService {
|
||||
}
|
||||
|
||||
/** 按全部有效工作项汇总,不受画布筛选影响;取消不计入完成,时间覆盖单独返回。 */
|
||||
private Map<String,Object> summary(List<Map<String,Object>> items,Long stageId) {
|
||||
List<Map<String,Object>> group=items.stream().filter(i->Objects.equals(nullable(i,"stageId"),stageId)).toList();
|
||||
private Map<String,Object> summary(List<Map<String,Object>> items,Long stageId,Graph graph) {
|
||||
Set<Long> scope=stageId==null?Set.of():com.ruoyi.project.manage.rule.PmStageHierarchyRules.subtree(graph,stageId);
|
||||
List<Map<String,Object>> group=items.stream().filter(i->stageId==null?nullable(i,"stageId")==null:scope.contains(nullable(i,"stageId"))).toList();
|
||||
Map<String,Object> counts=map("total",group.size());
|
||||
for(String state:List.of("READY","IN_PROGRESS","COMPLETED","CANCELLED","CLOSED")) counts.put(state,group.stream().filter(i->state.equals(i.get("status"))).count());
|
||||
counts.put("overdue",group.stream().filter(i->Boolean.TRUE.equals(i.get("overdue"))).count());
|
||||
@ -196,6 +274,7 @@ public class PmStageServiceImpl implements IPmStageService {
|
||||
|
||||
/** 校验阶段引用、负责人及大小限制;同项目软删除检查不能仅依赖物理外键。 */
|
||||
private void validateStage(long projectId,StageInput input) {
|
||||
if(input==null) throw PmException.bad("阶段内容不能为空");
|
||||
if(input.name()==null||input.name().isBlank()||input.name().trim().length()>120) throw PmException.bad("阶段名称需为 1—120 个字符");
|
||||
if(input.description()!=null&&input.description().length()>10000) throw PmException.bad("阶段描述过长");
|
||||
if(input.sortOrder()!=null&&(input.sortOrder()<0||input.sortOrder()>100000)) throw PmException.bad("阶段顺序需在 0—100000 之间");
|
||||
|
||||
@ -26,8 +26,9 @@ public class PmGraphService {
|
||||
private final PmRevisionMapper revisionMapper;
|
||||
private final PmIterationMapper iterationMapper;
|
||||
private final PmParticipantService participants;
|
||||
private final com.ruoyi.project.manage.mapper.PmGroupMapper groupMapper;
|
||||
/** 注入只负责数据库访问的 Mapper,不在加载过程中触发业务写入。 */
|
||||
public PmGraphService(PmWorkItemMapper workItemMapper,PmDependencyMapper dependencyMapper,PmStageMapper stageMapper,PmRevisionMapper revisionMapper,PmIterationMapper iterationMapper,PmParticipantService participants) { this.workItemMapper=workItemMapper; this.dependencyMapper=dependencyMapper; this.stageMapper=stageMapper; this.revisionMapper=revisionMapper; this.iterationMapper=iterationMapper; this.participants=participants; }
|
||||
public PmGraphService(PmWorkItemMapper workItemMapper,PmDependencyMapper dependencyMapper,PmStageMapper stageMapper,PmRevisionMapper revisionMapper,PmIterationMapper iterationMapper,PmParticipantService participants,com.ruoyi.project.manage.mapper.PmGroupMapper groupMapper) { this.groupMapper=groupMapper; this.workItemMapper=workItemMapper; this.dependencyMapper=dependencyMapper; this.stageMapper=stageMapper; this.revisionMapper=revisionMapper; this.iterationMapper=iterationMapper; this.participants=participants; }
|
||||
/** 旧项目图入口拒绝隐式选取迭代,内部调用也不能意外加载多个迭代的任务。 */
|
||||
public Graph load(long projectId) { throw new PmException(400,"ITERATION_REQUIRED","请明确选择迭代",Map.of()); }
|
||||
/**
|
||||
@ -49,8 +50,11 @@ public class PmGraphService {
|
||||
// 两种条件标识表达同一工作项完成规则;历史任务条件与新增统一条件必须一起参与图校验。
|
||||
List<Dependency> dependencies=new ArrayList<>();
|
||||
for(Map<String,Object> r:dependencyMapper.selectGraphDependencies(projectId,iterationId)) dependencies.add(new Dependency(number(r,"id"),projectId,number(r,"successor_task_id"),text(r,"condition_type"),nullable(r,"predecessor_task_id"),text(r,"expected_status"),(int)number(r,"version")));
|
||||
Map<Long,String> names=new LinkedHashMap<>();
|
||||
for(Map<String,Object> row:stageMapper.selectVisibleStages(projectId,iterationId)) names.put(number(row,"id"),text(row,"name"));
|
||||
Map<Long,String> names=new LinkedHashMap<>(); Map<Long,com.ruoyi.project.manage.domain.StageInfo> hierarchy=new LinkedHashMap<>();
|
||||
for(Map<String,Object> row:stageMapper.selectVisibleStages(projectId,iterationId)) {
|
||||
long id=number(row,"id"); names.put(id,text(row,"name"));
|
||||
hierarchy.put(id,new com.ruoyi.project.manage.domain.StageInfo(id,text(row,"stageKind"),nullable(row,"parentStageId"),text(row,"description")));
|
||||
}
|
||||
List<StageLink> links=new ArrayList<>();
|
||||
for(Map<String,Object> row:stageMapper.selectStageEdges(projectId,iterationId)) links.add(new StageLink(number(row,"id"),projectId,number(row,"predecessor_stage_id"),number(row,"successor_stage_id"),(int)number(row,"version")));
|
||||
Map<Long,StageRevision> revisions=new LinkedHashMap<>();
|
||||
@ -58,7 +62,16 @@ public class PmGraphService {
|
||||
StageRevision revision=revision(row);
|
||||
revisions.put(revision.stageId(),revision);
|
||||
}
|
||||
return new Graph(items,dependencies,names,links,revisions,new IterationScope(iterationId,projectId,text(iteration,"status"),nullable(iteration,"archived_at")!=null));
|
||||
Graph graph=new Graph(items,dependencies,names,links,revisions,new IterationScope(iterationId,projectId,text(iteration,"status"),nullable(iteration,"archived_at")!=null),hierarchy);
|
||||
com.ruoyi.project.manage.rule.PmStageHierarchyRules.validate(graph);
|
||||
// 父级必须引用精确的当前子版本。禁止读时自动修复,否则历史组合错误会被悄悄覆盖。
|
||||
for(var entry:hierarchy.entrySet()) if(entry.getValue().group()) {
|
||||
Map<Long,Long> expected=new TreeMap<>(),actual=new TreeMap<>();
|
||||
for(Long child:com.ruoyi.project.manage.rule.PmStageHierarchyRules.children(graph,entry.getKey())) expected.put(child,revisions.get(child).id());
|
||||
for(var member:groupMapper.selectMembers(revisions.get(entry.getKey()).id())) actual.put(number(member,"child_stage_id"),number(member,"child_revision_id"));
|
||||
if(!expected.equals(actual)) throw new IllegalStateException("阶段组当前子版本组合不一致");
|
||||
}
|
||||
return graph;
|
||||
}
|
||||
/** 当前与历史版本使用相同字段解码,但历史不会被加入当前依赖图。 */
|
||||
public static StageRevision revision(Map<String,Object> row) { return new StageRevision(number(row,"id"),number(row,"stage_id"),(int)number(row,"revision_no"),nullable(row,"started_at"),nullable(row,"completed_at"),nullable(row,"legacy_passed_at"),nullable(row,"planned_start_at"),nullable(row,"planned_end_at"),nullable(row,"reference_planned_start_at"),nullable(row,"reference_planned_end_at"),nullable(row,"schedule_review_rework_id"),text(row,"plan_source"),nullable(row,"plan_recorded_at"),(int)number(row,"version")); }
|
||||
|
||||
@ -0,0 +1,153 @@
|
||||
package com.ruoyi.project.manage.service.support;
|
||||
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.ruoyi.project.manage.domain.*;
|
||||
import com.ruoyi.project.manage.mapper.*;
|
||||
import com.ruoyi.project.manage.rule.*;
|
||||
import com.ruoyi.project.manage.exception.PmException;
|
||||
import com.ruoyi.project.manage.security.PmAccess;
|
||||
import com.ruoyi.project.manage.util.*;
|
||||
import java.util.*;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.*;
|
||||
import static com.ruoyi.project.manage.util.PmValues.*;
|
||||
|
||||
/** 阶段组汇总版本不复制无关分支;冻结旧视图时保存实际内容,避免引用仍可变化的子执行版本。 */
|
||||
@Service
|
||||
@Transactional(propagation=Propagation.MANDATORY)
|
||||
public class PmGroupVersionService {
|
||||
private final PmGroupMapper mapper;
|
||||
private final PmStageMapper stages;
|
||||
private final PmRevisionMapper revisions;
|
||||
private final PmActivityMapper activities;
|
||||
private final PmGraphService graphs;
|
||||
private final PmJson json;
|
||||
private final ObjectMapper decoder;
|
||||
private final PmAuditService audit;
|
||||
private final PmAccess access;
|
||||
/** 只在调用方已持项目图锁时使用,不创建独立事务或读取用户提交的快照。 */
|
||||
public PmGroupVersionService(PmGroupMapper mapper,PmStageMapper stages,PmRevisionMapper revisions,PmActivityMapper activities,PmGraphService graphs,PmJson json,ObjectMapper decoder,PmAuditService audit,PmAccess access) {
|
||||
this.audit=audit;this.access=access;
|
||||
this.mapper=mapper;this.stages=stages;this.revisions=revisions;this.activities=activities;this.graphs=graphs;this.json=json;this.decoder=decoder;
|
||||
}
|
||||
|
||||
/** 结构创建或换版后原子绑定当前子版本;冻结成员不允许被普通结构编辑替换。 */
|
||||
public void bind(long projectId,long iterationId) {
|
||||
List<Map<String,Object>> rows=stages.selectVisibleStages(projectId,iterationId);
|
||||
for(Map<String,Object> group:rows) if("GROUP".equals(text(group,"stageKind"))) {
|
||||
long id=number(group,"id"),revision=number(group,"currentRevisionId");
|
||||
var expected=new TreeMap<Long,Long>();
|
||||
for(Map<String,Object> child:rows) if(Objects.equals(nullable(child,"parentStageId"),id)) expected.put(number(child,"id"),number(child,"currentRevisionId"));
|
||||
List<Map<String,Object>> members=mapper.selectMembers(revision);
|
||||
var actual=new TreeMap<Long,Long>();for(var member:members)actual.put(number(member,"child_stage_id"),number(member,"child_revision_id"));
|
||||
if(expected.equals(actual)) continue;
|
||||
if(members.stream().anyMatch(m->nullable(m,"frozen_at")!=null)) throw PmException.conflict("STAGE_REVISION_FROZEN","已冻结的阶段组结构不能改写");
|
||||
mapper.deleteDraftMembers(revision);
|
||||
expected.forEach((child,childRevision)->mapper.bindMember(projectId,iterationId,id,revision,child,childRevision));
|
||||
}
|
||||
}
|
||||
|
||||
/** 子阶段状态改变后按当前组合汇总父级实际时间;完成时冻结该组合的全部可读内容。 */
|
||||
public void sync(long projectId,long iterationId) {
|
||||
Graph graph=graphs.load(projectId,iterationId);
|
||||
for(Long id:graph.stageNames().keySet()) if(PmStageHierarchyRules.info(graph,id).group()) {
|
||||
StageRevision old=graph.stageRevisions().get(id); Long first=null,last=null;
|
||||
for(Long child:PmStageHierarchyRules.children(graph,id)) {
|
||||
StageRevision r=graph.stageRevisions().get(child);
|
||||
if(r.startedAt()!=null)first=first==null?r.startedAt():Math.min(first,r.startedAt());
|
||||
if(r.completedAt()!=null)last=last==null?r.completedAt():Math.max(last,r.completedAt());
|
||||
}
|
||||
if(!"COMPLETED".equals(PmStageRules.executionStatus(graph,id)))last=null;
|
||||
if(!Objects.equals(first,old.startedAt())||!Objects.equals(last,old.completedAt())) {
|
||||
if(first!=null&&old.startedAt()==null) {
|
||||
var stage=stages.selectActiveStage(id,projectId,iterationId);
|
||||
revisions.refreshStartedIdentity(old.id(),text(stage,"name"),nullable(stage,"owner_id"));
|
||||
var definition=revisions.selectLatestDefinition(projectId,iterationId);
|
||||
if(definition!=null)revisions.bindStartedDefinition(old.id(),number(definition,"id"));
|
||||
}
|
||||
mapper.updateGroupState(old.id(),first,last);
|
||||
String previous=old.completedAt()!=null?"COMPLETED":old.startedAt()!=null?"IN_PROGRESS":"NOT_STARTED";
|
||||
audit.record(projectId,iterationId,null,"STAGE_STATUS_CHANGED",map("stageId",id,"from",previous,"to",PmStageRules.executionStatus(graph,id),"revisionId",old.id(),"aggregate",true),access.actor());
|
||||
}
|
||||
if(last!=null)freeze(graph,id);
|
||||
}
|
||||
}
|
||||
|
||||
/** 在任何子指针改变前冻结父版本;保留分支日后继续执行时,旧父版本不会读取到未来数据。 */
|
||||
public void freeze(Graph before,long groupId) {
|
||||
StageRevision parent=before.stageRevisions().get(groupId); if(parent==null)return;
|
||||
Map<Long,String> owners=ownerNames(before);
|
||||
for(Map<String,Object> member:mapper.selectMembers(parent.id())) if(nullable(member,"frozen_at")==null) {
|
||||
long child=number(member,"child_stage_id");
|
||||
if(before.stageRevisions().get(child).id()!=number(member,"child_revision_id"))throw new IllegalStateException("父子阶段版本组合不一致");
|
||||
mapper.freezeMember(number(member,"id"),json.encode(snapshot(before,child,owners)),PmTime.now());
|
||||
}
|
||||
}
|
||||
|
||||
/** 以明确父版本读取组合;当前组合可实时构造,缺失的历史冻结数据不能用当前状态补造。 */
|
||||
private List<Map<String,Object>> versionSnapshots(long projectId,long iterationId,long groupId,long revisionId) {
|
||||
Map<String,Object> revision=revisions.selectRevision(projectId,iterationId,groupId,revisionId); if(revision==null)throw PmAccess.denied();
|
||||
Graph current=null;Map<Long,String> owners=null;List<Map<String,Object>> result=new ArrayList<>();
|
||||
for(var member:mapper.selectMembers(revisionId)) {
|
||||
Map<String,Object> saved;
|
||||
if(text(member,"snapshot_json")!=null) {
|
||||
if(number(member,"snapshot_format_version")!=1)throw new IllegalStateException("不支持的阶段组历史快照格式");
|
||||
saved=decode(text(member,"snapshot_json"));
|
||||
}
|
||||
else {
|
||||
if(nullable(revision,"superseded_at")!=null)throw new IllegalStateException("历史阶段组缺少冻结快照");
|
||||
if(current==null) {current=graphs.load(projectId,iterationId);owners=ownerNames(current);}
|
||||
if(current.stageRevisions().get(number(member,"child_stage_id")).id()!=number(member,"child_revision_id"))throw new IllegalStateException("阶段组实时成员版本不一致");
|
||||
saved=snapshot(current,number(member,"child_stage_id"),owners);
|
||||
}
|
||||
saved.put("snapshotFrozen",nullable(member,"frozen_at")!=null);result.add(saved);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/** 父级列表按工作项去重展开精确子版本组合,冻结标记供界面区分历史与当前只读查询。 */
|
||||
public List<Map<String,Object>> versionItems(long projectId,long iterationId,long groupId,long revisionId) {
|
||||
Map<Long,Map<String,Object>> items=new LinkedHashMap<>();
|
||||
for(var snapshot:versionSnapshots(projectId,iterationId,groupId,revisionId))for(Object item:(List<?>)snapshot.get("items")) {
|
||||
var row=stringMap((Map<?,?>)item);row.put("snapshotFrozen",snapshot.get("snapshotFrozen"));items.put(number(row,"id"),row);
|
||||
}
|
||||
return List.copyOf(items.values());
|
||||
}
|
||||
|
||||
/** 子阶段版本和计划取当时快照,返回计数而非重复携带整份工作项列表。 */
|
||||
public List<Map<String,Object>> versionStages(long projectId,long iterationId,long groupId,long revisionId) {
|
||||
List<Map<String,Object>> rows=new ArrayList<>();
|
||||
for(var snapshot:versionSnapshots(projectId,iterationId,groupId,revisionId)) {var row=new LinkedHashMap<>(snapshot);row.put("itemCount",((List<?>)row.remove("items")).size());rows.add(row);}
|
||||
return rows;
|
||||
}
|
||||
|
||||
/** 历史工作项详情必须属于精确的父汇总版本,不能仅传当前工作项ID绕过版本上下文。 */
|
||||
public Map<String,Object> itemSnapshot(long projectId,long iterationId,long groupId,long revisionId,long itemId) {
|
||||
return versionItems(projectId,iterationId,groupId,revisionId).stream().filter(row->number(row,"id")==itemId).findFirst().orElseThrow(PmAccess::denied);
|
||||
}
|
||||
|
||||
/** 为单个子执行版本截取完整只读展示,附件仅保存受鉴权下载所需元信息,不含存储对象键。 */
|
||||
private Map<String,Object> snapshot(Graph graph,long childId,Map<Long,String> owners) {
|
||||
List<Map<String,Object>> items=new ArrayList<>();
|
||||
for(Item item:graph.items().values()) if(!item.deleted()&&Objects.equals(item.stageId(),childId)) {
|
||||
var row=map("id",item.id(),"title",item.title(),"type",item.type(),"description",item.description(),"status",item.status(),"priority",item.priority(),"assigneeId",item.assigneeId(),"collaborators",item.collaborators(),"parent_task_id",item.parentTaskId(),"parentTaskId",item.parentTaskId(),"stageId",childId,"stagePath",PmStageHierarchyRules.path(graph,childId),"version",item.version(),"plannedStartAt",time(item.start()),"plannedEndAt",time(item.end()),"actualStartAt",time(item.actualStart()),"actualEndAt",time(item.actualEnd()),"historical",true,"readOnly",true,"dependencyConditions",PmRules.conditions(graph,item.id(),"Asia/Shanghai"));
|
||||
row.put("projectId",graph.iteration().projectId());row.put("iterationId",graph.iteration().id());
|
||||
row.put("assigneeName",owners.get(item.id()));
|
||||
row.put("comments",activityTimes(activities.selectComments(item.id())));row.put("attachments",activities.selectAttachments(item.id()));row.put("history",activityTimes(activities.selectHistory(item.id())));
|
||||
items.add(row);
|
||||
}
|
||||
Map<String,Object> result=map("stageId",childId,"name",graph.stageNames().get(childId),"description",PmStageHierarchyRules.info(graph,childId).description(),"revisionId",graph.stageRevisions().get(childId).id(),"revisionNo",graph.stageRevisions().get(childId).revisionNo(),"executionStatus",PmStageRules.executionStatus(graph,childId),"items",items);
|
||||
result.putAll(PmStageScheduleRules.times(graph.stageRevisions().get(childId)));return result;
|
||||
}
|
||||
/** JSON 仅来自服务器保存的冻结内容,解码失败使历史查询明确失败而非退回实时内容。 */
|
||||
private Map<String,Object> decode(String value) { try{return decoder.readValue(value,new TypeReference<LinkedHashMap<String,Object>>(){});}catch(Exception failure){throw new IllegalStateException("阶段组快照无法读取",failure);} }
|
||||
/** 将内部快照键安全转换为字符串,避免不受控泛型转换。 */
|
||||
private static Map<String,Object> stringMap(Map<?,?> source) {Map<String,Object> row=new LinkedHashMap<>();source.forEach((key,value)->row.put(String.valueOf(key),value));return row;}
|
||||
/** 时间展示继续使用北京时间,保存与比较保持UTC微秒。 */
|
||||
private static String time(Long value){return PmTime.format(value,"Asia/Shanghai");}
|
||||
/** 审计时间在冻结前转换为标准ISO字段,历史客户端无需猜测数据库微秒的精度。 */
|
||||
private static List<Map<String,Object>> activityTimes(List<Map<String,Object>> rows) {for(var row:rows)row.put("createdAt",time(nullable(row,"createdAt")));return rows;}
|
||||
/** 一次读取整个已鉴权迭代,避免逐工作项查询负责人而放大冻结事务的锁持有时间。 */
|
||||
private Map<Long,String> ownerNames(Graph graph) {Map<Long,String> names=new HashMap<>();for(var row:mapper.selectItemOwners(graph.iteration().projectId(),graph.iteration().id()))names.put(number(row,"id"),text(row,"name"));return names;}
|
||||
}
|
||||
@ -0,0 +1,26 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
|
||||
<!--suppress SqlNoDataSourceInspection -->
|
||||
<mapper namespace="com.ruoyi.project.manage.mapper.PmGroupMapper">
|
||||
<select id="selectItemOwners" resultType="java.util.LinkedHashMap">
|
||||
SELECT w.id,u.nick_name AS name FROM pm_collab_work_item w LEFT JOIN sys_user u ON u.user_id=w.assignee_id
|
||||
LEFT JOIN pm_collab_project_stage s ON s.id=w.stage_id
|
||||
WHERE w.project_id=#{projectId} AND w.iteration_id=#{iterationId} AND w.deleted=false AND (w.stage_id IS NULL OR w.stage_revision_id=s.current_revision_id)
|
||||
</select>
|
||||
<select id="selectMembers" resultType="java.util.LinkedHashMap">
|
||||
SELECT * FROM pm_collab_stage_revision_member WHERE parent_revision_id=#{revisionId} ORDER BY child_stage_id
|
||||
</select>
|
||||
<insert id="bindMember">
|
||||
INSERT INTO pm_collab_stage_revision_member(project_id,iteration_id,parent_stage_id,parent_revision_id,child_stage_id,child_revision_id)
|
||||
VALUES(#{projectId},#{iterationId},#{parentId},#{revisionId},#{childId},#{childRevisionId})
|
||||
</insert>
|
||||
<delete id="deleteDraftMembers">
|
||||
DELETE FROM pm_collab_stage_revision_member WHERE parent_revision_id=#{revisionId} AND frozen_at IS NULL
|
||||
</delete>
|
||||
<update id="freezeMember">
|
||||
UPDATE pm_collab_stage_revision_member SET snapshot_json=#{snapshot},frozen_at=#{at} WHERE id=#{id} AND frozen_at IS NULL
|
||||
</update>
|
||||
<update id="updateGroupState">
|
||||
UPDATE pm_collab_stage_revision SET started_at=#{start},completed_at=#{end},version=version+1 WHERE id=#{revisionId} AND superseded_at IS NULL
|
||||
</update>
|
||||
</mapper>
|
||||
@ -53,8 +53,8 @@
|
||||
OR completed_at IS NOT NULL OR superseded_at IS NOT NULL OR legacy_passed_at IS NOT NULL))
|
||||
</select>
|
||||
<select id="selectCopyStages" resultType="java.util.LinkedHashMap">
|
||||
SELECT id,name,sort_order,owner_id,description FROM pm_collab_project_stage
|
||||
WHERE project_id=#{projectId} AND iteration_id=#{iterationId} AND deleted=false ORDER BY sort_order,id
|
||||
SELECT id,name,sort_order,owner_id,description,stage_kind,parent_stage_id FROM pm_collab_project_stage
|
||||
WHERE project_id=#{projectId} AND iteration_id=#{iterationId} AND deleted=false ORDER BY (parent_stage_id IS NOT NULL),sort_order,id
|
||||
</select>
|
||||
<select id="selectCopyEdges" resultType="java.util.LinkedHashMap">
|
||||
SELECT e.predecessor_stage_id,e.successor_stage_id FROM pm_collab_stage_edge e
|
||||
@ -63,19 +63,19 @@
|
||||
WHERE e.project_id=#{projectId} AND e.iteration_id=#{iterationId} ORDER BY e.id
|
||||
</select>
|
||||
<insert id="insertCopiedStageRow" useGeneratedKeys="true" keyProperty="values.id" keyColumn="id">
|
||||
INSERT INTO pm_collab_project_stage(project_id,iteration_id,name,sort_order,owner_id,description,created_by,created_at)
|
||||
VALUES(#{values.project_id},#{values.iteration_id},#{values.name},#{values.sort_order},#{values.owner_id},#{values.description},#{values.created_by},#{values.created_at})
|
||||
INSERT INTO pm_collab_project_stage(project_id,iteration_id,name,sort_order,owner_id,description,stage_kind,parent_stage_id,created_by,created_at)
|
||||
VALUES(#{values.project_id},#{values.iteration_id},#{values.name},#{values.sort_order},#{values.owner_id},#{values.description},#{values.stage_kind},#{values.parent_stage_id},#{values.created_by},#{values.created_at})
|
||||
</insert>
|
||||
<insert id="insertCopiedRevisionRow" useGeneratedKeys="true" keyProperty="values.id" keyColumn="id">
|
||||
INSERT INTO pm_collab_stage_revision(project_id,iteration_id,stage_id,revision_no,stage_name_snapshot,stage_owner_snapshot,created_by,created_at)
|
||||
VALUES(#{values.project_id},#{values.iteration_id},#{values.stage_id},1,#{values.name},#{values.owner_id},#{values.created_by},#{values.created_at})
|
||||
INSERT INTO pm_collab_stage_revision(project_id,iteration_id,stage_id,revision_no,stage_name_snapshot,stage_owner_snapshot,stage_kind_snapshot,parent_stage_snapshot_id,stage_description_snapshot,created_by,created_at)
|
||||
VALUES(#{values.project_id},#{values.iteration_id},#{values.stage_id},1,#{values.name},#{values.owner_id},#{values.stage_kind},#{values.parent_stage_id},#{values.description},#{values.created_by},#{values.created_at})
|
||||
</insert>
|
||||
<update id="initializeCopiedRevision">
|
||||
UPDATE pm_collab_project_stage SET current_revision_id=#{revisionId} WHERE id=#{stageId} AND current_revision_id IS NULL
|
||||
</update>
|
||||
<insert id="insertCopiedEdge">
|
||||
INSERT INTO pm_collab_stage_edge(project_id,iteration_id,predecessor_stage_id,successor_stage_id,created_by,created_at)
|
||||
VALUES(#{values.project_id},#{values.iteration_id},#{values.predecessor_stage_id},#{values.successor_stage_id},#{values.created_by},#{values.created_at})
|
||||
INSERT INTO pm_collab_stage_edge(project_id,iteration_id,predecessor_stage_id,successor_stage_id,parent_stage_id,created_by,created_at)
|
||||
VALUES(#{values.project_id},#{values.iteration_id},#{values.predecessor_stage_id},#{values.successor_stage_id},(SELECT parent_stage_id FROM pm_collab_project_stage WHERE id=#{values.predecessor_stage_id}),#{values.created_by},#{values.created_at})
|
||||
</insert>
|
||||
<insert id="insertCopiedDefinition">
|
||||
INSERT INTO pm_collab_flow_definition_revision(project_id,iteration_id,revision_no,graph_json,created_by,created_at)
|
||||
|
||||
@ -17,8 +17,8 @@
|
||||
SELECT * FROM pm_collab_work_item WHERE stage_revision_id=#{revisionId} ORDER BY id
|
||||
</select>
|
||||
<insert id="insertRevisionRow" useGeneratedKeys="true" keyProperty="values.id" keyColumn="id">
|
||||
INSERT INTO pm_collab_stage_revision(project_id,iteration_id,stage_id,revision_no,rework_id,previous_revision_id,flow_definition_revision_id,stage_name_snapshot,stage_owner_snapshot,created_by,created_at)
|
||||
VALUES(#{values.project_id},#{values.iteration_id},#{values.stage_id},#{values.revision_no},#{values.rework_id},#{values.previous_revision_id},#{values.flow_definition_revision_id},#{values.stage_name_snapshot},#{values.stage_owner_snapshot},#{values.created_by},#{values.created_at})
|
||||
INSERT INTO pm_collab_stage_revision(project_id,iteration_id,stage_id,revision_no,rework_id,previous_revision_id,flow_definition_revision_id,stage_name_snapshot,stage_owner_snapshot,stage_kind_snapshot,parent_stage_snapshot_id,stage_description_snapshot,revision_reason,planned_start_at,planned_end_at,plan_source,plan_recorded_at,reference_planned_start_at,reference_planned_end_at,schedule_review_rework_id,created_by,created_at)
|
||||
VALUES(#{values.project_id},#{values.iteration_id},#{values.stage_id},#{values.revision_no},#{values.rework_id},#{values.previous_revision_id},#{values.flow_definition_revision_id},#{values.stage_name_snapshot},#{values.stage_owner_snapshot},COALESCE(#{values.stage_kind_snapshot},'WORK'),#{values.parent_stage_snapshot_id},#{values.stage_description_snapshot},COALESCE(#{values.revision_reason},'INITIAL'),#{values.planned_start_at},#{values.planned_end_at},#{values.plan_source},#{values.plan_recorded_at},#{values.reference_planned_start_at},#{values.reference_planned_end_at},#{values.schedule_review_rework_id},#{values.created_by},#{values.created_at})
|
||||
</insert>
|
||||
<update id="switchCurrentRevision">
|
||||
UPDATE pm_collab_project_stage SET current_revision_id=#{nextId},version=version+1
|
||||
|
||||
@ -3,6 +3,11 @@
|
||||
<!-- SQL 由应用数据源执行;未在 IDEA 关联数据源时,仅豁免这一环境提示,保留 SQL 语法检查。 -->
|
||||
<!--suppress SqlNoDataSourceInspection -->
|
||||
<mapper namespace="com.ruoyi.project.manage.mapper.PmStageMapper">
|
||||
<update id="refreshDraftRevisionIdentity">
|
||||
UPDATE pm_collab_stage_revision SET stage_kind_snapshot=#{kind},parent_stage_snapshot_id=#{parentId},stage_description_snapshot=#{description}
|
||||
WHERE id=#{revisionId} AND started_at IS NULL AND superseded_at IS NULL
|
||||
</update>
|
||||
<delete id="deleteIterationEdges">DELETE FROM pm_collab_stage_edge WHERE project_id=#{projectId} AND iteration_id=#{iterationId}</delete>
|
||||
<select id="selectOwnedStage" resultType="java.util.LinkedHashMap">
|
||||
SELECT s.id FROM pm_collab_project_stage s JOIN pm_collab_iteration i ON i.project_id=s.project_id AND i.id=s.iteration_id WHERE s.project_id=#{projectId} AND s.owner_id=#{userId} AND s.deleted=false AND i.deleted=false AND i.archived_at IS NULL AND i.status IN ('PLANNED','ACTIVE') LIMIT 1
|
||||
</select>
|
||||
@ -13,7 +18,8 @@
|
||||
|
||||
<select id="selectVisibleStages" resultType="java.util.LinkedHashMap">
|
||||
<!-- 仅返回当前版本的回退来源,避免画布把有历史回退记录的正常阶段持续标记为待重做。 -->
|
||||
SELECT s.id,s.name,s.sort_order AS sortOrder,s.owner_id AS ownerId,u.nick_name AS ownerName,s.description,s.version,s.current_revision_id AS currentRevisionId,r.revision_no AS revisionNo,r.rework_id AS reworkId,s.created_by AS creatorId,s.created_at AS createdAt
|
||||
SELECT s.id,s.name,s.stage_kind AS stageKind,s.parent_stage_id AS parentStageId,s.sort_order AS sortOrder,s.owner_id AS ownerId,u.nick_name AS ownerName,s.description,s.version,s.current_revision_id AS currentRevisionId,r.revision_no AS revisionNo,r.rework_id AS reworkId,s.created_by AS creatorId,s.created_at AS createdAt,
|
||||
EXISTS(SELECT 1 FROM pm_collab_stage_revision h WHERE h.stage_id=s.id AND h.project_id=s.project_id AND (h.started_at IS NOT NULL OR h.legacy_passed_at IS NOT NULL)) AS executionHistory
|
||||
FROM pm_collab_project_stage s LEFT JOIN sys_user u ON u.user_id=s.owner_id
|
||||
LEFT JOIN pm_collab_stage_revision r ON r.id=s.current_revision_id
|
||||
WHERE s.project_id=#{projectId} AND s.iteration_id=#{iterationId} AND s.deleted=false ORDER BY s.sort_order,s.id
|
||||
@ -32,6 +38,8 @@
|
||||
<trim prefix="(" suffix=")" suffixOverrides=",">
|
||||
<if test="values.containsKey('project_id')">project_id,</if>
|
||||
<if test="values.containsKey('iteration_id')">iteration_id,</if>
|
||||
<if test="values.containsKey('stage_kind')">stage_kind,</if>
|
||||
<if test="values.containsKey('parent_stage_id')">parent_stage_id,</if>
|
||||
<if test="values.containsKey('name')">name,</if>
|
||||
<if test="values.containsKey('sort_order')">sort_order,</if>
|
||||
<if test="values.containsKey('owner_id')">owner_id,</if>
|
||||
@ -45,6 +53,8 @@
|
||||
<trim prefix="(" suffix=")" suffixOverrides=",">
|
||||
<if test="values.containsKey('project_id')">#{values.project_id},</if>
|
||||
<if test="values.containsKey('iteration_id')">#{values.iteration_id},</if>
|
||||
<if test="values.containsKey('stage_kind')">#{values.stage_kind},</if>
|
||||
<if test="values.containsKey('parent_stage_id')">#{values.parent_stage_id},</if>
|
||||
<if test="values.containsKey('name')">#{values.name},</if>
|
||||
<if test="values.containsKey('sort_order')">#{values.sort_order},</if>
|
||||
<if test="values.containsKey('owner_id')">#{values.owner_id},</if>
|
||||
@ -60,6 +70,8 @@
|
||||
UPDATE pm_collab_project_stage
|
||||
<set>
|
||||
<if test="values.containsKey('project_id')">project_id=#{values.project_id},</if>
|
||||
<if test="values.containsKey('stage_kind')">stage_kind=#{values.stage_kind},</if>
|
||||
<if test="values.containsKey('parent_stage_id')">parent_stage_id=#{values.parent_stage_id},</if>
|
||||
<if test="values.containsKey('name')">name=#{values.name},</if>
|
||||
<if test="values.containsKey('sort_order')">sort_order=#{values.sort_order},</if>
|
||||
<if test="values.containsKey('owner_id')">owner_id=#{values.owner_id},</if>
|
||||
@ -73,7 +85,7 @@
|
||||
</update>
|
||||
|
||||
<select id="selectStageEdges" resultType="java.util.LinkedHashMap">
|
||||
SELECT e.id,e.project_id,e.predecessor_stage_id,e.successor_stage_id,e.version
|
||||
SELECT e.id,e.parent_stage_id,e.project_id,e.predecessor_stage_id,e.successor_stage_id,e.version
|
||||
FROM pm_collab_stage_edge e
|
||||
JOIN pm_collab_project_stage source ON source.id=e.predecessor_stage_id AND source.deleted=false
|
||||
JOIN pm_collab_project_stage target ON target.id=e.successor_stage_id AND target.deleted=false
|
||||
@ -81,8 +93,8 @@
|
||||
</select>
|
||||
|
||||
<insert id="insertStageEdgeRow" useGeneratedKeys="true" keyProperty="values.id" keyColumn="id">
|
||||
INSERT INTO pm_collab_stage_edge(project_id,iteration_id,predecessor_stage_id,successor_stage_id,created_by,created_at)
|
||||
VALUES(#{values.project_id},#{values.iteration_id},#{values.predecessor_stage_id},#{values.successor_stage_id},#{values.created_by},#{values.created_at})
|
||||
INSERT INTO pm_collab_stage_edge(project_id,iteration_id,predecessor_stage_id,successor_stage_id,parent_stage_id,created_by,created_at)
|
||||
VALUES(#{values.project_id},#{values.iteration_id},#{values.predecessor_stage_id},#{values.successor_stage_id},(SELECT parent_stage_id FROM pm_collab_project_stage WHERE id=#{values.predecessor_stage_id}),#{values.created_by},#{values.created_at})
|
||||
</insert>
|
||||
|
||||
<delete id="deleteStageEdge">
|
||||
|
||||
@ -36,6 +36,8 @@
|
||||
<if test="values.containsKey('stage_revision_id')">stage_revision_id,</if>
|
||||
<if test="values.containsKey('origin_work_item_id')">origin_work_item_id,</if>
|
||||
<if test="values.containsKey('schedule_review_rework_id')">schedule_review_rework_id,</if>
|
||||
<if test="values.containsKey('reference_planned_start_at')">reference_planned_start_at,</if>
|
||||
<if test="values.containsKey('reference_planned_end_at')">reference_planned_end_at,</if>
|
||||
<if test="values.containsKey('parent_task_id')">parent_task_id,</if>
|
||||
<if test="values.containsKey('version')">version,</if>
|
||||
<if test="values.containsKey('deleted')">deleted,</if>
|
||||
@ -60,6 +62,8 @@
|
||||
<if test="values.containsKey('stage_revision_id')">#{values.stage_revision_id},</if>
|
||||
<if test="values.containsKey('origin_work_item_id')">#{values.origin_work_item_id},</if>
|
||||
<if test="values.containsKey('schedule_review_rework_id')">#{values.schedule_review_rework_id},</if>
|
||||
<if test="values.containsKey('reference_planned_start_at')">#{values.reference_planned_start_at},</if>
|
||||
<if test="values.containsKey('reference_planned_end_at')">#{values.reference_planned_end_at},</if>
|
||||
<if test="values.containsKey('parent_task_id')">#{values.parent_task_id},</if>
|
||||
<if test="values.containsKey('version')">#{values.version},</if>
|
||||
<if test="values.containsKey('deleted')">#{values.deleted},</if>
|
||||
|
||||
@ -1,8 +1,14 @@
|
||||
import { request } from './client'
|
||||
import { iterationPath } from './paths'
|
||||
import type { FlowView, ReworkInput, ReworkPreview, StageRevision, StageRevisionDetail, StageInput } from '../types'
|
||||
import type { FlowView, ReworkInput, ReworkPreview, StageRevision, StageRevisionDetail, StageInput, StageStructureInput, WorkItem } from '../types'
|
||||
|
||||
export const stageApi = {
|
||||
/** 精确父级组合下读取冻结详情,不用实时子项替代历史数据。 */
|
||||
stageItemSnapshot: (id: number, iterationId: number, stageId: number, revisionId: number, itemId: number) => request<WorkItem>('get', iterationPath(id, iterationId, `stages/${stageId}/revisions/${revisionId}/items/${itemId}`)),
|
||||
/** 迁入迁出未执行阶段前预览完整最终结构,调用方明确提供全部保留边。 */
|
||||
previewStageStructure: (id: number, iterationId: number, input: StageStructureInput) => request<{ canCommit: boolean; graphVersion: number }>('post', iterationPath(id, iterationId, 'stage-structure/preview'), input),
|
||||
/** 以同一图版本确认已预览的结构;历史和已执行阶段由后端保护。 */
|
||||
commitStageStructure: (id: number, iterationId: number, input: StageStructureInput) => request<void>('post', iterationPath(id, iterationId, 'stage-structure'), input),
|
||||
/** 仅读取当前迭代阶段及计数摘要;工作项由各视图独立分页查询。 */
|
||||
flowView: (id: number, iterationId?: number) => request<FlowView>('get', iterationPath(id, iterationId, `flow-view`)),
|
||||
/** 回退预览从项目锁下的最新图计算影响范围,界面只展示后端裁定结果。 */
|
||||
|
||||
@ -65,6 +65,7 @@ export function useProjectCollaboration() {
|
||||
const keyword = ref('')
|
||||
const typeFilter = ref<ItemType | null>(null)
|
||||
const blockedOnly = ref(false)
|
||||
const stageFilter = ref<number | null>(null)
|
||||
const detailId = ref<number | null>(null)
|
||||
const refreshKey = ref(0)
|
||||
const selection = ref<WorkItem[]>([])
|
||||
@ -163,7 +164,7 @@ export function useProjectCollaboration() {
|
||||
|
||||
/** 分页筛选交由服务端;甘特独有的成员条件不传给列表、看板或前置选择器。 */
|
||||
function query(view: ItemQuery['view']): ItemQuery {
|
||||
return { view, page: page.value, pageSize, keyword: keyword.value, type: typeFilter.value, blockedOnly: blockedOnly.value, ...(view === 'gantt' ? { from: ganttFrom.value, to: ganttTo.value, memberIds: [...ganttMemberIds.value] } : {}) }
|
||||
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] } : {}) }
|
||||
}
|
||||
|
||||
/** 用户主动刷新或业务操作完成时显示加载状态;独立包装避免分页事件的页码被当作后台标志。 */
|
||||
@ -270,7 +271,7 @@ export function useProjectCollaboration() {
|
||||
flowView.value = null
|
||||
selection.value = []
|
||||
members.value = []
|
||||
ganttMemberIds.value = []
|
||||
ganttMemberIds.value = []; stageFilter.value = null
|
||||
detailId.value = null
|
||||
editing.value = null
|
||||
creatingParent.value = null
|
||||
@ -476,7 +477,7 @@ export function useProjectCollaboration() {
|
||||
finally { polling = false }
|
||||
}
|
||||
|
||||
watch([tab, keyword, typeFilter, blockedOnly], () => {
|
||||
watch([tab, keyword, typeFilter, blockedOnly, stageFilter], () => {
|
||||
page.value = 1
|
||||
void refresh()
|
||||
})
|
||||
@ -598,7 +599,7 @@ export function useProjectCollaboration() {
|
||||
return {
|
||||
projectId, iterations, iterationId, includeArchived,
|
||||
items, members, flowView, current, selectedIteration, zone, canWrite, canCreate, canExecute,
|
||||
loading, failure, tab, keyword, typeFilter, blockedOnly, detailId, refreshKey, selection,
|
||||
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,
|
||||
notifications, statCards, userStore,
|
||||
|
||||
@ -0,0 +1,58 @@
|
||||
# 阶段组与子流程实施计划
|
||||
|
||||
**目标**:在现有协作中实现两层阶段树、同层执行图、整日阶段计划、局部回退和稳定的父级历史。
|
||||
|
||||
**规格**:本会话最终审查方案(用户已授权实施)。WORK 承载工作项,GROUP 承载 WORK 子阶段;空节点不放行。实际准入与预计排期分开。局部回退只重做相关执行分支,父级汇总独立换版。
|
||||
|
||||
**范围**:前端仅 manage 目录;后端仅 ruoyi-project。复用项目权限、MyBatis、项目图锁、UTC 微秒存储、北京时间日期控件及 outbox;不更改其他模块。
|
||||
|
||||
**验证重点**:父级阻塞不能绕过;无关并行分支不误复制;父级旧快照不随保留分支变化;空节点可回退但不自动放行;有效整批父子排期可以原子提交。
|
||||
|
||||
## 任务与进度
|
||||
|
||||
- [x] 1. 层级模型和迁移:StageInfo、Graph 层级快照、StageInput 日期/类型/父级、019 升级 SQL、Mapper XML。
|
||||
- [x] 2. 执行与排期:PmStageHierarchyRules 校验两层及同层连线,PmStageRules 聚合状态/父级准入,PmRules 混合环,PmStageScheduleRules 父子范围及内部排期状态。
|
||||
- [x] 3. 阶段管理和结构预览:新建首版同时保存计划;父级可写性;管理者明确调整未执行阶段父级和边;工作项阶段归属不能用普通字段更新绕过。
|
||||
- [x] 4. 版本与回退:阶段组成员表、冻结快照和历史详情;重做与汇总集合分离;空阶段回退;排期复核及任务前置映射。
|
||||
- [x] 5. 子流程画布:GROUP 自适应父节点、WORK 子节点、同层边、折叠偏好、统一创建表单及阶段/历史抽屉。
|
||||
- [x] 6. 跨视图兼容:阶段路径、组筛选、甘特层级、迭代结构复制和结束预览、合并通知。
|
||||
- [x] 7. 验收:规则红绿测试、真实 MySQL 事务/并发测试、前端交互、严格类型检查和前后端构建;逐项复核需求、注释和范围;删除临时测试。
|
||||
|
||||
每项按失败测试→实现→相关验证推进。临时验证代码放在模块 target 或 manage/tests,验收结束清理;不提交或推送本次改动。当前工作区是用户正在使用的仓库,直接按用户指定路径实施,不另开会影响 IDEA 的目录或重启用户服务。
|
||||
|
||||
## 业务边界与约束
|
||||
|
||||
FR-001:根画布可创建工作阶段或阶段组;组内只支持工作阶段,不支持第三层。空阶段不自动完成。父级入边约束子阶段进入,父级完成依据全部子阶段,防止父子互相等待。
|
||||
|
||||
FR-002:手工创建阶段须填写整日计划;子阶段在父组范围内,同层执行边使用完成后开始约束。未连线的同级节点可并行。保留已有精确排期,实际开始不必等预计日期。
|
||||
|
||||
FR-003:回退限当前阶段及同一画布严格上游。重做执行阶段、父级汇总换版和排期复核为三个集合。显式重做组会重做整个子树;仅子阶段换版不会复制无关并行分支。父组有效计划未变时不清空外层后继计划。
|
||||
|
||||
FR-004:父级版本绑定精确子执行版本组合。在子指针变动前冻结旧组合;冻结名称、工作项字段、分工、依赖情况及当时详情展示的评论、附件元数据和历史。附件不复制二进制和存储对象键,下载仍遵守当前权限和软删除规则。
|
||||
|
||||
FR-005:项目图行锁与原项目共享锁协调所有业务写入,使用稳定的原项目→协作图锁序。回退幂等键和图版本保护预览;业务、版本、历史、outbox 同事务提交。异步通知继续合并为每人一次回退提醒,邮件仍须明确勾选。
|
||||
|
||||
FR-006:所有成员共享阶段树和内容;位置、视口、折叠和坐标所属画布只保存在当前浏览器。阶段层级改变后废弃该节点原坐标,不把根画布位置当成子画布相对坐标。
|
||||
|
||||
## 迁移与使用
|
||||
|
||||
- 已安装环境在 018 之后执行后端 `sql/upgrade/019_stage_groups.sql` 一次;全新环境使用完整安装文件,不再重复执行 019。
|
||||
- 当前开发库 `cmvr-project-dev` 已执行 019,升级只增列、索引、约束及 `pm_collab_stage_revision_member`,未删除业务数据。原阶段保持根工作阶段。
|
||||
- 原三个表的升级前结构保存在 `E:/workspace/cmvr-wms-recovery/20261020-170237-stage-groups`。
|
||||
- 新建阶段从画布拖入;选择阶段组后可在组内拖入/创建子阶段。管理阶段提供未执行结构的预览与确认入口;已有执行历史的阶段组冻结父级和子阶段集合。
|
||||
- 列表、看板和甘特显示完整阶段路径并支持组筛选;组抽屉聚合工作项,历史页可查看当时子版本组合和冻结工作项详情。
|
||||
- 后端继续通过 ruoyi-admin 启动,前端沿用原项目启动方式。升级完成后重启后端并刷新前端;不由 ORM 或应用启动执行建表。
|
||||
|
||||
## 验收记录
|
||||
|
||||
- FR-001~FR-006:PASS;AC-001 层级与门禁、AC-002 父子排期、AC-003 局部回退与稳定历史、AC-004 并发一致性、AC-005 子画布交互及跨视图:PASS。
|
||||
- 临时 `StageRulesCheck`:PASS,覆盖组状态、父级准入、并行汇总、取消与空阶段、混合环、父子计划范围、自身计划与内部冲突区分。
|
||||
- 临时 `StageIntegrationCheck`:PASS。使用独立 MySQL 8 临时数据库安装完整结构、外键和真实 MyBatis/Spring 事务服务,覆盖局部回退不复制并行分支、旧父快照不随标题及评论变化、精确子版本绑定、幂等、组完成后放行、实际时间汇总、结构预览不写入、迭代结构复制、空阶段回退及非成员拒绝。并发验证反向加边、父子排期修改、开始与回退;拒绝的操作不产生成功事件。临时库已删除。
|
||||
- 临时 Chrome 浏览器脚本:PASS,覆盖子节点边界及避让、相对坐标拖动、折叠刷新后恢复、明暗主题、精确父级历史详情接口、只读日期控件及整日提交、结构变更后预览失效。交互验收使用受控 API 响应;后端业务由上述真实数据库测试验证。
|
||||
- 实际开发库 019 结构及新增 7 个字段的中文注释:PASS。
|
||||
- 后端构建:`mvn -pl ruoyi-admin -am -DskipTests package`:PASS;该命令不代表运行 Maven 测试,规则与数据库用例单独执行。
|
||||
- 前端严格检查:`npx --no-install vue-tsc --noEmit -p src/views/project/manage/tsconfig.json --noUnusedLocals --noUnusedParameters`:PASS。
|
||||
- 前端构建:`npm run build:prod`:PASS;清理临时页面后再次构建,避免测试页面进入动态路由产物。
|
||||
- 未单独执行 Lint。新增与修改方法的中文说明、复杂图与快照注释已复核。Scope Drift:NONE;Requirement Drift:NONE。
|
||||
|
||||
按用户约定,上述临时用例、辅助类、测试页面、截图、日志及专用缓存均在验收后删除;临时用例名称是执行记录,不是保留的测试入口。
|
||||
@ -48,7 +48,7 @@ watch(() => [props.visible, props.projectId, props.iterationId], async () => {
|
||||
const view = await api.flowView(props.projectId, props.iterationId)
|
||||
if (request !== sequence) return
|
||||
stages.value = view.stages; graphVersion.value = view.graphVersion
|
||||
stageRows.value = view.stages.filter(stage => !frozen(stage.id)).map(stage => ({ ...draft(stage.id, stage.revisionVersion ?? 0, stage.name, stage), revisionId: stage.revisionId ?? stage.currentRevisionId }))
|
||||
stageRows.value = view.stages.filter(stage => !frozen(stage.id)).map(stage => ({ ...draft(stage.id, stage.revisionVersion ?? 0, stage.stagePath || stage.name, stage), revisionId: stage.revisionId ?? stage.currentRevisionId }))
|
||||
await loadMore()
|
||||
} catch (error) { if (request === sequence) failure.value = errorText(error) }
|
||||
finally { if (request === sequence) loading.value = false }
|
||||
|
||||
@ -1,6 +1,7 @@
|
||||
<template>
|
||||
<section class="stage-schedule">
|
||||
<div class="schedule-heading"><strong>阶段时间</strong><el-tag v-if="schedule.planSource === 'BACKFILLED'" size="small" type="info">完成后补录</el-tag><el-tag v-if="schedule.overdue" size="small" type="danger">超期未完成</el-tag><el-button v-if="canEdit && !editing" size="small" :loading="busy" @click="openEditor">{{ completed ? '补录缺失计划' : schedule.scheduleReviewRequired ? '确认或调整计划' : '编辑阶段计划' }}</el-button></div>
|
||||
<p v-if="schedule.scheduleValidationStatus" class="note">阶段自身计划:{{ scheduleLabel(schedule.scheduleValidationStatus) }}<span v-if="schedule.subtreeScheduleValidationStatus"> · 工作项与子阶段排期:{{ scheduleLabel(schedule.subtreeScheduleValidationStatus) }}</span></p>
|
||||
<div class="time-grid"><span>预计开始</span><span>{{ plannedDate(schedule.plannedStartAt) }}</span><span>预计结束</span><span>{{ plannedDate(schedule.plannedEndAt) }}</span><span>实际开始</span><span>{{ readable(schedule.actualStartAt) }}</span><span>实际完成</span><span>{{ readable(schedule.actualEndAt) }}</span></div>
|
||||
<p v-if="schedule.scheduleReviewRequired" class="reference">{{ schedule.scheduleReviewClosed || historical ? '本轮未确认排期' : '上游回退,排期待复核' }} · 仅供参考:{{ plannedDate(schedule.referencePlannedStartAt) }} → {{ plannedDate(schedule.referencePlannedEndAt) }}</p>
|
||||
<p v-else-if="!schedule.plannedStartAt || !schedule.plannedEndAt" class="note">排期未完成;实际开始仍按前置完成条件判断。</p>
|
||||
@ -9,7 +10,7 @@
|
||||
<el-form v-if="editing" size="small" label-position="top" @submit.prevent="save">
|
||||
<p v-if="draftSource?.earliestPlannedStartAt" class="note">最早合法开始:{{ planningLimitDate(draftSource.earliestPlannedStartAt, 'start', 'min') }}<span v-if="draftSource.sources?.length"> · 来源:{{ draftSource.sources.map(s => s.sourceName).join('、') }}</span></p>
|
||||
<el-alert v-if="draftSource?.unresolvedSources?.length" type="warning" :closable="false" :title="`前置计划尚未确认:${draftSource.unresolvedSources.map(s => s.sourceName).join('、')}。可在批量排期中一起调整。`" />
|
||||
<div class="picker-grid"><el-form-item label="预计开始"><TimeField boundary="start" v-model="start" zone="Asia/Shanghai" :earliest="draftSource?.earliestPlannedStartAt" @invalid="invalidStart = $event" /></el-form-item><el-form-item label="预计结束"><TimeField boundary="end" v-model="end" zone="Asia/Shanghai" :earliest="start" @invalid="invalidEnd = $event" /></el-form-item></div>
|
||||
<div class="picker-grid"><el-form-item label="预计开始"><TimeField boundary="start" v-model="start" zone="Asia/Shanghai" :earliest="draftSource?.earliestPlannedStartAt" :latest="draftSource?.latestPlannedEndAt" @invalid="invalidStart = $event" /></el-form-item><el-form-item label="预计结束"><TimeField boundary="end" v-model="end" zone="Asia/Shanghai" :earliest="start" :latest="draftSource?.latestPlannedEndAt" @invalid="invalidEnd = $event" /></el-form-item></div>
|
||||
<el-form-item :label="completed || draftSource?.actualStartAt ? '调整原因(必填)' : '调整说明'"><el-input v-model="reason" size="small" maxlength="2000" type="textarea" :rows="2" /></el-form-item>
|
||||
<div class="schedule-actions"><el-button size="small" :disabled="busy" @click="editing = false">取消</el-button><el-button size="small" type="primary" :loading="busy" :disabled="invalidStart || invalidEnd || !canEdit" @click="save">保存计划</el-button></div>
|
||||
</el-form>
|
||||
@ -31,6 +32,8 @@ let sequence = 0
|
||||
const canEdit = computed(() => !!props.canManage && !!props.iterationId && !props.historical && (!props.completed || !props.schedule.plannedStartAt && !props.schedule.plannedEndAt && props.schedule.planSource !== 'BACKFILLED'))
|
||||
/** 切换项目、阶段或历史轮次时销毁草稿,异步结果不能写到另一个范围。 */
|
||||
watch(() => [props.projectId, props.iterationId, props.stageId, props.historical, props.schedule.revisionId, canEdit.value], () => { sequence++; editing.value = false; busy.value = false; failure.value = '' })
|
||||
/** 自身计划与内部排期分开展示,避免有父计划便误认为全部子项已排好。 */
|
||||
function scheduleLabel(status: string) { return status === 'VALID' ? '合法' : status === 'CONFLICT' ? '冲突' : '未完成' }
|
||||
/** 显示保留实际精度,空值表示尚未发生或尚未设置。 */
|
||||
function readable(value?: string | null) { return value ? localTime(value, 'Asia/Shanghai').replace('T', ' ') : '未设置' }
|
||||
/** 编辑前读取最新版本和边界;参考值只预填草稿,必须经用户保存才恢复有效。 */
|
||||
|
||||
@ -0,0 +1,37 @@
|
||||
<template>
|
||||
<el-dialog :model-value="visible" :title="parent ? `新建子阶段 · ${parent.name}` : '新建阶段'" width="540px" append-to-body @close="emit('close')">
|
||||
<el-form size="small" label-position="top" @submit.prevent>
|
||||
<el-form-item v-if="!parent" label="阶段类型"><el-radio-group v-model="draft.stageKind"><el-radio-button value="WORK">工作阶段</el-radio-button><el-radio-button value="GROUP">阶段组</el-radio-button></el-radio-group></el-form-item>
|
||||
<p class="hint">{{ draft.stageKind === 'GROUP' ? '阶段组只承载子阶段,全部子阶段完成后才放行后续。' : '工作阶段可以保持为空;添加工作项并全部完成后才放行后续。' }}</p>
|
||||
<el-form-item label="阶段名称" required><el-input v-model="draft.name" maxlength="120" /></el-form-item>
|
||||
<el-form-item label="阶段描述"><el-input v-model="draft.description" type="textarea" :rows="3" maxlength="10000" placeholder="说明本阶段需要完成的事项" /></el-form-item>
|
||||
<el-form-item label="阶段负责人"><el-select v-model="draft.ownerId" clearable><el-option v-for="member in members" :key="member.userId" :value="member.userId" :label="member.name" /></el-select></el-form-item>
|
||||
<el-row :gutter="16"><el-col :span="12"><el-form-item label="预计开始" required><TimeField v-model="draft.plannedStartAt" zone="Asia/Shanghai" boundary="start" :earliest="parent?.plannedStartAt" :latest="parent?.plannedEndAt" /></el-form-item></el-col><el-col :span="12"><el-form-item label="预计结束" required><TimeField v-model="draft.plannedEndAt" zone="Asia/Shanghai" boundary="end" :earliest="draft.plannedStartAt" :latest="parent?.plannedEndAt" /></el-form-item></el-col></el-row>
|
||||
</el-form>
|
||||
<el-alert v-if="failure" :title="failure" type="error" :closable="false" />
|
||||
<template #footer><el-button size="small" @click="emit('close')">取消</el-button><el-button size="small" type="primary" :loading="busy" :disabled="!draft.name.trim() || !draft.plannedStartAt || !draft.plannedEndAt" @click="save">创建</el-button></template>
|
||||
</el-dialog>
|
||||
</template>
|
||||
<script setup lang="ts">
|
||||
import { onBeforeUnmount, reactive, ref, watch } from 'vue'
|
||||
import type { Member, Stage } from '../../../types'
|
||||
import { api, errorText } from '../../../api'
|
||||
import TimeField from '../../../shared/components/TimeField.vue'
|
||||
const props = defineProps<{ visible: boolean; projectId: number; iterationId?: number; parent?: Stage | null; members: Member[] }>()
|
||||
const emit = defineEmits<{ close: []; created: [id: number] }>()
|
||||
const busy = ref(false), failure = ref('')
|
||||
const draft = reactive({ name: '', description: '', stageKind: 'WORK' as 'WORK' | 'GROUP', ownerId: null as number | null, plannedStartAt: null as string | null, plannedEndAt: null as string | null })
|
||||
let generation = 0
|
||||
/** 每次创建重置类型与日期,子阶段固定为工作阶段,不继承旧迭代的草稿。 */
|
||||
watch(() => props.visible, visible => { generation++; if (visible) { Object.assign(draft, { name: '', description: '', stageKind: 'WORK', ownerId: null, plannedStartAt: null, plannedEndAt: null }); failure.value = '' } })
|
||||
/** 离开项目或迭代后不再处理旧创建请求的界面回调,服务端事务结果仍由后续同步读取。 */
|
||||
onBeforeUnmount(() => { generation++ })
|
||||
/** 日期与结构在同一后端事务创建;失败保留输入以便调整父级范围。 */
|
||||
async function save() {
|
||||
if (busy.value || !draft.name.trim() || !draft.plannedStartAt || !draft.plannedEndAt) return
|
||||
const request = generation; busy.value = true; failure.value = ''
|
||||
try { const id = await api.createStage(props.projectId, { ...draft, name: draft.name.trim(), sortOrder: 0, parentStageId: props.parent?.id ?? null }, props.iterationId); if (request === generation) emit('created', id) }
|
||||
catch (error) { if (request === generation) failure.value = errorText(error) } finally { busy.value = false }
|
||||
}
|
||||
</script>
|
||||
<style scoped>.hint{font-size:12px;line-height:1.6;color:var(--el-text-color-secondary)}:deep([class~="el-select"]){width:100%}</style>
|
||||
@ -1,16 +1,18 @@
|
||||
<template>
|
||||
<el-dialog :model-value="visible" title="项目阶段" width="780px" append-to-body @close="emit('close')">
|
||||
<el-alert title="在流程画布拖入阶段并手工连线确定执行顺序;前置阶段全部工作项完成或关闭后,下游工作项才可开始。含工作项的阶段须先调整归属再删除。" type="info" :closable="false" />
|
||||
<el-button v-if="iterationId && view" size="small" class="structure-button" @click="structureOpen = true">调整阶段层级与连线</el-button>
|
||||
<el-table :data="stages" size="small" max-height="450">
|
||||
<el-table-column label="阶段" prop="name" min-width="140" />
|
||||
<el-table-column label="阶段" min-width="180"><template #default="{ row }">{{ row.stagePath || row.name }}<el-tag v-if="row.stageKind === 'GROUP'" size="small" type="info">阶段组</el-tag></template></el-table-column>
|
||||
<el-table-column label="负责人" width="120"><template #default="{ row }">{{ row.ownerName || '未分配' }}</template></el-table-column>
|
||||
<el-table-column label="工作项" width="80"><template #default="{ row }">{{ row.counts.total }}</template></el-table-column><el-table-column label="完成" width="80"><template #default="{ row }">{{ row.complete ? '已完成' : '未完成' }}</template></el-table-column>
|
||||
<el-table-column label="描述" prop="description" min-width="200" show-overflow-tooltip />
|
||||
<el-table-column label="操作" width="145" class-name="business-operation-cell"><template #default="{ row }"><el-button link type="primary" @click="open(row)">编辑</el-button><el-tooltip content="请先移动阶段中的工作项" :disabled="!row.counts.total"><span><el-button link type="danger" :disabled="!!row.counts.total || busy" @click="remove(row)">删除</el-button></span></el-tooltip></template></el-table-column>
|
||||
<el-table-column label="操作" width="145" class-name="business-operation-cell"><template #default="{ row }"><el-button link type="primary" @click="open(row)">编辑</el-button><el-tooltip content="请先移动阶段中的工作项" :disabled="!row.counts.total"><span><el-button link type="danger" :disabled="!!row.counts.total || !!row.childStageCount || busy" @click="remove(row)">删除</el-button></span></el-tooltip></template></el-table-column>
|
||||
</el-table>
|
||||
<el-alert v-if="failure" type="error" :title="failure" :closable="false" class="failure" />
|
||||
<el-dialog v-model="editorOpen" title="编辑阶段" width="520px" append-to-body>
|
||||
<el-form label-position="top" size="small">
|
||||
<el-form-item v-if="!editing?.parentStageId" label="阶段类型"><el-select v-model="draft.stageKind" :disabled="!editing?.canEditStructure || !!editing?.counts.total || !!editing?.childStageCount"><el-option label="工作阶段" value="WORK" /><el-option label="阶段组" value="GROUP" /></el-select></el-form-item>
|
||||
<el-form-item label="阶段名称" required><el-input v-model="draft.name" maxlength="120" /></el-form-item>
|
||||
<el-form-item label="阶段负责人"><el-select v-model="draft.ownerId" clearable placeholder="未分配"><el-option v-for="member in members" :key="member.userId" :value="member.userId" :label="member.name" /></el-select></el-form-item>
|
||||
<el-form-item label="阶段描述"><el-input v-model="draft.description" type="textarea" :rows="3" maxlength="10000" placeholder="说明本阶段需要完成的事项" /></el-form-item>
|
||||
@ -19,24 +21,27 @@
|
||||
<template #footer><el-button @click="editorOpen = false">取消</el-button><el-button type="primary" :loading="busy" :disabled="!draft.name.trim()" @click="save">保存</el-button></template>
|
||||
</el-dialog>
|
||||
</el-dialog>
|
||||
<StageStructureDialog v-if="view && iterationId" :visible="structureOpen" :project-id="projectId" :iteration-id="iterationId" :view="view" @close="structureOpen = false" @changed="emit('changed')" />
|
||||
</template>
|
||||
<script setup lang="ts">
|
||||
import { reactive, ref, watch } from 'vue'
|
||||
import { ElMessageBox } from 'element-plus'
|
||||
import { api, errorText } from '../../../api'
|
||||
import type { Stage, StageInput, Member } from '../../../types'
|
||||
const props = defineProps<{ visible: boolean; projectId: number; iterationId?: number; stages: Stage[]; members: Member[] }>()
|
||||
import StageStructureDialog from './StageStructureDialog.vue'
|
||||
import type { Stage, StageInput, Member, FlowView } from '../../../types'
|
||||
const props = defineProps<{ visible: boolean; projectId: number; iterationId?: number; stages: Stage[]; members: Member[]; view?: FlowView }>()
|
||||
const emit = defineEmits<{ close: []; changed: [] }>()
|
||||
const structureOpen = ref(false)
|
||||
const editing = ref<Stage | null>(null), editorOpen = ref(false), busy = ref(false), failure = ref(''), editorFailure = ref('')
|
||||
const draft = reactive<StageInput>({ name: '', sortOrder: 0, ownerId: null, description: '' })
|
||||
watch(() => props.visible, visible => { if (!visible) editorOpen.value = false; failure.value = '' })
|
||||
watch(() => props.visible, visible => { if (!visible) { editorOpen.value = false; structureOpen.value = false } failure.value = '' })
|
||||
/** 只编辑现有阶段元数据;新增阶段由画布拖入操作提供明确落点。 */
|
||||
function open(stage: Stage) { editing.value = stage; Object.assign(draft, { name: stage.name, sortOrder: stage.sortOrder, ownerId: stage.ownerId ?? null, description: stage.description || '', version: stage.version }); editorFailure.value = ''; editorOpen.value = true }
|
||||
function open(stage: Stage) { editing.value = stage; Object.assign(draft, { name: stage.name, sortOrder: stage.sortOrder, ownerId: stage.ownerId ?? null, description: stage.description || '', stageKind: stage.stageKind || 'WORK', version: stage.version }); editorFailure.value = ''; editorOpen.value = true }
|
||||
/** 保存经经理鉴权与阶段版本校验的元数据,失败保留草稿。 */
|
||||
async function save() { if (!editing.value) return; busy.value = true; editorFailure.value = ''; try { await api.editStage(props.projectId, editing.value.id, { ...draft }, props.iterationId); editorOpen.value = false; emit('changed') } catch (error) { editorFailure.value = errorText(error) } finally { busy.value = false } }
|
||||
/** 经产品内确认软删除空阶段,后端仍在项目锁内重查是否为空。 */
|
||||
async function remove(stage: Stage) { try { await ElMessageBox.confirm('删除这个空阶段?历史数据将保留。', '删除阶段', { type: 'warning' }) } catch { return } busy.value = true; failure.value = ''; try { await api.removeStage(props.projectId, stage.id, stage.version, props.iterationId); emit('changed') } catch (error) { failure.value = errorText(error) } finally { busy.value = false } }
|
||||
</script>
|
||||
<style scoped>.failure{margin-top:12px;white-space:pre-line}
|
||||
<style scoped>.failure{margin-top:12px;white-space:pre-line}.structure-button{margin:10px 0}
|
||||
/* 组件 DOM 和状态类由运行时生成;按 class token 匹配保持原选择器的含义和优先级,避免 IDE 静态模板匹配误报。 */
|
||||
:deep([class~="el-select"]){width:100%}</style>
|
||||
|
||||
@ -4,13 +4,14 @@
|
||||
<el-alert v-if="!sourceCanRework" title="来源已不是可回退的当前阶段,或没有回退权限,请关闭后刷新流程。" type="warning" :closable="false" class="rework-alert" />
|
||||
<el-form label-position="top" size="small" class="rework-form">
|
||||
<el-form-item label="发现问题的来源阶段"><strong>{{ stageName(sourceId) }}</strong></el-form-item>
|
||||
<el-form-item label="回退到"><el-select v-model="targetId" placeholder="选择上游阶段"><el-option v-for="stage in targets" :key="stage.id" :label="stage.name" :value="stage.id" /></el-select></el-form-item>
|
||||
<el-form-item label="回退到"><el-select v-model="targetId" placeholder="选择上游阶段"><el-option v-for="stage in targets" :key="stage.id" :label="stage.stagePath || stage.name" :value="stage.id" /></el-select></el-form-item>
|
||||
<el-form-item label="回退原因"><el-input v-model="reason" type="textarea" :rows="2" maxlength="2000" show-word-limit placeholder="说明需要重做的原因" /></el-form-item>
|
||||
<el-form-item><el-checkbox v-model="sendEmail" size="small" :disabled="busy">发送邮件通知</el-checkbox><span class="rework-note">站内消息始终发送;勾选后,每名相关人员最多收到一封回退汇总邮件。</span></el-form-item>
|
||||
</el-form>
|
||||
<el-button size="small" :loading="busy" :disabled="!sourceCanRework || !targetId" @click="loadPreview">查看影响预览</el-button>
|
||||
<el-alert v-if="failure" :title="failure" type="error" :closable="false" class="rework-alert" />
|
||||
<template v-if="preview">
|
||||
<p v-if="preview.aggregateStageIds?.length" class="rework-note">仅汇总换版:{{ preview.aggregateStageIds.map(stageName).join('、') }}。保留分支不会复制,旧父版本将冻结本次回退前的内容。</p>
|
||||
<p class="rework-note">图版本 {{ preview.graphVersion }} · 影响 {{ preview.affectedStages.length }} 个阶段。下列旧工作项将留在历史中,只在当前版本显示新副本。</p>
|
||||
<el-table :data="preview.affectedStages" size="small" max-height="230"><el-table-column label="阶段" prop="name" /><el-table-column label="当前版本" width="95"><template #default="{ row }">v{{ row.revisionNo }}</template></el-table-column><el-table-column label="自动复制" prop="copyCount" width="90" /><el-table-column label="补录" prop="additionalCount" width="70" /></el-table>
|
||||
<el-alert v-if="preview.excludedItems.length" type="warning" :closable="false" class="rework-alert" :title="`已取消工作项不复制:${preview.excludedItems.map(item => item.taskName).join('、')}`" />
|
||||
|
||||
@ -0,0 +1,31 @@
|
||||
<template>
|
||||
<el-dialog :model-value="!!item" title="阶段组版本工作项快照" width="min(820px, 95%)" append-to-body @close="emit('close')">
|
||||
<template v-if="item">
|
||||
<el-alert :title="item.snapshotFrozen ? '此处展示父阶段组该版本冻结时的内容。保留分支后续发生的修改、评论和附件变动不会改写本快照。' : '当前父阶段组组合的只读查询快照;本轮尚未冻结,后续内容仍可能变化。'" type="info" :closable="false" />
|
||||
<h3>{{ item.title }} <el-tag size="small" type="info">{{ statusNames[item.status] || item.status }}</el-tag></h3>
|
||||
<el-descriptions :column="2" border size="small"><el-descriptions-item label="所属阶段">{{ item.stagePath }}</el-descriptions-item><el-descriptions-item label="类型">{{ typeNames[item.type] }}</el-descriptions-item><el-descriptions-item label="负责人">{{ item.assigneeName || members.find(member => member.userId === item!.assigneeId)?.name || (item.assigneeId ? '用户 #' + item.assigneeId : '未分配') }}</el-descriptions-item><el-descriptions-item label="协作人">{{ item.collaborators?.map(person => person.name).join('、') || '未设置' }}</el-descriptions-item><el-descriptions-item label="优先级">{{ priorityNames[item.priority] || item.priority }}</el-descriptions-item><el-descriptions-item label="工作项">#{{ item.id }}</el-descriptions-item><el-descriptions-item label="预计开始">{{ plannedDate(item.plannedStartAt) }}</el-descriptions-item><el-descriptions-item label="预计结束">{{ plannedDate(item.plannedEndAt) }}</el-descriptions-item><el-descriptions-item label="实际开始">{{ time(item.actualStartAt) }}</el-descriptions-item><el-descriptions-item label="实际结束">{{ time(item.actualEndAt) }}</el-descriptions-item></el-descriptions>
|
||||
<p class="description">{{ item.description || '尚未填写描述' }}</p>
|
||||
<h4>前置依赖</h4><p v-if="!item.dependencyConditions?.length" class="muted">无前置工作项</p><p v-for="condition in item.dependencyConditions" :key="condition.id"><el-tag size="small" :type="condition.satisfied ? 'success' : 'warning'">{{ condition.satisfied ? '已满足' : '未满足' }}</el-tag> {{ condition.sourceName }} · {{ statusNames[condition.currentStatus as Lifecycle] || condition.currentStatus }}</p>
|
||||
<h4>评论</h4><article v-for="comment in item.comments" :key="comment.id"><strong>{{ comment.author }}</strong><small>{{ time(comment.createdAt) }}</small><p>{{ comment.body }}</p></article>
|
||||
<h4>附件</h4><p v-for="file in item.attachments" :key="file.id"><el-link @click="download(file.id, file.name)">{{ file.name }}</el-link> · {{ (file.size / 1024).toFixed(1) }} KB</p><p class="muted">附件下载仍检查当前成员权限及删除状态;历史元信息保留。</p>
|
||||
<h4>操作历史</h4><article v-for="entry in item.history" :key="entry.id"><strong>{{ actionNames[entry.action] || '工作项更新' }}</strong><small>{{ time(entry.createdAt) }}</small><p>{{ entry.detail }}</p></article>
|
||||
<el-alert v-if="failure" :title="failure" type="error" :closable="false" />
|
||||
</template>
|
||||
</el-dialog>
|
||||
</template>
|
||||
<script setup lang="ts">
|
||||
import { ref, watch } from 'vue'
|
||||
import type { WorkItem, Member, Lifecycle } from '../../../types'
|
||||
import { downloadAttachment, errorText } from '../../../api'
|
||||
import { plannedDate, localTime } from '../../../shared/utils/time'
|
||||
import { actionNames, priorityNames, statusNames, typeNames } from '../../../shared/constants/labels'
|
||||
const props = defineProps<{ item: WorkItem | null; members: Member[] }>()
|
||||
const emit = defineEmits<{ close: [] }>()
|
||||
const failure = ref('')
|
||||
watch(() => props.item, () => { failure.value = '' })
|
||||
/** 冻结时间仍按北京时间显示,缺失值保持未执行语义。 */
|
||||
function time(value?: string | null) { return value ? localTime(value, 'Asia/Shanghai').replace('T', ' ').slice(0, 19) : '未设置' }
|
||||
/** 只使用附件ID走原鉴权下载入口,冻结内容不能授予已失去的下载权限。 */
|
||||
async function download(id: number, name: string) { failure.value = ''; try { await downloadAttachment(id, name) } catch (error) { failure.value = errorText(error) } }
|
||||
</script>
|
||||
<style scoped>h3{font-size:17px}h4{margin:22px 0 8px}article{border-bottom:1px solid var(--el-border-color-lighter);padding:8px 0}article p,.description{white-space:pre-wrap;overflow-wrap:anywhere}small,.muted{font-size:12px;color:var(--el-text-color-secondary)}small{margin-left:12px}</style>
|
||||
@ -0,0 +1,37 @@
|
||||
<template>
|
||||
<el-dialog :model-value="visible" title="调整未执行阶段结构" width="min(900px, 96%)" append-to-body @close="emit('close')">
|
||||
<el-alert title="先指定父级,再明确编辑最终保留的全部连线。不会自动猜测跨层连线;已执行阶段、执行过的阶段组结构受保护。预览成功后才能确认。" type="info" :closable="false" />
|
||||
<el-table :data="view.stages" size="small" max-height="280"><el-table-column label="阶段" min-width="200"><template #default="{ row }">{{ row.stagePath || row.name }}</template></el-table-column><el-table-column label="类型" width="90"><template #default="{ row }">{{ row.stageKind === 'GROUP' ? '阶段组' : '工作阶段' }}</template></el-table-column><el-table-column label="父阶段组" min-width="220"><template #default="{ row }"><el-select v-model="parents[row.id]" size="small" clearable placeholder="根画布" :disabled="busy || row.stageKind === 'GROUP' || !row.canEditStructure"><el-option v-for="group in groups" :key="group.id" :value="group.id" :label="group.name" /></el-select></template></el-table-column></el-table>
|
||||
<h4>最终执行连线</h4>
|
||||
<div v-for="(edge, index) in links" :key="index" class="edge-row"><el-select v-model="edge.predecessorStageId" :disabled="busy" size="small" filterable><el-option v-for="stage in view.stages" :key="stage.id" :value="stage.id" :label="stage.name" /></el-select><span>→</span><el-select v-model="edge.successorStageId" :disabled="busy" size="small" filterable><el-option v-for="stage in view.stages" :key="stage.id" :value="stage.id" :label="stage.name" /></el-select><span v-if="scope(edge.predecessorStageId) !== scope(edge.successorStageId)" class="invalid">跨画布,请调整</span><el-button size="small" link type="danger" :disabled="busy" @click="links.splice(index, 1)">移除</el-button></div>
|
||||
<el-button size="small" :disabled="busy || view.stages.length < 2" @click="addEdge">增加连线</el-button>
|
||||
<el-alert v-if="failure" :title="failure" type="error" :closable="false" class="message" />
|
||||
<el-alert v-if="approved" title="最终结构校验通过。确认后在同一事务中更新父级、版本绑定和连线,阶段及工作项ID保持不变。" type="success" :closable="false" class="message" />
|
||||
<template #footer><el-button size="small" @click="emit('close')">取消</el-button><el-button size="small" :loading="busy" @click="preview">预览校验</el-button><el-button size="small" type="primary" :disabled="!approved" :loading="busy" @click="commit">确认调整</el-button></template>
|
||||
</el-dialog>
|
||||
</template>
|
||||
<script setup lang="ts">
|
||||
import { computed, ref, watch } from 'vue'
|
||||
import { api, errorText } from '../../../api'
|
||||
import type { FlowView, StageStructureInput } from '../../../types'
|
||||
const props = defineProps<{ visible: boolean; projectId: number; iterationId: number; view: FlowView }>()
|
||||
const emit = defineEmits<{ close: []; changed: [] }>()
|
||||
const parents = ref<Record<number, number | null>>({}), links = ref<StageStructureInput['edges']>([]), busy = ref(false), approved = ref(false), failure = ref('')
|
||||
const groups = computed(() => props.view.stages.filter(stage => stage.stageKind === 'GROUP' && stage.canEditStructure))
|
||||
let generation = 0
|
||||
/** 打开时从共享图构造草稿,重复打开不沿用过期图版本或上次迁移内容。 */
|
||||
watch(() => props.visible, visible => { if (visible) { parents.value = Object.fromEntries(props.view.stages.map(stage => [stage.id, stage.parentStageId ?? null])); links.value = props.view.stageEdges.map(edge => ({ predecessorStageId: edge.predecessorStageId, successorStageId: edge.successorStageId })); approved.value = false; failure.value = '' } })
|
||||
/** 每次编辑和后台图变化均废弃预览,提交不能沿用另一份结构的校验。 */
|
||||
watch([parents, links, () => props.view.graphVersion, () => props.visible], () => { generation++; approved.value = false }, { deep: true, flush: 'sync' })
|
||||
/** clearable控件的空值统一为根画布,不把空字符串写入父级外键。 */
|
||||
function scope(id: number): number | null { return parents.value[id] || null }
|
||||
/** 仅明确记录改变的阶段归属;未变更的已执行阶段不作为迁移对象。 */
|
||||
function input(): StageStructureInput { return { graphVersion: props.view.graphVersion!, stages: props.view.stages.filter(stage => (stage.parentStageId ?? null) !== scope(stage.id)).map(stage => ({ id: stage.id, version: stage.version, parentStageId: scope(stage.id) })), edges: links.value.map(edge => ({ ...edge })) } }
|
||||
/** 新边由管理者明确选择端点,最终由后端检查同层、排期和混合依赖环。 */
|
||||
function addEdge() { links.value.push({ predecessorStageId: props.view.stages[0]!.id, successorStageId: props.view.stages[1]!.id }) }
|
||||
/** 预览仅验证最终态,任何失败都保留草稿并关闭提交资格。 */
|
||||
async function preview() { if (busy.value) return; const request = generation; busy.value = true; failure.value = ''; approved.value = false; try { const result = await api.previewStageStructure(props.projectId, props.iterationId, input()); if (request === generation) approved.value = result.canCommit } catch (error) { if (request === generation) failure.value = errorText(error) } finally { busy.value = false } }
|
||||
/** 提交重新核对图版本和全部约束,成功后由父组件刷新共享快照。 */
|
||||
async function commit() { if (!approved.value || busy.value) return; busy.value = true; failure.value = ''; try { await api.commitStageStructure(props.projectId, props.iterationId, input()); emit('changed'); emit('close') } catch (error) { approved.value = false; failure.value = errorText(error) } finally { busy.value = false } }
|
||||
</script>
|
||||
<style scoped>.edge-row{display:flex;align-items:center;gap:8px;margin:8px 0}.edge-row :deep([class~="el-select"]){width:240px}.invalid{font-size:12px;color:var(--el-color-danger)}.message{margin-top:12px}</style>
|
||||
@ -3,13 +3,15 @@
|
||||
<p v-if="stage?.description" class="stage-description">{{ stage.description }}</p>
|
||||
<el-tabs v-model="mode">
|
||||
<el-tab-pane :label="`当前版本 · ${stageTotal}`" name="current">
|
||||
<div class="drawer-intro"><el-tag v-if="stage" size="small">v{{ stage.revisionNo || 1 }} · {{ stageStatusNames[stage.executionStatus || 'NOT_STARTED'] }}</el-tag><span>当前版本共 {{ stageTotal }} 个工作项,包含子任务。</span><el-button v-if="canCreate && (stageId === 0 || stage && !['COMPLETED', 'LEGACY_PASSED'].includes(stage.executionStatus || ''))" size="small" type="primary" @click="emit('create', stageId || null)">新建工作项</el-button></div>
|
||||
<div class="drawer-intro"><el-tag v-if="stage" size="small">v{{ stage.revisionNo || 1 }} · {{ stageStatusNames[stage.executionStatus || 'NOT_STARTED'] }}</el-tag><span>当前版本共 {{ stageTotal }} 个工作项,包含子任务。</span><el-button v-if="canCreate && (stageId === 0 || stage?.canCreateWorkItem)" size="small" type="primary" @click="emit('create', stageId || null)">新建工作项</el-button></div>
|
||||
<div v-if="stage?.stageKind === 'GROUP'" class="group-overview"><p>阶段组 · 子阶段 {{ stage.completedChildStageCount || 0 }}/{{ stage.childStageCount || 0 }} 已完成;下表按工作项去重汇总。</p><el-button v-for="child in children" :key="child.id" size="small" @click="emit('navigate', child.id)">{{ child.name }} · {{ stageStatusNames[child.executionStatus || 'NOT_STARTED'] }} · {{ child.counts.total }} 项</el-button><el-button v-if="stage.canCreateChildStage && canManage" size="small" type="primary" @click="emit('createChild', stage.id)">新建子阶段</el-button></div>
|
||||
<StageSchedulePanel v-if="stage" :project-id="projectId" :iteration-id="iterationId" :stage-id="stage.id" :schedule="stage" :completed="['COMPLETED', 'LEGACY_PASSED'].includes(stage.executionStatus || '')" :can-manage="canManage" @changed="emit('changed')" />
|
||||
<div class="drawer-filters"><el-input v-model="keyword" size="small" clearable placeholder="搜索工作项名称" /><el-select v-model="typeFilter" size="small" clearable placeholder="全部类型"><el-option v-for="(name, type) in typeNames" :key="type" :value="type" :label="name" /></el-select><el-select v-model="statusFilter" size="small" clearable placeholder="全部状态"><el-option v-for="(name, status) in statusNames" :key="status" :value="status" :label="name" /></el-select></div>
|
||||
<p class="drawer-count">显示 {{ filteredItems.length }}/{{ iterationId ? currentTotal : currentItems.length }} 个</p>
|
||||
<el-alert v-if="failure" :title="failure" type="error" :closable="false" />
|
||||
<el-table v-loading="currentLoading" :data="filteredItems" size="small" max-height="calc(100vh - 290px)" empty-text="当前阶段没有符合条件的工作项">
|
||||
<el-table-column label="工作项" min-width="230"><template #default="{ row }"><el-link @click="emit('open', row.id)">{{ row.parentTaskId ? '↳ ' : '' }}{{ row.title }}</el-link></template></el-table-column>
|
||||
<el-table-column v-if="stage?.stageKind === 'GROUP'" label="子阶段" min-width="140"><template #default="{ row }">{{ row.stagePath }}</template></el-table-column>
|
||||
<el-table-column label="类型" width="75"><template #default="{ row }">{{ typeNames[row.type as ItemType] }}</template></el-table-column>
|
||||
<el-table-column label="状态" width="115" class-name="business-status-cell"><template #default="{ row }"><el-tag size="small" :type="row.overdue ? 'danger' : 'info'">{{ itemStatusLabel(row) }}</el-tag></template></el-table-column>
|
||||
<el-table-column label="负责人" min-width="100"><template #default="{ row }">{{ members.find(member => member.userId === row.assigneeId)?.name || '未分配' }}</template></el-table-column>
|
||||
@ -24,10 +26,11 @@
|
||||
<el-alert v-if="failure" :title="failure" type="error" :closable="false" class="history-message" />
|
||||
<el-table v-loading="loading" :data="revisions" size="small" class="history-table"><el-table-column label="版本" width="70"><template #default="{ row }">v{{ row.revision_no }}</template></el-table-column><el-table-column label="阶段名称" prop="stage_name_snapshot" /><el-table-column label="开始" width="155"><template #default="{ row }">{{ readable(row.startedAt) }}</template></el-table-column><el-table-column label="状态" width="100" class-name="business-status-cell"><template #default="{ row }">{{ row.supersededAt ? '已被取代' : '当前版本' }}</template></el-table-column><el-table-column label="操作" width="70" class-name="business-operation-cell"><template #default="{ row }"><el-button size="small" link type="primary" @click="openRevision(row)">查看</el-button></template></el-table-column></el-table>
|
||||
<el-pagination v-if="revisionTotal > 20" v-model:current-page="revisionPage" :page-size="20" :total="revisionTotal" layout="prev, pager, next, total" @current-change="reloadRevisions" />
|
||||
<template v-if="selected"><StageSchedulePanel :project-id="projectId" :iteration-id="iterationId" :stage-id="stageId!" :schedule="selected.revision" :historical="true" :superseded-at="selected.revision.supersededAt" /><h3>v{{ selected.revision.revision_no }} 工作项 · {{ selected.total ?? selected.items.length }} 个</h3><el-table :data="selected.items" size="small" max-height="330" empty-text="此版本没有工作项"><el-table-column label="工作项" min-width="190"><template #default="{ row }"><el-link @click="emit('open', row.id)">{{ row.parent_task_id ? '↳ ' : '' }}{{ row.title }}</el-link></template></el-table-column><el-table-column label="状态" width="105" class-name="business-status-cell"><template #default="{ row }">{{ statusNames[row.status as Lifecycle] || row.status }}</template></el-table-column><el-table-column label="原预计结束" width="155"><template #default="{ row }">{{ plannedDate(row.plannedEndAt) }}</template></el-table-column><el-table-column label="操作" width="70" class-name="business-operation-cell"><template #default="{ row }"><el-button size="small" link type="primary" @click="emit('open', row.id)">详情</el-button></template></el-table-column></el-table><el-pagination v-if="(selected.total || 0) > 50" v-model:current-page="detailPage" :page-size="50" :total="selected.total" layout="prev, pager, next, total" @current-change="reloadDetail" /><h3>当时的阶段连线</h3><p v-if="!selected.flowDefinition" class="history-muted">该轮次尚未开始,或迁移前未留存流程定义快照。</p><p v-else-if="!selected.flowDefinition.edges.length" class="history-muted">定义 v{{ selected.flowDefinition.revisionNo }} 没有连线。</p><div v-else class="history-edges"><el-tag v-for="edge in selected.flowDefinition.edges" :key="`${edge.predecessorStageId}-${edge.successorStageId}`" size="small">{{ edge.predecessorName }} → {{ edge.successorName }}</el-tag></div></template>
|
||||
<template v-if="selected"><h3 v-if="selected.childStages?.length">本版本子阶段组合</h3><el-table v-if="selected.childStages?.length" :data="selected.childStages" size="small"><el-table-column label="子阶段" prop="name" /><el-table-column label="版本" width="80"><template #default="{ row }">v{{ row.revisionNo }}</template></el-table-column><el-table-column label="状态" width="100"><template #default="{ row }">{{ stageStatusNames[row.executionStatus as keyof typeof stageStatusNames] }}</template></el-table-column><el-table-column label="工作项" prop="itemCount" width="80" /><el-table-column label="当时预计结束" width="140"><template #default="{ row }">{{ plannedDate(row.plannedEndAt) }}</template></el-table-column></el-table><StageSchedulePanel :project-id="projectId" :iteration-id="iterationId" :stage-id="stageId!" :schedule="selected.revision" :historical="true" :superseded-at="selected.revision.supersededAt" /><h3>v{{ selected.revision.revision_no }} 工作项 · {{ selected.total ?? selected.items.length }} 个</h3><el-table :data="selected.items" size="small" max-height="330" empty-text="此版本没有工作项"><el-table-column label="工作项" min-width="190"><template #default="{ row }"><el-link @click="openHistorical(row.id)">{{ row.parent_task_id ? '↳ ' : '' }}{{ row.title }}</el-link></template></el-table-column><el-table-column label="状态" width="105" class-name="business-status-cell"><template #default="{ row }">{{ statusNames[row.status as Lifecycle] || row.status }}</template></el-table-column><el-table-column label="原预计结束" width="155"><template #default="{ row }">{{ plannedDate(row.plannedEndAt) }}</template></el-table-column><el-table-column label="操作" width="70" class-name="business-operation-cell"><template #default="{ row }"><el-button size="small" link type="primary" @click="openHistorical(row.id)">详情</el-button></template></el-table-column></el-table><el-pagination v-if="(selected.total || 0) > 50" v-model:current-page="detailPage" :page-size="50" :total="selected.total" layout="prev, pager, next, total" @current-change="reloadDetail" /><h3>当时的阶段连线</h3><p v-if="!selected.flowDefinition" class="history-muted">该轮次尚未开始,或迁移前未留存流程定义快照。</p><p v-else-if="!selected.flowDefinition.edges.length" class="history-muted">定义 v{{ selected.flowDefinition.revisionNo }} 没有连线。</p><div v-else class="history-edges"><el-tag v-for="edge in selected.flowDefinition.edges" :key="`${edge.predecessorStageId}-${edge.successorStageId}`" size="small">{{ edge.predecessorName }} → {{ edge.successorName }}</el-tag></div></template>
|
||||
</el-tab-pane>
|
||||
</el-tabs>
|
||||
</el-drawer>
|
||||
<StageSnapshotDialog :item="snapshotItem" :members="members" @close="closeSnapshot" />
|
||||
</template>
|
||||
<script setup lang="ts">
|
||||
import { collaboratorNames } from '../../work-items/utils/participants'
|
||||
@ -36,14 +39,17 @@ import { vLoading } from 'element-plus'
|
||||
import { api, errorText } from '../../../api'
|
||||
import { localTime, plannedDate } from '../../../shared/utils/time'
|
||||
import StageSchedulePanel from '../../schedules/components/StageSchedulePanel.vue'
|
||||
import StageSnapshotDialog from './StageSnapshotDialog.vue'
|
||||
import type { FlowView, Member, ItemType, Lifecycle, StageRevision, StageRevisionDetail, WorkItem } from '../../../types'
|
||||
import { itemStatusLabel, stageStatusNames, statusNames, typeNames } from '../../../shared/constants/labels'
|
||||
|
||||
const props = defineProps<{ projectId: number; iterationId?: number; stageId: number | null; initialTab: 'current' | 'history'; view: FlowView; members: Member[]; canCreate: boolean; canManage?: boolean }>()
|
||||
const emit = defineEmits<{ close: []; open: [id: number]; create: [stageId: number | null]; changed: [] }>()
|
||||
const emit = defineEmits<{ close: []; open: [id: number]; create: [stageId: number | null]; changed: []; navigate: [id: number]; createChild: [id: number] }>()
|
||||
const mode = ref<'current' | 'history'>('current'), keyword = ref(''), typeFilter = ref<ItemType | null>(null), statusFilter = ref<Lifecycle | null>(null)
|
||||
const currentRows = ref<WorkItem[]>([]), currentTotal = ref(0), currentPage = ref(1), currentLoading = ref(false), revisionPage = ref(1), revisionTotal = ref(0), detailPage = ref(1)
|
||||
const loading = ref(false), failure = ref(''), revisions = ref<StageRevision[]>([]), selected = ref<StageRevisionDetail | null>(null)
|
||||
const snapshotItem = ref<WorkItem | null>(null)
|
||||
const children = computed(() => props.view.stages.filter(value => value.parentStageId === props.stageId))
|
||||
const stage = computed(() => props.view.stages.find(value => value.id === props.stageId))
|
||||
const stageName = computed(() => stage.value?.name || '未分配')
|
||||
/** 当前迭代使用阶段分页结果;旧快照仅用于兼容组件独立展示。 */
|
||||
@ -55,13 +61,13 @@ const currentItems = computed(() => {
|
||||
const stageTotal = computed(() => props.iterationId ? (props.stageId === 0 ? props.view.unassigned?.counts?.total : stage.value?.counts?.total) || 0 : currentItems.value.length)
|
||||
const filteredItems = computed(() => props.iterationId ? currentItems.value : currentItems.value.filter(item => (!keyword.value || item.title.includes(keyword.value)) && (!typeFilter.value || item.type === typeFilter.value) && (!statusFilter.value || item.status === statusFilter.value)))
|
||||
let currentSequence = 0, revisionSequence = 0, detailSequence = 0, loadedPage = 0
|
||||
let sequence = 0, loadedStage: number | null = null
|
||||
let sequence = 0, snapshotSequence = 0, loadedStage: number | null = null
|
||||
|
||||
/** 切换完整范围时清理筛选、分页和历史详情,当前项按阶段独立读取。 */
|
||||
watch(() => [props.projectId, props.iterationId, props.stageId], () => {
|
||||
const stageId = props.stageId
|
||||
sequence++; currentSequence++; revisionSequence++; detailSequence++; loadedPage = 0; currentRows.value = []; currentPage.value = 1; currentTotal.value = 0; revisionPage.value = 1; detailPage.value = 1; keyword.value = ''; typeFilter.value = null; statusFilter.value = null
|
||||
revisions.value = []; selected.value = null; failure.value = ''; loadedStage = null
|
||||
revisions.value = []; selected.value = null; snapshotItem.value = null; failure.value = ''; loadedStage = null
|
||||
mode.value = stageId === 0 ? 'current' : props.initialTab
|
||||
if (mode.value === 'history') void loadRevisions(); else void loadCurrent()
|
||||
}, { immediate: true })
|
||||
@ -90,16 +96,28 @@ async function loadRevisions() {
|
||||
async function openRevision(row: StageRevision, reset = true) {
|
||||
const stageId = props.stageId
|
||||
if (!stageId) return
|
||||
closeSnapshot()
|
||||
if (reset) { detailPage.value = 1; selected.value = null }
|
||||
const current = sequence, request = ++detailSequence; loading.value = true; failure.value = ''
|
||||
try { const result = await api.stageRevision(props.projectId, stageId, row.id, props.iterationId, detailPage.value); if (current === sequence && request === detailSequence) selected.value = result }
|
||||
catch (error) { if (current === sequence && request === detailSequence) failure.value = errorText(error) }
|
||||
finally { if (current === sequence && request === detailSequence) loading.value = false }
|
||||
}
|
||||
/** 父级组合历史使用冻结详情;普通叶阶段仍可打开已有的只读工作项详情。 */
|
||||
async function openHistorical(id: number) {
|
||||
if (!selected.value?.frozenSnapshot) { emit('open', id); return }
|
||||
if (!props.iterationId || !props.stageId) return
|
||||
const current = sequence, request = ++snapshotSequence, revisionId = selected.value.revision.id
|
||||
failure.value = ''
|
||||
try { const item = await api.stageItemSnapshot(props.projectId, props.iterationId, props.stageId, revisionId, id); if (current === sequence && request === snapshotSequence && selected.value?.revision.id === revisionId) snapshotItem.value = item }
|
||||
catch (error) { if (current === sequence && request === snapshotSequence) failure.value = errorText(error) }
|
||||
}
|
||||
/** 关闭详情或更换版本时废弃在途请求,迟到结果不得重新弹出旧快照。 */
|
||||
function closeSnapshot() { snapshotSequence++; snapshotItem.value = null }
|
||||
/** 历史时间统一按北京时间展示,未设置的排期和开始时间保留空值语义。 */
|
||||
function readable(value: string | null | undefined): string { return value ? localTime(value, 'Asia/Shanghai').replace('T', ' ').slice(0, 16) : '未设置' }
|
||||
</script>
|
||||
<style scoped>.stage-description{white-space:pre-wrap;overflow-wrap:anywhere;line-height:1.7;color:var(--el-text-color-regular);margin:0 0 12px}.drawer-intro,.drawer-filters{display:flex;align-items:center;gap:8px;flex-wrap:wrap;margin:4px 0 12px}.drawer-intro{font-size:12px;color:var(--el-text-color-secondary)}.drawer-intro .el-button{margin-left:auto}
|
||||
<style scoped>.group-overview{padding:8px;border:1px solid var(--el-border-color-light);border-radius:6px;font-size:12px;margin-bottom:10px}.group-overview .el-button{margin:4px}.stage-description{white-space:pre-wrap;overflow-wrap:anywhere;line-height:1.7;color:var(--el-text-color-regular);margin:0 0 12px}.drawer-intro,.drawer-filters{display:flex;align-items:center;gap:8px;flex-wrap:wrap;margin:4px 0 12px}.drawer-intro{font-size:12px;color:var(--el-text-color-secondary)}.drawer-intro .el-button{margin-left:auto}
|
||||
/* 组件 DOM 和状态类由运行时生成;按 class token 匹配保持原选择器的含义和优先级,避免 IDE 静态模板匹配误报。 */
|
||||
.drawer-filters [class~="el-input"]{width:220px}
|
||||
.drawer-filters [class~="el-select"]{width:130px}.drawer-count,.history-muted{font-size:12px;color:var(--el-text-color-secondary)}.history-message,.history-table{margin-top:12px}h3{font-size:14px;margin:20px 0 9px}.history-edges{display:flex;flex-wrap:wrap;gap:6px}</style>
|
||||
|
||||
@ -13,7 +13,7 @@
|
||||
<el-button v-if="detail.scheduleReviewRequired && !detail.scheduleReviewClosed && writable" size="small" @click="confirmReview">确认保留原排期</el-button>
|
||||
<div class="actions" v-if="writable">
|
||||
<el-tooltip :disabled="detail.canStart" :content="blockedText"><span><el-button type="primary" :disabled="!canExecute || !detail.canStart || busy" @click="start">开始</el-button></span></el-tooltip>
|
||||
<el-button @click="emit('edit', detail)">编辑</el-button><el-button v-if="!detail.scheduleReviewClosed" size="small" @click="scheduleOpen = true">调整排期</el-button>
|
||||
<el-button @click="emit('edit', detail)">编辑</el-button><el-button v-if="canManage && detail.status === 'READY' && !detail.parentTaskId" size="small" @click="openAssignment">调整阶段归属</el-button><el-button v-if="!detail.scheduleReviewClosed" size="small" @click="scheduleOpen = true">调整排期</el-button>
|
||||
<el-button v-if="detail.canCreateChild" :disabled="busy" @click="emit('create-child', detail)">创建子任务</el-button>
|
||||
<el-button v-if="detail.status === 'IN_PROGRESS'" :disabled="busy || detail.canComplete === false" @click="transition('COMPLETED')">完成</el-button>
|
||||
<el-button v-if="detail.status === 'COMPLETED'" :disabled="busy" @click="transition('CLOSED')">关闭</el-button>
|
||||
@ -31,7 +31,7 @@
|
||||
<el-descriptions-item label="负责人">{{ members.find(m => m.userId === detail!.assigneeId)?.name || '未分配' }}</el-descriptions-item>
|
||||
<el-descriptions-item label="协作人"><span v-if="!detail.collaborators?.length">未设置</span><span v-else>{{ detail.collaborators.map(member => member.name || `用户 #${member.userId}`).join('、') }}</span></el-descriptions-item>
|
||||
<el-descriptions-item label="优先级">{{ priorityNames[detail.priority] }}</el-descriptions-item>
|
||||
<el-descriptions-item label="所属阶段">{{ detail.historical ? detail.stageNameSnapshot : stages.find(stage => stage.id === detail!.stageId)?.name || '未分配阶段' }}</el-descriptions-item>
|
||||
<el-descriptions-item label="所属阶段">{{ detail.historical ? detail.stageNameSnapshot : detail.stagePath || stages.find(stage => stage.id === detail!.stageId)?.name || '未分配阶段' }}</el-descriptions-item>
|
||||
<el-descriptions-item label="预计开始">{{ plannedDate(detail.plannedStartAt) }}</el-descriptions-item>
|
||||
<el-descriptions-item label="预计结束">{{ plannedDate(detail.plannedEndAt) }}</el-descriptions-item>
|
||||
<el-descriptions-item label="实际开始">{{ displayTime(detail.actualStartAt) }}</el-descriptions-item>
|
||||
@ -59,6 +59,7 @@
|
||||
</div>
|
||||
</el-drawer>
|
||||
|
||||
<el-dialog v-model="assignmentOpen" title="调整工作项阶段归属" width="480px" append-to-body><el-alert type="info" :closable="false" title="仅项目管理者可移动待开始根任务,子任务同步继承。阶段组不能直接承载工作项;后端复验新门禁、排期及循环依赖。" /><el-select v-model="assignmentStageId" size="small" clearable filterable placeholder="未分配阶段" style="width:100%;margin:14px 0"><el-option v-for="stage in stages.filter(value => value.stageKind !== 'GROUP')" :key="stage.id" :value="stage.id" :label="stage.stagePath || stage.name" /></el-select><el-alert v-if="assignmentFailure" :title="assignmentFailure" type="error" :closable="false" /><template #footer><el-button size="small" @click="assignmentOpen = false">取消</el-button><el-button size="small" type="primary" :loading="busy" @click="saveAssignment">保存</el-button></template></el-dialog>
|
||||
<ItemScheduleDialog :item-id="scheduleOpen && writable ? id : null" @close="scheduleOpen = false" @saved="scheduleSaved" />
|
||||
<el-dialog v-model="depOpen" :title="editingDependency ? '编辑前置条件' : '添加前置条件'" width="600px" append-to-body>
|
||||
<el-form label-position="top">
|
||||
@ -81,12 +82,12 @@ import type { WorkItem, Member, Condition, Lifecycle, StageEdge, Stage, Predeces
|
||||
import { typeNames, priorityNames, statusNames, actionNames, itemStatusLabel } from '../../../shared/constants/labels'
|
||||
|
||||
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; stages?: Stage[]; stageEdges?: StageEdge[] }>(), { stages: () => [], stageEdges: () => [], canExecute: true })
|
||||
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 scheduleOpen = ref(false)
|
||||
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。
|
||||
@ -96,7 +97,11 @@ const writable = computed(() => props.canWrite && !detail.value?.iterationReadOn
|
||||
const editableDependencies = computed(() => writable.value && detail.value?.status === 'READY')
|
||||
const loadedChildren = ref<WorkItem[]>([])
|
||||
const childItems = computed(() => detail.value?.historical ? detail.value.historicalChildren || [] : loadedChildren.value)
|
||||
watch(() => [props.id, props.projectId, props.iterationId], () => { detail.value = null; commentText.value = ''; scheduleOpen.value = false; depOpen.value = false; sourceId.value = null; loadedChildren.value = []; failure.value = ''; void load() })
|
||||
/** 阶段归属使用独立的经理入口,普通编辑不能清空阶段绕过门禁。 */
|
||||
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() })
|
||||
watch(() => props.refreshKey, () => { void load() })
|
||||
/**
|
||||
* 加载详情和子任务后校验范围与请求代次;后台相同内容保留引用,短暂失败保留已有详情。
|
||||
@ -166,7 +171,7 @@ async function removeAttachment(file: { id: number; name: string }) {
|
||||
|
||||
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 || depOpen.value || !!commentText.value.trim())
|
||||
const isEditing = computed(() => busy.value || loading.value || attachmentConfirmationOpen.value || scheduleOpen.value || assignmentOpen.value || depOpen.value || !!commentText.value.trim())
|
||||
/** 工作区轮询只静默更新空闲详情,评论、依赖和排期草稿均保留到用户完成操作。 */
|
||||
async function synchronize() { if (!isEditing.value) await load(true) }
|
||||
defineExpose({ isEditing, synchronize })
|
||||
|
||||
@ -10,7 +10,7 @@
|
||||
<el-form-item label="协作人"><el-select v-model="draft.collaboratorIds" multiple filterable clearable collapse-tags collapse-tags-tooltip :max-collapse-tags="3" placeholder="选择项目成员(可多选)"><el-option v-for="member in members" :key="member.userId" :value="member.userId" :label="member.name" /></el-select></el-form-item>
|
||||
<el-form-item label="标题" required><el-input v-model="draft.title" maxlength="200" /></el-form-item>
|
||||
<el-form-item label="描述"><el-input v-model="draft.description" type="textarea" :rows="4" maxlength="50000" /></el-form-item>
|
||||
<el-form-item label="所属阶段"><el-select v-model="draft.stageId" :disabled="!!parent || !!item?.parentTaskId" clearable placeholder="未分配阶段"><el-option v-for="stage in stages" :key="stage.id" :value="stage.id" :label="stage.name" /></el-select></el-form-item>
|
||||
<el-form-item label="所属阶段"><el-select v-model="draft.stageId" :disabled="!!parent || !!item" clearable placeholder="未分配阶段"><el-option v-for="stage in workStages" :key="stage.id" :value="stage.id" :label="stage.stagePath || stage.name" /></el-select><span v-if="item" class="dependency-note">归属调整由项目管理者通过详情中的阶段归属操作完成。</span></el-form-item>
|
||||
<el-form-item v-if="!item" label="前置工作项(可选)"><PredecessorPicker v-model="draft.predecessorWorkItemIds" :project-id="projectId" :iteration-id="iterationId" :active="visible" @error="constraintFailure = $event" /><span class="dependency-note">需求、任务、缺陷均可选择;所有前置工作项已完成或已关闭后才能开始。</span></el-form-item>
|
||||
<el-alert v-if="!item && constraints?.earliestPlannedStartAt" type="info" :closable="false" :title="`最早合法预计开始:${planningLimitDate(constraints.earliestPlannedStartAt, 'start', 'min')}`" />
|
||||
<el-alert v-if="!item && constraints?.scheduleBlockedReasons.length" type="warning" :closable="false" :title="constraints.scheduleBlockedReasons.map(reason => `${reason.sourceName || ''}:${reason.message || '排期约束未完整'}`).join(';')" />
|
||||
@ -38,6 +38,8 @@ const draft = reactive<ItemInput & { collaboratorIds: number[]; predecessorWorkI
|
||||
const busy = ref(false), failure = ref(''), invalidStart = ref(false), invalidEnd = ref(false)
|
||||
const initialConstraints = ref<Schedule | null>(null), constraintFailure = ref('')
|
||||
const constraints = computed(() => props.item?.scheduleConstraints || initialConstraints.value)
|
||||
/** 阶段组只能容纳子阶段,工作项创建不得将其作为可选归属。 */
|
||||
const workStages = computed(() => props.stages.filter(stage => stage.stageKind !== 'GROUP'))
|
||||
let constraintSequence = 0, constraintTimer: ReturnType<typeof setTimeout> | undefined
|
||||
let generation = 0, mounted = true
|
||||
/** 子任务继承父阶段,编辑保留原归属;每次打开清空旧草稿,并要求重新明确选择邮件通知。 */
|
||||
|
||||
@ -27,9 +27,12 @@ export interface ReworkPreview {
|
||||
targetStageId: number
|
||||
graphVersion: number
|
||||
affectedStageIds: number[]
|
||||
aggregateStageIds?: number[]
|
||||
affectedStages: {
|
||||
stageId: number
|
||||
name: string
|
||||
stageKind?: 'WORK' | 'GROUP'
|
||||
stagePath?: string
|
||||
revisionNo: number
|
||||
copyCount: number
|
||||
additionalCount: number
|
||||
|
||||
@ -36,6 +36,8 @@ export interface StageSchedule {
|
||||
scheduleReviewClosed?: boolean
|
||||
|
||||
earliestPlannedStartAt?: string | null
|
||||
latestPlannedEndAt?: string | null
|
||||
subtreeScheduleValidationStatus?: 'VALID' | 'INCOMPLETE' | 'CONFLICT'
|
||||
unresolvedSources?: Reason[]
|
||||
conflicts?: Reason[]
|
||||
sources?: Reason[]
|
||||
|
||||
@ -26,6 +26,15 @@ export interface StageSummary {
|
||||
export type StageExecutionStatus = 'NOT_STARTED' | 'IN_PROGRESS' | 'COMPLETED' | 'LEGACY_PASSED'
|
||||
|
||||
export interface Stage extends StageSummary, Omit<StageSchedule, 'plannedStartAt' | 'plannedEndAt'> {
|
||||
stageKind?: 'WORK' | 'GROUP'
|
||||
parentStageId?: number | null
|
||||
stagePath?: string
|
||||
childStageCount?: number
|
||||
completedChildStageCount?: number
|
||||
canCreateWorkItem?: boolean
|
||||
canCreateChildStage?: boolean
|
||||
canEditStructure?: boolean
|
||||
subtreeScheduleValidationStatus?: 'VALID' | 'INCOMPLETE' | 'CONFLICT'
|
||||
|
||||
id: number
|
||||
name: string
|
||||
@ -50,6 +59,10 @@ export interface Stage extends StageSummary, Omit<StageSchedule, 'plannedStartAt
|
||||
}
|
||||
|
||||
export interface StageInput {
|
||||
stageKind?: 'WORK' | 'GROUP'
|
||||
parentStageId?: number | null
|
||||
plannedStartAt?: string | null
|
||||
plannedEndAt?: string | null
|
||||
name: string
|
||||
sortOrder: number
|
||||
ownerId: number | null
|
||||
@ -58,6 +71,8 @@ export interface StageInput {
|
||||
}
|
||||
|
||||
export interface StageRevision extends StageSchedule {
|
||||
stage_kind_snapshot?: 'WORK' | 'GROUP'
|
||||
revision_reason?: 'INITIAL' | 'REWORK' | 'CHILD_REWORK'
|
||||
|
||||
id: number
|
||||
project_id: number
|
||||
@ -72,6 +87,8 @@ export interface StageRevision extends StageSchedule {
|
||||
}
|
||||
|
||||
export interface StageRevisionDetail {
|
||||
childStages?: { stageId: number; name: string; revisionId: number; revisionNo: number; executionStatus: StageExecutionStatus; itemCount: number; plannedStartAt: string | null; plannedEndAt: string | null }[]
|
||||
frozenSnapshot?: boolean
|
||||
total?: number
|
||||
revision: StageRevision
|
||||
readOnly: boolean
|
||||
@ -93,3 +110,10 @@ export interface StageRevisionDetail {
|
||||
}[]
|
||||
} | null
|
||||
}
|
||||
|
||||
/** 结构提交是完整同层执行边集合;预览不会改写父级或连线。 */
|
||||
export interface StageStructureInput {
|
||||
graphVersion: number
|
||||
stages: { id: number; version: number; parentStageId: number | null }[]
|
||||
edges: { predecessorStageId: number; successorStageId: number }[]
|
||||
}
|
||||
|
||||
@ -35,6 +35,10 @@ export interface Condition extends Reason {
|
||||
}
|
||||
|
||||
export interface WorkItem {
|
||||
stageGroupId?: number | null
|
||||
stagePath?: string
|
||||
snapshotFrozen?: boolean
|
||||
assigneeName?: string | null
|
||||
|
||||
iterationId?: number
|
||||
iterationStatus?: IterationStatus
|
||||
|
||||
@ -4,7 +4,7 @@
|
||||
<header>{{ label }} <span>{{ counts?.[state] ?? items.filter(i => i.status === state).length }}</span></header>
|
||||
<div class="lane-content" role="region" :aria-label="label + '工作项'" tabindex="0">
|
||||
<article v-for="item in items.filter(i => i.status === state)" :key="item.id" class="work-card" :draggable="canWrite && !busy.has(item.id)" @dragstart="dragged = item.id" @dragend="dragged = null" @click="emit('open', item.id)">
|
||||
<div class="card-meta"><span class="card-id">{{ typeNames[item.type] }} #{{ item.id }}</span><small v-if="item.stageId" class="stage-version" :title="stages.find(stage => stage.id === item.stageId)?.name">{{ stages.find(stage => stage.id === item.stageId)?.name || '阶段' }} · v{{ stages.find(stage => stage.id === item.stageId)?.revisionNo || 1 }}</small><el-tag size="small" :type="item.priority === 'URGENT' ? 'danger' : 'info'">{{ priorityNames[item.priority] }}</el-tag></div>
|
||||
<div class="card-meta"><span class="card-id">{{ typeNames[item.type] }} #{{ item.id }}</span><small v-if="item.stageId" class="stage-version" :title="item.stagePath || stages.find(stage => stage.id === item.stageId)?.name">{{ item.stagePath || stages.find(stage => stage.id === item.stageId)?.name || '阶段' }} · v{{ stages.find(stage => stage.id === item.stageId)?.revisionNo || 1 }}</small><el-tag size="small" :type="item.priority === 'URGENT' ? 'danger' : 'info'">{{ priorityNames[item.priority] }}</el-tag></div>
|
||||
<strong class="card-title" :title="item.title">{{ item.title }}</strong>
|
||||
<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>
|
||||
|
||||
@ -6,30 +6,28 @@
|
||||
</div>
|
||||
<el-alert v-if="failure" type="error" :title="failure" :closable="false" class="flow-failure" />
|
||||
<div ref="canvas" class="flow-canvas" :class="{ inactive: !active }" @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" @connect="connectStages" @edge-click="edgeClicked" @node-click="selectNode" @node-drag-start="dragging = true" @node-drag-stop="dragStopped" @move-end="viewportMoved" @nodes-initialized="restoreViewport">
|
||||
<!-- 保持阶段组、子阶段和连线的固定层级;选中时自动提升父组会使其背景遮住内部连线。 -->
|
||||
<VueFlow v-if="active" :id="flowId" v-model:nodes="nodes" :edges="edges" :connection-line-type="ConnectionLineType.Bezier" :delete-key-code="null" :min-zoom="0.1" :max-zoom="4" :nodes-connectable="canManage && !busy" :edges-updatable="false" :nodes-draggable="!busy" :elevate-nodes-on-select="false" @connect="connectStages" @edge-click="edgeClicked" @node-click="selectNode" @node-drag-start="dragging = true" @node-drag="nodeDragged" @node-drag-stop="dragStopped" @move-end="viewportMoved" @nodes-initialized="restoreViewport">
|
||||
<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>
|
||||
</VueFlow>
|
||||
<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>
|
||||
<el-dialog v-model="stageNameOpen" title="新建阶段" width="360px" append-to-body>
|
||||
<el-form label-position="top" size="small"><el-form-item label="阶段名称" required><el-input v-model="stageName" maxlength="120" placeholder="输入阶段名称" @keyup.enter="saveNewStage" /></el-form-item><el-form-item label="阶段描述"><el-input v-model="stageDescription" type="textarea" :rows="3" maxlength="10000" placeholder="说明本阶段需要完成的事项" /></el-form-item></el-form>
|
||||
<el-alert v-if="failure" type="error" :title="failure" :closable="false" class="flow-failure" />
|
||||
<template #footer><el-button size="small" @click="stageNameOpen = false">取消</el-button><el-button size="small" type="primary" :loading="busy" :disabled="!stageName.trim()" @click="saveNewStage">创建</el-button></template>
|
||||
</el-dialog>
|
||||
<StageManager :visible="stageOpen" :project-id="projectId" :iteration-id="iterationId" :stages="view.stages" :members="members" @close="stageOpen = false" @changed="emit('changed')" />
|
||||
<StageCreateDialog :visible="stageNameOpen" :project-id="projectId" :iteration-id="iterationId" :parent="createParent" :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')" />
|
||||
<StageReworkDialog :visible="reworkSourceId !== null" :source-id="reworkSourceId" :project-id="projectId" :iteration-id="iterationId" :view="view" @close="reworkSourceId = null" @changed="emit('changed')" />
|
||||
<StageWorkItemsDrawer :stage-id="drawerStageId" :initial-tab="drawerTab" :project-id="projectId" :iteration-id="iterationId" :view="view" :members="members" :can-create="canCreate" :can-manage="canManage" @changed="emit('changed')" @close="drawerStageId = null" @open="openItem" @create="createFromDrawer" />
|
||||
<StageWorkItemsDrawer :stage-id="drawerStageId" :initial-tab="drawerTab" :project-id="projectId" :iteration-id="iterationId" :view="view" :members="members" :can-create="canCreate" :can-manage="canManage" @changed="emit('changed')" @close="drawerStageId = null" @open="openItem" @create="createFromDrawer" @navigate="drawerStageId = $event" @create-child="createChildFromDrawer" />
|
||||
</section>
|
||||
</template>
|
||||
<script setup lang="ts">
|
||||
import { computed, nextTick, ref, watch } from 'vue'
|
||||
import { ConnectionLineType, VueFlow, useVueFlow } from '@vue-flow/core'
|
||||
import type { Node, Edge, NodeMouseEvent, GraphNode, Connection } 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'
|
||||
import { Controls } from '@vue-flow/controls'
|
||||
@ -39,12 +37,13 @@ import '@vue-flow/core/dist/theme-default.css'
|
||||
import '@vue-flow/controls/dist/style.css'
|
||||
import '@vue-flow/minimap/dist/style.css'
|
||||
import { api, errorText } from '../../api'
|
||||
import { buildFlowGraph, FLOW_STAGE_WIDTH, FLOW_STAGE_HEIGHT } from './utils/graph'
|
||||
import { buildFlowGraph, absoluteRectangle, resizeStageGroup, updateReworkRoutes } from './utils/graph'
|
||||
import { readFlowPreferences, writeFlowPreferences } from './utils/preferences'
|
||||
import { stageAppearance } from './utils/stageAppearance'
|
||||
import type { FlowNodeData, FlowEdgeData } from './utils/graph'
|
||||
import type { FlowView, Member, Point } from '../../types'
|
||||
import StageManager from '../../features/stages/components/StageManager.vue'
|
||||
import StageCreateDialog from '../../features/stages/components/StageCreateDialog.vue'
|
||||
import FlowStageNode from './components/FlowStageNode.vue'
|
||||
import FlowReworkEdge from './components/FlowReworkEdge.vue'
|
||||
import { FLOW_REWORK_COLOR } from './constants/theme'
|
||||
@ -55,24 +54,31 @@ 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 } = useVueFlow(flowId)
|
||||
const { fitView, setViewport, viewport, screenToFlowCoordinate, getNodes, updateNodeInternals } = 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), stageName = ref(''), pendingStagePoint = ref<Point | null>(null)
|
||||
const busy = ref(false), dragging = ref(false), failure = ref(''), stageOpen = ref(false), stageNameOpen = ref(false), pendingStagePoint = ref<Point | null>(null)
|
||||
const draftViewport = ref<(Point & { zoom: number }) | null>(null)
|
||||
const stageDescription = ref('')
|
||||
const createParentId = ref<number | null>(null), collapsedStages = ref<number[]>([])
|
||||
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 isEditing = computed(() => drawerStageId.value !== null || dragging.value || busy.value || stageOpen.value || stageNameOpen.value || reworkSourceId.value !== null)
|
||||
defineExpose({ isEditing })
|
||||
let loaded = false, movingProgrammatically = false
|
||||
let previousParents: Record<string, number | null> = {}
|
||||
|
||||
watch(() => props.view, () => {
|
||||
if (!loaded) {
|
||||
const preference = readFlowPreferences(props.userId, props.projectId, props.iterationId)
|
||||
positions.value = Object.fromEntries(Object.entries(preference?.positions || {}).filter(([id]) => id.startsWith('s:')))
|
||||
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 || []
|
||||
loaded = true
|
||||
}
|
||||
// 迁入或迁出阶段组后坐标原点已变化;只清除该节点的旧坐标,避免把根画布绝对位置当成子画布相对位置。
|
||||
const parents = Object.fromEntries(props.view.stages.map(stage => ['s:' + stage.id, stage.parentStageId ?? null]))
|
||||
for (const [id, parent] of Object.entries(parents)) if (id in previousParents && previousParents[id] !== parent) delete positions.value[id]
|
||||
previousParents = parents
|
||||
rebuild()
|
||||
}, { immediate: true })
|
||||
watch(() => [props.canCreate, props.canManage], rebuild)
|
||||
@ -80,18 +86,32 @@ watch(() => [props.canCreate, props.canManage], rebuild)
|
||||
watch(() => props.canManage, allowed => { if (!allowed) { stageOpen.value = false; stageNameOpen.value = false; 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 graph = buildFlowGraph(props.view, positions.value)
|
||||
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 edge of graph.edges) edge.selectable = props.canManage && edge.data?.kind !== 'rework'
|
||||
nodes.value = graph.nodes; edges.value = graph.edges
|
||||
}
|
||||
/** 本地偏好只保存阶段坐标和视口;旧工作项坐标不再写回浏览器。 */
|
||||
function savePreference() { writeFlowPreferences(props.userId, props.projectId, { positions: positions.value, collapsedStages: [], viewport: draftViewport.value }, props.iterationId) }
|
||||
/** 阶段拖动结束后记录画布坐标,不调用工作项归属或排期接口。 */
|
||||
function dragStopped() { positions.value = Object.fromEntries(nodes.value.filter(node => node.type === 'stage').map(node => [node.id, { ...node.position }])); dragging.value = false; savePreference(); rebuild() }
|
||||
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) {
|
||||
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)
|
||||
if (groups.length) void nextTick(() => updateNodeInternals(groups))
|
||||
}
|
||||
/**
|
||||
* 松开时保存补偿后的父子坐标;重新进入页面可恢复相同外框,不调用业务写接口。
|
||||
* @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() }
|
||||
/** 删除旧手动阶段坐标后按显式阶段图重新布局。 */
|
||||
async function autoLayout() { positions.value = {}; savePreference(); rebuild(); await nextTick(); await fitAll() }
|
||||
/** 缩放和平移只影响当前浏览器的展示偏好。 */
|
||||
@ -104,8 +124,9 @@ async function fitAll() {
|
||||
try {
|
||||
const lanes = edges.value.filter(edge => edge.data?.kind === 'rework').map(edge => edge.data?.laneY || 0)
|
||||
if (canvas.value && nodes.value.length && lanes.length) {
|
||||
const minX = Math.min(...nodes.value.map(node => node.position.x)) - 30, minY = Math.min(...nodes.value.map(node => node.position.y)) - 20
|
||||
const maxX = Math.max(...nodes.value.map(node => node.position.x + FLOW_STAGE_WIDTH)) + 30, maxY = Math.max(...lanes, ...nodes.value.map(node => node.position.y + FLOW_STAGE_HEIGHT)) + 38
|
||||
const rectangles = nodes.value.map(node => absoluteRectangle(node, nodes.value))
|
||||
const minX = Math.min(...rectangles.map(rect => rect.x)) - 30, minY = Math.min(...rectangles.map(rect => rect.y)) - 20
|
||||
const maxX = Math.max(...rectangles.map(rect => rect.x + rect.width)) + 30, maxY = Math.max(...lanes, ...rectangles.map(rect => rect.y + rect.height)) + 38
|
||||
const width = maxX - minX, height = maxY - minY, area = canvas.value
|
||||
const zoom = Math.max(0.1, Math.min(1, (area.clientWidth - 72) / width, (area.clientHeight - 72) / height))
|
||||
await setViewport({ x: (area.clientWidth - width * zoom) / 2 - minX * zoom, y: (area.clientHeight - height * zoom) / 2 - minY * zoom, zoom })
|
||||
@ -114,13 +135,15 @@ async function fitAll() {
|
||||
} finally { movingProgrammatically = false }
|
||||
}
|
||||
/** 点击阶段打开当前工作项;按钮事件会停止冒泡以保留历史、创建和回退动作。 */
|
||||
function selectNode(event: NodeMouseEvent) { if (event.node.type === 'stage') openDrawer(Number(event.node.id.slice(2)), 'current') }
|
||||
function selectNode(event: NodeMouseEvent) { 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 }
|
||||
/** 工作项详情沿用项目级详情抽屉;先关闭阶段列表,避免两个遮罩层争夺焦点。 */
|
||||
function openItem(id: number) { drawerStageId.value = null; emit('open', id) }
|
||||
/** 打开新建表单前关闭阶段抽屉,使表单返回后由项目快照刷新当前列表。 */
|
||||
function createFromDrawer(stageId: number | null) { drawerStageId.value = null; emit('create', stageId) }
|
||||
/** 从组概览创建子阶段时先关闭抽屉,复用画布同一表单。 */
|
||||
function createChildFromDrawer(id: number) { drawerStageId.value = null; createChildStage(id) }
|
||||
/** 阶段内创建仅预选阶段,后端仍复验当前版本、成员权限和阶段冻结状态。 */
|
||||
function createInStage(stageId: number) { if (!props.canCreate || stageId !== 0 && !props.view.stages.some(stage => stage.id === stageId)) return; emit('create', stageId || null) }
|
||||
/** 回退入口使用后端当前阶段能力,待开始阶段也可进入;提交仍须通过项目锁内复验。 */
|
||||
@ -129,16 +152,22 @@ function openRework(stageId: number) { if (props.canManage && props.view.stages.
|
||||
function minimapColor(node: GraphNode<FlowNodeData>) { return stageAppearance(node.data?.stage).accent }
|
||||
/** 阶段素材只发出拖放标记,普通阶段点击不会误创建新阶段。 */
|
||||
function dragPalette(event: DragEvent) { if (!props.canManage || !event.dataTransfer) return; event.dataTransfer.setData('application/x-pm-stage', 'new-stage'); event.dataTransfer.effectAllowed = 'copy' }
|
||||
/** 将画布落点转为坐标后先命名,确认前不写项目共享阶段。 */
|
||||
function dropStage(event: DragEvent) { if (!props.canManage || busy.value || event.dataTransfer?.getData('application/x-pm-stage') !== 'new-stage') return; pendingStagePoint.value = screenToFlowCoordinate({ x: event.clientX, y: event.clientY }); stageName.value = ''; stageDescription.value = ''; failure.value = ''; stageNameOpen.value = true }
|
||||
/** 创建成功后只在当前浏览器保存阶段位置,失败仍保留命名输入。 */
|
||||
async function saveNewStage() {
|
||||
const name = stageName.value.trim(), point = pendingStagePoint.value
|
||||
if (!props.canManage || busy.value || !point || !name || name.length > 120) return
|
||||
busy.value = true; failure.value = ''
|
||||
try { const id = await api.createStage(props.projectId, { name, sortOrder: 0, ownerId: null, description: stageDescription.value }, props.iterationId); positions.value = { ...positions.value, ['s:' + id]: point }; stageNameOpen.value = false; pendingStagePoint.value = null; savePreference(); emit('changed') }
|
||||
catch (error) { failure.value = errorText(error) } finally { busy.value = false }
|
||||
/** 拖入阶段组内部时预选父级;外层落点创建根阶段,最终归属始终由后端校验。 */
|
||||
function dropStage(event: DragEvent) {
|
||||
if (!props.canManage || busy.value || event.dataTransfer?.getData('application/x-pm-stage') !== 'new-stage') return
|
||||
const target = (event.target as Element).closest('[data-stage]'), id = Number(target?.getAttribute('data-stage'))
|
||||
const parent = props.view.stages.find(stage => stage.id === id && stage.stageKind === 'GROUP' && stage.canCreateChildStage)
|
||||
createParentId.value = parent?.id ?? null
|
||||
const point = screenToFlowCoordinate({ x: event.clientX, y: event.clientY }), parentNode = nodes.value.find(node => node.id === 's:' + parent?.id)
|
||||
const origin = parentNode ? absoluteRectangle(parentNode, nodes.value) : { x: 0, y: 0 }
|
||||
pendingStagePoint.value = { x: point.x - origin.x, y: point.y - origin.y }; failure.value = ''; stageNameOpen.value = true
|
||||
}
|
||||
/** 阶段组上的入口与拖入子画布共用日期表单,不创建第三层阶段组。 */
|
||||
function createChildStage(id: number) { if (!props.view.stages.some(stage => stage.id === id && stage.canCreateChildStage)) return; createParentId.value = id; pendingStagePoint.value = null; stageNameOpen.value = true }
|
||||
/** 创建后只保存本地位置,跨用户共享的阶段内容来自后端下一次同步。 */
|
||||
function stageCreated(id: number) { if (pendingStagePoint.value) positions.value = { ...positions.value, ['s:' + id]: pendingStagePoint.value }; stageNameOpen.value = false; pendingStagePoint.value = null; if (createParentId.value) collapsedStages.value = collapsedStages.value.filter(value => value !== createParentId.value); savePreference(); emit('changed') }
|
||||
/** 折叠状态按用户、项目、迭代保存在当前浏览器,展开后恢复子节点相对位置。 */
|
||||
function toggleGroup(id: number) { collapsedStages.value = collapsedStages.value.includes(id) ? collapsedStages.value.filter(value => value !== id) : [...collapsedStages.value, id]; savePreference(); rebuild() }
|
||||
/** 仅连接当前项目的两个真实阶段;后端在项目锁内复验权限、环和已执行门禁。 */
|
||||
async function connectStages(connection: Connection) {
|
||||
if (!props.canManage || busy.value || !connection.source?.startsWith('s:') || !connection.target?.startsWith('s:')) return
|
||||
@ -163,7 +192,7 @@ async function edgeClicked(event: { edge: Edge<FlowEdgeData> }) {
|
||||
.flow-toolbar,.flow-tools{display:flex;align-items:center;gap:8px;flex-wrap:wrap}.flow-toolbar{justify-content:space-between;margin-bottom:10px}.flow-tools :deep(.el-button+.el-button){margin-left:0}.flow-help{font-size:11px;color:var(--el-text-color-secondary)}.flow-canvas{--vf-connection-path:var(--el-color-primary);height:max(470px,calc(100vh - 315px));position:relative;overflow:hidden;border:1px solid var(--el-border-color-light);border-radius:10px;background:var(--el-fill-color-extra-light)}.flow-canvas.inactive{height:0}
|
||||
/* 组件 DOM 和状态类由运行时生成;按 class token 匹配保持原选择器的含义和优先级,避免 IDE 静态模板匹配误报。 */
|
||||
.flow-canvas :deep([class~="vue-flow"]){height:100%}
|
||||
.flow-canvas :deep([class~="vue-flow__node-stage"]){padding:0;border:0;background:transparent}.canvas-legend{position:absolute;left:16px;bottom:12px;display:flex;align-items:center;gap:8px;font-size:11px;color:var(--el-text-color-secondary);pointer-events:none}.legend-line{width:24px;border-top:2px solid var(--el-text-color-placeholder)}.legend-line.green{border-color:var(--el-color-success)}.legend-line.rework{border-top-style:dashed}.legend-line.legacy{border-color:var(--el-color-warning);border-top-style:dashed}.canvas-empty{position:absolute;left:50%;top:50%;transform:translate(-50%,-50%);color:var(--el-text-color-secondary);pointer-events:none}.flow-failure{margin-bottom:10px;white-space:pre-line}.stage-palette{border:1px dashed var(--el-color-primary-light-3);border-radius:6px;background:var(--el-color-primary-light-9);color:var(--el-color-primary);padding:6px 11px;font-size:12px;cursor:grab}.stage-palette:active{cursor:grabbing}@media(max-width:900px){.flow-canvas{height:560px}}
|
||||
.flow-canvas :deep([class~="vue-flow__node-stage"]),.flow-canvas :deep([class~="vue-flow__node-group"]){padding:0;border:0;background:transparent}.canvas-legend{position:absolute;left:16px;bottom:12px;display:flex;align-items:center;gap:8px;font-size:11px;color:var(--el-text-color-secondary);pointer-events:none}.legend-line{width:24px;border-top:2px solid var(--el-text-color-placeholder)}.legend-line.green{border-color:var(--el-color-success)}.legend-line.rework{border-top-style:dashed}.legend-line.legacy{border-color:var(--el-color-warning);border-top-style:dashed}.canvas-empty{position:absolute;left:50%;top:50%;transform:translate(-50%,-50%);color:var(--el-text-color-secondary);pointer-events:none}.flow-failure{margin-bottom:10px;white-space:pre-line}.stage-palette{border:1px dashed var(--el-color-primary-light-3);border-radius:6px;background:var(--el-color-primary-light-9);color:var(--el-color-primary);padding:6px 11px;font-size:12px;cursor:grab}.stage-palette:active{cursor:grabbing}@media(max-width:900px){.flow-canvas{height:560px}}
|
||||
/* Vue Flow 自带控件和小地图有独立浅色默认值,限定在协作画布内覆盖,避免影响系统其他页面。 */
|
||||
.flow-canvas :deep([class~="vue-flow__controls"]){box-shadow:var(--el-box-shadow-lighter)}
|
||||
.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)}
|
||||
|
||||
@ -38,5 +38,6 @@ const path = computed(() => {
|
||||
const latest = computed(() => props.data?.latestReworkAt ? localTime(props.data.latestReworkAt, 'Asia/Shanghai').replace('T', ' ') : '未记录')
|
||||
</script>
|
||||
<style scoped>
|
||||
.rework-label{position:absolute;display:flex;flex-direction:column;align-items:center;gap:2px;background:var(--el-bg-color-overlay);border:1px solid;border-radius:5px;padding:3px 8px;color:var(--el-text-color-primary);font-size:10px;white-space:nowrap;pointer-events:none;box-shadow:var(--el-box-shadow-lighter)}.rework-label strong{font-size:11px;font-weight:500}.rework-label span{color:var(--el-text-color-secondary)}
|
||||
/* 阶段组有独立背景,标签需高于父子节点,否则内部回退次数和时间会被组外框覆盖。 */
|
||||
.rework-label{position:absolute;z-index:30;display:flex;flex-direction:column;align-items:center;gap:2px;background:var(--el-bg-color-overlay);border:1px solid;border-radius:5px;padding:3px 8px;color:var(--el-text-color-primary);font-size:10px;white-space:nowrap;pointer-events:none;box-shadow:var(--el-box-shadow-lighter)}.rework-label strong{font-size:11px;font-weight:500}.rework-label span{color:var(--el-text-color-secondary)}
|
||||
</style>
|
||||
|
||||
@ -1,11 +1,12 @@
|
||||
<template>
|
||||
<div class="phase-group" :class="{ 'is-current': data.stage?.isCurrent }" :data-stage="data.stageId" :data-state="appearance.tone" :style="{ '--phase-background': appearance.background, '--phase-border': appearance.border, '--phase-accent': appearance.accent }">
|
||||
<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><strong :title="data.title">{{ data.title }}</strong><span v-if="data.stage?.isCurrent" class="stage-current">当前</span><span v-if="data.stage" class="stage-version">v{{ data.stage.revisionNo || 1 }}</span></header>
|
||||
<header class="stage-drag"><span class="phase-dot"></span><strong :title="data.title">{{ data.title }}</strong><span v-if="data.stage?.isCurrent" class="stage-current">当前</span><button v-if="data.stage?.stageKind === 'GROUP'" class="nodrag stage-toggle" @click.stop="emit('toggle', data.stageId!)">{{ data.collapsed ? '展开' : '折叠' }}</button><span v-if="data.stage" class="stage-version">v{{ data.stage.revisionNo || 1 }}</span></header>
|
||||
<p v-if="data.stage" class="phase-description" :class="{ empty: !data.stage.description?.trim() }" :title="data.stage.description || '未填写阶段描述'">{{ data.stage.description || '未填写阶段描述' }}</p>
|
||||
<div class="phase-body"><button class="nodrag stage-items" title="查看当前版本工作项" @click.stop="emit('view', data.stageId!)">{{ data.itemCount || 0 }} 个工作项</button><span v-if="data.stage" class="stage-status" :title="appearance.description">{{ appearance.label }}</span></div>
|
||||
<div v-if="data.stage" class="phase-plan" :class="{ warning: data.stage.scheduleReviewRequired || data.stage.overdue }" :title="planLabel(data.stage)">{{ planLabel(data.stage) }}</div>
|
||||
<div v-if="data.stage" class="phase-actions"><button v-if="data.canWrite && data.stage.executionStatus !== 'COMPLETED' && data.stage.executionStatus !== 'LEGACY_PASSED'" class="nodrag stage-create" @click.stop="emit('create', data.stageId!)">新建</button><button class="nodrag stage-history" @click.stop="emit('history', data.stageId!)">历史版本</button><button v-if="data.canManage && data.stage.canRework" class="nodrag stage-rework" @click.stop="emit('rework', data.stageId!)">回退</button></div>
|
||||
<div v-if="data.stage?.stageKind === 'GROUP'" class="group-summary">子阶段 {{ data.stage.completedChildStageCount || 0 }}/{{ data.stage.childStageCount || 0 }} 已完成 · 内部排期{{ data.stage.subtreeScheduleValidationStatus === 'VALID' ? '完整' : '待完善' }}</div>
|
||||
<div v-if="data.stage" class="phase-actions"><button v-if="data.canManage && data.stage.canCreateChildStage" class="nodrag stage-create" @click.stop="emit('createChild', data.stageId!)">+ 子阶段</button><button v-if="data.canWrite && data.stage.canCreateWorkItem" class="nodrag stage-create" @click.stop="emit('create', data.stageId!)">新建</button><button class="nodrag stage-history" @click.stop="emit('history', data.stageId!)">历史版本</button><button v-if="data.canManage && data.stage.canRework" class="nodrag stage-rework" @click.stop="emit('rework', data.stageId!)">回退</button></div>
|
||||
<Handle v-if="data.stage" id="rework-out" type="source" :position="Position.Bottom" :connectable="false" :style="{ left: '70%', opacity: 0, pointerEvents: 'none' }" />
|
||||
<Handle v-if="data.stage" id="rework-in" type="target" :position="Position.Bottom" :connectable="false" :style="{ left: '30%', opacity: 0, pointerEvents: 'none' }" />
|
||||
<Handle v-if="data.stage" id="out" type="source" :position="Position.Right" :connectable="!!data.canManage" :style="{ top: '42px' }" />
|
||||
@ -21,7 +22,7 @@ import { plannedDate } from '../../../shared/utils/time'
|
||||
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] }>()
|
||||
const emit = defineEmits<{ view: [id: number]; create: [id: number]; rework: [id: number]; history: [id: number]; createChild: [id: number]; toggle: [id: number] }>()
|
||||
/** 节点仅展示阶段自身的预计日期;参考时间留在抽屉,避免混作本轮有效排期。 */
|
||||
function planLabel(stage: Stage): string {
|
||||
if (stage.scheduleReviewRequired) return stage.scheduleReviewClosed ? '本轮未确认排期' : '排期待复核'
|
||||
@ -36,4 +37,6 @@ function planLabel(stage: Stage): string {
|
||||
.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)}
|
||||
.phase-group :deep([class~="vue-flow__handle"]){width:10px;height:10px;background:var(--el-color-primary);border:2px solid var(--el-bg-color-overlay)}
|
||||
/* 组外框包裹同一画布中的子节点,只有标题可拖动,内部背景保留为次要层级。 */
|
||||
.phase-group.is-container{background:color-mix(in srgb,var(--phase-background) 70%,var(--el-bg-color));border-style:dashed}.stage-toggle{border:0;background:transparent;color:var(--el-color-primary);cursor:pointer;font-size:11px}.group-summary{padding:3px 14px 0;font-size:11px;color:var(--el-text-color-secondary)}
|
||||
</style>
|
||||
|
||||
@ -1,101 +1,168 @@
|
||||
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, WorkItem } from '../../../types'
|
||||
import type { FlowView, Point, Stage, WorkItem } from '../../../types'
|
||||
|
||||
export interface FlowNodeData { item?: WorkItem; children?: WorkItem[]; stage?: FlowView['stages'][number]; stageId?: number; title?: string; itemCount?: number; [key: string]: unknown }
|
||||
export interface FlowNodeData { 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
|
||||
export const FLOW_VISIBLE_CHILD_ROWS = 5
|
||||
export const FLOW_CHILD_ROW_HEIGHT = 24
|
||||
export const FLOW_STAGE_WIDTH = 252
|
||||
// 固定高度包含两行阶段说明,旧浏览器坐标仍由freePosition避让,长描述不会撑大节点或覆盖同级阶段。
|
||||
export const FLOW_STAGE_HEIGHT = 164
|
||||
const GROUP_INSET = { left: 24, top: 194, right: 28, bottom: 38 }
|
||||
|
||||
/** 旧工作项卡片仍可被独立组件使用;流程画布不再根据工作项数量改变阶段尺寸。 */
|
||||
/** 独立卡片仍可估算高度;流程画布只使用阶段摘要和独立的工作项抽屉。 */
|
||||
export function workItemHeight(item: WorkItem, childCount = 0): number { const count = item.dependencyConditions.length; return 124 + (item.parentTaskId || item.childCount || item.canCreateChild ? 24 : 0) + (count ? 24 + Math.min(count, 3) * 19 + (count > 3 ? 20 : 0) : 0) + (item.stageBlockedReasons?.length ? 20 : 0) + (childCount ? 8 + Math.min(childCount, FLOW_VISIBLE_CHILD_ROWS) * FLOW_CHILD_ROW_HEIGHT : 0) }
|
||||
|
||||
/**
|
||||
* 只以阶段及显式阶段边组成画布,工作项留在按当前版本分组的抽屉中。
|
||||
* 阶段大小固定且数量取完整服务端快照;搜索或筛选不会改变流程拓扑和显示总数。
|
||||
* 执行连线使用内置三次贝塞尔曲线,回退线继续走独立历史通道并保留状态样式。
|
||||
* @param view 已通过项目成员鉴权的当前版本流程快照
|
||||
* @param positions 当前浏览器保存的阶段坐标,旧工作项坐标自然忽略
|
||||
* @return 只有阶段节点及阶段间连线的画布数据
|
||||
* 先布局子画布,再以实际外框布局根画布;同一 Vue Flow 的父子节点使用相对坐标。
|
||||
* 展开、折叠和拖动均是浏览器展示偏好,不参与同层执行关系或后端状态计算。
|
||||
* @param view 完整的已鉴权阶段树和同层边,工作项数量来自服务端摘要
|
||||
* @param positions 浏览器坐标;子节点坐标以父外框左上角为原点
|
||||
* @param collapsed 已折叠的阶段组ID,内部节点及连线不渲染
|
||||
* @returns 按父级在前顺序生成的节点与执行/回退边
|
||||
*/
|
||||
export function buildFlowGraph(view: FlowView, positions: Record<string, Point>): { nodes: Node<FlowNodeData>[]; edges: Edge<FlowEdgeData>[] } {
|
||||
const phases = [...view.stages].sort((a, b) => a.sortOrder - b.sortOrder || a.id - b.id)
|
||||
const stageIds = new Set(phases.map(stage => stage.id))
|
||||
const links = view.stageEdges.filter(edge => stageIds.has(edge.predecessorStageId) && stageIds.has(edge.successorStageId))
|
||||
// 最长路径层级只决定首次打开的布局;执行条件完全以数据库保存的有向边为准。
|
||||
const levels = new Map(phases.map(stage => [stage.id, 0]))
|
||||
const indegree = new Map(phases.map(stage => [stage.id, 0]))
|
||||
const outgoing = new Map<number, typeof links>()
|
||||
for (const edge of links) {
|
||||
indegree.set(edge.successorStageId, (indegree.get(edge.successorStageId) || 0) + 1)
|
||||
const next = outgoing.get(edge.predecessorStageId) || []
|
||||
next.push(edge); outgoing.set(edge.predecessorStageId, next)
|
||||
export function buildFlowGraph(view: FlowView, positions: Record<string, Point>, collapsed: number[] = []): { nodes: Node<FlowNodeData>[]; edges: Edge<FlowEdgeData>[] } {
|
||||
const stages = [...view.stages].sort((a, b) => a.sortOrder - b.sortOrder || a.id - b.id)
|
||||
const byId = new Map(stages.map(stage => [stage.id, stage]))
|
||||
const rectangles = new Map<number, Rectangle>(), scopes = new Map<number | null, Stage[]>(), groupOffsets = new Map<number, Point>()
|
||||
for (const stage of stages) { const scope = stage.parentStageId ?? null; scopes.set(scope, [...(scopes.get(scope) || []), stage]) }
|
||||
for (const group of stages.filter(stage => stage.stageKind === 'GROUP')) {
|
||||
if (!collapsed.includes(group.id)) layout(scopes.get(group.id) || [], GROUP_INSET.left, GROUP_INSET.top)
|
||||
const children = (scopes.get(group.id) || []).map(child => rectangles.get(child.id)).filter((rect): rect is Rectangle => !!rect)
|
||||
const lanes = (view.reworkEdges || []).filter(edge => byId.get(edge.sourceStageId)?.parentStageId === group.id).length
|
||||
const bounds = collapsed.includes(group.id) ? { x: 0, y: 0, width: 320, height: 190 } : stageGroupBounds(children, lanes)
|
||||
groupOffsets.set(group.id, { x: bounds.x, y: bounds.y })
|
||||
for (const child of children) { child.x -= bounds.x; child.y -= bounds.y }
|
||||
rectangles.set(group.id, { ...bounds, x: 0, y: 0 })
|
||||
}
|
||||
const queue = phases.filter(stage => indegree.get(stage.id) === 0).map(stage => stage.id)
|
||||
for (let cursor = 0; cursor < queue.length; cursor++) {
|
||||
const source = queue[cursor]!
|
||||
for (const edge of outgoing.get(source) || []) {
|
||||
levels.set(edge.successorStageId, Math.max(levels.get(edge.successorStageId) || 0, (levels.get(source) || 0) + 1))
|
||||
const remaining = (indegree.get(edge.successorStageId) || 0) - 1
|
||||
indegree.set(edge.successorStageId, remaining)
|
||||
if (remaining === 0) queue.push(edge.successorStageId)
|
||||
}
|
||||
layout(scopes.get(null) || [], 30, 40)
|
||||
const nodes: Node<FlowNodeData>[] = []
|
||||
for (const stage of [...stages.filter(stage => !stage.parentStageId), ...stages.filter(stage => !!stage.parentStageId)]) {
|
||||
if (stage.parentStageId && collapsed.includes(stage.parentStageId)) continue
|
||||
const rect = rectangles.get(stage.id)!
|
||||
// 子节点不受旧父框限制;拖动时由实际边界重算父框,才能向四个方向扩大或收拢。
|
||||
nodes.push({ id: 's:' + stage.id, type: stage.stageKind === 'GROUP' ? 'group' : 'stage', parentNode: stage.parentStageId ? 's:' + stage.parentStageId : undefined,
|
||||
position: { x: rect.x, y: rect.y }, style: { width: rect.width + 'px', height: rect.height + 'px' }, zIndex: stage.parentStageId ? 10 : 0,
|
||||
data: { stage, stageId: stage.id, title: stage.name, itemCount: stage.counts.total, collapsed: collapsed.includes(stage.id) }, dragHandle: '.stage-drag' })
|
||||
}
|
||||
const counts = new Map<number, number>()
|
||||
for (const item of view.items) {
|
||||
const stageId = item.stageId && stageIds.has(item.stageId) ? item.stageId : 0
|
||||
counts.set(stageId, (counts.get(stageId) || 0) + 1)
|
||||
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)
|
||||
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 groups = [
|
||||
...phases.map(stage => ({ id: stage.id, title: stage.name, stage, level: levels.get(stage.id) || 0, itemCount: stage.counts?.total ?? counts.get(stage.id) ?? 0 })),
|
||||
...(!phases.length || (view.unassigned?.counts?.total ?? counts.get(0) ?? 0) > 0 ? [{ id: 0, title: '未分配', stage: undefined, level: Math.max(-1, ...levels.values()) + 1, itemCount: view.unassigned?.counts?.total ?? counts.get(0) ?? 0 }] : []),
|
||||
]
|
||||
const nextY = new Map<number, number>(), occupied: Rectangle[] = []
|
||||
const nodes: Node<FlowNodeData>[] = groups.map(group => {
|
||||
const preferred = positions['s:' + group.id] || { x: group.level * (FLOW_STAGE_WIDTH + 116), y: nextY.get(group.level) || 40 }
|
||||
const position = freePosition(preferred, FLOW_STAGE_WIDTH, FLOW_STAGE_HEIGHT, occupied, 48)
|
||||
occupied.push({ ...position, width: FLOW_STAGE_WIDTH, height: FLOW_STAGE_HEIGHT })
|
||||
nextY.set(group.level, Math.max(nextY.get(group.level) || 40, position.y + FLOW_STAGE_HEIGHT + 56))
|
||||
return { id: 's:' + group.id, type: 'stage', position, style: { width: FLOW_STAGE_WIDTH + 'px', height: FLOW_STAGE_HEIGHT + 'px' }, data: { stageId: group.id, title: group.title, stage: group.stage, itemCount: group.itemCount }, connectable: !!group.stage, dragHandle: '.stage-drag' }
|
||||
})
|
||||
const edges: Edge<FlowEdgeData>[] = links.map(link => {
|
||||
// SVG 连线与箭头共用主题变量,无需重新请求或重建节点即可响应明暗切换。
|
||||
const visible = new Set(nodes.map(node => node.id))
|
||||
const edges: Edge<FlowEdgeData>[] = view.stageEdges.filter(link => visible.has('s:' + link.predecessorStageId) && visible.has('s:' + link.successorStageId)).map(link => {
|
||||
const color = link.legacyPassed ? 'var(--el-color-warning)' : link.satisfied ? 'var(--el-color-success)' : 'var(--el-text-color-placeholder)'
|
||||
return {
|
||||
id: 'stage:' + link.id, source: 's:' + link.predecessorStageId, target: 's:' + link.successorStageId, sourceHandle: 'out', targetHandle: 'in',
|
||||
// 颜色只编码后端当前执行事实,迁移放行与真正完成必须有不同视觉语义。
|
||||
type: ConnectionLineType.Bezier, updatable: false, selectable: false, markerEnd: { type: MarkerType.ArrowClosed, color },
|
||||
style: { stroke: color, strokeWidth: link.satisfied ? 2.4 : 1.8, strokeDasharray: link.legacyPassed ? '6 4' : undefined },
|
||||
data: { linkId: link.id, version: link.version },
|
||||
}
|
||||
return { id: 'stage:' + link.id, source: 's:' + link.predecessorStageId, target: 's:' + link.successorStageId, sourceHandle: 'out', targetHandle: 'in', type: ConnectionLineType.Bezier, updatable: false, selectable: false, zIndex: 15,
|
||||
markerEnd: { type: MarkerType.ArrowClosed, color }, style: { stroke: color, strokeWidth: link.satisfied ? 2.4 : 1.8, strokeDasharray: link.legacyPassed ? '6 4' : undefined }, data: { kind: 'execution', linkId: link.id, version: link.version } }
|
||||
})
|
||||
// 回退记录只在执行层级计算结束后追加,禁止把反向历史线交给拓扑排序或执行门禁。
|
||||
const lowerBound = Math.max(0, ...nodes.map(node => node.position.y + FLOW_STAGE_HEIGHT))
|
||||
for (const [index, event] of (view.reworkEdges || []).filter(event => stageIds.has(event.sourceStageId) && stageIds.has(event.targetStageId)).entries()) {
|
||||
const source = nodes.find(node => node.id === 's:' + event.sourceStageId)!, target = nodes.find(node => node.id === 's:' + event.targetStageId)!
|
||||
const self = event.sourceStageId === event.targetStageId
|
||||
edges.push({ id: 'rework:' + event.sourceStageId + ':' + event.targetStageId, source: 's:' + event.sourceStageId, target: 's:' + event.targetStageId,
|
||||
sourceHandle: 'rework-out', targetHandle: 'rework-in', type: 'rework', updatable: false, selectable: false, deletable: false,
|
||||
for (const event of view.reworkEdges || []) {
|
||||
const source = nodes.find(node => node.id === 's:' + event.sourceStageId), target = nodes.find(node => node.id === 's:' + event.targetStageId)
|
||||
if (!source || !target) continue
|
||||
edges.push({ id: 'rework:' + event.sourceStageId + ':' + event.targetStageId, source: source.id, target: target.id, sourceHandle: 'rework-out', targetHandle: 'rework-in', type: 'rework', updatable: false, selectable: false, deletable: false, zIndex: 16,
|
||||
markerEnd: { type: MarkerType.ArrowClosed, color: FLOW_REWORK_COLOR }, style: { stroke: FLOW_REWORK_COLOR, strokeWidth: 2, strokeDasharray: '7 5' },
|
||||
data: { kind: 'rework', reworkCount: event.reworkCount, latestReworkAt: event.latestReworkAt, laneY: self ? source.position.y + FLOW_STAGE_HEIGHT + 30 : lowerBound + 64 + index * 52, sourceEscapeX: source.position.x + FLOW_STAGE_WIDTH + 24, targetEscapeX: target.position.x - 24 },
|
||||
})
|
||||
data: { kind: 'rework', reworkCount: event.reworkCount, latestReworkAt: event.latestReworkAt } })
|
||||
}
|
||||
updateReworkRoutes(nodes, edges)
|
||||
return { nodes, edges }
|
||||
|
||||
/**
|
||||
* 同层最长路径用于初始摆放;恢复组坐标时补偿内部原点变化,保留子节点绝对位置。
|
||||
* @param list 当前画布内的阶段,结果写入共享矩形索引
|
||||
* @param left 自动布局首列的起始横坐标
|
||||
* @param top 自动布局首行的起始纵坐标,子画布需避开父组标题
|
||||
*/
|
||||
function layout(list: Stage[], left: number, top: number) {
|
||||
const ids = new Set(list.map(stage => stage.id)), links = view.stageEdges.filter(edge => ids.has(edge.predecessorStageId) && ids.has(edge.successorStageId))
|
||||
const levels = new Map(list.map(stage => [stage.id, 0])), degree = new Map(list.map(stage => [stage.id, 0]))
|
||||
for (const edge of links) degree.set(edge.successorStageId, (degree.get(edge.successorStageId) || 0) + 1)
|
||||
const queue = list.filter(stage => !degree.get(stage.id)).map(stage => stage.id)
|
||||
for (let cursor = 0; cursor < queue.length; cursor++) for (const edge of links.filter(link => link.predecessorStageId === queue[cursor])) {
|
||||
levels.set(edge.successorStageId, Math.max(levels.get(edge.successorStageId) || 0, (levels.get(edge.predecessorStageId) || 0) + 1))
|
||||
degree.set(edge.successorStageId, degree.get(edge.successorStageId)! - 1); if (!degree.get(edge.successorStageId)) queue.push(edge.successorStageId)
|
||||
}
|
||||
const widths = new Map<number, number>(), columns = new Map<number, number>(), nextY = new Map<number, number>(), occupied: Rectangle[] = []
|
||||
for (const stage of list) { const level = levels.get(stage.id)!; widths.set(level, Math.max(widths.get(level) || 0, rectangles.get(stage.id)?.width || FLOW_STAGE_WIDTH)) }
|
||||
let offset = left
|
||||
for (const level of [...widths.keys()].sort((a, b) => a - b)) { columns.set(level, offset); offset += widths.get(level)! + 116 }
|
||||
for (const stage of list) {
|
||||
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 }
|
||||
rectangles.set(stage.id, rect); occupied.push(rect); nextY.set(level, point.y + size.height + 56)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** 浏览器旧坐标可能互相覆盖;以固定阶段尺寸逐个向下避让,保持拖动后的位置尽量稳定。 */
|
||||
/**
|
||||
* 根据子节点最小、最大边界计算组外框,同时为标题和回退连线预留空间。
|
||||
* 单个子节点的边界跨度恒定,因此拖动只平移固定尺寸的组,不会留下不断增大的空白。
|
||||
* @param children 同一组内的相对矩形,包含节点自身宽高
|
||||
* @param lanes 组内回退通道数
|
||||
* @returns 父框应平移的偏移量及新宽高;空组保留可创建子阶段的最小区域
|
||||
*/
|
||||
function stageGroupBounds(children: Rectangle[], lanes: number): Rectangle {
|
||||
if (!children.length) return { x: 0, y: 0, width: 360, height: 290 }
|
||||
const left = Math.min(...children.map(rect => rect.x)), top = Math.min(...children.map(rect => rect.y))
|
||||
const right = Math.max(...children.map(rect => rect.x + rect.width)), bottom = Math.max(...children.map(rect => rect.y + rect.height))
|
||||
return { x: left - GROUP_INSET.left, y: top - GROUP_INSET.top,
|
||||
width: Math.max(360, right - left + GROUP_INSET.left + GROUP_INSET.right),
|
||||
height: bottom - top + GROUP_INSET.top + GROUP_INSET.bottom + lanes * 52 }
|
||||
}
|
||||
|
||||
/**
|
||||
* 原地调整展开组的尺寸和坐标,避免拖动中重建整图导致拖拽中断。
|
||||
* 父框原点随最左、最上子节点移动,所有子节点反向补偿相对坐标,未拖动的兄弟节点保持绝对位置。
|
||||
* @param nodes Vue Flow 当前节点,子节点位置均相对父框
|
||||
* @param groupId 需要跟随拖动更新的父组ID
|
||||
* @param edges 当前可见边,用于预留组内回退通道
|
||||
* @remarks 只修改浏览器展示坐标和尺寸;不存在或已折叠的组保持原状。
|
||||
*/
|
||||
export function resizeStageGroup(nodes: Node<FlowNodeData>[], groupId: string, edges: Edge<FlowEdgeData>[]): void {
|
||||
const group = nodes.find(node => node.id === groupId)
|
||||
if (!group || group.type !== 'group' || group.data?.collapsed) return
|
||||
const children = nodes.filter(node => node.parentNode === groupId)
|
||||
const childIds = new Set(children.map(node => node.id)), lanes = edges.filter(edge => edge.data?.kind === 'rework' && childIds.has(edge.source)).length
|
||||
// 边界计算使用局部坐标,不叠加父框原点;尺寸仍读取节点的真实展示样式。
|
||||
const bounds = stageGroupBounds(children.map(node => absoluteRectangle(node, [])), lanes)
|
||||
group.position = { x: group.position.x + bounds.x, y: group.position.y + bounds.y }
|
||||
for (const child of children) child.position = { x: child.position.x - bounds.x, y: child.position.y - bounds.y }
|
||||
group.style = { ...(typeof group.style === 'object' ? group.style : {}), width: bounds.width + 'px', height: bounds.height + 'px' }
|
||||
}
|
||||
|
||||
/**
|
||||
* 按当前节点的绝对边界更新回退通道,保持拖动和组尺寸变化时连线及次数标签位于节点下方。
|
||||
* @param nodes 当前节点及父子坐标
|
||||
* @param edges 原地更新的可见连线;执行边的几何位置继续由 Vue Flow 维护
|
||||
*/
|
||||
export function updateReworkRoutes(nodes: Node<FlowNodeData>[], edges: Edge<FlowEdgeData>[]): void {
|
||||
const laneCounts = new Map<string | null, number>()
|
||||
for (const edge of edges) {
|
||||
if (edge.data?.kind !== 'rework') continue
|
||||
const source = nodes.find(node => node.id === edge.source), target = nodes.find(node => node.id === edge.target)
|
||||
if (!source || !target) continue
|
||||
const scope = source.parentNode || null, index = laneCounts.get(scope) || 0
|
||||
laneCounts.set(scope, index + 1)
|
||||
const siblings = nodes.filter(node => (node.parentNode || null) === scope).map(node => absoluteRectangle(node, nodes))
|
||||
const from = absoluteRectangle(source, nodes), to = absoluteRectangle(target, nodes)
|
||||
edge.data = { ...edge.data, laneY: Math.max(...siblings.map(rect => rect.y + rect.height)) + 32 + index * 52, sourceEscapeX: from.x + from.width + 12, targetEscapeX: to.x - 12 }
|
||||
}
|
||||
}
|
||||
|
||||
/** 将相对子节点转为绝对矩形,用于适应画布和回退通道,避免硬编码阶段组尺寸。 */
|
||||
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 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)
|
||||
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)
|
||||
return point
|
||||
}
|
||||
|
||||
@ -1,12 +1,14 @@
|
||||
import type { Point } from '../../../types'
|
||||
|
||||
export interface FlowPreferences {
|
||||
parents?: Record<string, number | null>
|
||||
collapsedStages: number[]
|
||||
positions: Record<string, Point>
|
||||
viewport: (Point & { zoom: number }) | null
|
||||
}
|
||||
|
||||
const VERSION = 1
|
||||
// 两层节点使用相对坐标,旧平铺坐标不能直接解释为子节点位置。
|
||||
const VERSION = 2
|
||||
|
||||
/** 按登录用户、项目和迭代分隔浏览器偏好,避免同设备或同项目串用画布状态。 */
|
||||
function key(userId: number | string, projectId: number, iterationId?: number): string { return `pm-flow-view:${userId}:${projectId}${iterationId ? `:${iterationId}` : ""}` }
|
||||
@ -17,13 +19,14 @@ export function readFlowPreferences(userId: number | string, projectId: number,
|
||||
const raw = localStorage.getItem(key(userId, projectId, iterationId))
|
||||
if (!raw) return null
|
||||
const value: unknown = JSON.parse(raw)
|
||||
if (!value || typeof value !== 'object' || (value as { version?: unknown }).version !== VERSION) return null
|
||||
if (!value || typeof value !== 'object' || ![1, VERSION].includes(Number((value as { version?: unknown }).version))) return null
|
||||
const source = value as Partial<FlowPreferences>
|
||||
if (!Array.isArray(source.collapsedStages) || !source.positions || typeof source.positions !== 'object') return null
|
||||
const collapsedStages = source.collapsedStages.filter(id => Number.isSafeInteger(id) && id >= 0)
|
||||
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
|
||||
return { collapsedStages, positions, viewport }
|
||||
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 }
|
||||
} catch { return null }
|
||||
}
|
||||
|
||||
|
||||
@ -6,7 +6,7 @@
|
||||
<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 }">
|
||||
<div class="item-label" :title="row.label" @click="openRow(row)"><span v-if="row.item?.dependencyBlocked" class="blocked-dot" />{{ row.stage ? '◆ ' : row.item?.stageId || row.item?.parentTaskId ? '↳ ' : '' }}{{ row.label }} <small v-if="row.stage">v{{ row.stage.revisionNo || 1 }}</small></div>
|
||||
<div class="item-label" :style="{ paddingLeft: (8 + (row.depth || 0) * 16) + 'px' }" :title="row.label" @click="openRow(row)"><span v-if="row.item?.dependencyBlocked" class="blocked-dot" />{{ row.stage ? '◆ ' : row.item?.stageId || row.item?.parentTaskId ? '↳ ' : '' }}{{ row.label }} <small v-if="row.stage">v{{ row.stage.revisionNo || 1 }}</small></div>
|
||||
<div class="timeline" :style="{ width: days * unit + 'px' }">
|
||||
<div v-if="row.start && row.end" class="bar" :class="{ blocked: row.item?.dependencyBlocked, busy: pending.has(row.key), reference: row.reference, 'stage-bar': !!row.stage }" :style="barStyle(row)" @pointerdown="begin(row, $event, 'move')" @dblclick="openRow(row)">
|
||||
<span v-if="editable(row)" class="handle left" @pointerdown.stop="begin(row, $event, 'start')" />{{ row.reference ? (row.stage || row.item)?.scheduleReviewClosed ? '参考 · 本轮未确认' : '参考 · 待复核' : row.stage ? stageStatusNames[row.stage.executionStatus || 'NOT_STARTED'] : itemStatusLabel(row.item!) }}<span v-if="editable(row)" class="handle right" @pointerdown.stop="begin(row, $event, 'end')" />
|
||||
@ -32,22 +32,32 @@ import { api, errorText } from '../../api'
|
||||
import { moveSchedule } from '../../shared/utils/optimistic'
|
||||
import StageSchedulePanel from '../../features/schedules/components/StageSchedulePanel.vue'
|
||||
|
||||
interface TimelineRow { key: string; label: string; 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 }>(), { stages: () => [], memberFiltered: false })
|
||||
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 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 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))
|
||||
for (const stage of props.stages.filter(stage => !props.memberFiltered || props.items.some(item => item.stageId === stage.id))) {
|
||||
result.push(timelineRow('s:' + stage.id, stage.name, stage, true))
|
||||
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))
|
||||
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 {
|
||||
|
||||
@ -62,7 +62,7 @@
|
||||
label="阶段"
|
||||
width="150"
|
||||
>
|
||||
<template #default="{ row }">{{ stages.find(stage => stage.id === row.stageId)?.name || '未分配' }}
|
||||
<template #default="{ row }">{{ row.stagePath || stages.find(stage => stage.id === row.stageId)?.name || '未分配' }}
|
||||
<small
|
||||
v-if="row.stageId"
|
||||
class="muted"
|
||||
|
||||
@ -111,6 +111,7 @@
|
||||
:label="label"
|
||||
/>
|
||||
</el-select>
|
||||
<el-select v-model="stageFilter" size="small" clearable filterable placeholder="全部阶段 / 阶段组" style="width:210px"><el-option :value="0" label="未分配阶段" /><el-option v-for="stage in flowView?.stages || []" :key="stage.id" :value="stage.id" :label="(stage.stageKind === 'GROUP' ? '▣ ' : '') + (stage.stagePath || stage.name)" /></el-select>
|
||||
<el-switch
|
||||
v-model="blockedOnly"
|
||||
active-text="仅看依赖阻塞"
|
||||
@ -177,6 +178,7 @@
|
||||
:from="ganttFrom"
|
||||
:to="ganttTo"
|
||||
:member-filtered="ganttMemberIds.length > 0"
|
||||
:stage-filter="stageFilter"
|
||||
:can-write="canWrite"
|
||||
:can-manage="canWrite && current.canManage"
|
||||
:project-id="current.id"
|
||||
@ -219,6 +221,7 @@
|
||||
</template>
|
||||
</template>
|
||||
<ItemDetail
|
||||
:can-manage="!!current?.canManage"
|
||||
ref="itemDetail"
|
||||
:id="detailId"
|
||||
:project-id="projectId || undefined"
|
||||
@ -295,7 +298,7 @@ const emit = defineEmits<{ back: [] }>()
|
||||
const {
|
||||
projectId, iterations, iterationId, includeArchived,
|
||||
items, members, flowView, current, selectedIteration, zone, canWrite, canCreate, canExecute,
|
||||
loading, failure, tab, keyword, typeFilter, blockedOnly, detailId, refreshKey, selection,
|
||||
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,
|
||||
notifications, statCards, userStore,
|
||||
|
||||
Loading…
Reference in New Issue
Block a user