feat: 新增“我的代办”

This commit is contained in:
zhanghao 2026-11-02 16:55:58 +08:00
parent 5231df9153
commit 23352ada54
21 changed files with 783 additions and 34 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

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

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

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

@ -81,6 +81,14 @@ manage/
- 后端在当前项目、迭代鉴权后,先组合成员、标题、类型和时间窗口条件,再计算总数和分页。未排期工作项继续保留查看入口,完整依赖与排期校验不受筛选影响。
- 看板与甘特分别保存成员选择,普通列表和前置工作项候选不受影响;切换项目或迭代会清空,失效成员自动移除。看板五列计数、加载更多和静默刷新共用当前成员条件,条件改变后从第一页读取并丢弃旧响应;甘特筛选保留命中项所属阶段作为上下文。成员条件使用现有分工字段,无需数据库结构升级。
## 我的代办
- 外部项目表格右上角的“我的代办”汇总本人负责或协作的待开始、进行中工作项(含超期未完成),以及待本人审批的阶段完成申请;支持类别筛选、分页和刷新。
- 数据从现有表实时查询,项目成员按原项目 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)。
## 检查命令
在 `ruoyi-ui-vue3` 执行:

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,7 +19,7 @@ import type ItemDetail from '../features/work-items/components/ItemDetail.vue'
* 协调项目协作页面的项目/迭代范围、加载、路由及编辑状态。
* 将原页面生命周期集中在同一个 setup 调用中,保留请求代次和轮询暂停规则,
* 防止拆分视图后出现重复轮询或旧迭代响应覆盖新范围。
* 首次进入默认展示排在首位的流程视图,使项目阶段进度优先可见。
* 首次进入默认展示流程视图;待办深链接恢复其明确的看板或阶段及完整归属。
* 看板和甘特各自保存成员读取条件,切换迭代清空,继续由后端完整图校验执行及排期。
* 轮询静默合并变化的快照,保留选择和已加载分页;编辑及拖动期间不提交后台结果。
* @returns 页面装配使用的响应式状态、组件引用和业务动作;解构后仍保持 Ref。
@ -61,7 +62,7 @@ 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('')
@ -99,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
@ -123,8 +127,12 @@ 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)
}
@ -231,6 +239,8 @@ export function useProjectCollaboration() {
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]))
// 保留有效勾选,但同步其版本;删除或离开当前筛选范围的行不能继续参与批量操作。
@ -293,6 +303,8 @@ export function useProjectCollaboration() {
/** 清空旧范围和未提交输入;重置期间暂停成员 watcher 查询,避免仍向旧迭代发起请求。 */
function clearScope() {
clearingScope = true
clearTarget()
restoredTargetKey = ''
scopeSequence++
refreshSequence++
navigationSequence++
@ -378,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。 */
@ -529,18 +562,23 @@ 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' && !clearingScope) { page.value = 1; void refreshData(applyingBackgroundMembers) } }, { 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) {
if (tab.value === 'board' && !clearingScope && !initializing && !restoringRoute) {
if (!applyingBackgroundMembers && focusedItem.value) { clearTarget(); syncQuery() }
items.value = []
page.value = 1
void refreshData(applyingBackgroundMembers)
@ -570,7 +608,7 @@ export function useProjectCollaboration() {
}
})
/** 浏览器前进后退恢复同项目迭代;跨项目切换由页面装配重新创建独立工作区。 */
/** 浏览器导航恢复同项目迭代和待办目标;只有鉴权读取归属后才打开定位详情。 */
watch(() => route?.query, async value => {
if (!active || route.path !== pagePath || Number(value?.sourceProjectId) !== sourceProjectId.value) return
restoringRoute = true
@ -579,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()
@ -595,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()
@ -617,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) }
@ -636,8 +697,10 @@ export function useProjectCollaboration() {
onMounted(() => { void initializeWorkspace() })
/** 缓存页离开时取消定位与所有在途导航;重新激活按当时路由读取,不能复活旧待办。 */
onDeactivated(() => {
active = false
clearTarget()
scopeSequence++
if (timer) clearInterval(timer)
timer = undefined
@ -655,8 +718,10 @@ export function useProjectCollaboration() {
if (!initializing) void initializeWorkspace()
})
/** 真正卸载时释放轮询并使读取代次失效,待办响应不能写回已经销毁的工作区。 */
onBeforeUnmount(() => {
active = false
clearTarget()
scopeSequence++
if (timer) clearInterval(timer)
refreshSequence++
@ -669,7 +734,7 @@ 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, boardMemberIds, ganttExportQuery, ganttExportFilters, membersOpen, inviteUser, inviteRole, userCandidates, batchOpen,
notifications, statCards, userStore,

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

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

@ -3,21 +3,22 @@
<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'
@ -25,20 +26,33 @@ import { plannedDate } from '../../shared/utils/time'
import { api, errorText } from '../../api'
import { moveCard } from '../../shared/utils/optimistic'
import { canCompleteWorkItem, completionBlockedText } from '../../features/work-items/utils/execution'
const props = withDefaults(defineProps<{ items: WorkItem[]; stages?: Stage[]; canWrite: boolean; canExecute?: boolean; counts?: Partial<Record<Lifecycle, number>> }>(), { stages: () => [], canExecute: true })
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) }
@ -56,10 +70,11 @@ onBeforeUnmount(() => { sizeObserver?.disconnect(); window.removeEventListener('
/**
* 拖动开始或完成先检查服务端能力,再进行乐观移动;避免非负责人短暂看到执行成功的状态。
* @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) {
@ -80,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 ? '正在加载项目协作' : '项目不存在或无权访问'"
@ -177,6 +178,7 @@
:key="`${current.id}:${iterationId}`"
:items="items"
:counts="boardCounts"
:focused-item="focusedItem"
:stages="flowView?.stages || []"
:can-write="canWrite"
:can-execute="canExecute"
@ -225,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)"
@ -319,7 +322,7 @@ const emit = defineEmits<{ back: [] }>()
const {
projectId, iterations, iterationId, includeArchived,
items, members, flowView, current, selectedIteration, zone, canWrite, canCreate, canExecute,
loading, failure, tab, keyword, typeFilter, blockedOnly, 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, boardMemberIds, ganttExportQuery, ganttExportFilters, membersOpen, inviteUser, inviteRole, userCandidates, batchOpen,
notifications, statCards, userStore,