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

This commit is contained in:
lixiaolong 2026-11-03 09:22:40 +08:00
commit 204c2eba76
28 changed files with 1006 additions and 96 deletions

View File

@ -0,0 +1,40 @@
package com.ruoyi.project.manage.controller;
import com.ruoyi.project.manage.dto.TodoQuery;
import com.ruoyi.project.manage.service.IPmTodoService;
import java.util.Map;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import static com.ruoyi.project.manage.util.PmValues.map;
/** 我的待办只读入口;请求不接收用户身份,服务层统一执行鉴权。 */
@RestController
@RequestMapping("/project/manage")
public class PmTodoController {
private final IPmTodoService service;
/**
* 注入个人待办服务,控制层只适配请求及标准成功响应。
* @param service 包含用户资格、查询边界和可见性过滤的待办服务
*/
public PmTodoController(IPmTodoService service) {
this.service = service;
}
/**
* 返回当前用户跨项目的有效待办,分页和类型由服务严格校验。
* @param page 页码,默认第一页
* @param pageSize 每页条数,默认 20,最多 100
* @param kind 可选 WORK_ITEM 或 STAGE_APPROVAL
* @return 既有 code=200、data 包装下的分页内容;本接口没有业务写入副作用
*/
@GetMapping("/my-todos")
public Map<String, Object> page(@RequestParam(defaultValue = "1") int page,
@RequestParam(defaultValue = "20") int pageSize,
@RequestParam(required = false) String kind) {
return map("code", 200, "msg", "操作成功", "data", service.page(new TodoQuery(page, pageSize, kind)));
}
}

View File

@ -2,7 +2,7 @@ package com.ruoyi.project.manage.dto;
import java.util.List;
/** 视图查询白名单;分页仅限制返回内容,不缩小服务端依赖或排期校验的图。 */
/** 视图查询白名单;看板及甘特成员条件仅筛选返回内容,不能缩小服务端实际依赖或排期校验图。 */
public record ItemQuery(Integer page,Integer pageSize,String view,String keyword,String type,String status,Boolean blockedOnly,Long stageId,String from,String to,List<Long> memberIds) {
/** 既有内部查询省略成员条件时继续返回全部匹配项,不改变列表和看板的查询口径。 */
public ItemQuery(Integer page,Integer pageSize,String view,String keyword,String type,String status,Boolean blockedOnly,Long stageId,String from,String to){this(page,pageSize,view,keyword,type,status,blockedOnly,stageId,from,to,null);}

View File

@ -0,0 +1,4 @@
package com.ruoyi.project.manage.dto;
/** 我的待办仅接受分页与类型条件;用户身份始终由服务从当前登录态取得。 */
public record TodoQuery(int page, int pageSize, String kind) { }

View File

@ -0,0 +1,29 @@
package com.ruoyi.project.manage.mapper;
import com.ruoyi.project.manage.dto.TodoQuery;
import java.util.List;
import java.util.Map;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
/** 个人待办只读投影;工作项和阶段审批在数据库完成权限过滤及统一分页。 */
@Mapper
public interface PmTodoMapper {
/**
* 查询本人仍可访问的当前有效待办,使用 EXISTS 合并负责人和协作人身份以避免重复。
* @param userId 经 PmAccess 校验的登录用户,不能取自请求参数
* @param query 已校验的类型与分页条件
* @param offset 服务计算的分页偏移量
* @return 审批优先、截止时间及对象 ID 稳定排序的一页原始投影;时间仍为 UTC 微秒
*/
List<Map<String, Object>> selectPage(@Param("userId") long userId, @Param("query") TodoQuery query,
@Param("offset") int offset);
/**
* 复用分页查询的完整 UNION 与可见性条件计数,避免过滤后总数与列表口径不同。
* @param userId 当前有效登录用户
* @param query 与分页相同的筛选条件
* @return 两类去重后待办的总条数;不读取其它成员的待办内容
*/
long countVisible(@Param("userId") long userId, @Param("query") TodoQuery query);
}

View File

@ -16,6 +16,19 @@ public final class PmRules {
/** 工具类不持有数据库或用户上下文,所有判断基于传入的当前快照。 */
private PmRules() { }
/**
* 只按工作项当前负责人判断执行身份,协作、创建或项目管理身份不自动授予开始及完成权限。
* @param item 项目锁内读取的工作项;子任务独立使用自身负责人,不继承父任务身份
* @param actor 已完成项目成员和操作权限校验的认证用户
* @return 身份不满足的结构化原因;空列表表示本人负责,状态、前置和版本仍须另行校验
* 注意:此判断不改变 dependencyBlocked,参与筛选和具备执行权限是不同概念。
*/
public static List<Map<String,Object>> executionBlocked(Item item,long actor) {
if(Objects.equals(item.assigneeId(),actor)) return List.of();
return List.of(map("code","WORK_ITEM_ASSIGNEE_REQUIRED","taskId",item.id(),"assigneeId",item.assigneeId(),
"message",item.assigneeId()==null?"工作项尚未分配负责人,请先指定负责人":"只有工作项负责人可以开始或完成工作项"));
}
/** 所有类型的工作项共用完成规则;关闭保留完成事实,取消和软删除不满足前置。 */
public static boolean completed(Item item) { return !item.deleted() && Set.of("COMPLETED","CLOSED").contains(item.status()); }

View File

@ -116,7 +116,7 @@ public interface IPmService {
Map<String,Object> startability(long id);
/**
* 所有进入进行中的公共入口:先校验身份权限、状态、版本和工作项依赖,再原子保存状态/时间/历史/outbox。
* 所有进入进行中的公共入口:核对当前负责人、项目权限、版本和任务/阶段前置,再原子保存执行记录。
* @param id 要开始的工作项 ID
* @param input 用户当前看到的数据版本;缺失或过期时拒绝开始
* <p>副作用:唯一开始入口更新状态、实际开始时间、历史及 outbox;失败全部回滚。</p>
@ -124,7 +124,7 @@ public interface IPmService {
void start(long id,VersionInput input);
/**
* 状态修改委托统一开始;完成检查子终态,关闭/重开保留完成时间,回退保护全部已开始后续和父任务。
* 状态修改委托统一开始;进入已完成同样须当前负责人,仍检查子终态并保护全部已开始后续和父任务。
*
* @param id 路径中的目标对象 ID;服务按当前身份校验维护或查看权限
* @param input 仅包含接口允许字段的请求对象;身份、版本及关联由对应业务入口复验

View File

@ -0,0 +1,14 @@
package com.ruoyi.project.manage.service;
import com.ruoyi.project.manage.dto.TodoQuery;
import java.util.Map;
/** 当前用户跨项目待办查询,不包含执行或审批写入能力。 */
public interface IPmTodoService {
/**
* 返回当前登录用户相关、仍有项目读取资格的未完成工作项及待本人审批的阶段申请。
* @param query 分页与可选待办类型,不允许指定操作人
* @return rows、total、page 和 pageSize;空对象 ID 和未排期时间显式为 null
*/
Map<String, Object> page(TodoQuery query);
}

View File

@ -117,16 +117,17 @@ public class PmServiceImpl implements IPmService {
auditService.record(projectId,null,remove?"MEMBER_REMOVED":"MEMBER_CHANGED",map("userId",input.userId(),"role",input.role()),access.actor());
}
/** 列表在锁内只计算一次项目写资格,避免逐项查询成员;状态与任务/阶段阻塞分别返回。 */
/** 列表复用一次锁内身份和项目写资格,逐项计算本人执行能力,不为负责人比较重复查询用户。 */
public List<Map<String,Object>> items(long projectId,long iterationId) {
locked(projectId,iterationId,"read"); Graph graph=graphService.load(projectId,iterationId); String zone=zone(projectId); boolean writable=access.canWrite(projectId);
return graph.items().values().stream().filter(i->!i.deleted()).map(i->view(graph,i,zone,writable)).toList();
long actor=access.actor();
return graph.items().values().stream().filter(i->!i.deleted()).map(i->view(graph,i,zone,writable,actor)).toList();
}
/** 详情实时计算项目操作和附件删除资格;仅工作项负责人或创建者可删除,历史与冻结范围仍只读。 */
/** 详情按当前身份计算负责人执行能力和既有附件删除资格;历史与冻结范围仍只读。 */
public Map<String,Object> detail(long id) {
long projectId=projectOf(id),iterationId=iterationOf(id); locked(projectId,iterationId,"read"); Graph graph=graphService.load(projectId,iterationId);
boolean writable=access.canWrite(projectId);
boolean writable=access.canWrite(projectId); long actor=access.actor();
Item current=graph.items().get(id);
Map<String,Object> result;
if(current==null) {
@ -137,10 +138,10 @@ public class PmServiceImpl implements IPmService {
Item old=historicalItem(projectId,saved); oldItems.put(old.id(),old.withCollaborators(historicalParticipants.getOrDefault(old.id(),List.of())));
}
Graph oldGraph=new Graph(oldItems,new ArrayList<>(),new LinkedHashMap<>(),new ArrayList<>(),new LinkedHashMap<>(),graph.iteration()); Item historical=item(oldGraph,id);
result=view(oldGraph,historical,zone(projectId),false);
result=view(oldGraph,historical,zone(projectId),false,actor);
result.put("stageRevisionNo",(int)number(row,"stage_revision_no"));
result.put("stageNameSnapshot",text(row,"stage_name_snapshot"));
result.put("historicalChildren",PmRules.children(oldGraph,id).stream().map(child->{ Map<String,Object> childView=view(oldGraph,child,zone(projectId),false); childView.put("historical",true); childView.put("canStart",false); return childView; }).toList());
result.put("historicalChildren",PmRules.children(oldGraph,id).stream().map(child->{ Map<String,Object> childView=view(oldGraph,child,zone(projectId),false,actor); childView.put("historical",true); childView.put("canStart",false); return childView; }).toList());
List<Map<String,Object>> originalConditions=new ArrayList<>();
for(Map<String,Object> dependency:dependencyMapper.selectItemDependencies(projectId,id)) {
boolean available=!flag(dependency,"source_deleted"); String status=text(dependency,"source_status");
@ -152,7 +153,7 @@ public class PmServiceImpl implements IPmService {
}
result.put("dependencyConditions",originalConditions);
result.putAll(map("historical",true,"canStart",false,"canComplete",false,"canCreateChild",false,"blockedReasons",List.of(map("code","HISTORICAL_WORK_ITEM","message","历史版本只读"))));
} else result=view(graph,item(graph,id),zone(projectId),writable);
} else result=view(graph,item(graph,id),zone(projectId),writable,actor);
result.put("comments",auditTimes(activityMapper.selectComments(id),zone(projectId)));
result.put("attachments",activityMapper.selectAttachments(id));
result.put("canDeleteAttachments",canDeleteAttachments(graph,id,writable));
@ -221,11 +222,12 @@ public class PmServiceImpl implements IPmService {
/**
* 在父项目鉴权后返回有效子任务,详情和外部客户端复用实时业务摘要。
* @param id 有权限访问的父工作项 ID,不接受跨项目来源
* @return 未软删除子任务的当前状态、门禁及排期;无子任务返回空列表,不产生业务历史
* @return 未软删除子任务的状态、排期和按各自负责人计算的能力;不继承父项执行权限
*/
public List<Map<String,Object>> children(long id) {
long projectId=projectOf(id),iterationId=iterationOf(id); locked(projectId,iterationId,"read"); Graph graph=graphService.load(projectId,iterationId); item(graph,id); boolean writable=access.canWrite(projectId);
return PmRules.children(graph,id).stream().map(i->view(graph,i,zone(projectId),writable)).toList();
long actor=access.actor();
return PmRules.children(graph,id).stream().map(i->view(graph,i,zone(projectId),writable,actor)).toList();
}
/** 普通编辑原子更新分工、字段及本次通知选择;省略协作人则保留,邮件选择省略则不发。 */
@ -290,14 +292,14 @@ public class PmServiceImpl implements IPmService {
for(Item child:PmRules.children(graph,parent.id())) graph.items().put(child.id(),child.inStage(stageId));
}
/** 返回后端实时可开始判断;与提交校验使用同一实际条件函数。 */
/** 返回锁内负责人、迭代及前置的实时可开始结果,不能用看板成员筛选推断执行资格。 */
public Map<String,Object> startability(long id) {
long projectId=projectOf(id),iterationId=iterationOf(id); locked(projectId,iterationId,"read"); Graph graph=graphService.load(projectId,iterationId);
return startability(graph,item(graph,id),zone(projectId),access.canWrite(projectId));
return startability(graph,item(graph,id),zone(projectId),access.canWrite(projectId),access.actor());
}
/**
* 所有进入进行中的公共入口:先校验身份权限、状态、版本和任务/阶段前置,再原子保存状态/时间/历史/outbox。
* 所有进入进行中的公共入口:项目锁内校验当前负责人、状态、版本及任务/阶段前置,原子保存执行记录。
* @param id 要开始的工作项 ID
* @param input 用户当前看到的数据版本;缺失或过期时拒绝开始
*/
@ -306,11 +308,12 @@ public class PmServiceImpl implements IPmService {
performStart(graph,writableItem(graph,id),input.version(),zone(projectId));
}
/** 状态修改委托统一开始;完成检查子终态,关闭/重开保留完成时间,回退保护全部已开始后续和父任务。 */
/** 进入进行中或已完成均须当前负责人;完成仍检查子终态,关闭保留实际时间,其他状态维持既有门禁。 */
public void transition(long id,TransitionInput input) {
long projectId=projectOf(id),iterationId=iterationOf(id); locked(projectId,iterationId,"write"); Graph graph=graphService.load(projectId,iterationId); Item existing=writableItem(graph,id);
if("IN_PROGRESS".equals(input.status())) { performStart(graph,existing,input.version(),zone(projectId)); return; }
version(input.version(),existing.version());
if("COMPLETED".equals(input.status())) requireExecutionAssignee(existing);
if(input.status()==null || existing.status().equals(input.status())) throw PmException.bad("目标状态无效");
boolean allowed="READY".equals(input.status())&&!"CLOSED".equals(existing.status()) || "COMPLETED".equals(input.status())&&Set.of("IN_PROGRESS","CLOSED").contains(existing.status()) || "CLOSED".equals(input.status())&&"COMPLETED".equals(existing.status()) || "CANCELLED".equals(input.status())&&Set.of("READY","IN_PROGRESS").contains(existing.status());
if(!allowed) throw PmException.conflict("INVALID_TRANSITION","当前状态不允许此转换");
@ -411,13 +414,14 @@ public class PmServiceImpl implements IPmService {
/** 混合批量与单项时间修改共用一个事务入口,不按对象逐次提交。 */
public void scheduleBatch(long projectId,long iterationId,com.ruoyi.project.manage.dto.BatchInput input) { schedules.schedule(projectId,iterationId,input); }
/** 后续任务只返回当前有效依赖,整批摘要共享锁内计算的项目写资格。 */
/** 后续任务只返回当前有效依赖;批量共享锁内身份,各自负责人决定执行能力。 */
public List<Map<String,Object>> successors(long id) {
long projectId=projectOf(id),iterationId=iterationOf(id); locked(projectId,iterationId,"read"); Graph graph=graphService.load(projectId,iterationId); item(graph,id);
Set<Long> targets=new LinkedHashSet<>();
for(Dependency d:graph.dependencies()) if(Objects.equals(d.taskId(),id)) targets.add(d.successorId());
String zone=zone(projectId); boolean writable=access.canWrite(projectId);
return targets.stream().map(graph.items()::get).filter(i->!i.deleted()).map(i->view(graph,i,zone,writable)).toList();
long actor=access.actor();
return targets.stream().map(graph.items()::get).filter(i->!i.deleted()).map(i->view(graph,i,zone,writable,actor)).toList();
}
/** 待审批仍允许讨论,但历史、已完成阶段和终态迭代继续只读;评论不改写交付证据。 */
@ -496,7 +500,7 @@ public class PmServiceImpl implements IPmService {
}
/**
* 按视图限定返回行;列表以父项为分页单位,甘特成员按负责或协作取并集后计数、分页。
* 按视图限定返回行;列表以父项分页,看板及甘特成员按负责或协作取并集后计数、分页。
* @param query 白名单查询;成员和时间窗口只影响返回内容,所有业务约束仍以完整迭代图计算
* @return 当前页、真实总数、各状态计数和当前图版本,不向其他迭代扩展候选
*/
@ -510,7 +514,7 @@ public class PmServiceImpl implements IPmService {
if(memberId==null||memberId<=0) throw PmException.bad("成员筛选必须使用有效的正整数用户ID");
memberIds.add(memberId);
}
if(!memberIds.isEmpty()&&!"gantt".equals(mode)) throw PmException.bad("成员筛选仅适用于甘特排期");
if(!memberIds.isEmpty()&&!Set.of("gantt","board").contains(mode)) throw PmException.bad("成员筛选仅适用于看板和甘特排期");
if(query.type()!=null&&!query.type().isBlank()&&!Set.of("TASK","REQUIREMENT","BUG").contains(query.type())) throw PmException.bad("工作项类型无效");
if(query.status()!=null&&!query.status().isBlank()&&!Set.of("READY","IN_PROGRESS","COMPLETED","CANCELLED","CLOSED").contains(query.status())) throw PmException.bad("工作项状态无效");
Long from=PmTime.parse(query.from()),to=PmTime.parse(query.to());
@ -585,11 +589,12 @@ public class PmServiceImpl implements IPmService {
return result;
}
/** 在锁内复验任务和分类阶段门禁,启动记录保存来源版本事实;实际执行仍不等待预计开始日期。 */
/** 在锁内复验负责人及实际前置,启动记录保存来源版本事实;预计开始日期仍不作为实际执行门禁。 */
private void performStart(Graph graph,Item item,Integer requestedVersion,String zone) {
if(graph.iteration()==null||!graph.iteration().active()) throw PmException.conflict("ITERATION_NOT_ACTIVE","迭代尚未开始或已结束,不能执行工作项");
if(!"READY".equals(item.status())) throw PmException.conflict("INVALID_TASK_STATUS","只有待开始工作项可以开始");
version(requestedVersion,item.version());
requireExecutionAssignee(item);
List<Map<String,Object>> reasons=new ArrayList<>(PmRules.blocked(graph,item.id(),zone));
reasons.addAll(PmStageRules.blocked(graph,item.id()));
if(!reasons.isEmpty()) throw new PmException(409,"DEPENDENCY_NOT_SATISFIED","任务暂时无法开始",map("blockedReasons",reasons));
@ -599,20 +604,40 @@ public class PmServiceImpl implements IPmService {
syncStage(item.projectId(),graph.iteration().id(),item.stageId(),PmStageRules.executionStatus(graph,item.stageId()==null?-1:item.stageId()));
}
/** 可开始摘要与实际开始共用门禁,同时返回完整来源版本事实供详情展示,避免前端自行遗漏父组条件。 */
private Map<String,Object> startability(Graph graph,Item item,String zone,boolean writable) {
/**
* 统一显示负责人、生命周期、冻结及前置条件;这些能力来自完整图而非分页或成员筛选。
* @param graph 当前迭代完整快照
* @param item 待显示工作项,包括各自独立负责的子任务
* @param zone 统一展示时区
* @param writable 当前项目写资格,历史摘要显式传 false
* @param actor 已验证身份,列表复用同一值避免 N+1 查询
* @return 可开始能力和具体原因,不产生任何状态或历史写入
*/
private Map<String,Object> startability(Graph graph,Item item,String zone,boolean writable,long actor) {
List<Map<String,Object>> reasons=new ArrayList<>();
if(graph.iteration()==null||!graph.iteration().active()) reasons.add(map("code","ITERATION_NOT_ACTIVE","message","迭代尚未开始或已结束"));
if(!writable) reasons.add(map("code","FORBIDDEN","message","没有工作项维护权限"));
reasons.addAll(PmRules.executionBlocked(item,actor));
if(!"READY".equals(item.status())) reasons.add(map("code","INVALID_TASK_STATUS","message","当前不是待开始状态"));
var revision=item.stageId()==null?null:graph.stageRevisions().get(item.stageId());
if(revision!=null&&"PENDING".equals(revision.approvalStatus())) reasons.add(map("code","STAGE_APPROVAL_PENDING","message","阶段正在审批,工作项交付已冻结"));
if(item.stageId()!=null&&Set.of("COMPLETED","LEGACY_PASSED").contains(PmStageRules.executionStatus(graph,item.stageId()))) reasons.add(map("code","STAGE_REVISION_FROZEN","message","阶段已完成,工作项只读"));
reasons.addAll(PmRules.blocked(graph,item.id(),zone));
List<Map<String,Object>> stageReasons=PmStageRules.blocked(graph,item.id()); reasons.addAll(stageReasons);
return map("canStart",reasons.isEmpty(),"blockedReasons",reasons,"stageBlockedReasons",stageReasons,"dependencyConditions",PmRules.conditions(graph,item.id(),zone),
"stageAdmissionConditions",item.stageId()==null?List.of():PmStageRules.conditions(graph,item.stageId()));
}
/** 工作项摘要复用调用者统一计算的项目写资格;生命周期、实际阻塞与排期校验分别表达。 */
private Map<String,Object> view(Graph graph,Item item,String zone,boolean writable) {
/**
* 按当前负责人返回执行能力,项目可写仍不代表可以替其他成员开始或完成工作项。
* @param graph 已鉴权的完整迭代快照
* @param item 当前行或明确只读的历史工作项
* @param zone 展示时区
* @param writable 当前项目写资格;不能用于绕过负责人或历史冻结条件
* @param actor 本批摘要共享的认证用户
* @return 状态、能力、身份原因及前置/排期摘要;身份原因不计为依赖阻塞
*/
private Map<String,Object> view(Graph graph,Item item,String zone,boolean writable,long actor) {
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()));
@ -621,15 +646,29 @@ public class PmServiceImpl implements IPmService {
boolean mutable=graph.iteration()!=null&&graph.iteration().mutable();
var stageRevision=item.stageId()==null?null:graph.stageRevisions().get(item.stageId());
boolean frozen=stageRevision!=null&&("PENDING".equals(stageRevision.approvalStatus())||Set.of("COMPLETED","LEGACY_PASSED").contains(PmStageRules.executionStatus(graph,item.stageId())));
List<Map<String,Object>> executionReasons=PmRules.executionBlocked(item,actor);
boolean executable=writable&&mutable&&!frozen&&executionReasons.isEmpty();
response.put("canExecuteWorkItem",executable);
response.put("stageApprovalStatus",stageRevision==null?null:stageRevision.approvalStatus());response.put("stageReadOnly",frozen);
response.putAll(map("iterationId",graph.iteration()==null?null:graph.iteration().id(),"iterationStatus",graph.iteration()==null?null:graph.iteration().status(),"iterationReadOnly",!mutable));
Item parent=item.parentTaskId()==null?null:graph.items().get(item.parentTaskId());
List<Item> children=PmRules.children(graph,item.id()); List<Map<String,Object>> unfinished=PmRules.unfinishedChildren(graph,item.id());
List<Map<String,Object>> completionReasons=new ArrayList<>(executionReasons); completionReasons.addAll(unfinished);
boolean overdue=PmRules.overdue(item,PmTime.now());
response.putAll(map("parentTaskId",item.parentTaskId(),"parentTaskTitle",parent==null?null:parent.title(),"parentPlannedStartAt",parent==null?null:PmTime.format(parent.start(),zone),"parentPlannedEndAt",parent==null?null:PmTime.format(parent.end(),zone),"childCount",children.size(),"childTerminalCount",children.stream().filter(PmRules::terminal).count(),"canCreateChild",writable&&"TASK".equals(item.type())&&item.parentTaskId()==null&&!PmRules.terminal(item),"canComplete",writable&&"IN_PROGRESS".equals(item.status())&&unfinished.isEmpty(),"completionBlockedReasons",unfinished,"overdue",overdue,"displayStatus",overdue?"OVERDUE":item.status()));
response.putAll(map("parentTaskId",item.parentTaskId(),"parentTaskTitle",parent==null?null:parent.title(),"parentPlannedStartAt",parent==null?null:PmTime.format(parent.start(),zone),"parentPlannedEndAt",parent==null?null:PmTime.format(parent.end(),zone),"childCount",children.size(),"childTerminalCount",children.stream().filter(PmRules::terminal).count(),"canCreateChild",writable&&"TASK".equals(item.type())&&item.parentTaskId()==null&&!PmRules.terminal(item),"canComplete",executable&&"IN_PROGRESS".equals(item.status())&&unfinished.isEmpty(),"completionBlockedReasons",completionReasons,"overdue",overdue,"displayStatus",overdue?"OVERDUE":item.status()));
response.put("stageId",item.stageId()); response.put("stageRevisionId",item.stageRevisionId()); response.put("stageRevisionNo",item.stageId()==null?null:graph.stageRevisions().get(item.stageId())==null?null:graph.stageRevisions().get(item.stageId()).revisionNo()); response.put("originWorkItemId",item.originWorkItemId()); response.put("scheduleReviewRequired",item.scheduleReviewReworkId()!=null); response.put("scheduleReviewClosed",item.scheduleReviewReworkId()!=null&&(!mutable||PmRules.completed(item)||item.stageId()!=null&&Set.of("COMPLETED","LEGACY_PASSED").contains(PmStageRules.executionStatus(graph,item.stageId())))); response.put("referencePlannedStartAt",PmTime.format(item.referenceStart(),zone)); response.put("referencePlannedEndAt",PmTime.format(item.referenceEnd(),zone));
if(!mutable||frozen) { response.put("canCreateChild",false); response.put("canComplete",false); }
response.putAll(startability(graph,item,zone,writable)); response.put("dependencyBlocked",!PmRules.blocked(graph,item.id(),zone).isEmpty()||!PmStageRules.blocked(graph,item.id()).isEmpty()); response.put("scheduleConstraints",PmRules.schedule(graph,item,zone)); return response;
response.putAll(startability(graph,item,zone,writable,actor)); response.put("dependencyBlocked",!PmRules.blocked(graph,item.id(),zone).isEmpty()||!PmStageRules.blocked(graph,item.id()).isEmpty()); response.put("scheduleConstraints",PmRules.schedule(graph,item,zone)); return response;
}
/**
* 在项目锁覆盖的真实命令中核验当前负责人,防止直接状态 API、管理者代办或过期改派绕过界面。
* @param item 获取锁后重新加载的工作项,不能使用客户端传来的负责人 ID
* @throws PmException 非当前负责人或未分配时返回 403;在任何业务写入和成功历史前中止
*/
private void requireExecutionAssignee(Item item) {
List<Map<String,Object>> reasons=PmRules.executionBlocked(item,access.actor());
if(!reasons.isEmpty()) throw new PmException(403,"WORK_ITEM_ASSIGNEE_REQUIRED",text(reasons.get(0),"message"),map("blockedReasons",reasons));
}
/** 先鉴权再锁图,取得锁后重新验证成员资格,防止与撤权同时操作。 */

View File

@ -0,0 +1,70 @@
package com.ruoyi.project.manage.service.impl;
import com.ruoyi.project.manage.dto.TodoQuery;
import com.ruoyi.project.manage.exception.PmException;
import com.ruoyi.project.manage.mapper.PmTodoMapper;
import com.ruoyi.project.manage.security.PmAccess;
import com.ruoyi.project.manage.service.IPmTodoService;
import com.ruoyi.project.manage.util.PmTime;
import java.util.Map;
import java.util.Set;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;
import static com.ruoyi.project.manage.util.PmValues.map;
/** 个人待办只读服务;统一身份、分页边界与时间表达,不扩大既有项目成员权限。 */
@Service
@Transactional(readOnly = true, isolation = Isolation.REPEATABLE_READ)
public class PmTodoServiceImpl implements IPmTodoService {
private final PmTodoMapper mapper;
private final PmAccess access;
/**
* 注入只读 Mapper 和现有鉴权组件,使内部调用也必须通过菜单及有效用户校验。
* @param mapper 两类待办共享的数据库过滤查询
* @param access 当前登录用户及项目菜单权限的统一入口
*/
public PmTodoServiceImpl(PmTodoMapper mapper, PmAccess access) {
this.mapper = mapper;
this.access = access;
}
/**
* 校验输入后按登录用户查询待办;同一只读快照中读取列表和总数,避免并发状态变化造成口径分裂。
* @param query page 为 1..100000,pageSize 为 1..100,kind 可省略
* @return 带北京时间 ISO 截止时间及实时超期标记的分页结果
* @throws PmException 无读取资格或分页、类型无效时拒绝;不写入任何业务数据
*/
@Override
public Map<String, Object> page(TodoQuery query) {
access.permission("read");
if (query == null || query.page() < 1 || query.page() > 100000
|| query.pageSize() < 1 || query.pageSize() > 100) {
throw PmException.bad("分页范围无效");
}
if (query.kind() != null && !Set.of("WORK_ITEM", "STAGE_APPROVAL").contains(query.kind())) {
throw PmException.bad("待办类型无效");
}
long actor = access.actor();
long now = PmTime.now();
var rows = mapper.selectPage(actor, query, (query.page() - 1) * query.pageSize());
for (Map<String, Object> row : rows) decorate(row, now);
return map("rows", rows, "total", mapper.countVisible(actor, query),
"page", query.page(), "pageSize", query.pageSize());
}
/**
* 将数据库投影规范为稳定的接口字段,所有行共享一次取样的当前时间。
* @param row 当前页单行;仅修改查询结果,不修改持久化对象
* @param now 本次请求的 UTC 微秒时间,截止时刻相等时尚不算超期
*/
private static void decorate(Map<String, Object> row, long now) {
Long end = row.get("plannedEndAt") instanceof Number value ? value.longValue() : null;
row.put("overdue", end != null && end < now);
row.put("plannedEndAt", PmTime.format(end, "Asia/Shanghai"));
// MyBatis 默认省略 SQL NULL;接口显式保留空 ID,调用方才能可靠区分两类定位目标。
for (String field : new String[]{"workItemId", "stageId", "approvalId"}) row.putIfAbsent(field, null);
}
}

View File

@ -0,0 +1,62 @@
<?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.PmTodoMapper">
<!-- 成员表存原项目 ID;不可改成 e.id,否则可能把同数字的其它项目成员误认为本项目成员。管理员也走相同数据过滤。 -->
<sql id="visibleProject">
p.del_flag='0' AND (p.creator_user_id=#{userId} OR EXISTS(
SELECT 1 FROM pm_collab_project_member m WHERE m.project_id=p.id AND m.user_id=#{userId}
))
</sql>
<!-- UNION ALL 的两个分支类别互斥;工作项身份通过 EXISTS 合并,避免负责人兼协作人时重复计数。 -->
<sql id="visibleTodos">
SELECT CONCAT('WORK_ITEM:',w.id) AS `key`,'WORK_ITEM' AS kind,
p.id AS sourceProjectId,e.id AS projectId,p.project_code AS projectCode,p.project_name AS projectName,
i.id AS iterationId,i.name AS iterationName,w.id AS workItemId,w.stage_id AS stageId,
NULL AS approvalId,w.title,w.status,w.planned_end_at AS plannedEndAt,
CASE WHEN w.assignee_id=#{userId} THEN 'ASSIGNEE' ELSE 'COLLABORATOR' END AS myRole
FROM pm_collab_work_item w
JOIN pm_collab_project e ON e.id=w.project_id
JOIN project_info p ON p.id=e.source_project_id
JOIN pm_collab_iteration i ON i.project_id=w.project_id AND i.id=w.iteration_id
LEFT JOIN pm_collab_project_stage s ON s.project_id=w.project_id AND s.iteration_id=w.iteration_id AND s.id=w.stage_id
LEFT JOIN pm_collab_stage_revision r ON r.project_id=w.project_id AND r.iteration_id=w.iteration_id
AND r.stage_id=w.stage_id AND r.id=w.stage_revision_id
WHERE <include refid="visibleProject"/>
AND w.deleted=false AND w.status IN ('READY','IN_PROGRESS')
AND (w.assignee_id=#{userId} OR EXISTS(
SELECT 1 FROM pm_collab_work_item_collaborator c WHERE c.project_id=w.project_id
AND c.iteration_id=w.iteration_id AND c.work_item_id=w.id AND c.user_id=#{userId}
))
AND i.deleted=false AND i.archived_at IS NULL AND i.status IN ('PLANNED','ACTIVE')
AND ((w.stage_id IS NULL AND w.stage_revision_id IS NULL) OR
(s.deleted=false AND s.current_revision_id=r.id AND r.superseded_at IS NULL AND r.completed_at IS NULL))
<if test="query.kind != null">AND #{query.kind}='WORK_ITEM'</if>
UNION ALL
SELECT CONCAT('STAGE_APPROVAL:',a.id) AS `key`,'STAGE_APPROVAL' AS kind,
p.id AS sourceProjectId,e.id AS projectId,p.project_code AS projectCode,p.project_name AS projectName,
i.id AS iterationId,i.name AS iterationName,NULL AS workItemId,s.id AS stageId,
a.id AS approvalId,s.name AS title,a.status,r.planned_end_at AS plannedEndAt,'APPROVER' AS myRole
FROM pm_collab_stage_approval a
JOIN pm_collab_project e ON e.id=a.project_id
JOIN project_info p ON p.id=e.source_project_id
JOIN pm_collab_iteration i ON i.project_id=a.project_id AND i.id=a.iteration_id
JOIN pm_collab_project_stage s ON s.project_id=a.project_id AND s.iteration_id=a.iteration_id AND s.id=a.stage_id
JOIN pm_collab_stage_revision r ON r.project_id=a.project_id AND r.iteration_id=a.iteration_id
AND r.stage_id=a.stage_id AND r.id=a.revision_id AND s.current_revision_id=r.id
WHERE <include refid="visibleProject"/>
AND a.status='PENDING' AND a.approver_id=#{userId}
AND i.deleted=false AND i.archived_at IS NULL AND i.status='ACTIVE'
AND s.deleted=false AND r.superseded_at IS NULL AND r.completed_at IS NULL AND r.approval_status='PENDING'
<if test="query.kind != null">AND #{query.kind}='STAGE_APPROVAL'</if>
</sql>
<select id="selectPage" resultType="java.util.LinkedHashMap">
SELECT t.* FROM (<include refid="visibleTodos"/>) t
ORDER BY (t.kind='STAGE_APPROVAL') DESC,(t.plannedEndAt IS NULL),t.plannedEndAt,
t.projectId,t.iterationId,t.stageId,t.workItemId,t.approvalId
LIMIT #{query.pageSize} OFFSET #{offset}
</select>
<select id="countVisible" resultType="long">
SELECT COUNT(*) FROM (<include refid="visibleTodos"/>) t
</select>
</mapper>

View File

@ -64,6 +64,7 @@ manage/
- 已完成 023 的数据库执行 `ruoyi-project/sql/upgrade/024_custom_stage_node.sql` 开放自定义类型;该升级只扩展类型约束及中文字段注释,不转换历史节点分类。
- 项目管理者可通过节点名称后的编辑图标快捷改名,接口只接收名称和阶段版本;审批中或已完成版本仍只读。节点右上角删除图标与阶段管理表共用保护条件,已有执行历史、工作项、子阶段、交付附件或采购批次时禁用并说明原因,后端仍持锁复验后软删除。
- 新建和编辑工作项可从项目成员中多选协作人,负责人仍为单选。协作分工不改变项目角色或访问权限,历史版本保留原分工;回退复制仅继承仍有效的成员,并在预览中说明移除项。
- 工作项及子任务仅当前负责人可以开始或进入已完成;未分配负责人、创建者、协作人和项目管理者身份均不额外授予执行资格。关闭后重开到已完成同样受此限制,其余编辑、排期、关闭、取消及回退规则保持原样。看板和详情使用服务端执行能力,服务端在项目锁内重新验证身份及完整准入条件。
- 新建工作项可选多个同迭代前置工作项,需求、任务、缺陷均可作为依赖两端。所有前置已完成或已关闭才满足条件,取消不满足;编辑依赖仍使用详情中的专用入口。
- 依赖、工作项和协作分工在同一项目锁事务中保存,继续共用实际开始、排期及混合执行图环检测。新建表单排期提示由后端约束预览计算,提交时重新验证。
- 已有数据库先完成 `ruoyi-project/sql/upgrade/016_work_item_collaboration.sql` 增量升级;该文件新增协作人关联表并兼容新旧依赖标识,保留已有工作项与排期。全新环境使用 `ruoyi-project/sql/project_collaboration.sql`。
@ -74,11 +75,19 @@ manage/
- 筹备迭代由管理者手动开始并记录实际开始时间;执行中由管理者预览、确认结束并记录实际结束时间,不根据预计日期自动切换状态。待开始或进行中的工作项阻止结束,取消工作项或未审批阶段须逐条确认异常并说明原因后才能带异常结束。
- 删除沿用软删除:项目管理者可删除从未执行且没有任何工作项或执行历史的筹备迭代;已结束迭代(正常完成或带异常结束)只允许迭代创建者删除,可保留已有工作项和执行记录。创建者仍须是有效项目成员,其他管理者不能代删;归档须先取消归档,执行中及已取消迭代不可删除。后端返回 `canDelete`、`deleteBlockedReason`,在项目锁内复验身份和版本,仅隐藏迭代,阶段、工作项、附件、审计及幂等记录均保留。
## 甘特成员筛选
## 看板与甘特成员筛选
- 甘特排期的成员下拉支持多选当前项目成员;清空表示全部,多选按负责人或协作人任一匹配取并集,同一工作项只显示一次。
- 看板与甘特排期的成员下拉支持多选当前项目成员;清空表示全部,多选按负责人或协作人任一匹配取并集,同一工作项只显示一次。
- 后端在当前项目、迭代鉴权后,先组合成员、标题、类型和时间窗口条件,再计算总数和分页。未排期工作项继续保留查看入口,完整依赖与排期校验不受筛选影响。
- 成员选择仅影响甘特视图,切换迭代会清空;筛选时保留命中项所属阶段作为上下文。成员条件使用现有分工字段,无需数据库结构升级。
- 看板与甘特分别保存成员选择,普通列表和前置工作项候选不受影响;切换项目或迭代会清空,失效成员自动移除。看板五列计数、加载更多和静默刷新共用当前成员条件,条件改变后从第一页读取并丢弃旧响应;甘特筛选保留命中项所属阶段作为上下文。成员条件使用现有分工字段,无需数据库结构升级。
## 我的代办
- 外部项目表格右上角的“我的代办”汇总本人负责或协作的待开始、进行中工作项(含超期未完成),以及待本人审批的阶段完成申请;支持类别筛选、分页和刷新。
- 数据从现有表实时查询,项目成员按原项目 ID 匹配;仅返回未删除项目、未删除且未归档的有效迭代及阶段当前版本。终态工作项、历史版本、已结束或取消的迭代不进入待办,负责人兼协作人只计一次。采购待确认不虚构为审批申请。
- 点击工作项进入其项目、迭代的看板,临时置顶和高亮目标并打开详情,首批分页以外的工作项同样能定位;关闭详情保留定位,主动修改看板筛选取消临时置顶,分页及状态列计数仍由正常查询决定。
- 点击阶段审批进入流程视图,复核原申请仍是本人待审申请后展开父阶段组并打开对应阶段。失效、换版、撤权或已处理目标明确提示,不误开另一条审批;读取临时失败后可用页面“刷新”重试原链接。
- 新增代码分别位于 `features/todos`、`composables/useMyTodos.ts`、`composables/useWorkspaceTarget.ts`、`api/todos.ts` 和 `types/todo.ts`;后端使用 `/project/manage/my-todos` 的 Controller、Service、Mapper 分层,无需数据库升级。实施及实际验证见 [我的待办实施记录](docs/my-todos-implementation.md)。
## 检查命令

View File

@ -6,6 +6,7 @@ import { stageApi } from './stages'
import { stageCompletionApi } from './stage-completion'
import { scheduleApi } from './schedules'
import { notificationApi } from './notifications'
import { todoApi } from './todos'
// 对上层保留统一入口,具体请求按业务归属维护;客户端、鉴权与错误处理只实现一次。
export const api = {
@ -17,6 +18,7 @@ export const api = {
...stageCompletionApi,
...scheduleApi,
...notificationApi,
...todoApi,
}
export { PmApiError, errorText, isAccessFailure } from './errors'

View File

@ -0,0 +1,15 @@
import { request } from './client'
import type { MyTodoPage, MyTodoQuery } from '../types'
export const todoApi = {
/**
* 分页读取当前会话的待办;服务端统一判断成员资格、分工和当前执行版本。
* @param query 页码、每页数量和可选类别,不接受客户端用户身份
* @returns 权限过滤后的待办快照和总数,不修改工作项或审批状态
*/
myTodos: (query: MyTodoQuery) => {
const params = new URLSearchParams({ page: String(query.page), pageSize: String(query.pageSize) })
if (query.kind) params.set('kind', query.kind)
return request<MyTodoPage>('get', `/my-todos?${params}`)
},
}

View File

@ -0,0 +1,85 @@
import { onBeforeUnmount, reactive, ref, watch, type Ref } from 'vue'
import { api, errorText } from '../api'
import type { MyTodo, MyTodoKind, MyTodoQuery } from '../types'
/**
* 协调待办抽屉的服务端筛选和分页,仅在目录及抽屉同时可见时查询。
* @param active 目录是否为当前活动页面
* @param visible 抽屉是否打开;关闭、离开目录和卸载都会使在途结果失效
* @returns 待办快照、加载状态及筛选分页动作,不缓存跨项目的工作区详情
*/
export function useMyTodos(active: Ref<boolean>, visible: Ref<boolean>) {
const query = reactive<MyTodoQuery>({ page: 1, pageSize: 20 })
const rows = ref<MyTodo[]>([]), total = ref(0), loading = ref(false), failure = ref('')
let sequence = 0
/** 递增请求代次并清理展示快照,避免关闭后重新打开时短暂出现旧待办。 */
function invalidate() {
sequence++
rows.value = []
total.value = 0
loading.value = false
failure.value = ''
}
/**
* 使用独立查询快照加载当前页;只接受最新且仍可见的请求结果。
* 总数因权限或业务状态变化而缩小时自动重查最后一页,避免停留在失效空页。
* @returns 请求处理完成;失败信息交给抽屉展示,不向组件事件处理器抛出
*/
async function load() {
if (!active.value || !visible.value) return
const request = ++sequence
const snapshot = { ...query }
loading.value = true
failure.value = ''
try {
const result = await api.myTodos(snapshot)
if (request !== sequence || !active.value || !visible.value) return
const lastPage = Math.max(1, Math.ceil(result.total / snapshot.pageSize))
if (snapshot.page > lastPage) {
query.page = lastPage
await load()
return
}
rows.value = result.rows
total.value = result.total
} catch (error) {
if (request !== sequence || !active.value || !visible.value) return
rows.value = []
total.value = 0
failure.value = errorText(error)
} finally {
if (request === sequence) loading.value = false
}
}
/**
* 切换类别时从第一页重查,并立即移除旧类别的可点击行。
* @param kind 空字符串表示全部;其它值沿用服务端类别契约
*/
function changeKind(kind: MyTodoKind | '') {
query.kind = kind || undefined
query.page = 1
rows.value = []
total.value = 0
void load()
}
/** 根据分页控件的目标页读取服务端数据,保留当前类别和每页数量。 */
function changePage(page: number) {
query.page = page
void load()
}
/** 同步响应可见范围变化,确保同一轮关闭再打开也不会接收关闭前的响应。 */
function syncAvailability() {
if (active.value && visible.value) void load()
else invalidate()
}
// 代次控制覆盖成功、失败及 loading 清理;单纯检查 visible 无法区分关闭前后的两次打开。
watch([active, visible], syncAvailability, { immediate: true, flush: 'sync' })
onBeforeUnmount(invalidate)
return { query, rows, total, loading, failure, load, changeKind, changePage }
}

View File

@ -1,5 +1,5 @@
import { computed, onMounted, onBeforeUnmount, onActivated, onDeactivated, reactive, ref, useTemplateRef, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useRoute, useRouter, type LocationQuery } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import useUserStore from '@/store/modules/user'
import { api, errorText, isAccessFailure } from '../api'
@ -8,6 +8,7 @@ import { typeNames } from '../shared/constants/labels'
import { reconcileRows, retainSnapshot } from '../shared/utils/snapshot'
import type { Project, Member, WorkItem, ItemType, Lifecycle, FlowView, Iteration, ItemQuery } from '../types'
import { iterationReadOnly, iterationCanExecute } from '../features/iterations/utils/scope'
import { useWorkspaceTarget, workspaceLinkId, workspaceLinkView } from './useWorkspaceTarget'
import type IterationControls from '../features/iterations/components/IterationControls.vue'
import type WorkFlow from '../views/flow/WorkFlow.vue'
import type WorkGantt from '../views/gantt/WorkGantt.vue'
@ -18,8 +19,8 @@ import type ItemDetail from '../features/work-items/components/ItemDetail.vue'
* 协调项目协作页面的项目/迭代范围、加载、路由及编辑状态。
* 将原页面生命周期集中在同一个 setup 调用中,保留请求代次和轮询暂停规则,
* 防止拆分视图后出现重复轮询或旧迭代响应覆盖新范围。
* 首次进入默认展示排在首位的流程视图,使项目阶段进度优先可见。
* 甘特成员选择仅作为读取条件,切换迭代清空,继续由后端完整图校验排期。
* 首次进入默认展示流程视图;待办深链接恢复其明确的看板或阶段及完整归属。
* 看板和甘特各自保存成员读取条件,切换迭代清空,继续由后端完整图校验执行及排期。
* 轮询静默合并变化的快照,保留选择和已加载分页;编辑及拖动期间不提交后台结果。
* @returns 页面装配使用的响应式状态、组件引用和业务动作;解构后仍保持 Ref。
* 注意:必须在页面 setup 内调用;卸载时清除定时器并使在途刷新失效。
@ -61,8 +62,9 @@ export function useProjectCollaboration() {
const loading = ref(false)
const failure = ref('')
const tab = ref('flow')
const tab = ref(workspaceLinkView(initialQuery.view) || 'flow')
const ganttMemberIds = ref<number[]>([])
const boardMemberIds = ref<number[]>([])
const keyword = ref('')
const typeFilter = ref<ItemType | null>(null)
const blockedOnly = ref(false)
@ -98,6 +100,9 @@ export function useProjectCollaboration() {
workItemId: number | null
}[]>([])
const { focusedItem, focusedStageId, targetFailure, clearTarget, restoreTarget, synchronizeTarget } = useWorkspaceTarget({ projectId, iterationId, iteration: selectedIteration, flowView, userId: () => Number(userStore.id) })
let restoredTargetKey = ''
const statCards = computed(() => [{ label: '全部工作项', value: statistics.value.total || 0 }, { label: '进行中', value: statistics.value.inProgress || 0 }, { label: '已完成', value: statistics.value.completed || 0 }, { label: '关闭', value: statistics.value.closed || 0 }, { label: '超期未完成', value: statistics.value.overdue || 0 }, { label: '实际前置阻塞', value: statistics.value.blocked || 0 }, { label: '排期未完成', value: statistics.value.scheduleIncomplete || 0 }])
let refreshSequence = 0, workspaceSequence = 0, navigationSequence = 0, iterationSequence = 0, initializationSequence = 0
@ -105,7 +110,7 @@ export function useProjectCollaboration() {
let scopeSequence = 0
let timer: ReturnType<typeof setInterval> | undefined
let active = true, initialized = false, initializing = false, restoringRoute = false
let polling = false, applyingBackgroundMembers = false
let polling = false, applyingBackgroundMembers = false, clearingScope = false
/** 固定读取路由项目;后台结果仅在页面仍空闲时应用,同内容沿用旧引用以避免重绘。 */
async function loadWorkspace(initialize = false, background = false) {
@ -122,13 +127,18 @@ export function useProjectCollaboration() {
return true
}
/** 手动重读固定项目身份和迭代,保留显式加载及失败提示,不接受模板事件作为同步选项。 */
/** 手动重读固定范围;定位请求曾失败时重新初始化原链接,使网络恢复后可直接重试待办。 */
async function refreshWorkspace() {
if (targetFailure.value && (route.query.fromTodo === '1' || route.query.focusItemId || route.query.stageId)) {
await initializeWorkspace()
return
}
await synchronizeWorkspace(false)
}
/**
* 协调项目身份、迭代和数据刷新;后台瞬时失败留待下一次重试,访问失效仍立即清理。
* 迭代真实回退优先清理旧范围;成员修剪引发的内部查询不能阻止详情、草稿和筛选失效。
* @param background 是否来自后台轮询;此路径不显示遮罩,也不能覆盖后来发起的前台操作。
*/
async function synchronizeWorkspace(background: boolean) {
@ -142,13 +152,15 @@ export function useProjectCollaboration() {
try {
const iteration = iterationId.value
if (!await loadWorkspace(false, background) || navigation !== navigationSequence || background && refreshAtStart !== refreshSequence) return
if (!await loadIterations(undefined, background) || navigation !== navigationSequence || background && refreshAtStart !== refreshSequence) return
if (!await loadIterations(undefined, background) || navigation !== navigationSequence) return
if (iteration !== iterationId.value) {
// 成员修剪可能已查询旧迭代并增加刷新代次;先清理真实范围变化,同时使该查询及其错误失效。
// 导航代次仍在上方优先检查,不能用元数据回退覆盖后来发生的用户切换。
const people = members.value
clearScope()
navigation = navigationSequence
members.value = people
}
} else if (background && refreshAtStart !== refreshSequence) return
await refreshData(background)
} catch (error) {
if (!active || navigation !== navigationSequence) return
@ -165,9 +177,13 @@ export function useProjectCollaboration() {
failure.value = errorText(error)
}
/** 分页筛选交由服务端;甘特独有的成员条件不传给列表、看板或前置选择器。 */
/**
* 分页筛选交由服务端;看板与甘特使用各自成员条件,列表和前置选择器保持完整范围。
* @param view 当前读取视图,不作为执行授权依据。
* @returns 本次请求独立的筛选快照,成员数组复制后不受后续选择修改影响。
*/
function query(view: ItemQuery['view']): ItemQuery {
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] } : {}) }
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] } : view === 'board' ? { memberIds: [...boardMemberIds.value] } : {}) }
}
/** 导出沿用甘特的完整服务端筛选,但独立从第一页读取,翻页不改变导出范围。 */
@ -188,6 +204,7 @@ export function useProjectCollaboration() {
/**
* 只合并当前范围、请求代次的结果,流程仅请求阶段摘要,后台保留选择和看板已加载页数。
* 成员失效可能改变读取条件,先修剪并检查代次,防止原筛选响应覆盖重新发起的查询。
* @param background 后台刷新不显示加载状态,瞬时失败不清空已有内容,编辑开始后丢弃其响应。
*/
async function refreshData(background: boolean) {
@ -196,7 +213,8 @@ export function useProjectCollaboration() {
if (!background) loading.value = false
return
}
if (!background) { loading.value = true; failure.value = '' }
// 前台刷新接管旧续页,立即释放其忙碌标记;旧请求不能在结束时清除后来新续页的标记。
if (!background) { loading.value = true; failure.value = ''; boardBusy.clear() }
try {
const states: Lifecycle[] = ['READY', 'IN_PROGRESS', 'COMPLETED', 'CANCELLED', 'CLOSED']
const loadedPages = Object.fromEntries(states.map(status => [status, background ? boardPages[status] || 1 : 1]))
@ -208,18 +226,21 @@ export function useProjectCollaboration() {
})) : ['flow', 'notifications'].includes(tab.value) ? Promise.resolve([]) : Promise.all([api.items(id, iteration, query(tab.value === 'gantt' ? 'gantt' : 'list'))])
const [graph, people, notices, stats, pages] = await Promise.all([api.flowView(id, iteration), api.members(id), api.notifications(), api.statistics(id, iteration), request])
if (!active || sequence !== refreshSequence || id !== projectId.value || iteration !== iterationId.value || background && (!canSynchronize() || tab.value === 'board' && states.some(status => loadedPages[status] !== (boardPages[status] || 1)))) return
updateMembers(people, background)
if (sequence !== refreshSequence) return
items.value = reconcileRows(items.value, pages.flatMap(result => result.rows))
total.value = pages[0]?.total || 0
if (tab.value === 'board') {
boardCounts.value = retainSnapshot(boardCounts.value, Object.fromEntries(states.map((status, index) => [status, pages[index]?.total || 0])))
if (!background) for (const status of states) boardPages[status] = 1
}
updateMembers(people, background)
flowView.value = retainSnapshot(flowView.value, graph)
iterations.value = retainSnapshot(iterations.value, iterations.value.map(row => row.id === iteration ? { ...row, graphVersion: graph.graphVersion ?? row.graphVersion } : row))
statistics.value = retainSnapshot(statistics.value, stats)
notifications.value = retainSnapshot(notifications.value, notices)
failure.value = ''
await synchronizeTarget(background)
if (!active || sequence !== refreshSequence || id !== projectId.value || iteration !== iterationId.value) return
if (background) {
const available = new Map(items.value.map(row => [row.id, row]))
// 保留有效勾选,但同步其版本;删除或离开当前筛选范围的行不能继续参与批量操作。
@ -241,7 +262,10 @@ export function useProjectCollaboration() {
}
}
/** 状态列独立续页并保留后端总数,同列重复点击不重复提交。 */
/**
* 状态列按当前成员条件独立续页;筛选或范围变化后丢弃旧结果、旧错误及旧忙碌清理。
* @param status 需要加载下一页的状态列;同列忙碌期间不重复请求。
*/
async function loadBoardMore(status: Lifecycle) {
const id = projectId.value, iteration = iterationId.value, sequence = refreshSequence
if (!id || !iteration || boardBusy.has(status)) return
@ -249,18 +273,25 @@ export function useProjectCollaboration() {
boardBusy.add(status)
try {
const result = await api.items(id, iteration, { ...query('board'), page: next, status })
if (sequence !== refreshSequence || iteration !== iterationId.value) return
if (!active || sequence !== refreshSequence || id !== projectId.value || iteration !== iterationId.value) return
const known = new Set(items.value.map(row => row.id))
items.value.push(...result.rows.filter(row => !known.has(row.id)))
boardPages[status] = next
boardCounts.value[status] = result.total
} catch (error) {
ElMessage.error(errorText(error))
if (active && sequence === refreshSequence) ElMessage.error(errorText(error))
} finally {
boardBusy.delete(status)
if (sequence === refreshSequence) boardBusy.delete(status)
}
}
/** 成员读取条件改变后重置所有状态列页码和计数,旧续页由请求代次隔离。 */
function resetBoardPages() {
boardCounts.value = {}
boardBusy.clear()
for (const status of Object.keys(boardPages) as Lifecycle[]) delete boardPages[status]
}
/** 甘特按时间窗口查询,窗口移动从第一页开始。 */
function moveGanttWindow(days: number) {
ganttFrom.value = new Date(Date.parse(ganttFrom.value) + days * 86400000).toISOString()
@ -269,8 +300,11 @@ export function useProjectCollaboration() {
void refresh()
}
/** 清空旧范围数据与所有未提交输入,切回原迭代也不能恢复旧请求。 */
/** 清空旧范围和未提交输入;重置期间暂停成员 watcher 查询,避免仍向旧迭代发起请求。 */
function clearScope() {
clearingScope = true
clearTarget()
restoredTargetKey = ''
scopeSequence++
refreshSequence++
navigationSequence++
@ -280,13 +314,11 @@ export function useProjectCollaboration() {
notifications.value = []
total.value = 0
statistics.value = {}
boardCounts.value = {}
boardBusy.clear()
for (const status of Object.keys(boardPages) as Lifecycle[]) delete boardPages[status]
resetBoardPages()
flowView.value = null
selection.value = []
members.value = []
ganttMemberIds.value = []; stageFilter.value = null
ganttMemberIds.value = []; boardMemberIds.value = []; stageFilter.value = null
detailId.value = null
editing.value = null
creatingParent.value = null
@ -299,6 +331,7 @@ export function useProjectCollaboration() {
failure.value = ''
loading.value = false
page.value = 1
clearingScope = false
}
/** 可见迭代元数据独立计次;后台同值不重置引用,用户开始编辑或切换范围后不再应用结果。 */
@ -317,7 +350,11 @@ export function useProjectCollaboration() {
return true
}
/** 成员失效时修剪甘特筛选,后台元数据更新不应间接触发带遮罩的前台刷新。 */
/**
* 成员失效时同步修剪两个视图筛选,后台触发的重查继续使用静默模式。
* @param people 当前服务端成员快照;相同内容保留原引用以避免无意义重查。
* @param background 是否属于静默同步,用于继承成员修剪后查询的加载方式。
*/
function updateMembers(people: Member[], background: boolean) {
applyingBackgroundMembers = background
try { members.value = retainSnapshot(members.value, people) }
@ -353,10 +390,31 @@ export function useProjectCollaboration() {
await iterationsChanged()
}
/** 完整范围写入路由,工作项深链接不会被解释为当前迭代对象。 */
/** 完整范围和页签写入路由;定位卡片独立于详情 ID,关闭详情后仍能在看板找到目标。 */
function syncQuery() {
if (!active || route.path !== pagePath || !sourceProjectId.value) return
void router.replace({ query: { ...route.query, sourceProjectId: sourceProjectId.value, projectId: undefined, iterationId: iterationId.value || undefined, itemId: detailId.value || undefined } })
void router.replace({ query: { ...route.query, sourceProjectId: String(sourceProjectId.value), projectId: undefined, iterationId: iterationId.value ? String(iterationId.value) : undefined, itemId: detailId.value ? String(detailId.value) : undefined,
view: tab.value, focusItemId: tab.value === 'board' && focusedItem.value ? String(focusedItem.value.id) : undefined,
stageId: tab.value === 'flow' && focusedStageId.value ? String(focusedStageId.value) : undefined,
approvalId: tab.value === 'flow' && focusedStageId.value ? route.query.approvalId : undefined,
fromTodo: tab.value === 'board' && focusedItem.value || tab.value === 'flow' && focusedStageId.value ? route.query.fromTodo : undefined } })
}
/** 详情开关不改变定位身份;只有项目内的视图、置顶项或审批申请变化才重新读取目标。 */
function linkTargetKey(query: LocationQuery): string {
return JSON.stringify([query.view, query.focusItemId, query.stageId, query.approvalId, query.fromTodo])
}
/**
* 深链接明确的页签优先于默认流程视图;待办导航清空旧筛选,避免目标被成员或标题条件隐藏。
* @param query 导航时捕获的路由快照;调用方负责保持 restoringRoute,暂停普通筛选 watcher。
*/
function prepareLinkedTarget(query: LocationQuery) {
const view = workspaceLinkView(query.view)
if (view) tab.value = view
if (query.fromTodo === '1' || query.focusItemId) {
keyword.value = ''; typeFilter.value = null; blockedOnly.value = false; stageFilter.value = null; boardMemberIds.value = []
}
}
/** 通知先查真实归属与项目绑定,再交给路由切换工作区,不能混用源 ID 和协作 ID。 */
@ -405,9 +463,12 @@ export function useProjectCollaboration() {
return plannedDate(iso, zone)
}
/** 开始只使用统一后端接口;提交期间暂停轮询并防止重复点击,拒绝后刷新真实状态。 */
/**
* 开始只使用服务端 canStart 和统一接口;即使合成事件触发,也不能绕过当前负责人及准入条件。
* @param item 当前列表快照,提交其版本;服务端再次校验改派和执行条件,拒绝后刷新真实状态。
*/
async function startOne(item: WorkItem) {
if (!canExecute.value || busy.value) return
if (!canExecute.value || !item.canStart || busy.value) return
busy.value = true
try {
await api.start(item.id, item.version)
@ -422,6 +483,7 @@ export function useProjectCollaboration() {
* 逐项开始并报告部分成功,提交期间暂停轮询;项目或迭代范围变化即停止后续提交。
* 不能仅比较迭代 ID:切到其他迭代再返回时,旧批次也已失效,不应恢复后台写入。
* 同迭代内仅打开或关闭详情不会改变业务范围,仍应完成本次已选批次并报告结果。
* 各项独立检查服务端 canStart;不可开始项只报告原因,不向服务端提交无效执行请求。
*/
async function startSelection() {
if (!canExecute.value || busy.value) return
@ -431,6 +493,7 @@ export function useProjectCollaboration() {
try {
for (const item of [...selection.value]) {
if (!active || scope !== scopeSequence || !canExecute.value) break
if (!item.canStart) { errors.push(`${item.title}:${item.blockedReasons.map(reason => reason.message || reason.sourceName).filter(Boolean).join(';') || '当前无法开始'}`); continue }
try {
await api.start(item.id, item.version)
succeeded++
@ -499,16 +562,37 @@ export function useProjectCollaboration() {
finally { polling = false }
}
watch([tab, keyword, typeFilter, blockedOnly, stageFilter], () => {
/** 主动筛选取消临时置顶,防止不匹配当前条件的卡片出现在筛选计数之外;导航恢复由单独流程处理。 */
watch([tab, keyword, typeFilter, blockedOnly, stageFilter], (values, previous) => {
if (clearingScope || initializing || restoringRoute) return
if (focusedItem.value && values.some((value, index) => index > 0 && value !== previous[index])) clearTarget()
page.value = 1
void refresh()
if (initialized) syncQuery()
})
/** 成员多选按并集重新查询第一页,防止只在已加载50项里筛选或沿用旧页码。 */
watch(ganttMemberIds, () => { if (tab.value === 'gantt') { page.value = 1; if (!applyingBackgroundMembers) void refresh() } }, { deep: true, flush: 'sync' })
watch(ganttMemberIds, () => { if (tab.value === 'gantt' && !clearingScope && !initializing && !restoringRoute) { page.value = 1; void refreshData(applyingBackgroundMembers) } }, { deep: true, flush: 'sync' })
/** 看板成员变化立即失效旧续页,所有状态列从第一页重读;不改变甘特或列表的数据条件。 */
watch(boardMemberIds, () => {
resetBoardPages()
if (tab.value === 'board' && !clearingScope && !initializing && !restoringRoute) {
if (!applyingBackgroundMembers && focusedItem.value) { clearTarget(); syncQuery() }
items.value = []
page.value = 1
void refreshData(applyingBackgroundMembers)
}
}, { deep: true, flush: 'sync' })
/** 轮询更新项目成员后移除失效选择;保留仍有效的选择,避免列表退化成不可识别的用户ID。 */
watch(members, people => { const available = new Set(people.map(member => member.userId)); const retained = ganttMemberIds.value.filter(id => available.has(id)); if (retained.length !== ganttMemberIds.value.length) ganttMemberIds.value = retained }, { flush: 'sync' })
watch(members, people => {
const available = new Set(people.map(member => member.userId))
for (const selected of [ganttMemberIds, boardMemberIds]) {
const retained = selected.value.filter(id => available.has(id))
if (retained.length !== selected.value.length) selected.value = retained
}
}, { flush: 'sync' })
watch(detailId, () => {
// 接受外部深链接时,清空旧抽屉不能把尚未加载完成的新迭代路由回写为旧范围。
@ -524,7 +608,7 @@ export function useProjectCollaboration() {
}
})
/** 浏览器前进后退恢复同项目迭代;跨项目切换由页面装配重新创建独立工作区。 */
/** 浏览器导航恢复同项目迭代和待办目标;只有鉴权读取归属后才打开定位详情。 */
watch(() => route?.query, async value => {
if (!active || route.path !== pagePath || Number(value?.sourceProjectId) !== sourceProjectId.value) return
restoringRoute = true
@ -533,13 +617,25 @@ export function useProjectCollaboration() {
void initializeWorkspace()
return
}
const i = Number(value?.iterationId) || null, item = Number(value?.itemId) || null
const querySnapshot = { ...value }, i = workspaceLinkId(value?.iterationId), item = workspaceLinkId(value?.itemId)
if (i === iterationId.value && (!i || selectedIteration.value)) {
// 快速返回原迭代或仅改变详情时,同样终止旧导航链,不能让旧回调随后打开错误详情。
navigationSequence++
iterationSequence++
if (item !== detailId.value) detailId.value = item
restoringRoute = false
const navigation = navigationSequence, key = linkTargetKey(querySnapshot)
try {
if (key !== restoredTargetKey) {
clearTarget()
// 切换待办先关闭旧详情,不能在新对象校验期间或失败后把旧工作项留在前台。
if (querySnapshot.fromTodo === '1' || querySnapshot.focusItemId || querySnapshot.stageId) detailId.value = null
prepareLinkedTarget(querySnapshot)
await refresh()
if (!active || navigation !== navigationSequence) return
restoredTargetKey = key
const detail = await restoreTarget(querySnapshot)
if (active && navigation === navigationSequence) detailId.value = detail
} else if (item !== detailId.value) detailId.value = item
} finally { if (navigation === navigationSequence) restoringRoute = false }
return
}
clearScope()
@ -549,19 +645,24 @@ export function useProjectCollaboration() {
iterations.value = []
try {
if (!await loadIterations(i) || navigation !== navigationSequence) return
if (querySnapshot.fromTodo === '1' && i !== iterationId.value) iterationId.value = null
prepareLinkedTarget(querySnapshot)
await refresh()
if (active && navigation === navigationSequence && iterationId.value === i) detailId.value = item
if (!active || navigation !== navigationSequence) return
restoredTargetKey = linkTargetKey(querySnapshot)
const detail = await restoreTarget(querySnapshot)
if (active && navigation === navigationSequence && iterationId.value === i) detailId.value = detail
} catch (error) { if (active && navigation === navigationSequence) failure.value = errorText(error) }
finally { if (navigation === navigationSequence) restoringRoute = false }
})
/**
* 初始化可在 KeepAlive 重新激活时重试;每个等待点均校验代次,避免离页后的旧请求启动轮询。
* 使用本次激活的路由范围恢复迭代和详情,初始化失败后仍允许刷新重试。
* 使用本次激活的路由范围恢复迭代、页签和定位对象,初始化失败后仍允许刷新重试。
*/
async function initializeWorkspace() {
const sequence = ++initializationSequence
const requestedIteration = Number(route.query.iterationId) || null, requestedItem = Number(route.query.itemId) || null
const querySnapshot = { ...route.query }, requestedIteration = workspaceLinkId(querySnapshot.iterationId)
initialized = false
initializing = true
clearScope()
@ -571,11 +672,17 @@ export function useProjectCollaboration() {
if (!await loadWorkspace(true) || sequence !== initializationSequence) return
if (requestedIteration) includeArchived.value = true
if (!await loadIterations(requestedIteration) || sequence !== initializationSequence) return
if (querySnapshot.fromTodo === '1' && requestedIteration !== iterationId.value) iterationId.value = null
prepareLinkedTarget(querySnapshot)
await refresh()
if (!active || sequence !== initializationSequence) return
if (requestedItem && iterationId.value === requestedIteration) detailId.value = requestedItem
restoredTargetKey = linkTargetKey(querySnapshot)
const detail = await restoreTarget(querySnapshot)
if (!active || sequence !== initializationSequence) return
if (iterationId.value === requestedIteration) detailId.value = detail
initialized = true
syncQuery()
// 无效待办保留原链接和提示,不能用默认范围回写触发第二次恢复并抹掉失败原因。
if (!targetFailure.value) syncQuery()
if (!timer) timer = setInterval(poll, 15000)
} catch (error) {
if (active && sequence === initializationSequence) { clearScope(); current.value = null; failure.value = errorText(error) }
@ -590,8 +697,10 @@ export function useProjectCollaboration() {
onMounted(() => { void initializeWorkspace() })
/** 缓存页离开时取消定位与所有在途导航;重新激活按当时路由读取,不能复活旧待办。 */
onDeactivated(() => {
active = false
clearTarget()
scopeSequence++
if (timer) clearInterval(timer)
timer = undefined
@ -609,8 +718,10 @@ export function useProjectCollaboration() {
if (!initializing) void initializeWorkspace()
})
/** 真正卸载时释放轮询并使读取代次失效,待办响应不能写回已经销毁的工作区。 */
onBeforeUnmount(() => {
active = false
clearTarget()
scopeSequence++
if (timer) clearInterval(timer)
refreshSequence++
@ -623,9 +734,9 @@ export function useProjectCollaboration() {
return {
projectId, iterations, iterationId, includeArchived,
items, members, flowView, current, selectedIteration, zone, canWrite, canCreate, canExecute,
loading, failure, tab, keyword, typeFilter, blockedOnly, stageFilter, detailId, refreshKey, selection,
loading, failure, tab, keyword, typeFilter, blockedOnly, stageFilter, detailId, focusedItem, focusedStageId, targetFailure, refreshKey, selection,
editing, editorOpen, creatingParent, defaultStageId, page, pageSize, total, boardCounts,
ganttFrom, ganttTo, ganttMemberIds, ganttExportQuery, ganttExportFilters, membersOpen, inviteUser, inviteRole, userCandidates, batchOpen,
ganttFrom, ganttTo, ganttMemberIds, boardMemberIds, ganttExportQuery, ganttExportFilters, membersOpen, inviteUser, inviteRole, userCandidates, batchOpen,
notifications, statCards, userStore,
refreshWorkspace, refresh, loadBoardMore, moveGanttWindow,
changeIteration, iterationsChanged, archiveFilterChanged, openNotice,

View File

@ -0,0 +1,114 @@
import { ref, type Ref } from 'vue'
import type { LocationQuery } from 'vue-router'
import { api, errorText, isAccessFailure } from '../api'
import type { FlowView, Iteration, WorkItem } from '../types'
import { retainSnapshot } from '../shared/utils/snapshot'
/** 深链接 ID 必须是精确的单个正整数;数组和溢出值不能悄悄变成另一个对象。 */
export function workspaceLinkId(value: unknown): number | null {
if (typeof value !== 'string' || !/^[1-9]\d*$/.test(value)) return null
const id = Number(value)
return Number.isSafeInteger(id) ? id : null
}
/** 只恢复已有工作区页签;非法值按旧链接处理,不新增任意动态视图。 */
export function workspaceLinkView(value: unknown): string | null {
return typeof value === 'string' && ['flow', 'board', 'gantt', 'list', 'notifications'].includes(value) ? value : null
}
/**
* 读取待办定位对象时复核真实归属及当前版本,避免用待办列表的旧快照填充看板。
* @param scope 当前工作区及用户身份,切换范围时须调用 clearTarget 使在途请求失效。
* @returns 独立定位快照、阶段定位 ID 和错误提示;不写入工作项或审批,不授予操作权限。
*/
export function useWorkspaceTarget(scope: {
projectId: Ref<number | null>
iterationId: Ref<number | null>
iteration: Readonly<Ref<Iteration | undefined>>
flowView: Ref<FlowView | null>
userId: () => number
}) {
const focusedItem = ref<WorkItem | null>(null), focusedStageId = ref<number | null>(null), targetFailure = ref('')
let sequence = 0
/** 清理范围及定位快照,同时废弃旧请求;不让另一个迭代的详情重新打开。 */
function clearTarget() {
sequence++
focusedItem.value = null
focusedStageId.value = null
targetFailure.value = ''
}
/** 当前迭代已终止、归档或被删除时拒绝待办定位;普通历史书签不使用此限制。 */
function liveIteration(): boolean {
const iteration = scope.iteration.value
return !!iteration && !iteration.archivedAt && ['PLANNED', 'ACTIVE'].includes(iteration.status)
}
/**
* 恢复明确的待办目标;返回可打开的详情 ID,阶段目标只打开阶段抽屉。
* @param query 完整路由快照,focusItemId 独立于详情 itemId,关闭详情后仍能保留定位卡片。
* @returns 普通书签兼容原详情行为;失效、换版、越界对象返回 null 并说明原因。
*/
async function restoreTarget(query: LocationQuery): Promise<number | null> {
clearTarget()
const request = ++sequence, project = scope.projectId.value, iteration = scope.iterationId.value
const itemId = workspaceLinkId(query.itemId), focusId = workspaceLinkId(query.focusItemId)
const stageId = workspaceLinkId(query.stageId), approvalId = workspaceLinkId(query.approvalId)
const todo = query.fromTodo === '1'
if (!todo && !focusId && !stageId) return itemId
if (!project || !iteration || !liveIteration()) { targetFailure.value = '待办所属迭代已结束、归档或不可访问'; return null }
try {
if (query.view === 'board' && (focusId || itemId)) {
const item = await api.detail((focusId || itemId)!)
if (request !== sequence || project !== scope.projectId.value || iteration !== scope.iterationId.value) return null
if (item.projectId !== project || item.iterationId !== iteration) throw new Error('工作项不属于当前项目或迭代')
if (item.historical) throw new Error('该待办已成为历史版本,请刷新我的代办')
if (todo && !['READY', 'IN_PROGRESS'].includes(item.status)) throw new Error('该工作项已完成、取消或关闭,不再是待办')
if (todo && item.assigneeId !== scope.userId() && !item.collaboratorIds?.includes(scope.userId())) throw new Error('该工作项已调整分工,不再属于你的待办')
focusedItem.value = item
return itemId
}
if (query.view === 'flow' && stageId) {
if (!scope.flowView.value?.stages.some(stage => stage.id === stageId)) throw new Error('阶段已删除或不属于当前项目或迭代')
if (todo) {
if (!approvalId) throw new Error('待办缺少有效的审批申请标识')
const completion = await api.stageCompletion(project, iteration, stageId)
if (request !== sequence || project !== scope.projectId.value || iteration !== scope.iterationId.value) return null
if (completion.historical || completion.approvalStatus !== 'PENDING' || !completion.approvals.some(approval => approval.id === approvalId && approval.status === 'PENDING' && approval.approver_id === scope.userId())) throw new Error('该审批已处理或失效,请刷新我的代办')
}
focusedStageId.value = stageId
return null
}
throw new Error('待办链接缺少有效的定位对象')
} catch (error) {
if (request === sequence) targetFailure.value = errorText(error)
return null
}
}
/**
* 手动刷新和静默同步刷新置顶项的真实状态;完成后可移至完成列,回退或撤权后清除旧卡片。
* @param background 后台瞬时故障保留快照;明确访问失效必须立即移除,不能继续展示过期权限。
*/
async function synchronizeTarget(background: boolean) {
const previous = focusedItem.value
if (!previous) return
const request = ++sequence, project = scope.projectId.value, iteration = scope.iterationId.value
try {
const item = await api.detail(previous.id)
if (request !== sequence || project !== scope.projectId.value || iteration !== scope.iterationId.value) return
if (item.projectId !== project || item.iterationId !== iteration || item.historical || !liveIteration()) {
focusedItem.value = null
targetFailure.value = '定位工作项已换版、调整归属或所属迭代不再有效,请刷新我的代办'
} else focusedItem.value = retainSnapshot(focusedItem.value, item)
} catch (error) {
if (request === sequence && (!background || isAccessFailure(error))) {
focusedItem.value = null
targetFailure.value = errorText(error)
}
}
}
return { focusedItem, focusedStageId, targetFailure, clearTarget, restoreTarget, synchronizeTarget }
}

View File

@ -0,0 +1,59 @@
# 我的待办实施计划
**目标**:在项目协作外部项目表格右上角提供“我的代办”,汇总当前用户负责、协作的未完成工作项和待本人审批的阶段完成申请,并跳转到准确的项目、迭代及对象。
**范围**:后端仅 `ruoyi-project`;前端仅本模块目录。沿用 Spring、MyBatis、Vue 及 Element Plus,不新增依赖、数据表或业务写入,不变更执行和审批权限。
**需求门禁**:用户已确认推荐范围;RCS 96、RRS 32,关键未决事项 NONE,按已确认方案实施。
**已确认规则**:
- 工作项仅取 READY、IN_PROGRESS,包含超期未完成;本人同时是负责人、协作人时只出现一次。
- 只取本人仍可访问项目、未删除且未归档的 PLANNED/ACTIVE 迭代和阶段当前版本;排除历史、删除、已完成、取消及关闭对象。
- 阶段审批仅取当前版本的 PENDING 完成申请,审批人是当前用户;不虚构采购确认申请或其它业务待办。
- 工作项进入看板,定位卡片并打开详情;审批进入流程视图并打开对应阶段抽屉。前进后退和缓存恢复仍遵循完整项目、迭代范围。
- 无权访问、目标消失或状态已变化时明确提示,不定位到其它对象。现有负责人执行限制继续生效。
**接口契约**:`GET /project/manage/my-todos?page=1&pageSize=20&kind=WORK_ITEM|STAGE_APPROVAL`,kind 可省略。服务端从登录态确定用户,按权限、状态和当前版本过滤后分页。
返回 `{ rows, total, page, pageSize }`,每行包含 `key, kind, sourceProjectId, projectId, projectCode, projectName, iterationId, iterationName, workItemId, stageId, approvalId, title, status, overdue, plannedEndAt, myRole`。空对象 ID 为 null,时间使用现有北京时间 ISO 表达。审批优先,其余按截止日期、ID 稳定排序。
## 实施步骤
- [x] 后端新增 Todo 查询 DTO、Mapper/XML、Service 和 Controller;分页不信任外部 userId,复用原项目成员绑定。先用临时测试观察缺失功能失败,再验证真实数据库的可见性、状态、换版、去重和分页;不写入现有业务库。
- [x] 前端新增 todo 契约、请求、抽屉组件及请求协调;项目目录右侧添加入口。测试请求竞态、关闭后失效、分页、空数据、失败提示和行跳转事件。
- [x] 扩展深链接为 view=board/flow、itemId/stageId。看板通过既有鉴权详情接口读取定位项,临时置顶并高亮该卡片,不遍历全部分页、不改变普通分页计数;合并时按 ID 去重。流程打开指定阶段。验证同项目切换、跨迭代、旧响应、浏览器恢复及旧链接兼容。
- [x] 运行后端编译、前端严格类型检查和相关功能测试,审查鉴权、注释及范围;按项目规则删除全部临时测试文件、夹具和报告。
## 验收标准与风险
FR-001/AC-001:入口及抽屉在明暗主题、小屏可用,所有控件 small,遮罩点击不关闭。
FR-002/AC-002:跨项目汇总仅返回本人相关、仍可访问、当前有效的未完成工作项或待审申请;总数与分页一致,无角色越权或重复。
FR-003/AC-003:点击工作项打开准确看板并定位首屏以外的卡片;点击审批打开准确阶段;失效链接不误开其它对象。
重要风险:源项目 ID 与协作 ID 不可混用;成员撤权、阶段回退和审批完成可能发生于查询后;路由恢复不能被旧请求或静默同步覆盖。通过 SQL 即时过滤、目标接口再鉴权、明确归属校验和请求代次控制处理,不承诺点击时数据仍与待办列表快照相同。
Requirement Drift:NONE;Scope Drift:NONE。测试结果在交付时据实际执行报告。
## 实施与验证记录
- 后端新增 `PmTodoController`、`TodoQuery`、`PmTodoMapper`、`IPmTodoService`、`PmTodoServiceImpl` 和 `PmTodoMapper.xml`;复用现有业务表,无结构、数据迁移或待办持久化。
- 两类待办在 SQL 中通过相同权限谓词过滤并 UNION ALL;分工使用 EXISTS 去重。只读 REPEATABLE_READ 事务保证同次分页与总数基于相同快照,查询不需要项目写锁;点击后的读取及业务操作继续各自重新鉴权。
- `mvn.cmd -pl ruoyi-project -am -DskipTests compile` 成功。`mvn.cmd -pl ruoyi-project -am test` 成功,但相关模块没有现有测试,不能据此声称单元测试覆盖。
- 临时真实 MySQL 集成执行实际 MyBatis XML、PmAccess、事务服务及 Controller,47 项断言通过,覆盖身份隔离、源 ID 冲突、状态和版本过滤、分页、去重、时间及边界输入;测试库已删除并验证不存在,未写入原业务库。
- 临时待办抽屉运行测试 10 项通过;导航、首屏外卡片、旧链接、错误恢复、筛选一致性和阶段抽屉测试 22 项通过。新增功能缺失及审查发现的旧阶段抽屉残留,均观察到修复前失败和修复后通过。
- 严格模块 `vue-tsc --noUnusedLocals --noUnusedParameters` 通过;生产构建成功。`git diff --check` 通过。
- 全量前端单元测试 347/348 通过,剩余 `table-cell-policy.test.mjs` 指向本次未改动的 `src/views/system/mobileRelease/index.vue` 状态列。全量运行测试 341 项通过,但 `app-release.spec.js` 无法导入既有缺失文件 `@/views/system/file/AppRelease.vue`,所以完整测试集未通过。两项均未越出项目协作范围修复。
- 生产构建保留既有 Editor 同时静态与动态导入的分包提示;未改动其引用。浏览器视觉及真实 HTTP 端到端未执行:浏览器访问主机不可用,且当前环境无法解析已声明的 Playwright 包;不宣称明暗主题或小屏截图验收通过。
- 所有临时测试、夹具、日志、配置和报告按项目规则在验证完成后清理;上述临时测试命令不作为交付后的可执行入口。业务能力及关键分层保留中文方法注释。
FR-001~FR-003、AC-002~AC-003:按运行测试和代码审查通过;AC-001 的交互运行测试通过,浏览器视觉适配尚未人工验收。Scope Drift:NONE;Requirement Drift:NONE;无已知的本次功能阻塞问题。
## 本地验证步骤
1. 沿用现有 IDE 配置启动或重启后端,运行前端 `npm run dev`;部署环境需更新前端构建资源。无需执行数据库升级。
2. 登录具有项目协作读取权限且参与项目的用户,在项目目录右上角打开“我的代办”。验证不同项目的本人负责和协作项、阶段待审申请;切换类别及分页,检查终态、历史和失效范围不出现。
3. 点击工作项标题或“查看”,确认进入准确迭代的看板,卡片置顶高亮并打开详情;关闭详情后卡片仍可见,设置筛选后取消临时定位。非负责人仍不能开始或完成工作项。
4. 点击阶段审批,确认进入对应流程和阶段审批面板;审批处理或回退换版后,刷新待办,该申请不再出现。列表读取后才失效的目标,应显示提示并关闭旧目标,而不是误开其它任务或申请。

View File

@ -0,0 +1,89 @@
<template>
<el-drawer
class="my-todos-drawer"
title="我的代办"
:model-value="modelValue && active"
size="min(1180px, 100vw)"
:close-on-click-modal="false"
@update:model-value="updateVisibility"
>
<section class="my-todos">
<div class="todo-toolbar">
<el-select :model-value="query.kind || ''" class="todo-kind" size="small" aria-label="待办类别" @change="changeKind">
<el-option label="全部" value="" />
<el-option label="工作项" value="WORK_ITEM" />
<el-option label="阶段审批" value="STAGE_APPROVAL" />
</el-select>
<el-button size="small" icon="Refresh" :loading="loading" @click="load">刷新</el-button>
</div>
<el-alert v-if="failure" type="error" :title="failure" :closable="false" show-icon />
<div class="todo-table-scroll">
<el-table v-loading="loading" :data="rows" row-key="key" size="small" class="todo-table" empty-text="暂无我的待办">
<el-table-column label="项目" min-width="190" show-overflow-tooltip>
<template #default="{ row }"><div>{{ row.projectName }}</div><span class="project-code">{{ row.projectCode }}</span></template>
</el-table-column>
<el-table-column label="迭代" prop="iterationName" min-width="130" show-overflow-tooltip />
<el-table-column label="标题" min-width="230" show-overflow-tooltip class-name="business-operation-cell">
<template #default="{ row }"><el-button class="todo-title" link type="primary" size="small" @click="selectTodo(row)">{{ row.title }}</el-button></template>
</el-table-column>
<el-table-column label="状态" width="150" class-name="business-status-cell">
<template #default="{ row }"><div class="todo-status"><el-tag size="small" :type="row.status === 'PENDING' ? 'warning' : 'primary'">{{ statusName(row) }}</el-tag><el-tag v-if="row.overdue" size="small" type="danger">已超期</el-tag></div></template>
</el-table-column>
<el-table-column label="我的角色" width="100"><template #default="{ row }">{{ roleName(row) }}</template></el-table-column>
<el-table-column label="截止日期" width="115"><template #default="{ row }">{{ plannedDate(row.plannedEndAt) }}</template></el-table-column>
<el-table-column label="操作" width="90" fixed="right" class-name="business-operation-cell"><template #default="{ row }"><el-button link type="primary" size="small" @click="selectTodo(row)">查看</el-button></template></el-table-column>
</el-table>
</div>
<el-pagination :current-page="query.page" :page-size="query.pageSize" :total="total" size="small" layout="total, prev, pager, next" :pager-count="5" @current-change="changePage" />
</section>
</el-drawer>
</template>
<script setup lang="ts">
import { toRef, watch } from 'vue'
import { vLoading } from 'element-plus'
import { useMyTodos } from '../../../composables/useMyTodos'
import { plannedDate } from '../../../shared/utils/time'
import type { MyTodo } from '../../../types'
const props = defineProps<{ modelValue: boolean; active: boolean }>()
const emit = defineEmits<{ 'update:modelValue': [visible: boolean]; todo: [todo: MyTodo] }>()
const { query, rows, total, loading, failure, load, changeKind, changePage } = useMyTodos(toRef(props, 'active'), toRef(props, 'modelValue'))
const statusNames: Record<MyTodo['status'], string> = { READY: '待开始', IN_PROGRESS: '进行中', PENDING: '待审批' }
const roleNames: Record<MyTodo['myRole'], string> = { ASSIGNEE: '负责人', COLLABORATOR: '协作人', APPROVER: '审批人' }
/** 将服务端待办状态映射为展示文案,避免表格插槽的宽泛类型绕过契约检查。 */
function statusName(todo: MyTodo) { return statusNames[todo.status] }
/** 展示服务端计算的本人分工;前端不根据项目角色推断待办或操作权限。 */
function roleName(todo: MyTodo) { return roleNames[todo.myRole] }
/** 将关闭动作交给父组件保存,保持抽屉显示状态与请求可见范围一致。 */
function updateVisibility(visible: boolean) { emit('update:modelValue', visible) }
/** 目录隐藏时同步关闭抽屉,返回目录后由用户明确重新打开。 */
function syncActive(active: boolean) { if (!active) updateVisibility(false) }
/**
* 交付原始待办定位快照并关闭抽屉,路由与目标再校验由页面协调层处理。
* @param todo 服务端返回的完整目标,源项目 ID、迭代 ID 及对象 ID 必须保留
*/
function selectTodo(todo: MyTodo) {
updateVisibility(false)
emit('todo', todo)
}
watch(toRef(props, 'active'), syncActive, { flush: 'sync' })
</script>
<style scoped>
.my-todos { display: flex; flex-direction: column; gap: 12px; height: 100%; min-width: 0; color: var(--el-text-color-primary) }
.todo-toolbar { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; flex-shrink: 0 }
.todo-kind { width: 140px }
.todo-table-scroll { min-height: 160px; overflow: auto; border: 1px solid var(--el-border-color-lighter); border-radius: 6px; background: var(--el-bg-color) }
.todo-table { min-width: 1000px }
.todo-title { max-width: 100%; justify-content: flex-start; font-weight: normal }
.todo-title :deep(span) { overflow: hidden; text-overflow: ellipsis; white-space: nowrap }
.todo-status { display: flex; align-items: center; gap: 4px; flex-wrap: wrap }
.project-code { color: var(--el-text-color-secondary); font-size: 12px }
.my-todos>[class~="el-pagination"] { justify-content: flex-end; flex-shrink: 0; flex-wrap: wrap; row-gap: 8px }
@media (max-width: 600px) { .my-todos>[class~="el-pagination"] { justify-content: flex-start } }
</style>

View File

@ -15,15 +15,15 @@
<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="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 === 'IN_PROGRESS'" :disabled="busy || !canCompleteWorkItem(detail)" :title="canCompleteWorkItem(detail) ? undefined : completionBlockedText(detail)" @click="transition('COMPLETED')">完成</el-button>
<el-button v-if="detail.status === 'COMPLETED'" :disabled="busy" @click="transition('CLOSED')">关闭</el-button>
<el-button v-if="detail.status === 'CLOSED'" :disabled="busy" @click="transition('COMPLETED')">重开到已完成</el-button>
<el-button v-if="detail.status === 'CLOSED'" :disabled="busy || !canCompleteWorkItem(detail)" :title="canCompleteWorkItem(detail) ? undefined : completionBlockedText(detail)" @click="transition('COMPLETED')">重开到已完成</el-button>
<el-button v-if="!['READY', 'CLOSED'].includes(detail.status)" :disabled="busy" @click="transition('READY')">回退待开始</el-button>
<el-button v-if="['READY', 'IN_PROGRESS'].includes(detail.status)" :disabled="busy" @click="transition('CANCELLED')">取消工作项</el-button>
<el-button type="danger" text :disabled="busy" @click="remove">删除</el-button>
</div>
<el-alert v-if="!detail.canStart && detail.status === 'READY'" :title="blockedText" type="warning" :closable="false" class="failure" />
<el-alert v-if="detail.status === 'IN_PROGRESS' && detail.completionBlockedReasons?.length" type="warning" :closable="false" :title="`完成前请结束子任务:${detail.completionBlockedReasons.map(reason => reason.taskName).join('、')}`" class="failure" />
<el-alert v-if="['IN_PROGRESS', 'CLOSED'].includes(detail.status) && !canCompleteWorkItem(detail)" type="warning" :closable="false" :title="completionBlockedText(detail)" class="failure" />
<p v-if="detail.parentTaskId">父任务:<el-link type="primary" @click="emit('open', detail.parentTaskId)">{{ detail.parentTaskTitle }}</el-link>(预计时间须在父任务范围内)</p>
<section v-if="!detail.historical && detail.stageId && detail.stageAdmissionConditions?.length"><h3>阶段执行条件</h3><p class="muted">以下条件须全部满足:采购当前版本实际开始即放行直接下游,其他阶段须完成;继承的阶段组条件仍须全部子阶段完成。开始、完成及审批均由服务端复验。</p><article v-for="condition in detail.stageAdmissionConditions" :key="condition.stageId" class="condition"><div><el-tag size="small" :type="admissionAppearance(condition).type">{{ admissionAppearance(condition).label }}</el-tag><strong>{{ condition.sourceName }}</strong></div><p>当前:{{ stageStatusNames[condition.currentStatus] || condition.currentStatus }} · 要求:{{ condition.expectedStatus === 'STARTED' ? '当前版本已开始(开始即放行)' : '当前版本已完成' }}</p><p>{{ condition.expectedStatus === 'STARTED' ? '实际开始' : '实际完成' }}:{{ displayTime(condition.expectedStatus === 'STARTED' ? condition.startedAt : condition.completedAt) }}</p><p v-if="condition.message">{{ condition.message }}</p></article><el-alert v-if="detail.stageBlockedReasons?.length" type="warning" :closable="false" :title="`仍等待:${detail.stageBlockedReasons.map(reason => reason.sourceName).join('、')}`" /></section>
<p class="description">{{ detail.description || '尚未填写描述' }}</p>
@ -83,6 +83,7 @@ import type { WorkItem, Member, Condition, Lifecycle, StageEdge, Stage, StageAdm
import { typeNames, priorityNames, statusNames, stageStatusNames, actionNames, itemStatusLabel } from '../../../shared/constants/labels'
import { scheduleSourceLabel } from '../../../shared/constants/schedules'
import { ATTACHMENT_MAX_BYTES, ATTACHMENT_MAX_SIZE_LABEL } from '../../../shared/constants/attachments'
import { canCompleteWorkItem, completionBlockedText } from '../utils/execution'
const lifecycleLabels: Record<string, string> = statusNames
const props = withDefaults(defineProps<{ projectId?: number; iterationId?: number; canExecute?: boolean; id: number | null; refreshKey: number; items: WorkItem[]; members: Member[]; canWrite: boolean; canManage?: boolean; stages?: Stage[]; stageEdges?: StageEdge[] }>(), { stages: () => [], stageEdges: () => [], canExecute: true })
@ -195,14 +196,23 @@ async function action(commit: () => Promise<unknown>, discussion = false, onSucc
} catch (error) { if (sequence === scopeSequence) failure.value = errorText(error) }
finally { if (sequence === scopeSequence) busy.value = false }
}
/** 开始只调用统一后端方法,传递详情版本防止过期点击。 */
async function start() { if (props.canExecute && writable.value && detail.value) { const item = detail.value; await action(() => api.start(item.id, item.version)) } }
/** 开始必须具备服务端 canStart,合成事件也不能绕过负责人或准入限制;提交详情版本防止过期点击。 */
async function start() { if (props.canExecute && writable.value && detail.value?.canStart) { const item = detail.value; await action(() => api.start(item.id, item.version)) } }
/** 参考计划按整日重新确认,须通过阶段、父子和前置校验;失败保留待复核状态。 */
async function confirmReview() { if (detail.value?.scheduleReviewRequired) { const item = detail.value; await action(() => api.confirmScheduleReview(item.id, item.version)) } }
/** 排期成功后关闭草稿并刷新详情和所有视图。 */
async function scheduleSaved() { scheduleOpen.value = false; emit('changed'); await load() }
/** 回退、完成、取消及关闭/重开由后端状态机和子任务门禁判断,不在前端强制写状态。 */
async function transition(status: Lifecycle) { if (detail.value) { const item = detail.value; await action(() => api.transition(item.id, status, item.version)) } }
/**
* 提交当前详情版本的状态动作;开始和任何进入完成的路径先检查服务端能力,防止事件绕过禁用按钮。
* @param status 目标状态;回退、取消及关闭保持原权限,服务端仍复验完整状态机和子任务门禁。
*/
async function transition(status: Lifecycle) {
const item = detail.value
if (!item) return
if (status === 'IN_PROGRESS' && (!props.canExecute || !item.canStart)) { failure.value = blockedText.value; return }
if (status === 'COMPLETED' && !canCompleteWorkItem(item)) { failure.value = completionBlockedText(item); return }
await action(() => api.transition(item.id, status, item.version))
}
/** 确认绑定打开时的工作项及版本,换对象或关闭后作废;后端继续复验软删除条件。 */
async function remove() {
if (!detail.value || !writable.value || busy.value || loading.value || deleteConfirmationOpen.value) return

View File

@ -0,0 +1,19 @@
import type { WorkItem } from '../../../types'
/**
* 判断当前工作项能否进入已完成,统一看板和详情的服务端能力解释。
* @param item 当前响应快照;关闭后重开沿用执行身份能力,进行中仍须满足子任务等完成门禁。
* @returns 仅服务端明确授权时返回 true;旧响应缺少能力时保守禁用,不从成员筛选推断身份。
*/
export function canCompleteWorkItem(item: WorkItem): boolean {
return item.status === 'CLOSED' ? item.canExecuteWorkItem === true : item.status === 'IN_PROGRESS' && item.canComplete === true
}
/**
* 展示服务端完成阻塞原因,身份限制与未结束子任务使用同一提示口径。
* @param item 当前工作项;子任务名称仅在相关原因中拼接,避免身份原因被错误解释为子任务阻塞。
* @returns 可直接显示的说明;响应缺少原因时提示重新确认负责人和执行条件。
*/
export function completionBlockedText(item: WorkItem): string {
return item.completionBlockedReasons?.map(reason => reason.taskName ? `${reason.taskName}:${reason.message || '子任务尚未结束'}` : reason.message || reason.sourceName || '完成条件未满足').join(';') || '当前无法完成工作项,请确认负责人及执行条件'
}

View File

@ -1,16 +1,17 @@
<template>
<ElConfigProvider size="small">
<el-alert v-if="invalidLink" type="error" title="项目链接无效,请返回项目协作列表" :closable="false" />
<ProjectCatalog v-show="!workspaceKey" :active="catalogActive" @open="enterProject" />
<ProjectCatalog v-show="!workspaceKey" :active="catalogActive" @open="enterProject" @todo="openTodo" />
<ProjectWorkspace v-if="workspaceKey && !invalidLink" :key="workspaceKey" @back="backToCatalog" />
</ElConfigProvider>
</template>
<script setup lang="ts">
import { computed, ref, watch } from 'vue'
import { useRoute, useRouter, type LocationQuery } from 'vue-router'
import { ElConfigProvider } from 'element-plus'
import { ElConfigProvider, ElMessage } from 'element-plus'
import ProjectCatalog from './views/projects/ProjectCatalog.vue'
import ProjectWorkspace from './views/workspace/ProjectWorkspace.vue'
import type { MyTodo } from './types'
const route = useRoute(), router = useRouter(), pagePath = route.path
const ownQuery = ref<LocationQuery>({ ...route.query })
@ -38,6 +39,19 @@ function enterProject(id: number) {
void router.push({ path: pagePath, query: { sourceProjectId: String(id) } })
}
/**
* 待办携带明确的源项目、迭代和对象进入工作区;阶段审批独立于工作项,不能用阶段 ID 代替 itemId。
* @param todo 服务端按当前用户过滤的待办快照;工作区仍会重新鉴权及验证状态和当前版本。
*/
function openTodo(todo: MyTodo) {
const query = { sourceProjectId: String(todo.sourceProjectId), iterationId: String(todo.iterationId), fromTodo: '1' }
if (todo.kind === 'WORK_ITEM' && todo.workItemId) {
void router.push({ path: pagePath, query: { ...query, view: 'board', itemId: String(todo.workItemId), focusItemId: String(todo.workItemId) } })
} else if (todo.kind === 'STAGE_APPROVAL' && todo.stageId && todo.approvalId) {
void router.push({ path: pagePath, query: { ...query, view: 'flow', stageId: String(todo.stageId), approvalId: String(todo.approvalId) } })
} else ElMessage.error('待办链接不完整,请刷新我的代办')
}
/** 返回目录移除工作区范围,目录组件保留筛选和分页,并重新读取即时权限。 */
function backToCatalog() {
void router.push({ path: pagePath, query: {} })

View File

@ -7,3 +7,4 @@ export type * from './stage-completion'
export type * from './flow'
export type * from './rework'
export type * from './schedule'
export type * from './todo'

View File

@ -0,0 +1,34 @@
export type MyTodoKind = 'WORK_ITEM' | 'STAGE_APPROVAL'
/** 当前登录用户的只读待办快照;源项目 ID 用于进入目录对应项目,内部 ID 不可替代。 */
export interface MyTodo {
key: string
kind: MyTodoKind
sourceProjectId: number
projectId: number
projectCode: string
projectName: string
iterationId: number
iterationName: string
workItemId: number | null
stageId: number | null
approvalId: number | null
title: string
status: 'READY' | 'IN_PROGRESS' | 'PENDING'
overdue: boolean
plannedEndAt: string | null
myRole: 'ASSIGNEE' | 'COLLABORATOR' | 'APPROVER'
}
export interface MyTodoQuery {
page: number
pageSize: number
kind?: MyTodoKind
}
export interface MyTodoPage {
rows: MyTodo[]
total: number
page: number
pageSize: number
}

View File

@ -13,7 +13,7 @@ export interface ItemQuery {
stageId?: number | null
from?: string | null
to?: string | null
/** 仅甘特使用;负责人或协作人命中任一成员即显示,空集合表示全部。 */
/** 仅看板或甘特使用;负责人或协作人命中任一成员即显示,空集合表示全部。 */
memberIds?: number[]
}
@ -72,6 +72,8 @@ export interface WorkItem {
actualStartAt: string | null
actualEndAt: string | null
canStart: boolean
/** 服务端综合项目、迭代、阶段可写性及当前负责人身份计算;缺失时不能推断执行授权。 */
canExecuteWorkItem?: boolean
blockedReasons: Reason[]
stageBlockedReasons?: Reason[]
stageAdmissionConditions?: StageAdmissionCondition[]

View File

@ -3,41 +3,56 @@
<section v-for="(label, state) in statusNames" :key="state" class="lane" @dragover.prevent @drop.prevent="drop(state)">
<header>{{ label }} <span>{{ counts?.[state] ?? itemsByStatus[state].length }}</span></header>
<div class="lane-content" role="region" :aria-label="label + '工作项'" tabindex="0">
<article v-for="item in itemsByStatus[state]" :key="item.id" class="work-card" :draggable="canWrite && !item.stageReadOnly && !busy.has(item.id)" @dragstart="dragged = item.id" @dragend="dragged = null" @click="emit('open', item.id)">
<article v-for="item in itemsByStatus[state]" :key="item.id" class="work-card" :class="{ 'work-card--focused': item.id === focusedItem?.id }" :data-work-item-id="item.id" :draggable="canWrite && !item.stageReadOnly && !busy.has(item.id)" tabindex="0" @keydown.enter="emit('open', item.id)" @dragstart="dragged = item.id" @dragend="dragged = null" @click="emit('open', item.id)">
<span v-if="item.id === focusedItem?.id" class="focus-label">定位工作项</span>
<div class="card-meta"><span class="card-id">{{ typeNames[item.type] }} #{{ item.id }}</span><small v-if="item.stageId" class="stage-version" :title="item.stagePath || stagesById.get(item.stageId)?.name">{{ item.stagePath || stagesById.get(item.stageId)?.name || '阶段' }} · v{{ stagesById.get(item.stageId)?.revisionNo || 1 }}</small><el-tag size="small" :type="item.priority === 'URGENT' ? 'danger' : 'info'">{{ priorityNames[item.priority] }}</el-tag></div>
<strong class="card-title" :title="item.title">{{ item.title }}</strong>
<el-tag v-if="item.stageApprovalStatus === 'PENDING' || item.stageApprovalStatus === 'REJECTED'" size="small" :type="item.stageApprovalStatus === 'PENDING' ? 'warning' : 'danger'">阶段{{ approvalStatusNames[item.stageApprovalStatus] }}</el-tag>
<div v-if="item.parentTaskId" class="card-family" :title="'父任务:' + item.parentTaskTitle">↳ 子任务 · {{ item.parentTaskTitle }}</div><div v-else-if="item.childCount" class="card-family">子任务已结束 {{ item.childTerminalCount }}/{{ item.childCount }}</div>
<div class="card-footer"><div class="card-tags"><el-tag v-if="item.overdue" size="small" type="danger">超期未完成</el-tag><el-tag v-if="item.dependencyBlocked" size="small" type="warning">前置阻塞</el-tag><el-tag v-if="item.scheduleReviewRequired" size="small" type="warning">{{ item.scheduleReviewClosed ? '本轮未确认排期' : '排期待复核' }}</el-tag><el-tag v-if="item.scheduleConstraints.scheduleValidationStatus !== 'VALID'" size="small" type="info">{{ item.scheduleConstraints.scheduleValidationStatus === 'INCOMPLETE' ? '排期未完成' : '排期冲突' }}</el-tag></div><time class="card-deadline" :datetime="item.plannedEndAt || undefined">{{ item.plannedEndAt ? plannedDate(item.plannedEndAt, item.timezone) : '尚未设置预计结束' }}</time></div>
</article>
<el-button v-if="(counts?.[state] || 0) > itemsByStatus[state].length" size="small" text @click="emit('load-more', state)">加载更多({{ itemsByStatus[state].length }}/{{ counts?.[state] }})</el-button>
<el-button v-if="(counts?.[state] || 0) > loadedCounts[state]" size="small" text @click="emit('load-more', state)">加载更多({{ loadedCounts[state] }}/{{ counts?.[state] }})</el-button>
<div v-if="!itemsByStatus[state].length" class="empty-lane">暂无工作项</div>
</div>
</section>
</div>
</template>
<script setup lang="ts">
import { computed, nextTick, onBeforeUnmount, onMounted, reactive, ref } from 'vue'
import { computed, nextTick, onBeforeUnmount, onMounted, reactive, ref, watch } from 'vue'
import { ElMessage } from 'element-plus'
import type { WorkItem, Lifecycle, Stage } from '../../types'
import { statusNames, typeNames, priorityNames, approvalStatusNames } from '../../shared/constants/labels'
import { plannedDate } from '../../shared/utils/time'
import { api, errorText } from '../../api'
import { moveCard } from '../../shared/utils/optimistic'
const props = withDefaults(defineProps<{ items: WorkItem[]; stages?: Stage[]; canWrite: boolean; canExecute?: boolean; counts?: Partial<Record<Lifecycle, number>> }>(), { stages: () => [], canExecute: true })
import { canCompleteWorkItem, completionBlockedText } from '../../features/work-items/utils/execution'
const props = withDefaults(defineProps<{ items: WorkItem[]; focusedItem?: WorkItem | null; stages?: Stage[]; canWrite: boolean; canExecute?: boolean; counts?: Partial<Record<Lifecycle, number>> }>(), { stages: () => [], canExecute: true, focusedItem: null })
const emit = defineEmits<{ open: [id: number]; changed: []; 'load-more': [state: Lifecycle] }>()
const dragged = ref<number | null>(null); const busy = reactive(new Set<number>())
/** 一次遍历按状态分列并保持接口顺序;乐观移动和失败恢复会自动重算,避免每列重复扫描全部工作项。 */
/** 定位项临时置顶,按 ID 与普通分页去重;其真实状态仍决定所属列,不插入业务分页数组。 */
const itemsByStatus = computed(() => {
const result: Record<Lifecycle, WorkItem[]> = { READY: [], IN_PROGRESS: [], COMPLETED: [], CANCELLED: [], CLOSED: [] }
for (const item of props.items) result[item.status]?.push(item)
const rows = props.focusedItem ? [props.focusedItem, ...props.items.filter(item => item.id !== props.focusedItem?.id)] : props.items
for (const item of rows) result[item.status]?.push(item)
return result
})
/** 加载更多按服务端分页已返回的条数计算,不能因补入一张定位卡片而提前隐藏最后一页。 */
const loadedCounts = computed(() => {
const counts: Record<Lifecycle, number> = { READY: 0, IN_PROGRESS: 0, COMPLETED: 0, CANCELLED: 0, CLOSED: 0 }
for (const item of props.items) counts[item.status]++
return counts
})
/** 阶段名称和版本按 ID 索引,卡片较多时不为每个字段重复线性查找阶段。 */
const stagesById = computed(() => new Map(props.stages.map(stage => [stage.id, stage])))
// 拖动和提交期间暂停工作区静默同步,避免状态列被在途旧快照覆盖。
defineExpose({ isEditing: computed(() => dragged.value !== null || busy.size > 0) })
const board = ref<HTMLElement | null>(null), boardHeight = ref(480)
/** 只在定位身份变化时滚动,静默刷新卡片字段不会把用户阅读位置反复拉回顶部。 */
watch(() => props.focusedItem?.id, async id => {
if (!id) return
await nextTick()
board.value?.querySelector<HTMLElement>(`[data-work-item-id="${id}"]`)?.scrollIntoView({ block: 'nearest', inline: 'center', behavior: 'smooth' })
}, { immediate: true, flush: 'post' })
let sizeObserver: ResizeObserver | undefined
/** 按看板实际顶部计算剩余视口高度,顶部筛选换行时也不会让卡片数量撑高整个页面。 */
function updateBoardHeight() { if (board.value) boardHeight.value = Math.max(160, window.innerHeight - Math.max(0, board.value.getBoundingClientRect().top) - 32) }
@ -52,11 +67,24 @@ onMounted(() => {
})
/** 页签切走会卸载看板,释放观察器与窗口监听,避免重复进入累积回调。 */
onBeforeUnmount(() => { sizeObserver?.disconnect(); window.removeEventListener('resize', updateBoardHeight) })
/** 拖入进行中必须调用开始接口;失败恢复卡片并展示具体原因,成功后刷新版本。 */
/**
* 拖动开始或完成先检查服务端能力,再进行乐观移动;避免非负责人短暂看到执行成功的状态。
* @param state 目标状态;进行中调用统一开始接口,关闭后重开完成也须满足当前负责人身份。
* 定位项虽可能尚未出现在分页内,仍使用相同的服务端执行能力及提交入口。
* 其它状态继续由原状态机验证,不能因为缺少执行身份就禁用整张卡片拖动。
*/
async function drop(state: Lifecycle) {
const item = props.items.find(i => i.id === dragged.value)
const item = dragged.value === props.focusedItem?.id ? props.focusedItem : props.items.find(i => i.id === dragged.value)
dragged.value = null
if (!props.canWrite || state === 'IN_PROGRESS' && !props.canExecute || !item || item.status === state || busy.has(item.id)) return
if (state === 'IN_PROGRESS' && !item.canStart) {
ElMessage({ type: 'error', message: item.blockedReasons.map(reason => reason.message || reason.sourceName).filter(Boolean).join(';') || '当前无法开始,请确认负责人及执行条件', duration: 8000 })
return
}
if (state === 'COMPLETED' && !canCompleteWorkItem(item)) {
ElMessage({ type: 'error', message: completionBlockedText(item), duration: 8000 })
return
}
busy.add(item.id)
try { await moveCard(item, state, () => state === 'IN_PROGRESS' ? api.start(item.id, item.version) : api.transition(item.id, state, item.version)); ElMessage.success('状态已更新') }
catch (error) { ElMessage({ type: 'error', message: errorText(error), duration: 8000 }) }
@ -67,6 +95,8 @@ async function drop(state: Lifecycle) {
.board{display:grid;grid-template-columns:repeat(5,minmax(224px,1fr));grid-template-rows:minmax(0,1fr);gap:10px;min-width:0;overflow-x:auto;overflow-y:hidden;padding-bottom:6px;box-sizing:border-box}
.lane{display:flex;flex-direction:column;min-width:0;min-height:0;background:var(--el-fill-color-light);border-radius:9px;padding:10px 5px 8px 9px;overflow:hidden}
.lane header{flex:none;font-size:13px;font-weight:600;line-height:20px;margin:0 5px 8px 1px}.lane header span{margin-left:6px;color:var(--el-text-color-secondary);font-size:12px;font-weight:400}
.work-card.work-card--focused{outline:2px solid var(--el-color-primary);outline-offset:-1px;background:var(--el-color-primary-light-9)}
.focus-label{display:block;font-size:11px;line-height:16px;color:var(--el-color-primary);margin-bottom:3px}
/* 始终保留滚动区域与槽位,仅改变滚动条颜色,悬停显隐不会导致卡片宽度跳动。 */
.lane-content{flex:1;min-height:0;overflow-y:auto;overflow-x:hidden;overscroll-behavior-y:contain;scrollbar-gutter:stable;scrollbar-width:thin;scrollbar-color:transparent transparent;padding-right:4px}
.lane:hover .lane-content,.lane-content:focus-visible{scrollbar-color:var(--el-fill-color-darker) transparent}.lane-content:focus-visible{outline:1px solid var(--el-color-primary);outline-offset:-1px;border-radius:5px}

View File

@ -81,7 +81,7 @@ import { FLOW_REWORK_COLOR } from './constants/theme'
import StageReworkDialog from '../../features/stages/components/StageReworkDialog.vue'
import StageWorkItemsDrawer from '../../features/stages/components/StageWorkItemsDrawer.vue'
const props = defineProps<{ view: FlowView; projectId: number; iterationId?: number; userId: number | string; members: Member[]; canCreate: boolean; canManage: boolean; active: boolean }>()
const props = defineProps<{ view: FlowView; projectId: number; iterationId?: number; userId: number | string; members: Member[]; canCreate: boolean; canManage: boolean; active: boolean; focusStageId?: number | null }>()
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
@ -126,9 +126,27 @@ watch(() => props.view, () => {
rebuild()
}, { immediate: true })
watch(() => [props.canCreate, props.canManage], rebuild)
/**
* 待办已在工作区复核审批身份;这里只展开目标父组、定位节点并打开当前版本交付及审批面板。
* 原定位清空或换目标时先关闭旧抽屉,避免新申请失效后仍显示另一阶段;普通快照不会重开抽屉。
*/
watch(() => props.focusStageId, async (id, previousId) => {
if (previousId != null) { drawerStageId.value = null; drawerEditing.value = false }
const stage = props.view.stages.find(stage => stage.id === id)
if (!stage || !props.active) return
if (stage.parentStageId && collapsedStages.value.includes(stage.parentStageId)) {
collapsedStages.value = collapsedStages.value.filter(value => value !== stage.parentStageId)
rebuild()
}
await nextTick()
if (props.focusStageId !== id || !props.active) return
openDrawer(stage.id, 'current')
await fitView({ nodes: ['s:' + stage.id], padding: 0.4, maxZoom: 1, duration: 200 })
}, { immediate: true, flush: 'post' })
/** 生命周期或权限变成只读时关闭写对话框,避免已打开的入口继续提交。 */
watch(() => props.canManage, allowed => { if (!allowed) { stageOpen.value = false; stageNameOpen.value = false; renamingStage.value = null; reworkSourceId.value = null } })
watch(() => props.active, async active => { if (active) { await nextTick(); await restoreViewport() } else if (loaded) { draftViewport.value = { ...viewport.value }; savePreference() } })
/** 离开流程页签关闭其 Teleport 抽屉;返回时恢复视口,不凭旧定位 ID 重开用户已关闭的审批。 */
watch(() => props.active, async active => { if (active) { await nextTick(); await restoreViewport() } else { drawerStageId.value = null; drawerEditing.value = false; if (loaded) { draftViewport.value = { ...viewport.value }; savePreference() } } })
/** 按子画布和外框实际尺寸重建阶段摘要,折叠只隐藏内部节点,不改变共享业务图。 */
function rebuild() {

View File

@ -15,6 +15,7 @@
</el-select>
</el-form-item>
<el-form-item><el-button icon="Search" type="primary" native-type="submit">搜索</el-button><el-button icon="Refresh" @click="reset">重置</el-button><el-button icon="Refresh" :loading="loading" @click="load">刷新</el-button></el-form-item>
<el-form-item class="catalog-todos-entry"><el-button type="primary" size="small" @click="todosOpen = true">我的代办</el-button></el-form-item>
</el-form>
<el-alert v-if="failure" class="failure" type="error" :title="failure" :closable="false" show-icon />
<div class="catalog-table">
@ -32,16 +33,20 @@
</el-table>
</div>
<el-pagination v-model:current-page="query.page" :page-size="query.pageSize" :total="total" layout="total, prev, pager, next" @current-change="load" />
<MyTodosDrawer v-model="todosOpen" :active="active" @todo="emit('todo', $event)" />
</section>
</template>
<script setup lang="ts">
import { toRef } from 'vue'
import { ref, toRef } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { vLoading } from 'element-plus'
import { useProjectCatalog } from '../../composables/useProjectCatalog'
import MyTodosDrawer from '../../features/todos/components/MyTodosDrawer.vue'
import type { MyTodo } from '../../types'
const props = defineProps<{ active: boolean }>()
const emit = defineEmits<{ open: [sourceProjectId: number] }>()
const emit = defineEmits<{ open: [sourceProjectId: number]; todo: [todo: MyTodo] }>()
const todosOpen = ref(false)
const route = useRoute(), router = useRouter(), pagePath = route.path
const { query, rows, total, loading, failure, load, search, reset } = useProjectCatalog(toRef(props, 'active'))
const statusNames: Record<number, string> = { 0: '立项', 1: '进行中', 2: '结题', 3: '终止' }
@ -70,8 +75,9 @@ function statusType(status: number) {
.catalog-header { justify-content: space-between; flex-shrink: 0 }
.catalog-header h1 { margin: 0; font-size: 24px; line-height: 32px }
.catalog-header span { font-size: 12px; color: var(--el-text-color-secondary) }
.catalog-filters { flex-shrink: 0 }
.catalog-filters { display: flex; flex-wrap: wrap; align-items: center; row-gap: 8px; flex-shrink: 0 }
.catalog-filters :deep([class~="el-form-item"]) { margin-bottom: 0 }
.catalog-filters :deep(.catalog-todos-entry) { margin-left: auto; margin-right: 0 }
.keyword { width: 250px }.select { width: 130px }
.catalog-table { flex: 1; min-height: 220px; border: 1px solid var(--el-border-color-lighter); border-radius: 8px; overflow: hidden; background: var(--el-bg-color) }
.project-catalog>[class~="el-pagination"] { justify-content: flex-end; flex-shrink: 0 }

View File

@ -19,6 +19,7 @@
:closable="false"
class="failure"
/>
<el-alert v-if="targetFailure" type="warning" :title="targetFailure" :closable="false" show-icon class="failure" />
<el-empty
v-if="!current"
:description="loading ? '正在加载项目协作' : '项目不存在或无权访问'"
@ -115,6 +116,23 @@
v-model="blockedOnly"
active-text="仅看依赖阻塞"
/>
<el-select
v-if="tab === 'board'"
v-model="boardMemberIds"
class="board-member-filter"
size="small"
multiple
filterable
clearable
collapse-tags
collapse-tags-tooltip
:max-collapse-tags="2"
placeholder="全部成员"
aria-label="按成员筛选看板"
title="按负责人或协作人筛选;多选取并集,清空显示全部"
>
<el-option v-for="member in members" :key="member.userId" :value="member.userId" :label="member.name || `用户 #${member.userId}`" />
</el-select>
<template v-if="tab === 'gantt'">
<el-select
v-model="ganttMemberIds"
@ -160,6 +178,7 @@
:key="`${current.id}:${iterationId}`"
:items="items"
:counts="boardCounts"
:focused-item="focusedItem"
:stages="flowView?.stages || []"
:can-write="canWrite"
:can-execute="canExecute"
@ -208,6 +227,7 @@
:can-create="canCreate"
:can-manage="canWrite && current.canManage"
:active="tab === 'flow'"
:focus-stage-id="focusedStageId"
@open="detailId = $event"
@changed="refresh"
@create="openEditor(null, $event)"
@ -302,9 +322,9 @@ const emit = defineEmits<{ back: [] }>()
const {
projectId, iterations, iterationId, includeArchived,
items, members, flowView, current, selectedIteration, zone, canWrite, canCreate, canExecute,
loading, failure, tab, keyword, typeFilter, blockedOnly, stageFilter, detailId, refreshKey, selection,
loading, failure, tab, keyword, typeFilter, blockedOnly, stageFilter, detailId, focusedItem, focusedStageId, targetFailure, refreshKey, selection,
editing, editorOpen, creatingParent, defaultStageId, page, pageSize, total, boardCounts,
ganttFrom, ganttTo, ganttMemberIds, ganttExportQuery, ganttExportFilters, membersOpen, inviteUser, inviteRole, userCandidates, batchOpen,
ganttFrom, ganttTo, ganttMemberIds, boardMemberIds, ganttExportQuery, ganttExportFilters, membersOpen, inviteUser, inviteRole, userCandidates, batchOpen,
notifications, statCards, userStore,
refreshWorkspace, refresh, loadBoardMore, moveGanttWindow,
changeIteration, iterationsChanged, archiveFilterChanged, openNotice,
@ -435,7 +455,8 @@ const {
width: 160px
}
.filters .gantt-member-filter {
.filters .gantt-member-filter,
.filters .board-member-filter {
width: 230px
}