feat: 更改后台静默更新

This commit is contained in:
zhanghao 2026-10-16 16:49:45 +08:00
parent 2b7828f255
commit a3e1abbe40
11 changed files with 226 additions and 76 deletions

View File

@ -17,6 +17,10 @@ export class PmApiError extends Error {
this.details = body as typeof this.details
}
}
/** 区分确定的访问失效与短暂连接失败;静默同步仍须清除已撤权对象,不能沿用旧权限。 */
export function isAccessFailure(error: unknown): boolean {
return error instanceof PmApiError && ['401', '403', '404', 'UNAUTHORIZED', 'FORBIDDEN', 'NOT_FOUND'].includes(error.code)
}
/** 将业务原因转成简洁文本,保留受影响工作项和目标状态而不只显示 HTTP 错误码。 */
export function errorText(error: unknown): string {

View File

@ -17,5 +17,5 @@ export const api = {
...notificationApi,
}
export { PmApiError, errorText } from './errors'
export { PmApiError, errorText, isAccessFailure } from './errors'
export { downloadAttachment } from './attachments'

View File

@ -2,13 +2,16 @@ import { computed, onMounted, onBeforeUnmount, onActivated, onDeactivated, react
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import useUserStore from '@/store/modules/user'
import { api, errorText } from '../api'
import { api, errorText, isAccessFailure } from '../api'
import { plannedDate, planBoundary } from '../shared/utils/time'
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 type IterationControls from '../features/iterations/components/IterationControls.vue'
import type WorkFlow from '../views/flow/WorkFlow.vue'
import type WorkGantt from '../views/gantt/WorkGantt.vue'
import type WorkBoard from '../views/board/WorkBoard.vue'
import type ItemDetail from '../features/work-items/components/ItemDetail.vue'
/**
* 协调项目协作页面的项目/迭代范围、加载、路由及编辑状态。
@ -16,6 +19,7 @@ import type WorkGantt from '../views/gantt/WorkGantt.vue'
* 防止拆分视图后出现重复轮询或旧迭代响应覆盖新范围。
* 首次进入默认展示排在首位的流程视图,使项目阶段进度优先可见。
* 甘特成员选择仅作为读取条件,切换迭代清空,继续由后端完整图校验排期。
* 轮询静默合并变化的快照,保留选择和已加载分页;编辑及拖动期间不提交后台结果。
* @returns 页面装配使用的响应式状态、组件引用和业务动作;解构后仍保持 Ref。
* 注意:必须在页面 setup 内调用;卸载时清除定时器并使在途刷新失效。
*/
@ -32,6 +36,8 @@ export function useProjectCollaboration() {
const workFlow = useTemplateRef<InstanceType<typeof WorkFlow>>('workFlow')
const workGantt = useTemplateRef<InstanceType<typeof WorkGantt>>('workGantt')
const workBoard = useTemplateRef<InstanceType<typeof WorkBoard>>('workBoard')
const itemDetail = useTemplateRef<InstanceType<typeof ItemDetail>>('itemDetail')
const current = ref<Project | null>(null)
const sourceProjectId = ref<number | null>(requestedSource)
@ -95,93 +101,128 @@ export function useProjectCollaboration() {
let refreshSequence = 0, workspaceSequence = 0, navigationSequence = 0, iterationSequence = 0, initializationSequence = 0
let timer: ReturnType<typeof setInterval> | undefined
let active = true, initialized = false, initializing = false, restoringRoute = false
let polling = false, applyingBackgroundMembers = false
/** 只读取路由明确指定的项目;旧链接经服务鉴权解析绑定,不回退选择其他项目。 */
async function loadWorkspace(initialize = false) {
/** 固定读取路由项目;后台结果仅在页面仍空闲时应用,同内容沿用旧引用以避免重绘。 */
async function loadWorkspace(initialize = false, background = false) {
const sequence = ++workspaceSequence
let context: Project
if (sourceProjectId.value) {
context = initialize ? await api.openProject(sourceProjectId.value) : await api.projectContext(sourceProjectId.value)
} else if (projectId.value) context = await api.legacyProjectContext(projectId.value)
else throw new Error('项目链接缺少项目标识')
if (sequence !== workspaceSequence || !active) return false
current.value = context
if (sequence !== workspaceSequence || !active || background && !canSynchronize()) return false
current.value = retainSnapshot(current.value, context)
projectId.value = context.id
sourceProjectId.value = context.sourceProjectId
return true
}
/** 轮询重读固定项目的身份和迭代;失败时清除详情、草稿及旧权限,不显示其他项目。 */
/** 手动重读固定项目身份和迭代,保留显式加载及失败提示,不接受模板事件作为同步选项。 */
async function refreshWorkspace() {
await synchronizeWorkspace(false)
}
/**
* 协调项目身份、迭代和数据刷新;后台瞬时失败留待下一次重试,访问失效仍立即清理。
* @param background 是否来自后台轮询;此路径不显示遮罩,也不能覆盖后来发起的前台操作。
*/
async function synchronizeWorkspace(background: boolean) {
if (!active || restoringRoute) return
if (!initialized) {
if (!initializing) await initializeWorkspace()
return
}
let navigation = navigationSequence
const refreshAtStart = refreshSequence
try {
const iteration = iterationId.value
if (!await loadWorkspace() || navigation !== navigationSequence) return
if (!await loadIterations() || navigation !== navigationSequence) return
if (!await loadWorkspace(false, background) || navigation !== navigationSequence || background && refreshAtStart !== refreshSequence) return
if (!await loadIterations(undefined, background) || navigation !== navigationSequence || background && refreshAtStart !== refreshSequence) return
if (iteration !== iterationId.value) {
const people = members.value
clearScope()
navigation = navigationSequence
members.value = people
}
await refresh()
await refreshData(background)
} catch (error) {
if (!active || navigation !== navigationSequence) return
clearScope()
current.value = null
iterations.value = []
iterationId.value = null
failure.value = errorText(error)
if (!background || isAccessFailure(error)) invalidateWorkspace(error)
}
}
/** 权限、对象或会话明确失效时移除旧内容和草稿,后台同步也不能保留已失效的访问资格。 */
function invalidateWorkspace(error: unknown) {
clearScope()
current.value = null
iterations.value = []
iterationId.value = null
failure.value = errorText(error)
}
/** 分页筛选交由服务端;甘特独有的成员条件不传给列表、看板或前置选择器。 */
function query(view: ItemQuery['view']): ItemQuery {
return { view, page: page.value, pageSize, keyword: keyword.value, type: typeFilter.value, blockedOnly: blockedOnly.value, ...(view === 'gantt' ? { from: ganttFrom.value, to: ganttTo.value, memberIds: [...ganttMemberIds.value] } : {}) }
}
/** 只接受当前项目和迭代代次的结果,流程画布仅请求阶段摘要。 */
/** 用户主动刷新或业务操作完成时显示加载状态;独立包装避免分页事件的页码被当作后台标志。 */
async function refresh() {
await refreshData(false)
}
/**
* 只合并当前范围、请求代次的结果,流程仅请求阶段摘要,后台保留选择和看板已加载页数。
* @param background 后台刷新不显示加载状态,瞬时失败不清空已有内容,编辑开始后丢弃其响应。
*/
async function refreshData(background: boolean) {
const id = projectId.value, iteration = iterationId.value, sequence = ++refreshSequence
if (!id || !iteration || !current.value?.enabled) {
loading.value = false
if (!background) loading.value = false
return
}
loading.value = true
failure.value = ''
if (!background) { loading.value = true; failure.value = '' }
try {
const states: Lifecycle[] = ['READY', 'IN_PROGRESS', 'COMPLETED', 'CANCELLED', 'CLOSED']
const request = tab.value === 'board' ? Promise.all(states.map(status => api.items(id, iteration, { ...query('board'), page: 1, status }))) : ['flow', 'notifications'].includes(tab.value) ? Promise.resolve([]) : Promise.all([api.items(id, iteration, query(tab.value === 'gantt' ? 'gantt' : 'list'))])
const loadedPages = Object.fromEntries(states.map(status => [status, background ? boardPages[status] || 1 : 1]))
// 各列读取已加载的全部页再一起替换,避免轮询把“加载更多”的内容截回第一页。
// 页数在等待期间变化则放弃本轮结果,让用户当前的续页优先完成。
const request = tab.value === 'board' ? Promise.all(states.map(async status => {
const results = await Promise.all(Array.from({ length: loadedPages[status] }, (_, index) => api.items(id, iteration, { ...query('board'), page: index + 1, status })))
return { rows: results.flatMap(result => result.rows), total: results[0]?.total || 0 }
})) : ['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 (sequence !== refreshSequence || id !== projectId.value || iteration !== iterationId.value) return
items.value = pages.flatMap(result => result.rows)
if (!active || sequence !== refreshSequence || id !== projectId.value || iteration !== iterationId.value || background && (!canSynchronize() || tab.value === 'board' && states.some(status => loadedPages[status] !== (boardPages[status] || 1)))) return
items.value = reconcileRows(items.value, pages.flatMap(result => result.rows))
total.value = pages[0]?.total || 0
if (tab.value === 'board') {
boardCounts.value = Object.fromEntries(states.map((status, index) => [status, pages[index]?.total || 0]))
for (const status of states) boardPages[status] = 1
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
}
members.value = people
flowView.value = graph
iterations.value = iterations.value.map(row => row.id === iteration ? { ...row, graphVersion: graph.graphVersion ?? row.graphVersion } : row)
statistics.value = stats
notifications.value = notices
selection.value = []
refreshKey.value++
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 = ''
if (background) {
const available = new Map(items.value.map(row => [row.id, row]))
// 保留有效勾选,但同步其版本;删除或离开当前筛选范围的行不能继续参与批量操作。
selection.value = retainSnapshot(selection.value, selection.value.flatMap(row => available.get(row.id) ? [available.get(row.id)!] : []))
await itemDetail.value?.synchronize()
} else { selection.value = []; refreshKey.value++ }
} catch (error) {
if (sequence === refreshSequence) {
if (sequence === refreshSequence && active && isAccessFailure(error)) invalidateWorkspace(error)
else if (sequence === refreshSequence && !background) {
failure.value = errorText(error)
items.value = []
selection.value = []
flowView.value = null
statistics.value = {}
detailId.value = null
}
} finally {
if (sequence === refreshSequence) loading.value = false
if (!background && sequence === refreshSequence) loading.value = false
}
}
@ -225,6 +266,7 @@ export function useProjectCollaboration() {
statistics.value = {}
boardCounts.value = {}
boardBusy.clear()
for (const status of Object.keys(boardPages) as Lifecycle[]) delete boardPages[status]
flowView.value = null
selection.value = []
members.value = []
@ -239,11 +281,12 @@ export function useProjectCollaboration() {
inviteUser.value = null
userCandidates.value = []
failure.value = ''
loading.value = false
page.value = 1
}
/** 选择可见迭代并返回本次结果是否仍有效;元数据请求独立计次,失效调用者不得继续刷新视图。 */
async function loadIterations(preferred?: number | null) {
/** 可见迭代元数据独立计次;后台同值不重置引用,用户开始编辑或切换范围后不再应用结果。 */
async function loadIterations(preferred?: number | null, background = false) {
const id = projectId.value, sequence = ++iterationSequence, navigation = navigationSequence
if (!id) {
iterations.value = []
@ -251,13 +294,20 @@ export function useProjectCollaboration() {
return false
}
const [result, people] = await Promise.all([api.iterations(id, includeArchived.value), api.members(id)])
if (!active || id !== projectId.value || sequence !== iterationSequence || navigation !== navigationSequence) return false
iterations.value = result
members.value = people
if (!active || id !== projectId.value || sequence !== iterationSequence || navigation !== navigationSequence || background && !canSynchronize()) return false
iterations.value = retainSnapshot(iterations.value, result)
updateMembers(people, background)
iterationId.value = (result.find(row => row.id === (preferred || iterationId.value)) || result.find(row => row.status === 'ACTIVE' && !row.archivedAt) || result.find(row => !row.archivedAt) || result[0])?.id || null
return true
}
/** 成员失效时修剪甘特筛选,后台元数据更新不应间接触发带遮罩的前台刷新。 */
function updateMembers(people: Member[], background: boolean) {
applyingBackgroundMembers = background
try { members.value = retainSnapshot(members.value, people) }
finally { applyingBackgroundMembers = false }
}
/** 同项目切换迭代同样清理草稿并失效在途请求。 */
async function changeIteration(id: number) {
if (id === iterationId.value) return
@ -338,34 +388,38 @@ export function useProjectCollaboration() {
return plannedDate(iso, zone)
}
/** 开始只使用统一后端接口;拒绝后刷新真实状态。 */
/** 开始只使用统一后端接口;提交期间暂停轮询并防止重复点击,拒绝后刷新真实状态。 */
async function startOne(item: WorkItem) {
if (!canExecute.value) return
if (!canExecute.value || busy.value) return
busy.value = true
try {
await api.start(item.id, item.version)
await refresh()
} catch (error) {
ElMessage({ type: 'error', message: errorText(error), duration: 8000 })
await refresh()
}
} finally { busy.value = false }
}
/** 逐项开始明确报告部分成功,范围切换后停止继续提交。 */
/** 逐项开始明确报告部分成功,整批提交期间暂停轮询,范围切换后停止继续提交。 */
async function startSelection() {
if (!canExecute.value) return
if (!canExecute.value || busy.value) return
busy.value = true
const iteration = iterationId.value, errors: string[] = []
let succeeded = 0
for (const item of [...selection.value]) {
if (iteration !== iterationId.value || !canExecute.value) break
try {
await api.start(item.id, item.version)
succeeded++
} catch (error) {
errors.push(`${item.title}:${errorText(error)}`)
try {
for (const item of [...selection.value]) {
if (iteration !== iterationId.value || !canExecute.value) break
try {
await api.start(item.id, item.version)
succeeded++
} catch (error) {
errors.push(`${item.title}:${errorText(error)}`)
}
}
}
await refresh()
ElMessage({ type: errors.length ? 'warning' : 'success', message: `已开始 ${succeeded} 项${errors.length ? `\n${errors.join('\n')}` : ''}`, duration: 10000 })
await refresh()
ElMessage({ type: errors.length ? 'warning' : 'success', message: `已开始 ${succeeded} 项${errors.length ? `\n${errors.join('\n')}` : ''}`, duration: 10000 })
} finally { busy.value = false }
}
/** 用户搜索结果仅回填当前项目,避免跨项目显示旧候选。 */
@ -409,9 +463,17 @@ export function useProjectCollaboration() {
if (canWrite.value) batchOpen.value = true
}
/** 有未提交编辑时暂停轮询,避免破坏用户输入。 */
function poll() {
if (active && initialized && !restoringRoute && document.visibilityState === 'visible' && !loading.value && !editorOpen.value && !batchOpen.value && !busy.value && !membersOpen.value && !iterationControls.value?.isEditing && !workFlow.value?.isEditing && !workGantt.value?.isEditing) void refreshWorkspace()
/** 后台请求开始和提交时都检查交互状态,防止请求途中打开的编辑或拖动被旧快照打断。 */
function canSynchronize() {
return active && initialized && !restoringRoute && document.visibilityState === 'visible' && !loading.value && !editorOpen.value && !batchOpen.value && !busy.value && !membersOpen.value && boardBusy.size === 0 && !iterationControls.value?.isEditing && !workFlow.value?.isEditing && !workGantt.value?.isEditing && !workBoard.value?.isEditing && !itemDetail.value?.isEditing
}
/** 串行执行十五秒静默同步;网络超过一个周期也不叠加请求,前台操作仍可使在途结果失效。 */
async function poll() {
if (polling || !canSynchronize()) return
polling = true
try { await synchronizeWorkspace(true) }
finally { polling = false }
}
watch([tab, keyword, typeFilter, blockedOnly], () => {
@ -420,10 +482,10 @@ export function useProjectCollaboration() {
})
/** 成员多选按并集重新查询第一页,防止只在已加载50项里筛选或沿用旧页码。 */
watch(ganttMemberIds, () => { if (tab.value === 'gantt') { page.value = 1; void refresh() } }, { deep: true })
watch(ganttMemberIds, () => { if (tab.value === 'gantt') { page.value = 1; if (!applyingBackgroundMembers) void refresh() } }, { 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 })
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(detailId, () => {
// 接受外部深链接时,清空旧抽屉不能把尚未加载完成的新迭代路由回写为旧范围。

View File

@ -72,7 +72,8 @@
<script setup lang="ts">
import { computed, ref, watch } from 'vue'
import { ElMessage, ElMessageBox, vLoading } from 'element-plus'
import { api, errorText, downloadAttachment } from '../../../api'
import { api, errorText, isAccessFailure, downloadAttachment } from '../../../api'
import { reconcileRows, retainSnapshot } from '../../../shared/utils/snapshot'
import { localTime, plannedDate, planningLimitDate } from '../../../shared/utils/time'
import ItemScheduleDialog from '../../schedules/components/ItemScheduleDialog.vue'
import PredecessorPicker from './PredecessorPicker.vue'
@ -95,15 +96,27 @@ const editableDependencies = computed(() => writable.value && detail.value?.stat
const loadedChildren = ref<WorkItem[]>([])
const childItems = computed(() => detail.value?.historical ? detail.value.historicalChildren || [] : loadedChildren.value)
watch(() => [props.id, props.projectId, props.iterationId], () => { detail.value = null; commentText.value = ''; scheduleOpen.value = false; depOpen.value = false; sourceId.value = null; loadedChildren.value = []; failure.value = ''; void load() })
watch(() => props.refreshKey, load)
/** 加载后校验迭代归属并丢弃过期响应;不匹配时清除详情并提示,用户编辑草稿不随轮询重置。 */
async function load() {
watch(() => props.refreshKey, () => { void load() })
/**
* 加载详情和子任务后校验范围与请求代次;后台相同内容保留引用,短暂失败保留已有详情。
* @param background 为 true 时不显示加载遮罩;请求途中开始编辑则丢弃结果,访问失效仍清理。
*/
async function load(background = false) {
const sequence = ++loadSequence, id = props.id
if (id === null) { detail.value = null; return }
loading.value = true
try { const result = await api.detail(id); if (sequence !== loadSequence) return; if (props.projectId && result.projectId !== props.projectId || props.iterationId && result.iterationId !== props.iterationId) { detail.value = null; failure.value = '工作项不属于当前迭代'; return } detail.value = result; if (!result.historical && result.type === 'TASK' && !result.parentTaskId) { const children = await api.children(id); if (sequence === loadSequence) loadedChildren.value = children } }
catch (error) { if (sequence === loadSequence) { detail.value = null; failure.value = errorText(error) } }
finally { if (sequence === loadSequence) loading.value = false }
if (!background) loading.value = true
try {
const result = await api.detail(id)
if (sequence !== loadSequence) return
if (props.projectId && result.projectId !== props.projectId || props.iterationId && result.iterationId !== props.iterationId) { detail.value = null; failure.value = '工作项不属于当前迭代'; return }
const children = !result.historical && result.type === 'TASK' && !result.parentTaskId ? await api.children(id) : []
if (sequence !== loadSequence || background && isEditing.value) return
detail.value = retainSnapshot(detail.value, result)
loadedChildren.value = reconcileRows(loadedChildren.value, children)
failure.value = ''
} catch (error) {
if (sequence === loadSequence && (!background || isAccessFailure(error))) { detail.value = null; loadedChildren.value = []; failure.value = errorText(error) }
} finally { if (!background && sequence === loadSequence) loading.value = false }
}
/** 实际执行和审计发生时间保留北京时间及微秒,预计日期使用独立的日期展示函数。 */
function displayTime(value: string | null) { return value ? localTime(value, 'Asia/Shanghai').replace('T', ' ') : '未设置' }
@ -135,6 +148,10 @@ async function upload(event: Event) { const input = event.target as HTMLInputEle
async function download(id: number, name: string) { try { await downloadAttachment(id, name) } catch (error) { failure.value = errorText(error) } }
const depOpen = ref(false), editingDependency = ref<Condition | null>(null), sourceId = ref<number | null>(null), depFailure = ref('')
const isEditing = computed(() => busy.value || loading.value || scheduleOpen.value || depOpen.value || !!commentText.value.trim())
/** 工作区轮询只静默更新空闲详情,评论、依赖和排期草稿均保留到用户完成操作。 */
async function synchronize() { if (!isEditing.value) await load(true) }
defineExpose({ isEditing, synchronize })
/** 编辑已有条件保留服务端来源标签,不受当前候选搜索页影响。 */
const dependencySource = computed<PredecessorOption[]>(() => { const condition = editingDependency.value; return condition ? [{ id: condition.sourceId, title: condition.sourceName || '已选择工作项', type: condition.sourceType, plannedEndAt: condition.plannedEndAt }] : [] })
/** 生命周期变化立即销毁依赖草稿,不能继续提交已打开的编辑窗口。 */

View File

@ -0,0 +1,24 @@
/**
* 比较接口返回的 JSON 快照,忽略对象字段排列,保留数组顺序的业务含义。
* 只处理接口中的普通对象、数组和标量,不用于 Date、Map 或带循环引用的本地对象。
* @returns 内容相同为 true;不会修改任一输入。
*/
export function sameSnapshot(previous: unknown, incoming: unknown): boolean {
if (Object.is(previous, incoming)) return true
if (!previous || !incoming || typeof previous !== 'object' || typeof incoming !== 'object' || Array.isArray(previous) !== Array.isArray(incoming)) return false
const before = previous as Record<string, unknown>, after = incoming as Record<string, unknown>
const keys = Object.keys(before)
return keys.length === Object.keys(after).length && keys.every(key => Object.prototype.hasOwnProperty.call(after, key) && sameSnapshot(before[key], after[key]))
}
/** 内容相同则沿用已有引用,避免后台轮询触发依赖对象身份的画布重建和表格重置。 */
export function retainSnapshot<T>(previous: T, incoming: T): T {
return sameSnapshot(previous, incoming) ? previous : incoming
}
/** 按业务 ID 合并分页工作项;未变化的行和完整未变化的数组沿用原引用,顺序以服务端为准。 */
export function reconcileRows<T extends { id: number }>(previous: T[], incoming: T[]): T[] {
const known = new Map(previous.map(row => [row.id, row]))
const rows = incoming.map(row => retainSnapshot(known.get(row.id) ?? row, row))
return previous.length === rows.length && rows.every((row, index) => row === previous[index]) ? previous : rows
}

View File

@ -16,7 +16,7 @@
</div>
</template>
<script setup lang="ts">
import { nextTick, onBeforeUnmount, onMounted, reactive, ref } from 'vue'
import { computed, nextTick, onBeforeUnmount, onMounted, reactive, ref } from 'vue'
import { ElMessage } from 'element-plus'
import type { WorkItem, Lifecycle, Stage } from '../../types'
import { statusNames, typeNames, priorityNames } from '../../shared/constants/labels'
@ -26,6 +26,8 @@ import { moveCard } from '../../shared/utils/optimistic'
const props = withDefaults(defineProps<{ items: WorkItem[]; stages?: Stage[]; canWrite: boolean; canExecute?: boolean; counts?: Partial<Record<Lifecycle, number>> }>(), { stages: () => [], canExecute: true })
const emit = defineEmits<{ open: [id: number]; changed: []; 'load-more': [state: Lifecycle] }>()
const dragged = ref<number | null>(null); const busy = reactive(new Set<number>())
// 拖动和提交期间暂停工作区静默同步,避免状态列被在途旧快照覆盖。
defineExpose({ isEditing: computed(() => dragged.value !== null || busy.size > 0) })
const board = ref<HTMLElement | null>(null), boardHeight = ref(480)
let sizeObserver: ResizeObserver | undefined
/** 按看板实际顶部计算剩余视口高度,顶部筛选换行时也不会让卡片数量撑高整个页面。 */

View File

@ -6,7 +6,7 @@
</div>
<el-alert v-if="failure" type="error" :title="failure" :closable="false" class="flow-failure" />
<div ref="canvas" class="flow-canvas" :class="{ inactive: !active }" @dragover.prevent @drop.prevent="dropStage">
<VueFlow v-if="active" :id="flowId" v-model:nodes="nodes" :edges="edges" :delete-key-code="null" :min-zoom="0.1" :max-zoom="4" :nodes-connectable="canManage && !busy" :edges-updatable="false" :nodes-draggable="!busy" @connect="connectStages" @edge-click="edgeClicked" @node-click="selectNode" @node-drag-start="dragging = true" @node-drag-stop="dragStopped" @move-end="viewportMoved" @nodes-initialized="restoreViewport">
<VueFlow v-if="active" :id="flowId" v-model:nodes="nodes" :edges="edges" :connection-line-type="ConnectionLineType.Bezier" :delete-key-code="null" :min-zoom="0.1" :max-zoom="4" :nodes-connectable="canManage && !busy" :edges-updatable="false" :nodes-draggable="!busy" @connect="connectStages" @edge-click="edgeClicked" @node-click="selectNode" @node-drag-start="dragging = true" @node-drag-stop="dragStopped" @move-end="viewportMoved" @nodes-initialized="restoreViewport">
<Background :gap="22" :size="1" pattern-color="var(--el-border-color)" />
<MiniMap pannable zoomable :node-color="minimapColor" node-stroke-color="var(--el-color-primary-light-3)" mask-color="var(--el-mask-color-extra-light)" />
<Controls :show-interactive="false" />
@ -28,7 +28,7 @@
</template>
<script setup lang="ts">
import { computed, nextTick, ref, watch } from 'vue'
import { VueFlow, useVueFlow } from '@vue-flow/core'
import { ConnectionLineType, VueFlow, useVueFlow } from '@vue-flow/core'
import type { Node, Edge, NodeMouseEvent, GraphNode, Connection } from '@vue-flow/core'
import { ElMessageBox } from 'element-plus'
import { Background } from '@vue-flow/background'

View File

@ -19,11 +19,21 @@ const props = defineProps<EdgeProps<FlowEdgeData>>()
// 普通回退从节点侧面绕行;自身回退仅占用本节点下方间距,避免穿过同列后续阶段。
const laneY = computed(() => Math.max(props.data?.laneY || 0, props.sourceY + 20, props.targetY + 20))
const labelX = computed(() => (props.sourceX + props.targetX) / 2)
/** 先从底部短暂引出,再沿节点外侧通道到历史区,回入目标时保留清晰箭头。 */
/** 以分段三次贝塞尔曲线连接底部端口和历史通道;标签位于通道中点,控制点不超出既有画布边界。 */
const path = computed(() => {
if (props.source === props.target) return `M ${props.sourceX} ${props.sourceY} L ${props.sourceX} ${laneY.value} L ${props.targetX} ${laneY.value} L ${props.targetX} ${props.targetY}`
if (props.source === props.target) return `M ${props.sourceX} ${props.sourceY} C ${props.sourceX} ${laneY.value} ${props.sourceX} ${laneY.value} ${labelX.value} ${laneY.value} C ${props.targetX} ${laneY.value} ${props.targetX} ${laneY.value} ${props.targetX} ${props.targetY}`
const fromX = props.data?.sourceEscapeX ?? props.sourceX + 40, toX = props.data?.targetEscapeX ?? props.targetX - 40
return `M ${props.sourceX} ${props.sourceY} L ${props.sourceX} ${props.sourceY + 14} L ${fromX} ${props.sourceY + 14} L ${fromX} ${laneY.value} L ${toX} ${laneY.value} L ${toX} ${props.targetY + 14} L ${props.targetX} ${props.targetY + 14} L ${props.targetX} ${props.targetY}`
// 保留节点外侧的竖向通道,进入底部32px区域后再转弯,避免曲线切过同列其他阶段。
const sourceTurnY = Math.max(props.sourceY + 14, laneY.value - 32), targetTurnY = Math.max(props.targetY + 14, laneY.value - 32)
return [
`M ${props.sourceX} ${props.sourceY}`,
`C ${props.sourceX} ${props.sourceY + 14} ${fromX} ${props.sourceY} ${fromX} ${props.sourceY + 14}`,
`C ${fromX} ${props.sourceY + 14} ${fromX} ${sourceTurnY} ${fromX} ${sourceTurnY}`,
`C ${fromX} ${laneY.value} ${fromX} ${laneY.value} ${labelX.value} ${laneY.value}`,
`C ${toX} ${laneY.value} ${toX} ${laneY.value} ${toX} ${targetTurnY}`,
`C ${toX} ${targetTurnY} ${toX} ${props.targetY + 14} ${toX} ${props.targetY + 14}`,
`C ${toX} ${props.targetY} ${props.targetX} ${props.targetY + 14} ${props.targetX} ${props.targetY}`,
].join(' ')
})
const latest = computed(() => props.data?.latestReworkAt ? localTime(props.data.latestReworkAt, 'Asia/Shanghai').replace('T', ' ') : '未记录')
</script>

View File

@ -1,5 +1,5 @@
import type { Node, Edge } from '@vue-flow/core'
import { MarkerType } from '@vue-flow/core'
import { ConnectionLineType, MarkerType } from '@vue-flow/core'
import { FLOW_REWORK_COLOR } from '../constants/theme'
import type { FlowView, Point, WorkItem } from '../../../types'
@ -19,6 +19,7 @@ export function workItemHeight(item: WorkItem, childCount = 0): number { const c
/**
* 只以阶段及显式阶段边组成画布,工作项留在按当前版本分组的抽屉中。
* 阶段大小固定且数量取完整服务端快照;搜索或筛选不会改变流程拓扑和显示总数。
* 执行连线使用内置三次贝塞尔曲线,回退线继续走独立历史通道并保留状态样式。
* @param view 已通过项目成员鉴权的当前版本流程快照
* @param positions 当前浏览器保存的阶段坐标,旧工作项坐标自然忽略
* @return 只有阶段节点及阶段间连线的画布数据
@ -69,7 +70,7 @@ export function buildFlowGraph(view: FlowView, positions: Record<string, Point>)
return {
id: 'stage:' + link.id, source: 's:' + link.predecessorStageId, target: 's:' + link.successorStageId, sourceHandle: 'out', targetHandle: 'in',
// 颜色只编码后端当前执行事实,迁移放行与真正完成必须有不同视觉语义。
type: 'smoothstep', updatable: false, selectable: false, markerEnd: { type: MarkerType.ArrowClosed, color },
type: ConnectionLineType.Bezier, updatable: false, selectable: false, markerEnd: { type: MarkerType.ArrowClosed, color },
style: { stroke: color, strokeWidth: link.satisfied ? 2.4 : 1.8, strokeDasharray: link.legacyPassed ? '6 4' : undefined },
data: { linkId: link.id, version: link.version },
}

View File

@ -6,16 +6,19 @@
@click="emit('startSelection')"
>开始所选(逐项校验)</el-button>
<el-table
ref="table"
:data="treeItems"
row-key="id"
:indent="24"
:row-class-name="workItemRowClass"
default-expand-all
:expand-row-keys="expandedKeys"
@expand-change="rememberExpansion"
@selection-change="selection = $event"
empty-text="暂无工作项,创建一个任务开始协作"
>
<el-table-column
type="selection"
:reserve-selection="true"
width="44"
/>
<el-table-column
@ -159,7 +162,8 @@
</template>
<script setup lang="ts">
import { collaboratorNames } from '../../features/work-items/utils/participants'
import { computed } from 'vue'
import { computed, ref, useTemplateRef, watch } from 'vue'
import type { ElTable } from 'element-plus'
import { buildItemTree, type ItemTreeRow } from '../../features/work-items/utils/hierarchy'
import { plannedDate } from '../../shared/utils/time'
import { typeNames, statusNames, itemStatusLabel } from '../../shared/constants/labels'
@ -173,6 +177,7 @@ const props = defineProps<{
canExecute: boolean
}>()
const selection = defineModel<WorkItem[]>('selection', { required: true })
const table = useTemplateRef<InstanceType<typeof ElTable>>('table')
const emit = defineEmits<{
open: [id: number]
start: [item: WorkItem]
@ -180,6 +185,29 @@ const emit = defineEmits<{
createChild: [item: WorkItem]
}>()
const treeItems = computed(() => buildItemTree(props.items, props.items))
const expandedKeys = ref<string[]>([])
let knownParents = new Set<string>()
watch(treeItems, retainExpansion, { immediate: true })
watch(selection, pruneTableSelection, { flush: 'post' })
/** 新父任务默认展开,已知父行保留用户折叠选择,避免数据对象替换触发表格默认全部展开。 */
function retainExpansion(rows: ItemTreeRow[]) {
const parents = new Set(rows.filter(row => row.children?.length).map(row => String(row.id)))
expandedKeys.value = [...expandedKeys.value.filter(id => parents.has(id)), ...[...parents].filter(id => !knownParents.has(id))]
knownParents = parents
}
/** 记录当前列表的父行展开意图;该浏览器交互状态不写入业务数据。 */
function rememberExpansion(row: ItemTreeRow, expanded: boolean) {
const id = String(row.id)
expandedKeys.value = expanded ? [...new Set([...expandedKeys.value, id])] : expandedKeys.value.filter(key => key !== id)
}
/** 父页面清除或修剪选择时同步取消表格保留的勾选,避免静默保留机制留下与批量操作不一致的 UI。 */
function pruneTableSelection(selected: WorkItem[]) {
const retained = new Set(selected.map(row => row.id))
for (const row of table.value?.getSelectionRows() || []) if (!retained.has(row.id)) table.value?.toggleRowSelection(row, false)
}
/** 父行建立分组,子行保留树形缩进,仅调整展示。 */
function workItemRowClass({ row }: {

View File

@ -156,6 +156,7 @@
/>
<WorkBoard
v-else-if="tab === 'board'"
ref="workBoard"
:key="`${current.id}:${iterationId}`"
:items="items"
:counts="boardCounts"
@ -218,6 +219,7 @@
</template>
</template>
<ItemDetail
ref="itemDetail"
:id="detailId"
:project-id="projectId || undefined"
:iteration-id="iterationId || undefined"