cmvr-wms/ruoyi-ui-vue3/src/views/project/manage/composables/useProjectCollaboration.ts

748 lines
38 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import { computed, onMounted, onBeforeUnmount, onActivated, onDeactivated, reactive, ref, useTemplateRef, watch } from 'vue'
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'
import { plannedDate, planBoundary } from '../shared/utils/time'
import { typeNames } from '../shared/constants/labels'
import { reconcileRows, retainSnapshot } from '../shared/utils/snapshot'
import type { Project, Member, WorkItem, ItemType, Lifecycle, FlowView, Iteration, ItemQuery } from '../types'
import { iterationReadOnly, iterationCanExecute } from '../features/iterations/utils/scope'
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'
import type WorkBoard from '../views/board/WorkBoard.vue'
import type ItemDetail from '../features/work-items/components/ItemDetail.vue'
/**
* 协调项目协作页面的项目/迭代范围、加载、路由及编辑状态。
* 将原页面生命周期集中在同一个 setup 调用中,保留请求代次和轮询暂停规则,
* 防止拆分视图后出现重复轮询或旧迭代响应覆盖新范围。
* 首次进入默认展示流程视图;待办深链接恢复其明确的看板或阶段及完整归属。
* 看板和甘特各自保存成员读取条件,切换迭代清空,继续由后端完整图校验执行及排期。
* 轮询静默合并变化的快照,保留选择和已加载分页;编辑及拖动期间不提交后台结果。
* @returns 页面装配使用的响应式状态、组件引用和业务动作;解构后仍保持 Ref。
* 注意:必须在页面 setup 内调用;卸载时清除定时器并使在途刷新失效。
*/
export function useProjectCollaboration() {
const route = useRoute(), router = useRouter(), userStore = useUserStore(), initialQuery = route?.query || {}
const requestedSource = Number(initialQuery.sourceProjectId) || null
const requestedProject = Number(initialQuery.projectId) || null
const pagePath = route.path
// 引用在 composable 内声明,显式绑定模板 ref 名称,确保弹窗编辑状态仍能暂停页面轮询。
const iterationControls = useTemplateRef<InstanceType<typeof IterationControls>>('iterationControls')
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)
const projectId = ref<number | null>(requestedProject)
const iterations = ref<Iteration[]>([])
const iterationId = ref<number | null>(null)
const includeArchived = ref(false)
const items = ref<WorkItem[]>([])
const members = ref<Member[]>([])
const flowView = ref<FlowView | null>(null)
const statistics = ref<Record<string, number>>({})
const selectedIteration = computed(() => iterations.value.find(row => row.id === iterationId.value))
const zone = 'Asia/Shanghai'
const canWrite = computed(() => !!current.value?.canWrite && !iterationReadOnly(selectedIteration.value))
const canCreate = computed(() => !!current.value?.canCreate && !iterationReadOnly(selectedIteration.value))
const canExecute = computed(() => canWrite.value && iterationCanExecute(selectedIteration.value))
const loading = ref(false)
const failure = ref('')
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)
const stageFilter = ref<number | null>(null)
const detailId = ref<number | null>(null)
const refreshKey = ref(0)
const selection = ref<WorkItem[]>([])
const editing = ref<WorkItem | null>(null)
const editorOpen = ref(false)
const creatingParent = ref<WorkItem | null>(null)
const defaultStageId = ref<number | null>(null)
const page = ref(1)
const pageSize = 50
const total = ref(0)
const boardCounts = ref<Partial<Record<Lifecycle, number>>>({})
const boardPages = reactive<Partial<Record<Lifecycle, number>>>({})
const boardBusy = reactive(new Set<Lifecycle>())
// 查询窗口覆盖完整北京时间日期,避免日期刻度可见但当天工作项被查询时分秒截掉。
const ganttFrom = ref(planBoundary(plannedDate(new Date(Date.now() - 14 * 86400000).toISOString()), 'start')!)
const ganttTo = ref(planBoundary(plannedDate(new Date(Date.now() + 45 * 86400000).toISOString()), 'end')!)
const membersOpen = ref(false), inviteUser = ref<number | null>(null), inviteRole = ref('MEMBER'), userCandidates = ref<Member[]>([])
const busy = ref(false), batchOpen = ref(false)
const notifications = ref<{
id: number
message: string
projectId: number
iterationId?: number | null
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
// 批量写入绑定业务范围,不能使用会随详情深链接变化的 navigationSequence。
let scopeSequence = 0
let timer: ReturnType<typeof setInterval> | undefined
let active = true, initialized = false, initializing = false, restoringRoute = false
let polling = false, applyingBackgroundMembers = false, clearingScope = 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 || background && !canSynchronize()) return false
current.value = retainSnapshot(current.value, context)
projectId.value = context.id
sourceProjectId.value = context.sourceProjectId
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) {
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(false, 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
if (!background || isAccessFailure(error)) invalidateWorkspace(error)
}
}
/** 权限、对象或会话明确失效时移除旧内容和草稿,后台同步也不能保留已失效的访问资格。 */
function invalidateWorkspace(error: unknown) {
clearScope()
current.value = null
iterations.value = []
iterationId.value = null
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] } : view === 'board' ? { memberIds: [...boardMemberIds.value] } : {}) }
}
/** 导出沿用甘特的完整服务端筛选,但独立从第一页读取,翻页不改变导出范围。 */
const ganttExportQuery = computed(() => ({ ...query('gantt'), page: 1, pageSize: 200 }))
/** 文件中记录本次筛选含义,成员多选仍按负责人或协作人命中任一成员计算。 */
const ganttExportFilters = computed(() => [
keyword.value.trim() ? `标题:${keyword.value.trim()}` : '',
typeFilter.value ? `类型:${typeNames[typeFilter.value]}` : '全部类型',
blockedOnly.value ? '仅看依赖阻塞' : '',
stageFilter.value == null ? '全部阶段' : stageFilter.value === 0 ? '未分配阶段' : `阶段:${flowView.value?.stages.find(stage => stage.id === stageFilter.value)?.stagePath || flowView.value?.stages.find(stage => stage.id === stageFilter.value)?.name || stageFilter.value}`,
ganttMemberIds.value.length ? `成员:${ganttMemberIds.value.map(id => members.value.find(member => member.userId === id)?.name || `用户 #${id}`).join('、')}` : '全部成员',
].filter(Boolean).join(';'))
/** 用户主动刷新或业务操作完成时显示加载状态;独立包装避免分页事件的页码被当作后台标志。 */
async function refresh() {
await refreshData(false)
}
/**
* 只合并当前范围、请求代次的结果,流程仅请求阶段摘要,后台保留选择和看板已加载页数。
* 成员失效可能改变读取条件,先修剪并检查代次,防止原筛选响应覆盖重新发起的查询。
* @param background 后台刷新不显示加载状态,瞬时失败不清空已有内容,编辑开始后丢弃其响应。
*/
async function refreshData(background: boolean) {
const id = projectId.value, iteration = iterationId.value, sequence = ++refreshSequence
if (!id || !iteration || !current.value?.enabled) {
if (!background) loading.value = false
return
}
// 前台刷新接管旧续页,立即释放其忙碌标记;旧请求不能在结束时清除后来新续页的标记。
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]))
// 各列读取已加载的全部页再一起替换,避免轮询把“加载更多”的内容截回第一页。
// 页数在等待期间变化则放弃本轮结果,让用户当前的续页优先完成。
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 (!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
}
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]))
// 保留有效勾选,但同步其版本;删除或离开当前筛选范围的行不能继续参与批量操作。
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 && 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 (!background && sequence === refreshSequence) loading.value = false
}
}
/**
* 状态列按当前成员条件独立续页;筛选或范围变化后丢弃旧结果、旧错误及旧忙碌清理。
* @param status 需要加载下一页的状态列;同列忙碌期间不重复请求。
*/
async function loadBoardMore(status: Lifecycle) {
const id = projectId.value, iteration = iterationId.value, sequence = refreshSequence
if (!id || !iteration || boardBusy.has(status)) return
const next = (boardPages[status] || 1) + 1
boardBusy.add(status)
try {
const result = await api.items(id, iteration, { ...query('board'), page: next, status })
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) {
if (active && sequence === refreshSequence) ElMessage.error(errorText(error))
} finally {
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()
ganttTo.value = new Date(Date.parse(ganttTo.value) + days * 86400000).toISOString()
page.value = 1
void refresh()
}
/** 清空旧范围和未提交输入;重置期间暂停成员 watcher 查询,避免仍向旧迭代发起请求。 */
function clearScope() {
clearingScope = true
clearTarget()
restoredTargetKey = ''
scopeSequence++
refreshSequence++
navigationSequence++
iterationSequence++
restoringRoute = false
items.value = []
notifications.value = []
total.value = 0
statistics.value = {}
resetBoardPages()
flowView.value = null
selection.value = []
members.value = []
ganttMemberIds.value = []; boardMemberIds.value = []; stageFilter.value = null
detailId.value = null
editing.value = null
creatingParent.value = null
defaultStageId.value = null
editorOpen.value = false
batchOpen.value = false
membersOpen.value = false
inviteUser.value = null
userCandidates.value = []
failure.value = ''
loading.value = false
page.value = 1
clearingScope = false
}
/** 可见迭代元数据独立计次;后台同值不重置引用,用户开始编辑或切换范围后不再应用结果。 */
async function loadIterations(preferred?: number | null, background = false) {
const id = projectId.value, sequence = ++iterationSequence, navigation = navigationSequence
if (!id) {
iterations.value = []
iterationId.value = null
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 || 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
}
/**
* 成员失效时同步修剪两个视图筛选,后台触发的重查继续使用静默模式。
* @param people 当前服务端成员快照;相同内容保留原引用以避免无意义重查。
* @param background 是否属于静默同步,用于继承成员修剪后查询的加载方式。
*/
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
clearScope()
const navigation = navigationSequence
iterationId.value = id
await refresh()
if (active && navigation === navigationSequence) syncQuery()
}
/** 创建或生命周期动作完成后读取服务端结果。 */
async function iterationsChanged(id?: number) {
clearScope()
const navigation = navigationSequence
try {
if (!await loadIterations(id) || navigation !== navigationSequence) return
await refresh()
if (active && navigation === navigationSequence) syncQuery()
} catch (error) {
if (active && navigation === navigationSequence) failure.value = errorText(error)
}
}
/** 归档筛选只改变可见范围,不修改迭代状态。 */
async function archiveFilterChanged(include: boolean) {
includeArchived.value = include
await iterationsChanged()
}
/** 完整范围和页签写入路由;定位卡片独立于详情 ID,关闭详情后仍能在看板找到目标。 */
function syncQuery() {
if (!active || route.path !== pagePath || !sourceProjectId.value) return
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。 */
async function openNotice(notice: { workItemId: number | null }) {
if (!notice.workItemId) return
const request = ++navigationSequence
try {
const item = await api.detail(notice.workItemId)
const context = await api.legacyProjectContext(item.projectId)
if (request !== navigationSequence || !active) return
if (!item.iterationId) { ElMessage.error('工作项缺少迭代信息'); return }
await router.push({ path: pagePath, query: { sourceProjectId: context.sourceProjectId, iterationId: item.iterationId, itemId: item.id } })
} catch (error) {
if (request === navigationSequence && active) ElMessage.error(errorText(error))
}
}
/** 新建只预选阶段,编辑保留服务端原归属。 */
function openEditor(item: WorkItem | null, stageId: number | null = null) {
if (item ? !canWrite.value : !canCreate.value) return
creatingParent.value = null
editing.value = item
defaultStageId.value = item ? null : stageId
editorOpen.value = true
}
/** 子任务保存仍提交父版本并由后端验证阶段与排期。 */
function openChildEditor(parent: WorkItem) {
if (!parent.canCreateChild || !canWrite.value) return
editing.value = null
creatingParent.value = parent
defaultStageId.value = parent.stageId ?? null
editorOpen.value = true
}
/** 保存后只在原导航范围打开详情;刷新期间切换迭代或离页后不恢复旧工作项。 */
async function saved(id: number) {
const navigation = navigationSequence
editorOpen.value = false
await refresh()
if (active && navigation === navigationSequence && current.value) detailId.value = id
}
/** 预计时间仅展示北京时间日期,模型保留既有时间精度。 */
function briefTime(iso: string | null) {
return plannedDate(iso, zone)
}
/**
* 开始只使用服务端 canStart 和统一接口;即使合成事件触发,也不能绕过当前负责人及准入条件。
* @param item 当前列表快照,提交其版本;服务端再次校验改派和执行条件,拒绝后刷新真实状态。
*/
async function startOne(item: WorkItem) {
if (!canExecute.value || !item.canStart || 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 }
}
/**
* 逐项开始并报告部分成功,提交期间暂停轮询;项目或迭代范围变化即停止后续提交。
* 不能仅比较迭代 ID:切到其他迭代再返回时,旧批次也已失效,不应恢复后台写入。
* 同迭代内仅打开或关闭详情不会改变业务范围,仍应完成本次已选批次并报告结果。
* 各项独立检查服务端 canStart;不可开始项只报告原因,不向服务端提交无效执行请求。
*/
async function startSelection() {
if (!canExecute.value || busy.value) return
busy.value = true
const scope = scopeSequence, errors: string[] = []
let succeeded = 0
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++
} catch (error) {
errors.push(`${item.title}:${errorText(error)}`)
}
}
if (!active || scope !== scopeSequence) return
await refresh()
if (!active || scope !== scopeSequence) return
ElMessage({ type: errors.length ? 'warning' : 'success', message: `已开始 ${succeeded} 项${errors.length ? `\n${errors.join('\n')}` : ''}`, duration: 10000 })
} finally { busy.value = false }
}
/** 用户搜索结果仅回填当前项目,避免跨项目显示旧候选。 */
async function searchUsers(keyword: string) {
const id = projectId.value
if (!id) return
try {
const result = await api.candidates(id, keyword)
if (id === projectId.value) userCandidates.value = result
} catch (error) {
ElMessage.error(errorText(error))
}
}
/** 成员变更后重读项目角色;自降级或撤权不能继续沿用弹窗中的旧管理资格。 */
async function invite() {
if (!current.value || !inviteUser.value) return
try {
await api.member(current.value.id, inviteUser.value, inviteRole.value)
inviteUser.value = null
await refreshWorkspace()
} catch (error) {
ElMessage.error(errorText(error))
}
}
/** 移除成员先确认并检查未完分配,成功后重读项目身份;自移除会关闭工作区及成员弹窗。 */
async function removeMember(userId: number) {
if (!current.value) return
try {
await ElMessageBox.confirm('移除此项目成员?其项目详情与附件访问权限将被撤销。', '移除成员', { closeOnClickModal: false })
await api.removeMember(current.value.id, userId)
await refreshWorkspace()
} catch (error) {
if (error !== 'cancel' && error !== 'close') ElMessage.error(errorText(error))
}
}
/** 仅编辑当前页已加载工作项,轮询不覆盖未提交的排期草稿。 */
function openBatch() {
if (canWrite.value) batchOpen.value = true
}
/** 后台请求开始和提交时都检查交互状态,防止请求途中打开的编辑或拖动被旧快照打断。 */
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, 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 && !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))
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, () => {
// 接受外部深链接时,清空旧抽屉不能把尚未加载完成的新迭代路由回写为旧范围。
// 用户正常开关抽屉时路由和当前迭代一致;范围切换完成由对应导航流程主动同步。
if (initialized && !initializing && !restoringRoute && (Number(route.query.iterationId) || null) === iterationId.value) syncQuery()
})
watch([canWrite, canCreate], ([writable, creatable]) => {
if (editing.value || creatingParent.value ? !writable : !creatable) editorOpen.value = false
if (!writable) {
batchOpen.value = false
selection.value = []
}
})
/** 浏览器导航恢复同项目迭代和待办目标;只有鉴权读取归属后才打开定位详情。 */
watch(() => route?.query, async value => {
if (!active || route.path !== pagePath || Number(value?.sourceProjectId) !== sourceProjectId.value) return
restoringRoute = true
if (!initialized) {
// 初始化尚在等待接口时,最新路由接管整次初始化,旧异步链不能恢复旧迭代或启动轮询。
void initializeWorkspace()
return
}
const querySnapshot = { ...value }, i = workspaceLinkId(value?.iterationId), item = workspaceLinkId(value?.itemId)
if (i === iterationId.value && (!i || selectedIteration.value)) {
// 快速返回原迭代或仅改变详情时,同样终止旧导航链,不能让旧回调随后打开错误详情。
navigationSequence++
iterationSequence++
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()
restoringRoute = true
const navigation = navigationSequence
includeArchived.value = true
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) 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 querySnapshot = { ...route.query }, requestedIteration = workspaceLinkId(querySnapshot.iterationId)
initialized = false
initializing = true
clearScope()
restoringRoute = true
loading.value = true
try {
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
restoredTargetKey = linkTargetKey(querySnapshot)
const detail = await restoreTarget(querySnapshot)
if (!active || sequence !== initializationSequence) return
if (iterationId.value === requestedIteration) detailId.value = detail
initialized = true
// 无效待办保留原链接和提示,不能用默认范围回写触发第二次恢复并抹掉失败原因。
if (!targetFailure.value) syncQuery()
if (!timer) timer = setInterval(poll, 15000)
} catch (error) {
if (active && sequence === initializationSequence) { clearScope(); current.value = null; failure.value = errorText(error) }
} finally {
if (sequence === initializationSequence) {
initializing = false
restoringRoute = false
if (active) loading.value = false
}
}
}
onMounted(() => { void initializeWorkspace() })
/** 缓存页离开时取消定位与所有在途导航;重新激活按当时路由读取,不能复活旧待办。 */
onDeactivated(() => {
active = false
clearTarget()
scopeSequence++
if (timer) clearInterval(timer)
timer = undefined
refreshSequence++
workspaceSequence++
navigationSequence++
iterationSequence++
initializationSequence++
initializing = false
})
onActivated(() => {
active = true
// 缓存页可能通过另一个迭代/工作项深链接重新进入,必须读取本次路由而非沿用离页前范围。
if (!initializing) void initializeWorkspace()
})
/** 真正卸载时释放轮询并使读取代次失效,待办响应不能写回已经销毁的工作区。 */
onBeforeUnmount(() => {
active = false
clearTarget()
scopeSequence++
if (timer) clearInterval(timer)
refreshSequence++
workspaceSequence++
navigationSequence++
iterationSequence++
initializationSequence++
})
return {
projectId, iterations, iterationId, includeArchived,
items, members, flowView, current, selectedIteration, zone, canWrite, canCreate, canExecute,
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,
refreshWorkspace, refresh, loadBoardMore, moveGanttWindow,
changeIteration, iterationsChanged, archiveFilterChanged, openNotice,
openEditor, openChildEditor, saved, briefTime, startOne, startSelection,
searchUsers, invite, removeMember, openBatch
}
}