feat: 项目协作验证

This commit is contained in:
zhanghao 2026-10-28 14:52:46 +08:00
parent c100721ecf
commit d21f09d3a6
8 changed files with 168 additions and 52 deletions

View File

@ -66,7 +66,7 @@ public class PmController {
@PostMapping("/items/{id}/children") public Map<String,Object> child(@PathVariable long id,@RequestBody JsonNode body) { return ok(service.createChild(id,decode(body,ChildInput.class))); }
/** 子任务列表在服务层复验项目成员权限与实时状态。 */
@GetMapping("/items/{id}/children") public Map<String,Object> children(@PathVariable long id) { return ok(service.children(id)); }
/** 普通编辑拒绝状态;省略 stageId 时保留归属及本次邮件选择,显式 null 才移到未分配。 */
/** 普通编辑拒绝状态注入,省略 stageId 时保留归属;阶段迁移须走管理者专用入口,显式 null 也不能绕过。 */
@PatchMapping("/items/{id}") public Map<String,Object> edit(@PathVariable long id,@RequestBody JsonNode body) {
ItemInput input=decode(body,ItemInput.class);
if(!body.has("stageId")) input=new ItemInput(input.type(),input.title(),input.description(),input.assigneeId(),input.priority(),input.plannedStartAt(),input.plannedEndAt(),input.version(),nullableStage(service.detail(id).get("stageId")),input.collaboratorIds(),input.predecessorWorkItemIds(),input.sendEmail());

View File

@ -22,7 +22,13 @@ public interface PmDependencyMapper {
/** 版本不匹配必须拒绝覆盖;业务服务持有项目锁并在同一事务内记录历史。 */
default void updateDependency(long id,int version,Map<String,Object> values) { PmMapperWrite.requireUpdated(updateDependencyRow(id,version,values)); }
/** 加载任务前置边,供开始条件、排期及无环检查共用。 */
/**
* 加载当前有效后续项的前置边,供开始条件、排期、无环检查及阶段回退共用。
* 只排除已删除或历史轮次的后续项;已删除前置项的边仍需保留,以阻止有效后续项误判条件满足。
* @param projectId 已鉴权的协作项目 ID
* @param iterationId 当前校验的明确迭代 ID
* @return 当前图依赖;不删除原始依赖行,历史详情通过独立查询读取
*/
List<Map<String,Object>> selectGraphDependencies(@Param("projectId") long projectId,@Param("iterationId") long iterationId);
/** 历史工作项详情读取原始依赖行,不把旧边加载进当前执行图。 */

View File

@ -55,7 +55,13 @@ public final class PmRules {
return conditions(graph,taskId,zone).stream().filter(c -> !Boolean.TRUE.equals(c.get("satisfied"))).toList();
}
/** 合并工作项前置、父任务和阶段边界;缺失阶段计划只标记不完整,已知边界必须满足。 */
/**
* 合并工作项前置、父任务和阶段边界,计算最早开始、最晚结束及具体冲突。
* @param graph 已鉴权迭代的完整候选图,批量改期时包含整批最终时间
* @param item 待检查的当前工作项;允许暂缺一个日期,但已填写端点仍须落在父任务已知范围内
* @param zone 输出时间的展示时区,比较使用 UTC 微秒
* @return 排期摘要;缺失阶段计划标记为不完整,实际越界标记为冲突,不写入数据库
*/
public static Map<String,Object> schedule(Graph graph,Item item,String zone) {
Long earliest = null;
Long latest = null;
@ -67,7 +73,11 @@ public final class PmRules {
if(parent!=null) {
earliest=parent.start();
sources.add(map("sourceId",parent.id(),"sourceName",parent.title(),"plannedStartAt",PmTime.format(parent.start(),zone),"plannedEndAt",PmTime.format(parent.end(),zone),"kind","PARENT_RANGE"));
if(item.start()!=null&&(parent.start()==null||item.start()<parent.start()) || item.end()!=null&&(parent.end()==null||item.end()>parent.end())) {
// 子任务可以暂缺一个端点,但剩余端点仍必须同时遵守父任务的上下界。
// 仅比较开始对开始、结束对结束,会让单填结束落在父开始之前,或单填开始落在父结束之后。
boolean startOutside=item.start()!=null&&(parent.start()==null||item.start()<parent.start()||parent.end()!=null&&item.start()>parent.end());
boolean endOutside=item.end()!=null&&(parent.end()==null||item.end()>parent.end()||parent.start()!=null&&item.end()<parent.start());
if(startOutside||endOutside) {
conflict=true; reasons.add(map("code","PARENT_SCHEDULE_CONFLICT","sourceId",parent.id(),"sourceName",parent.title(),"message","子任务时间必须在父任务范围内,且对应父时间不能为空","plannedStartAt",PmTime.format(parent.start(),zone),"plannedEndAt",PmTime.format(parent.end(),zone)));
}
}

View File

@ -54,6 +54,8 @@
JOIN pm_collab_work_item successor ON successor.id=d.successor_task_id
LEFT JOIN pm_collab_project_stage ss ON ss.project_id=successor.project_id AND ss.id=successor.stage_id
WHERE d.project_id=#{projectId} AND d.iteration_id=#{iterationId} AND d.condition_type IN ('TASK_COMPLETED','WORK_ITEM_COMPLETED')
<!-- 已删除后续项不再参与执行、排期或回退;前置项不能对称过滤,否则会让有效后续项绕过失效依赖。原始依赖仍由详情查询保留。 -->
AND successor.deleted=false
AND (successor.stage_id IS NULL OR successor.stage_revision_id=ss.current_revision_id)
ORDER BY d.id
</select>

View File

@ -100,6 +100,8 @@ export function useProjectCollaboration() {
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
@ -257,6 +259,7 @@ export function useProjectCollaboration() {
/** 清空旧范围数据与所有未提交输入,切回原迭代也不能恢复旧请求。 */
function clearScope() {
scopeSequence++
refreshSequence++
navigationSequence++
iterationSequence++
@ -377,11 +380,12 @@ export function useProjectCollaboration() {
editorOpen.value = true
}
/** 保存后打开同迭代最新详情。 */
/** 保存后只在原导航范围打开详情;刷新期间切换迭代或离页后不恢复旧工作项。 */
async function saved(id: number) {
const navigation = navigationSequence
editorOpen.value = false
await refresh()
detailId.value = id
if (active && navigation === navigationSequence && current.value) detailId.value = id
}
/** 预计时间仅展示北京时间日期,模型保留既有时间精度。 */
@ -402,15 +406,19 @@ export function useProjectCollaboration() {
} finally { busy.value = false }
}
/** 逐项开始明确报告部分成功,整批提交期间暂停轮询,范围切换后停止继续提交。 */
/**
* 逐项开始并报告部分成功,提交期间暂停轮询;项目或迭代范围变化即停止后续提交。
* 不能仅比较迭代 ID:切到其他迭代再返回时,旧批次也已失效,不应恢复后台写入。
* 同迭代内仅打开或关闭详情不会改变业务范围,仍应完成本次已选批次并报告结果。
*/
async function startSelection() {
if (!canExecute.value || busy.value) return
busy.value = true
const iteration = iterationId.value, errors: string[] = []
const scope = scopeSequence, errors: string[] = []
let succeeded = 0
try {
for (const item of [...selection.value]) {
if (iteration !== iterationId.value || !canExecute.value) break
if (!active || scope !== scopeSequence || !canExecute.value) break
try {
await api.start(item.id, item.version)
succeeded++
@ -418,7 +426,9 @@ export function useProjectCollaboration() {
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 }
}
@ -570,6 +580,7 @@ export function useProjectCollaboration() {
onDeactivated(() => {
active = false
scopeSequence++
if (timer) clearInterval(timer)
timer = undefined
refreshSequence++
@ -588,6 +599,7 @@ export function useProjectCollaboration() {
onBeforeUnmount(() => {
active = false
scopeSequence++
if (timer) clearInterval(timer)
refreshSequence++
workspaceSequence++

View File

@ -12,7 +12,7 @@
<el-input v-if="canManage" v-model="reason" size="small" class="batch-reason" maxlength="2000" placeholder="调整说明(已开始阶段改期必填)" />
</el-tab-pane>
<el-tab-pane :label="`工作项排期 · ${itemRows.length}`" name="items">
<p class="note">已载入 {{ itemRows.length }} 个可编辑工作项;单次最多处理 500 个对象。已完成阶段的工作项只读。</p>
<p class="note">已载入 {{ itemRows.length }} 个可编辑工作项;单次最多处理 500 个对象。待审批或已完成阶段的工作项只读。</p>
<el-table v-loading="loading" :data="itemRows" size="small" max-height="420">
<el-table-column label="工作项" min-width="200" class-name="business-control-cell"><template #default="{ row }">{{ row.name }}<el-tag v-if="row.pending" size="small" type="warning">待复核</el-tag><el-checkbox v-if="row.pending" v-model="row.confirm" size="small">确认参考计划</el-checkbox></template></el-table-column>
<el-table-column label="预计开始" min-width="180"><template #default="{ row }"><TimeField boundary="start" v-model="row.plannedStartAt" zone="Asia/Shanghai" /></template></el-table-column>
@ -53,8 +53,11 @@ watch(() => [props.visible, props.projectId, props.iterationId], async () => {
} catch (error) { if (request === sequence) failure.value = errorText(error) }
finally { if (request === sequence) loading.value = false }
}, { immediate: true })
/** 只有当前未完成阶段允许改期,补录必须使用专门入口。 */
function frozen(stageId?: number | null) { return ['COMPLETED', 'LEGACY_PASSED'].includes(stages.value.find(stage => stage.id === stageId)?.executionStatus || '') }
/** 待审批交付与已完成阶段均冻结排期,避免让用户编辑后整批才被后端拒绝;补录仍使用专门入口。 */
function frozen(stageId?: number | null) {
const stage = stages.value.find(stage => stage.id === stageId)
return stage?.approvalStatus === 'PENDING' || ['COMPLETED', 'LEGACY_PASSED'].includes(stage?.executionStatus || '')
}
/** 参考只作为输入初值;未修改也未勾选的复核行绝不会被隐式确认。 */
function draft(id: number, version: number, name: string, source: Pick<WorkItem, 'plannedStartAt' | 'plannedEndAt' | 'referencePlannedStartAt' | 'referencePlannedEndAt' | 'scheduleReviewRequired'>): Draft {
const start = source.plannedStartAt ?? source.referencePlannedStartAt ?? null, end = source.plannedEndAt ?? source.referencePlannedEndAt ?? null
@ -66,7 +69,7 @@ async function loadMore() {
try {
const result = await api.items(props.projectId, props.iterationId, { view: 'flat', page: nextPage, pageSize: 100 })
if (request !== sequence) return
itemRows.value.push(...result.rows.filter(item => !item.historical && !item.scheduleReviewClosed && !frozen(item.stageId)).map(item => draft(item.id, item.version, item.title, item)))
itemRows.value.push(...result.rows.filter(item => !item.historical && !item.stageReadOnly && !item.scheduleReviewClosed && !frozen(item.stageId)).map(item => draft(item.id, item.version, item.title, item)))
loadedCount.value += result.rows.length; itemTotal.value = result.total; page = nextPage
} catch (error) { if (request === sequence) failure.value = errorText(error) }
finally { if (request === sequence) loading.value = false }

View File

@ -7,7 +7,7 @@
<div class="detail-title"><el-tag>{{ typeNames[detail.type] }}</el-tag><h2>{{ detail.title }}</h2></div>
<div class="detail-tags"><el-tag :type="detail.overdue ? 'danger' : 'info'">{{ itemStatusLabel(detail) }}</el-tag><el-tag v-if="detail.overdue" type="info">{{ statusNames[detail.status] }}</el-tag><el-tag v-if="detail.dependencyBlocked && !detail.historical" type="warning">实际前置条件未满足</el-tag><el-tag v-if="!detail.historical" :type="detail.scheduleConstraints.scheduleValidationStatus === 'VALID' ? 'success' : 'info'">{{ scheduleLabel }}</el-tag><el-tag v-if="detail.stageRevisionNo" type="info">阶段 v{{ detail.stageRevisionNo }}</el-tag><el-tag v-if="detail.historical" type="warning">历史只读</el-tag><el-tag type="info">工作项版本 {{ detail.version }}</el-tag></div>
<el-alert v-if="detail.historical" type="info" :closable="false" title="该工作项属于已被回退取代的阶段版本;原状态、排期、评论、附件和历史仅供查看。" class="failure" />
<el-alert v-else-if="stageFrozen" type="info" :closable="false" :title="currentStage?.approvalStatus === 'PENDING' ? '当前阶段正在审批,交付已冻结;需要修改请负责人先撤回申请,评论仍可讨论。' : '当前阶段已完成,工作项已冻结;如需重做,请由项目经理从流程视图回退。'" class="failure" />
<el-alert v-else-if="stageFrozen" type="info" :closable="false" :title="stagePending ? '当前阶段正在审批,交付已冻结;需要修改请负责人先撤回申请,评论仍可讨论。' : '当前阶段已完成,工作项已冻结;如需重做,请由项目经理从流程视图回退。'" class="failure" />
<el-alert v-if="detail.scheduleReviewRequired" type="warning" :closable="false" :title="detail.scheduleReviewClosed ? '本轮未确认排期;参考计划未参与本轮排期和超期统计。' : '上游阶段已回退,参考计划尚未生效;请确认阶段计划后调整工作项排期。'" class="failure" />
<p v-if="detail.scheduleReviewRequired" class="muted">参考时间:{{ plannedDate(detail.referencePlannedStartAt || null) }} → {{ plannedDate(detail.referencePlannedEndAt || null) }}</p>
<el-button v-if="detail.scheduleReviewRequired && !detail.scheduleReviewClosed && writable" size="small" @click="confirmReview">确认保留原排期</el-button>
@ -71,7 +71,7 @@
</el-dialog>
</template>
<script setup lang="ts">
import { computed, ref, watch } from 'vue'
import { computed, onBeforeUnmount, ref, watch } from 'vue'
import { ElMessage, ElMessageBox, vLoading } from 'element-plus'
import { api, errorText, isAccessFailure, downloadAttachment } from '../../../api'
import { reconcileRows, retainSnapshot } from '../../../shared/utils/snapshot'
@ -86,32 +86,68 @@ const props = withDefaults(defineProps<{ projectId?: number; iterationId?: numbe
const emit = defineEmits<{ close: []; changed: []; open: [id: number]; edit: [item: WorkItem]; 'create-child': [parent: WorkItem] }>()
const detail = ref<WorkItem | null>(null), loading = ref(false), busy = ref(false), failure = ref(''), commentText = ref('')
const attachmentConfirmationOpen = ref(false)
let loadSequence = 0
const deleteConfirmationOpen = ref(false)
let loadSequence = 0, scopeSequence = 0
const scheduleOpen = ref(false), assignmentOpen = ref(false), assignmentStageId = ref<number | null>(null), assignmentFailure = ref('')
const scheduleLabel = computed(() => detail.value?.scheduleConstraints.scheduleValidationStatus === 'VALID' ? '排期合法' : detail.value?.scheduleConstraints.scheduleValidationStatus === 'CONFLICT' ? '排期冲突' : '排期未完成')
const blockedText = computed(() => detail.value?.blockedReasons.map(r => r.stageId ? `${r.sourceName}:${r.message}` : r.message || `${r.sourceName}:当前 ${lifecycleLabels[r.currentStatus || ''] || r.currentStatus},要求 ${lifecycleLabels[String(r.expectedStatus)] || r.expectedStatus}`).join(';') || '当前无法开始')
// 阶段边只展示服务端完成摘要,不在前端重新判定实际 canStart。
const stagePredecessors = computed(() => props.stageEdges.filter(edge => edge.successorStageId === detail.value?.stageId).map(edge => props.stages.find(stage => stage.id === edge.predecessorStageId)).filter((stage): stage is Stage => !!stage))
const currentStage = computed(() => props.stages.find(stage => stage.id === detail.value?.stageId))
const stageFrozen = computed(() => currentStage.value?.approvalStatus === 'PENDING' || ['COMPLETED', 'LEGACY_PASSED'].includes(currentStage.value?.executionStatus || ''))
// 详情与画布分开刷新;详情已返回的冻结结果立即生效,不能等待旧画布下一轮同步才禁用编辑。
const stagePending = computed(() => detail.value?.stageApprovalStatus === 'PENDING' || currentStage.value?.approvalStatus === 'PENDING')
const stageCompleted = computed(() =>
(!!detail.value?.stageReadOnly && detail.value.stageApprovalStatus !== 'PENDING')
|| ['COMPLETED', 'LEGACY_PASSED'].includes(currentStage.value?.executionStatus || '')
)
const stageFrozen = computed(() => stagePending.value || stageCompleted.value)
const writable = computed(() => props.canWrite && !detail.value?.iterationReadOnly && !detail.value?.historical && !stageFrozen.value)
const canDiscuss = computed(() => props.canWrite && !detail.value?.iterationReadOnly && !detail.value?.historical && !['COMPLETED', 'LEGACY_PASSED'].includes(currentStage.value?.executionStatus || ''))
const canDiscuss = computed(() => props.canWrite && !detail.value?.iterationReadOnly && !detail.value?.historical && !stageCompleted.value)
const editableDependencies = computed(() => writable.value && detail.value?.status === 'READY')
const loadedChildren = ref<WorkItem[]>([])
const childItems = computed(() => detail.value?.historical ? detail.value.historicalChildren || [] : loadedChildren.value)
/** 阶段归属使用独立的经理入口,普通编辑不能清空阶段绕过门禁。 */
function openAssignment() { if (!detail.value || !props.canManage) return; assignmentStageId.value = detail.value.stageId ?? null; assignmentFailure.value = ''; assignmentOpen.value = true }
/** 失败保留选择并显示业务冲突,成功重新读取详情和共享阶段摘要。 */
async function saveAssignment() { if (!detail.value || !props.canManage || busy.value) return; busy.value = true; assignmentFailure.value = ''; try { await api.assignStage(detail.value, assignmentStageId.value || null); assignmentOpen.value = false; await load(); emit('changed') } catch (error) { assignmentFailure.value = errorText(error) } finally { busy.value = false } }
watch(() => [props.id, props.projectId, props.iterationId], () => { detail.value = null; commentText.value = ''; scheduleOpen.value = false; assignmentOpen.value = false; depOpen.value = false; sourceId.value = null; loadedChildren.value = []; failure.value = ''; void load() })
/** 阶段归属提交绑定当前详情;切换对象后不关闭新表单,也不显示旧请求错误。 */
async function saveAssignment() {
if (!detail.value || !props.canManage || !writable.value || busy.value || loading.value) return
const sequence = scopeSequence, item = detail.value, stageId = assignmentStageId.value
busy.value = true; assignmentFailure.value = ''; loadSequence++
try {
await api.assignStage(item, stageId)
if (sequence !== scopeSequence) return
assignmentOpen.value = false; emit('changed'); await load()
} catch (error) { if (sequence === scopeSequence) assignmentFailure.value = errorText(error) }
finally { if (sequence === scopeSequence) busy.value = false }
}
// 详情请求和写请求分别计次:刷新不能取消本次提交,换对象(包括离开再返回)必须使旧提交回调失效。
watch(() => [props.id, props.projectId, props.iterationId], () => {
scopeSequence++
busy.value = false
deleteConfirmationOpen.value = false
attachmentConfirmationOpen.value = false
detail.value = null
commentText.value = ''
scheduleOpen.value = false
assignmentOpen.value = false
depOpen.value = false
sourceId.value = null
loadedChildren.value = []
failure.value = ''
assignmentFailure.value = ''
depFailure.value = ''
void load()
}, { flush: 'sync' })
watch(() => props.refreshKey, () => { void load() })
/** 卸载后所有在途回调作废,防止离页后弹出旧错误或刷新另一工作区。 */
onBeforeUnmount(() => { scopeSequence++; loadSequence++ })
/**
* 加载详情和子任务后校验范围与请求代次;后台相同内容保留引用,短暂失败保留已有详情。
* @param background 为 true 时不显示加载遮罩;请求途中开始编辑则丢弃结果,访问失效仍清理。
*/
async function load(background = false) {
const sequence = ++loadSequence, id = props.id
if (id === null) { detail.value = null; return }
if (id === null) { detail.value = null; loading.value = false; return }
if (!background) loading.value = true
try {
const result = await api.detail(id)
@ -128,11 +164,23 @@ async function load(background = false) {
}
/** 实际执行和审计发生时间保留北京时间及微秒,预计日期使用独立的日期展示函数。 */
function displayTime(value: string | null) { return value ? localTime(value, 'Asia/Shanghai').replace('T', ' ') : '未设置' }
/** 执行业务动作并刷新受影响工作项;被拒绝时保留具体原因。 */
async function action(commit: () => Promise<unknown>, discussion = false) {
if (!(discussion ? canDiscuss.value : writable.value)) return
busy.value = true; failure.value = ''
try { await commit(); emit('changed'); await load() } catch (error) { failure.value = errorText(error) } finally { busy.value = false }
/**
* 串行提交当前工作项动作,仅在用户仍停留于本次详情时应用成功或失败回调。
* 前台重读期间不提交旧版本;只使在途后台读失效,避免前台加载状态失去对应的结束回调。
* @param commit 已捕获工作项 ID 和版本的请求,不能在等待之后重新读取当前详情作为写入目标。
* @param discussion 评论允许在待审批阶段发送,其余写入仍受交付冻结限制。
* @param onSuccess 本次详情内的成功处理,例如清理已发送草稿或关闭已删除对象。
*/
async function action(commit: () => Promise<unknown>, discussion = false, onSuccess?: () => void) {
if (!detail.value || busy.value || loading.value || !(discussion ? canDiscuss.value : writable.value)) return
const sequence = scopeSequence
busy.value = true; failure.value = ''; loadSequence++
try {
await commit()
if (sequence !== scopeSequence) return
onSuccess?.(); emit('changed'); await load()
} catch (error) { if (sequence === scopeSequence) failure.value = errorText(error) }
finally { if (sequence === scopeSequence) busy.value = false }
}
/** 开始只调用统一后端方法,传递详情版本防止过期点击。 */
async function start() { if (props.canExecute && writable.value && detail.value) { const item = detail.value; await action(() => api.start(item.id, item.version)) } }
@ -142,18 +190,40 @@ async function confirmReview() { if (detail.value?.scheduleReviewRequired) { con
async function scheduleSaved() { scheduleOpen.value = false; emit('changed'); await load() }
/** 回退、完成、取消及关闭/重开由后端状态机和子任务门禁判断,不在前端强制写状态。 */
async function transition(status: Lifecycle) { if (detail.value) { const item = detail.value; await action(() => api.transition(item.id, status, item.version)) } }
/** 删除经产品交互确认后调用受保护软删除,后续已开始时服务端拒绝。 */
/** 确认绑定打开时的工作项及版本,换对象或关闭后作废;后端继续复验软删除条件。 */
async function remove() {
if (!detail.value) return
try { await ElMessageBox.confirm('删除此工作项?操作历史会保留,存在已开始的后续任务时将拒绝删除。', '删除工作项', { type: 'warning', closeOnClickModal: false }) } catch { return }
const item = detail.value; await action(async () => { await api.remove(item.id, item.version); emit('close') })
if (!detail.value || !writable.value || busy.value || loading.value || deleteConfirmationOpen.value) return
const item = detail.value, sequence = scopeSequence
deleteConfirmationOpen.value = true
try { await ElMessageBox.confirm(`删除工作项“${item.title}”?操作历史会保留,存在已开始的后续任务时将拒绝删除。`, '删除工作项', { type: 'warning', closeOnClickModal: false }) }
catch { return }
finally { if (sequence === scopeSequence) deleteConfirmationOpen.value = false }
if (sequence !== scopeSequence) return
await action(() => api.remove(item.id, item.version), false, () => emit('close'))
}
/** 评论使用提交时的文本;只有未继续编辑的同一份草稿才在成功后清空。 */
async function comment() {
if (!detail.value || !commentText.value.trim()) return
const itemId = detail.value.id, body = commentText.value
await action(() => api.comment(itemId, body), true, () => { if (commentText.value === body) commentText.value = '' })
}
/** 选择文件时固定所属工作项,大小检查后通过统一动作上传;清空 input 以允许重试同一文件。 */
async function upload(event: Event) {
const input = event.target as HTMLInputElement, file = input.files?.[0]
if (!file || !detail.value) return
const itemId = detail.value.id
if (file.size > 10 * 1024 * 1024) {
ElMessage.error('附件不能超过 10 MiB'); input.value = ''; return
}
await action(() => api.upload(itemId, file))
input.value = ''
}
/** 鉴权下载失败仅反馈到发起下载的详情,不把旧错误展示在另一工作项中。 */
async function download(id: number, name: string) {
const sequence = scopeSequence
try { await downloadAttachment(id, name) }
catch (error) { if (sequence === scopeSequence) failure.value = errorText(error) }
}
/** 评论成功才清空输入,失败时保留草稿。 */
async function comment() { if (detail.value) await action(async () => { await api.comment(detail.value!.id, commentText.value); commentText.value = '' }, true) }
/** 文件大小先提示,服务端仍独立验证身份、权限与大小。 */
async function upload(event: Event) { const input = event.target as HTMLInputElement, file = input.files?.[0]; if (!file || !detail.value) return; if (file.size > 10 * 1024 * 1024) { ElMessage.error('附件不能超过 10 MiB'); return } await action(() => api.upload(detail.value!.id, file)); input.value = '' }
/** 下载失败展示权限或连接提示,不提供绕过鉴权的静态 URL。 */
async function download(id: number, name: string) { try { await downloadAttachment(id, name) } catch (error) { failure.value = errorText(error) } }
/**
* 先确认附件删除,再提交详情所属工作项与附件 ID;失败沿用统一错误展示并保留列表。
@ -161,19 +231,19 @@ async function download(id: number, name: string) { try { await downloadAttachme
* 确认期间暂停后台同步;切换详情后放弃旧确认,避免在另一个工作项中执行旧操作。
*/
async function removeAttachment(file: { id: number; name: string }) {
if (!detail.value?.canDeleteAttachments || !writable.value || busy.value || attachmentConfirmationOpen.value) return
const itemId = detail.value.id
if (!detail.value?.canDeleteAttachments || !writable.value || busy.value || loading.value || attachmentConfirmationOpen.value) return
const itemId = detail.value.id, sequence = scopeSequence
attachmentConfirmationOpen.value = true
try {
await ElMessageBox.confirm(`删除附件“${file.name}”?删除后将无法下载。`, '删除附件', { type: 'warning', closeOnClickModal: false, confirmButtonText: '删除', cancelButtonText: '取消' })
} catch { return } finally { attachmentConfirmationOpen.value = false }
if (props.id !== itemId || detail.value?.id !== itemId || !detail.value.canDeleteAttachments) return
} catch { return } finally { if (sequence === scopeSequence) attachmentConfirmationOpen.value = false }
if (sequence !== scopeSequence || props.id !== itemId || detail.value?.id !== itemId || !detail.value.canDeleteAttachments) return
await action(() => api.removeAttachment(itemId, file.id))
}
const depOpen = ref(false), editingDependency = ref<Condition | null>(null), sourceId = ref<number | null>(null), depFailure = ref('')
// 删除确认属于未提交的用户操作,静默同步不能在确认期间替换当前详情。
const isEditing = computed(() => busy.value || loading.value || attachmentConfirmationOpen.value || scheduleOpen.value || assignmentOpen.value || depOpen.value || !!commentText.value.trim())
const isEditing = computed(() => busy.value || loading.value || deleteConfirmationOpen.value || attachmentConfirmationOpen.value || scheduleOpen.value || assignmentOpen.value || depOpen.value || !!commentText.value.trim())
/** 工作区轮询只静默更新空闲详情,评论、依赖和排期草稿均保留到用户完成操作。 */
async function synchronize() { if (!isEditing.value) await load(true) }
defineExpose({ isEditing, synchronize })
@ -184,12 +254,17 @@ watch(editableDependencies, allowed => { if (!allowed) { depOpen.value = false;
void load()
/** 依赖编辑仅针对当前待开始工作项,候选组件覆盖当前迭代全部工作项类型。 */
function openDependency(condition?: Condition) { editingDependency.value = condition || null; depFailure.value = ''; sourceId.value = condition?.sourceId || null; depOpen.value = true }
/** 保存依赖使用两个版本;环或排期失败时保留表单并显示服务端路径/冲突。 */
/** 保存依赖绑定本次详情及双版本;同次请求防重,切换后的旧结果不关闭新表单。 */
async function saveDependency() {
if (!detail.value || !editableDependencies.value) return
busy.value = true; depFailure.value = ''
try { await api.dependency(detail.value.id, { conditionType: 'WORK_ITEM_COMPLETED', predecessorTaskId: sourceId.value, expectedStatus: 'COMPLETED', version: editingDependency.value?.version ?? null, taskVersion: detail.value.version }, editingDependency.value?.id); depOpen.value = false; emit('changed'); await load() }
catch (error) { depFailure.value = errorText(error) } finally { busy.value = false }
if (!detail.value || !editableDependencies.value || busy.value || loading.value) return
const sequence = scopeSequence, item = detail.value
busy.value = true; depFailure.value = ''; loadSequence++
try {
await api.dependency(item.id, { conditionType: 'WORK_ITEM_COMPLETED', predecessorTaskId: sourceId.value, expectedStatus: 'COMPLETED', version: editingDependency.value?.version ?? null, taskVersion: item.version }, editingDependency.value?.id)
if (sequence !== scopeSequence) return
depOpen.value = false; emit('changed'); await load()
} catch (error) { if (sequence === scopeSequence) depFailure.value = errorText(error) }
finally { if (sequence === scopeSequence) busy.value = false }
}
/** 删除依赖仍提交任务与依赖版本,失败不从页面移除条件。 */
async function deleteDependency(condition: Condition) { if (detail.value) { const item = detail.value; await action(() => api.removeDependency(item.id, condition.id, item.version, condition.version)) } }

View File

@ -1,17 +1,17 @@
<template>
<div ref="board" class="board" :style="{ height: boardHeight + 'px' }">
<section v-for="(label, state) in statusNames" :key="state" class="lane" @dragover.prevent @drop.prevent="drop(state)">
<header>{{ label }} <span>{{ counts?.[state] ?? items.filter(i => i.status === state).length }}</span></header>
<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 items.filter(i => i.status === 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)">
<div class="card-meta"><span class="card-id">{{ typeNames[item.type] }} #{{ item.id }}</span><small v-if="item.stageId" class="stage-version" :title="item.stagePath || stages.find(stage => stage.id === item.stageId)?.name">{{ item.stagePath || stages.find(stage => stage.id === item.stageId)?.name || '阶段' }} · v{{ stages.find(stage => stage.id === item.stageId)?.revisionNo || 1 }}</small><el-tag size="small" :type="item.priority === 'URGENT' ? 'danger' : 'info'">{{ priorityNames[item.priority] }}</el-tag></div>
<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)">
<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) > items.filter(i => i.status === state).length" size="small" text @click="emit('load-more', state)">加载更多({{ items.filter(i => i.status === state).length }}/{{ counts?.[state] }})</el-button>
<div v-if="!items.some(i => i.status === state)" class="empty-lane">暂无工作项</div>
<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>
<div v-if="!itemsByStatus[state].length" class="empty-lane">暂无工作项</div>
</div>
</section>
</div>
@ -27,6 +27,14 @@ 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>())
/** 一次遍历按状态分列并保持接口顺序;乐观移动和失败恢复会自动重算,避免每列重复扫描全部工作项。 */
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)
return result
})
/** 阶段名称和版本按 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)