am-freescan/am-web/src/views/lab/scan-task/index.vue

1612 lines
65 KiB
Vue
Raw Normal View History

2026-10-22 16:18:37 +08:00
<template>
<ContentWrap v-loading="loading" class="scan-task-header" :class="{ 'scan-task-embedded': props.embedded }" :body-style="{ padding: props.embedded ? '0' : '14px 16px' }">
<el-page-header v-if="!props.embedded" @back="router.push('/cmvr/intelligence-test/execution')">
2026-10-22 16:18:37 +08:00
<template #content
><span class="task-title" :title="detail?.task.taskName">{{
detail?.task.taskName || '扫描任务工作台'
}}</span></template
>
</el-page-header>
<template v-if="detail">
<Teleport :to="props.actionTarget || 'body'" :disabled="!props.embedded || !props.actionTarget">
<div v-if="!props.embedded || props.active" class="task-summary">
<el-tag v-if="!props.embedded">{{ statusLabel(detail.task.status) }}</el-tag>
<span v-if="!props.embedded" class="summary-count">完成 {{ completedCount }} / {{ detail.units.length }} 件</span>
2026-10-22 16:18:37 +08:00
<span class="summary-spacer" />
<el-popover v-if="!props.embedded" trigger="click" placement="bottom-end" :width="360">
<template #reference><el-button text>任务信息</el-button></template>
<div class="task-metadata">
<div><span>任务编号</span><strong>{{ detail.task.taskNo }}</strong></div>
<div><span>外部任务编号</span><strong>{{ detail.task.externalTaskNo || '-' }}</strong></div>
<div><span>执行测试用例</span><strong>{{ detail.config.caseName || '-' }}</strong></div>
<div><span>原始方法号</span><code>{{ detail.config.importedTestCaseId || '-' }}</code></div>
</div>
</el-popover>
<el-button v-if="!props.embedded" @click="manualRefresh">刷新状态</el-button>
2026-10-22 16:18:37 +08:00
<el-button
v-if="activeExecution?.status === 'RUNNING' && activeExecution?.executionType !== 'SUPPLEMENT' && !detail.config.stopPending"
2026-10-22 16:18:37 +08:00
:loading="busy"
v-hasPermi="['lab:execution:control']"
@click="pauseTask"
>暂停执行</el-button
>
<el-button
v-if="activeExecution?.status === 'PAUSED' && activeExecution?.executionType !== 'SUPPLEMENT' && !detail.config.stopPending"
2026-10-22 16:18:37 +08:00
:loading="busy"
v-hasPermi="['lab:execution:control']"
@click="resumeTask"
>恢复执行</el-button
>
<el-button
v-if="!terminal"
type="danger"
plain
:loading="busy"
v-hasPermi="['lab:execution:cancel']"
@click="cancelTask"
>取消任务</el-button
>
</div>
</Teleport>
2026-10-22 16:18:37 +08:00
<el-alert
v-if="detail.config.stopPending"
type="error"
:closable="false"
title="设备停止尚未确认,机器人继续由本任务占用。确认停止会重新向设备发送停止指令。"
>
<template #default
><el-button
type="danger"
:loading="busy"
v-hasPermi="['lab:execution:cancel']"
@click="confirmStop"
>重新停止并确认</el-button
></template
>
</el-alert>
<el-alert
v-else-if="locked && activeTab === 'prepare'"
2026-10-22 16:18:37 +08:00
type="info"
:closable="false"
title="本任务已进入装夹准备或执行,扫描方案、版本、参数和资源已冻结。暂停和换件期间保留占用;未开始时可释放准备占用。"
/>
<el-steps
v-if="!props.embedded && activeTab === 'prepare'"
2026-10-22 16:18:37 +08:00
class="mt-24px preparation-steps"
:active="stage"
:process-status="
['BLOCKED', 'STOP_PENDING', 'CANCELLED'].includes(detail.task.status)
? 'error'
: 'process'
"
finish-status="success"
align-center
>
<el-step title="任务导入" /><el-step title="样件与资料接收" /><el-step
title="夹具确认"
/><el-step title="扫描方案" /><el-step title="逐件执行" />
</el-steps>
</template>
</ContentWrap>
<template v-if="detail">
<ContentWrap v-loading="busy" class="scan-task-content" :class="{ 'scan-task-embedded': props.embedded }" :body-style="{ padding: props.embedded ? '0' : '0 16px 16px' }">
<el-tabs v-if="!props.embedded" v-model="activeTab">
<el-tab-pane label="准备与资源" name="prepare" />
<el-tab-pane label="执行进度与日志" name="units" />
</el-tabs>
<section v-show="activeTab === 'prepare'" class="scan-preparation" aria-label="扫描准备内容">
<div class="preparation-layout">
<div class="preparation-column">
2026-10-22 16:18:37 +08:00
<h3>样件接收与夹具</h3>
<el-form label-width="120px" :disabled="locked || busy" @change="markDirty">
<el-form-item label="检测要求"
><div>{{ detail.task.requirement || '-' }}</div></el-form-item
>
<el-form-item label="实物接收"
><el-checkbox v-model="form.sampleReceived" @change="markDirty"
>已收到并核对本任务样件</el-checkbox
></el-form-item
>
<el-form-item label="尺寸(mm)"
><div class="dimensions"
><el-input-number
v-model="form.lengthMm"
@change="dimensionsChanged"
:min="0.001"
placeholder="长"
:controls="false" /><el-input-number
v-model="form.widthMm"
@change="dimensionsChanged"
:min="0.001"
placeholder="宽"
:controls="false" /><el-input-number
v-model="form.heightMm"
@change="dimensionsChanged"
:min="0.001"
placeholder="高"
:controls="false" /></div
></el-form-item>
<el-form-item label="重量(kg)"
><el-input-number
v-model="form.weightKg"
:min="0"
:controls="false"
@change="dimensionsChanged"
/></el-form-item>
<el-form-item label="需要夹具"
><el-switch
v-model="form.requireFixture"
@change="fixtureRequirementChanged"
/><span class="hint ml-8px"
>软件验证可关闭;实际装夹任务应开启</span
></el-form-item
>
<template v-if="form.requireFixture">
<el-form-item label="推荐夹具"
><el-button :loading="fixtureLoading" @click="recommendFixtures"
>根据尺寸推荐</el-button
></el-form-item
>
<el-form-item label="选择夹具"
><el-select
v-model="form.fixtureId"
filterable
clearable
class="!w-full"
@change="dimensionsChanged"
@visible-change="open => { if (open) recommendFixtures() }"
2026-10-22 16:18:37 +08:00
><el-option
v-for="fixture in recommendations"
class="fixture-option"
2026-10-22 16:18:37 +08:00
:key="String(fixture.id)"
:value="fixture.id"
:disabled="!fixture.compatible"
:label="`${fixture.fixtureCode} ${fixture.fixtureName}`"><div>{{ fixture.fixtureName }} · {{ fixture.fixtureCode }}</div><div v-if="!fixture.compatible" class="fixture-option-reason">{{ fixture.reason }}</div></el-option></el-select
2026-10-22 16:18:37 +08:00
></el-form-item>
<el-form-item v-if="selectedFixture" label="匹配依据"
><span>{{ selectedFixture.reason }}</span></el-form-item
>
<el-form-item v-if="frameworkNeeded" label="夹具框架点"><el-alert :title="frameworkHint" :type="frameworkReady ? 'success' : 'warning'" :closable="false" /></el-form-item>
2026-10-22 16:18:37 +08:00
<el-form-item label="装夹确认"
><el-checkbox
v-model="form.fixtureConfirmed"
:disabled="locked || busy || !form.fixtureId"
@change="markDirty"
>已确认所选夹具及装夹条件</el-checkbox
></el-form-item
>
</template>
</el-form>
<el-table
v-if="recommendations.length && !locked"
:data="recommendations"
size="small"
class="mb-16px"
><el-table-column label="夹具" prop="fixtureName" /><el-table-column
label="匹配"
width="70"
><template #default="{ row }">{{
row.compatible ? '可用' : '不匹配'
}}</template></el-table-column
><el-table-column
label="依据"
prop="reason"
show-overflow-tooltip
/><el-table-column label="配置" width="95"
><template #default="{ row }"
><el-button
link
type="primary"
v-hasPermi="['lab:fixture:update']"
@click="openFixtureRange(row)"
>适用范围</el-button
></template
></el-table-column
></el-table
>
<template v-if="props.showTechnicalAttachments">
2026-10-22 16:18:37 +08:00
<h3>任务技术资料</h3>
<el-upload
v-if="!locked"
v-hasPermi="['lab:task:update']"
:show-file-list="false"
:http-request="uploadAttachment"
:disabled="uploading"
:before-upload="beforeAttachment"
><el-button :loading="uploading">上传模型、图纸或其他资料</el-button
><template #tip
><div class="hint">不设单文件大小上限;资料关联本次任务。分类及版本选用请在检测任务工作台管理。</div></template
2026-10-22 16:18:37 +08:00
></el-upload
>
<el-table :data="detail.attachments || []" size="small"
><el-table-column label="文件" min-width="180"
><template #default="{ row }"
><el-link
:href="safeFileUrl(row.fileUrl)"
target="_blank"
rel="noopener noreferrer"
type="primary"
>{{ row.fileName }}</el-link
></template
></el-table-column
><el-table-column label="操作" width="80"
><template #default="{ row }"
><el-button v-if="!locked" link type="danger" @click="removeAttachment(row)"
>删除</el-button
></template
></el-table-column
></el-table
>
</template>
</div>
<div class="preparation-column">
2026-10-22 16:18:37 +08:00
<h3>扫描方案 / 测试用例</h3>
<el-radio-group v-model="executionMode" :disabled="locked || busy" class="mb-16px" @change="executionModeChanged"><el-radio-button value="single">单个用例</el-radio-button><el-radio-button value="plan">执行方案</el-radio-button></el-radio-group>
<ExecutionPlanSetup v-if="executionMode === 'plan'" ref="planSetup" :cases="cases" :snapshot="planSnapshot" :disabled="locked || busy" @change="planSetupChanged" />
2026-10-22 16:18:37 +08:00
<el-form label-position="top" :disabled="locked || busy" @change="markDirty">
<template v-if="executionMode === 'single'">
2026-10-22 16:18:37 +08:00
<el-form-item label="测试用例(方法号)" required
><el-select
v-model="form.testCaseId"
:loading="catalogLoading"
2026-10-22 16:18:37 +08:00
filterable
class="!w-full"
@change="changeCase"
><el-option
v-for="item in caseOptions"
:key="item.id"
:value="String(item.id)"
:disabled="String(item.enabled) !== '0'"
:label="`${item.caseName} (${item.id})`" /></el-select
></el-form-item>
<div class="hint mb-16px"
>当前所选方法号 / 测试用例 ID:<code>{{ form.testCaseId || '-' }}</code></div
>
<el-form-item v-if="caseChanged" label="更换原因" required
><el-input
v-model="form.changeReason"
type="textarea"
placeholder="说明为何更换导入任务指定的测试用例"
/></el-form-item>
<el-form-item label="确认发布版本" required
><el-select
v-model="form.versionId"
class="!w-full"
:loading="versionLoading"
@change="changeVersion"
><el-option
v-for="version in versions"
:key="version.id"
:value="version.id"
:label="`V${version.versionNo} ${version.publishNote || ''}`" /></el-select
><div class="hint">全部样件使用开始任务时冻结的同一版本。</div></el-form-item
>
<div v-if="scannerSettings.visible" class="scanner-task-parameters">
<h4>扫描参数</h4>
<el-row :gutter="16">
<el-col :sm="12" :xs="24">
<el-form-item label="激光亮度" required>
<el-input-number v-model="form.scannerParameters.brightness" :min="1" :max="18" :precision="0" :step="1" step-strictly :disabled="!scannerSettings.available" @change="markDirty" />
<div class="hint">1–18,整数;默认8</div>
</el-form-item>
</el-col>
<el-col :sm="12" :xs="24">
<el-form-item label="点间距" required>
<el-input-number v-model="form.scannerParameters.pointDistance" :min="0.05" :max="10" :step="0.05" :disabled="!scannerSettings.available" @change="markDirty" />
<div class="hint">0.05–10;默认0.2</div>
</el-form-item>
</el-col>
</el-row>
<div class="hint mb-16px">{{ scannerSettings.available ? '本任务值覆盖方案中“修改扫描参数”节点的亮度和点间距,其他参数保持节点配置。' : '当前发布版本未包含“修改扫描参数”组件。请先在测试用例中将该组件连接到开始采集之前,并发布新版本后选择使用。' }}</div>
</div>
2026-10-22 16:18:37 +08:00
<ParameterFields
v-model="form.runParams"
:fields="fields"
:disabled="locked || busy"
@update:model-value="markDirty"
/>
<el-empty
v-if="!fields.length && !scannerSettings.visible"
2026-10-22 16:18:37 +08:00
:image-size="42"
description="此版本没有需要填写的运行参数"
/>
</template>
<el-form-item v-if="caseChanged && executionMode === 'plan'" label="更换原因" required><el-input v-model="form.changeReason" placeholder="说明本次选择执行方案的原因" /></el-form-item>
2026-10-22 16:18:37 +08:00
</el-form>
<h3>本任务机器人与设备</h3>
<template v-if="locked">
<div
v-for="assignment in form.runtimeAssignments"
:key="assignment.roleKey"
class="resource-snapshot"
><strong>{{ assignment.roleKey }}</strong
><div v-for="member in assignment.members" :key="member.memberKey"
>机器人:{{ member.robotId || '-'
}}<div v-for="(device, slot) in member.devices" :key="slot"
>{{ slot }}:{{ device || '-' }}</div
></div
></div
>
<el-empty
v-if="!form.runtimeAssignments.length"
:image-size="42"
description="此任务没有分配机器人"
/>
</template>
<RuntimeAssignmentsEditor
v-else-if="!versionLoading"
:key="`${form.testCaseId}:${form.versionId}:${resourceRevision}`"
ref="assignmentEditor"
:model-value="form.runtimeAssignments"
:roles="roles"
@update:model-value="resourcesChanged"
/>
<AgvLiveMap :assignments="form.runtimeAssignments" :flow-data="detail.flowData" :active="props.active && activeTab === 'prepare'" hide-empty />
2026-10-22 16:18:37 +08:00
<el-alert
v-if="!form.versionId"
type="warning"
:closable="false"
title="请选择已发布版本后再进行准备与执行。"
/>
</div>
</div>
2026-10-22 16:18:37 +08:00
<ResourceSchedule
:model-value="schedule"
@update:model-value="Object.assign(schedule, $event)"
@change="markDirty"
:state="detail.resourceState"
:disabled="locked || busy"
:busy="busy"
:terminal="terminal"
:acquired="!!detail.config.resourcesAcquiredAt"
:started="!!detail.config.startedAt"
@release="releasePreparation"
@extend="extendSchedule"
/>
<div class="actions">
<el-button
v-if="!locked"
type="primary"
:loading="busy"
v-hasPermi="['lab:execution:precheck']"
@click="savePreparation"
>保存准备配置</el-button
>
<el-button
:loading="busy"
:disabled="terminal || detail.config.stopPending"
v-hasPermi="['lab:execution:precheck']"
@click="runPrecheck"
>{{ dirty ? '保存并预检' : '执行前预检' }}</el-button
>
<span v-if="dirty && !locked" class="hint">配置已修改,保存不会触发执行。</span>
</div>
<el-table v-if="precheckResult" :data="precheckResult.items" class="mt-16px"
><el-table-column label="预检项" prop="code" width="160" /><el-table-column
label="结果"
width="90"
><template #default="{ row }"
><el-tag :type="row.passed ? 'success' : 'danger'">{{
row.passed ? '通过' : '阻断'
}}</el-tag></template
></el-table-column
><el-table-column label="说明" prop="message"
/></el-table>
</section>
<section v-show="activeTab === 'units'" aria-label="扫描执行内容">
2026-10-22 16:18:37 +08:00
<el-alert
v-if="dirty && !locked"
type="warning"
:closable="false"
class="mb-16px"
:title="props.embedded ? '准备配置尚未保存,请回到“扫描准备”保存并预检,再开始执行。' : '准备配置尚未保存。请回到“准备与资源”保存并预检,再开始执行所选测试用例。'"
2026-10-22 16:18:37 +08:00
/>
<div v-if="detail.units.length > 1" class="batch-progress">
2026-10-22 16:18:37 +08:00
<div class="section-heading"
><h3>批次进度</h3
2026-10-22 16:18:37 +08:00
><span>已完成 {{ completedCount }} / {{ detail.units.length }} 件</span></div
>
<el-progress
:percentage="overallProgress"
:stroke-width="6"
2026-10-22 16:18:37 +08:00
:status="
detail.task.status === 'COMPLETED'
? 'success'
: ['BLOCKED', 'STOP_PENDING'].includes(detail.task.status)
? 'exception'
: undefined
"
/>
</div>
<div class="execution-layout" :class="{ 'single-unit': detail.units.length === 1 }">
<aside v-if="detail.units.length > 1" class="sample-queue" aria-label="样件执行队列">
2026-10-22 16:18:37 +08:00
<h3>样件队列</h3>
<button
v-for="(unit, index) in detail.units"
:key="String(unit.id)"
type="button"
class="sample-card"
:class="{ selected: String(selectedUnit?.id) === String(unit.id) }"
:aria-current="String(selectedUnit?.id) === String(unit.id) ? 'true' : undefined"
@click="selectUnit(unit)"
>
<div class="sample-card-heading"
><strong>第 {{ index + 1 }} 件</strong
><el-tag
size="small"
:type="
unit.status === 'SUCCEEDED'
? 'success'
: unit.status === 'FAILED'
? 'danger'
: 'info'
"
>{{ statusLabel(unit.status) }}</el-tag
></div
>
<span class="sample-card-code" :title="unit.unitNo">{{ unit.unitNo }}</span>
<span class="sample-card-caption">{{
unit.attemptNo ? `${unit.attemptNo} 次执行` : '等待装夹'
}}</span>
</button>
</aside>
<div ref="executionPanel" class="selected-execution" v-if="selectedUnit">
2026-10-22 16:18:37 +08:00
<div class="selected-unit-heading">
<div
><h3 :title="selectedUnit.unitNo">样件 {{ detail.units.findIndex(unit => String(unit.id) === String(selectedUnit?.id)) + 1 }}</h3
><span v-if="selectedUnit.physicalSerial" class="hint"
>实物编号:{{ selectedUnit.physicalSerial }}</span
2026-10-22 16:18:37 +08:00
></div
>
<div class="selected-unit-actions">
<el-select
v-if="selectedUnit.attempts?.length"
v-model="selectedAttemptId"
class="attempt-select"
aria-label="选择执行记录"
>
<el-option
v-for="attempt in selectedUnit.attempts"
:key="String(attempt.id)"
:value="String(attempt.id)"
:label="`${attemptLabel(attempt)} · ${statusLabel(attempt.status)}`"
2026-10-22 16:18:37 +08:00
/>
</el-select>
<el-button
v-if="canStart(selectedUnit)"
type="primary"
:disabled="busy || dirty"
v-hasPermi="['lab:execution:dispatch']"
@click="openStart(selectedUnit)"
>{{ selectedUnit.attemptNo ? '重新装夹并重试' : '确认装夹并开始' }}</el-button
>
<ScanSupplementActions :detail="detail" :unit="selectedUnit" :execution="selectedExecution" @changed="supplementChanged" />
2026-10-22 16:18:37 +08:00
</div>
</div>
<div v-if="selectedExecution" class="execution-record-context">
<span>当前查看:{{ attemptLabel(selectedExecution) }}</span>
<el-button v-if="sourceAttempt(selectedUnit, selectedExecution)" link type="primary"
@click="selectedAttemptId = String(sourceAttempt(selectedUnit, selectedExecution)!.id)">查看补扫前记录与成果</el-button>
<el-button v-if="String(selectedExecution.id) !== String(selectedUnit.currentExecutionId)" link type="primary"
@click="selectedAttemptId = String(selectedUnit.currentExecutionId)">查看最新执行</el-button>
</div>
2026-10-22 16:18:37 +08:00
<ScanExecutionMonitor
:execution="selectedExecution"
:case-name="detail.config.caseName"
:test-case-id="detail.config.selectedTestCaseId"
:version-no="detail.config.versionNo"
:flow-data="detail.flowData"
:active="props.active && activeTab === 'units' && !logVisible"
2026-10-22 16:18:37 +08:00
/>
</div>
</div>
<el-collapse class="execution-history">
<el-collapse-item title="全部单件与重试历史" name="history">
<el-table :data="detail.units" row-key="id">
<el-table-column type="expand"
><template #default="{ row }"
><el-table :data="row.attempts || []" size="small"
><el-table-column
label="执行编号"
prop="executionNo"
min-width="200"
/><el-table-column label="类型" width="90"><template #default="{ row: attempt }">{{ attempt.executionType === 'SUPPLEMENT' ? '补扫' : attempt.executionType === 'RETEST' ? '重试' : '初次扫描' }}</template></el-table-column><el-table-column label="尝试" prop="attemptNo" width="80" /><el-table-column
2026-10-22 16:18:37 +08:00
label="状态"
width="130"
><template #default="{ row: attempt }">{{
statusLabel(attempt.status)
}}</template></el-table-column
><el-table-column
label="失败原因"
prop="failureReason"
min-width="180"
/><el-table-column label="操作" width="200"
2026-10-22 16:18:37 +08:00
><template #default="{ row: attempt }"
><el-button link type="primary" @click="viewAttempt(row, attempt)">查看记录与成果</el-button><el-button link type="primary" @click="openLogs(attempt)"
2026-10-22 16:18:37 +08:00
>流程与日志</el-button
></template
></el-table-column
></el-table
></template
></el-table-column
>
<el-table-column label="单件编号" prop="unitNo" min-width="180" />
<el-table-column label="实物编号" prop="physicalSerial" min-width="130" />
<el-table-column label="状态" min-width="140"
><template #default="{ row }"
><el-tag
:type="
row.status === 'SUCCEEDED'
? 'success'
: row.status === 'FAILED'
? 'danger'
: 'info'
"
>{{ statusLabel(row.status) }}</el-tag
></template
></el-table-column
>
<el-table-column label="尝试次数" prop="attemptNo" width="100" />
<el-table-column
label="输出引用"
prop="outputPath"
min-width="180"
show-overflow-tooltip
/>
<el-table-column label="操作" width="250"
><template #default="{ row }"
><el-button
v-if="canStart(row)"
type="primary"
:disabled="busy || dirty"
v-hasPermi="['lab:execution:dispatch']"
@click="openStart(row)"
>{{ row.attemptNo ? '重新装夹并重试' : '确认装夹并开始' }}</el-button
><el-button
v-if="row.currentExecutionId"
link
type="primary"
@click="openLogs({ id: row.currentExecutionId, executionNo: row.unitNo })"
>当前日志</el-button
></template
></el-table-column
>
</el-table>
</el-collapse-item>
</el-collapse>
<div class="hint mt-12px"
>执行完成只表示扫描流程已结束;尺寸比对、报告与最终交付请在任务的“比对与成果”中查看。</div
2026-10-22 16:18:37 +08:00
>
</section>
2026-10-22 16:18:37 +08:00
</ContentWrap>
</template>
<el-dialog
v-model="startVisible"
:title="startUnit?.attemptNo ? '重试当前样件' : '确认样件装夹并开始'"
width="520px"
:close-on-click-modal="false"
>
<el-form label-position="top">
<el-form-item label="本次执行测试用例">
<div
>{{ detail?.config.caseName }}<br />方法号:<code>{{
detail?.config.selectedTestCaseId
}}</code
><br />发布版本:V{{ detail?.config.versionNo }}</div
>
</el-form-item>
<el-form-item label="单件编号">{{ startUnit?.unitNo }}</el-form-item>
<el-form-item label="实物编号"
><el-input v-model="startForm.physicalSerial" placeholder="可填样件条码或实物序列号"
/></el-form-item>
<el-form-item v-if="startUnit?.attemptNo" label="重试原因" required
><el-input v-model="startForm.reason" type="textarea"
/></el-form-item>
<el-form-item
><el-checkbox v-model="startForm.loadedConfirmed"
>已核对当前样件编号,确认换件、装夹和现场执行条件</el-checkbox
></el-form-item
>
</el-form>
<template #footer
><el-button @click="startVisible = false">返回</el-button
><el-button
type="primary"
:loading="busy"
:disabled="!startForm.loadedConfirmed"
@click="submitStart"
>开始本件执行</el-button
></template
>
</el-dialog>
<el-dialog v-model="fixtureRangeVisible" title="配置夹具适用范围" width="500px">
<el-alert
class="mb-16px"
type="info"
:closable="false"
title="范围用于尺寸推荐;修改后请重新推荐夹具并确认装夹。"
/>
<el-form label-width="140px">
<el-form-item label="夹具">{{ fixtureRangeName }}</el-form-item>
<el-form-item label="最大长度(mm)" required
><el-input-number v-model="fixtureRange.maxLengthMm" :min="0.001" :controls="false"
/></el-form-item>
<el-form-item label="最大宽度(mm)" required
><el-input-number v-model="fixtureRange.maxWidthMm" :min="0.001" :controls="false"
/></el-form-item>
<el-form-item label="最大高度(mm)" required
><el-input-number v-model="fixtureRange.maxHeightMm" :min="0.001" :controls="false"
/></el-form-item>
<el-form-item label="最大重量(kg)"
><el-input-number v-model="fixtureRange.maxWeightKg" :min="0" :controls="false"
/></el-form-item>
</el-form>
<template #footer
><el-button @click="fixtureRangeVisible = false">返回</el-button
><el-button type="primary" :loading="busy" @click="saveFixtureRange"
>保存适用范围</el-button
></template
>
</el-dialog>
<el-drawer v-model="logVisible" :title="`执行日志 ${logExecution?.executionNo || ''}`" size="75%">
<ScanExecutionMonitor
v-if="detail && logVisible"
:execution="logExecution"
:case-name="detail.config.caseName"
:test-case-id="detail.config.selectedTestCaseId"
:version-no="detail.config.versionNo"
:flow-data="detail.flowData"
:active="props.active && logVisible"
2026-10-22 16:18:37 +08:00
:height="560"
/>
</el-drawer>
</template>
<script setup lang="ts">
import { ElMessageBox } from 'element-plus'
import { generateUUID } from '@/utils'
import { scannerTaskParameters, validateScannerParameters, SCANNER_PARAMETER_RUN_KEY } from '@/cmvr/common/utils/scannerParameters.mjs'
2026-10-22 16:18:37 +08:00
import * as ScanApi from '@/api/lab/scan-task'
import ScanSupplementActions from './ScanSupplementActions.vue'
import ExecutionPlanSetup from './ExecutionPlanSetup.vue'
2026-10-22 16:18:37 +08:00
import * as FileApi from '@/api/infra/file'
import type { LabExecutionVO } from '@/api/lab/execution'
import { getTestCaseList } from '@/cmvr/aima/api/intelligenceTest/testCase'
import { getDetect } from '@/cmvr/common/api/test/detect'
import { flowVersionList, flowVersionDetail } from '@/cmvr/common/api/flow/flow'
import { getResourceRoles, normalizeFlowResourceSchema } from '@/cmvr/common/utils/flowResources'
import RuntimeAssignmentsEditor from '@/cmvr/common/views/flow/components/RuntimeAssignmentsEditor.vue'
import ScanExecutionMonitor from './ScanExecutionMonitor.vue'
const AgvLiveMap = defineAsyncComponent(() => import('./AgvLiveMap.vue'))
import { scanTaskPollInterval } from './workbenchPolling.mjs'
2026-10-22 16:18:37 +08:00
import ResourceSchedule, { type ScheduleForm } from './ResourceSchedule.vue'
import { attemptLabel, sourceAttempt, batchProgress, preparationStage, unitExecution } from './executionPresentation.mjs'
2026-10-22 16:18:37 +08:00
import ParameterFields from './ParameterFields.vue'
import { getFramework } from '@/api/lab/master/fixture'
2026-10-22 16:18:37 +08:00
import {
readJson,
parameterFields,
parameterDefaults,
materializeParams,
nextRunnableUnit,
statusLabel
} from './scanForm.mjs'
defineOptions({ name: 'LabScanTaskWorkbench' })
const props = withDefaults(defineProps<{ active?: boolean; showTechnicalAttachments?: boolean; embedded?: boolean; view?: string; actionTarget?: HTMLElement }>(), { active: true, showTechnicalAttachments: true, embedded: false })
const emit = defineEmits(['update:view', 'summary-change'])
2026-10-22 16:18:37 +08:00
const route = useRoute()
const router = useRouter()
const message = useMessage()
const taskId = computed(() => String(route.params.id))
const detail = shallowRef<ScanApi.ScanTaskDetail>()
const catalogLoading=ref(false)
2026-10-22 16:18:37 +08:00
const loading = ref(false)
const busy = ref(false)
const dirty = ref(false)
const activeTab = ref('prepare')
watch(() => props.view, value => {
if (props.embedded && ['prepare','units'].includes(value || '') && value !== activeTab.value) activeTab.value = value!
}, { immediate: true })
watch(activeTab, value => { if (props.embedded) emit('update:view', value) })
2026-10-22 16:18:37 +08:00
const cases = ref<any[]>([])
const caseOptions = computed(() => {
const config = detail.value?.config
if (
!config?.selectedTestCaseId ||
cases.value.some((item) => String(item.id) === config.selectedTestCaseId)
)
return cases.value
return [
...cases.value,
{
id: config.selectedTestCaseId,
caseName: `${config.caseName || '已保存测试用例'}(已不可选)`,
enabled: '1'
}
]
})
const versions = ref<any[]>([])
const versionLoading = ref(false)
const recommendations = ref<ScanApi.FixtureOption[]>([])
const fixtureLoading = ref(false)
const uploading = ref(false)
const fields = ref<any[]>([])
const frameworkNeeded = ref(false), frameworkReady = ref(false), frameworkHint = ref('请选择夹具,系统自动匹配框架点')
let frameworkGeneration = 0
onMounted(() => watch(() => form.fixtureId, async id => {
const generation = ++frameworkGeneration
frameworkReady.value = false
frameworkHint.value = id ? '正在读取夹具框架点…' : '请选择夹具,系统自动匹配框架点'
if (!id) return
try {
const result = await getFramework(id)
if (generation !== frameworkGeneration) return
frameworkReady.value = !!result.current?.id
frameworkHint.value = frameworkReady.value ? '已匹配夹具框架点,开始执行时自动导入;本批次开始后固定所用版本' : '此夹具尚未录入框架点,请到主数据→夹具管理→夹具框架点先录入'
} catch { if (generation === frameworkGeneration) frameworkHint.value = '框架点读取失败,请刷新状态后重试' }
}, { immediate: true }))
const scannerSettings = ref({ visible: false, available: false })
2026-10-22 16:18:37 +08:00
const roles = ref<any[]>([])
const resourceRevision = ref(0)
const assignmentEditor = ref<any>()
const form = reactive({
testCaseId: '',
versionId: '',
changeReason: '',
sampleReceived: false,
fixtureId: undefined as ScanApi.Id | undefined,
fixtureConfirmed: false,
lengthMm: undefined as number | undefined,
widthMm: undefined as number | undefined,
heightMm: undefined as number | undefined,
weightKg: undefined as number | undefined,
requireFixture: true,
runParams: {} as Record<string, any>,
scannerParameters: { brightness: 8 as number | undefined, pointDistance: 0.2 as number | undefined },
2026-10-22 16:18:37 +08:00
runtimeAssignments: [] as ScanApi.RuntimeAssignment[],
robotId: ''
})
const executionMode = ref('single'), planSetup = ref<any>(), planSnapshot = ref<any>()
function executionModeChanged() {
form.runtimeAssignments = []; roles.value = []; fields.value = []; form.runParams = {}; frameworkNeeded.value = false
if(executionMode.value === 'single') loadVersions(true)
markDirty()
}
function planSetupChanged(value: any) {
if(value.first) { form.testCaseId = value.first.testCaseId; form.versionId = value.first.versionId }
roles.value = value.roles; frameworkNeeded.value = value.framework
fields.value = []; scannerSettings.value = { visible: false, available: false }
const allowed = new Set(value.roles.map(r => r.roleKey))
form.runtimeAssignments = form.runtimeAssignments.filter(a => allowed.has(a.roleKey))
resourceRevision.value++; if(!value.initial) markDirty()
}
2026-10-22 16:18:37 +08:00
const schedule = reactive<ScheduleForm>({
reservationMode: 'IMMEDIATE',
expectedMinutes: 60,
requireLaboratory: false
})
const precheckResult = ref<ScanApi.ScanPrecheck>()
const locked = computed(
() =>
!!detail.value?.config.resourcesAcquiredAt ||
!!detail.value?.config.startedAt ||
!!detail.value?.config.stopPending ||
terminal.value
)
const terminal = computed(() =>
['COMPLETED', 'CANCELLED'].includes(detail.value?.task.status || '')
)
const caseChanged = computed(
() => !!detail.value?.config.selectedTestCaseId && form.testCaseId !== detail.value.config.selectedTestCaseId
2026-10-22 16:18:37 +08:00
)
const selectedFixture = computed(() =>
recommendations.value.find((item) => String(item.id) === String(form.fixtureId))
)
const completedCount = computed(
() =>
detail.value?.units.filter((unit) => ['SUCCEEDED', 'COMPLETED'].includes(unit.status)).length ||
0
)
const activeExecution = computed(() =>
detail.value?.units
.flatMap((unit) => unit.attempts || [])
.find((attempt) => ['RUNNING', 'PAUSED'].includes(attempt.status))
)
const stage = computed(() => preparationStage(form, detail.value?.task.status))
const overallProgress = computed(() => batchProgress(detail.value?.units || []))
const selectedUnitId = ref('')
const selectedAttemptId = ref('')
const executionPanel = ref<HTMLElement>()
2026-10-22 16:18:37 +08:00
const selectedUnit = computed(() => {
const units = detail.value?.units || []
return (
units.find((unit) => String(unit.id) === selectedUnitId.value) ||
units.find((unit) => ['RUNNING', 'QUEUED', 'PAUSED', 'FAILED'].includes(unit.status)) ||
units[0]
)
})
const selectedExecution = computed(() => unitExecution(selectedUnit.value, selectedAttemptId.value))
const selectUnit = (unit: ScanApi.ScanUnit) => {
selectedUnitId.value = String(unit.id)
selectedAttemptId.value = unit.currentExecutionId ? String(unit.currentExecutionId) : ''
}
const viewAttempt = async (unit: ScanApi.ScanUnit, execution: Partial<LabExecutionVO>) => {
selectUnit(unit)
await nextTick()
selectedAttemptId.value = String(execution.id)
activeTab.value = 'units'
await nextTick()
executionPanel.value?.scrollIntoView({ block: 'start', behavior: 'smooth' })
}
2026-10-22 16:18:37 +08:00
watch(
() => selectedUnit.value?.id,
() => {
selectedAttemptId.value = String(unitExecution(selectedUnit.value)?.id || '')
}
)
const markDirty = () => {
if (!locked.value) {
dirty.value = true
precheckResult.value = undefined
}
}
const dimensionsChanged = () => {
form.fixtureConfirmed = false
markDirty()
if (!locked.value && !busy.value) void recommendFixtures()
2026-10-22 16:18:37 +08:00
}
const assignmentSignature = (assignments: ScanApi.RuntimeAssignment[]) =>
JSON.stringify(
assignments.map((assignment) => ({
roleKey: assignment.roleKey,
members: assignment.members.map((member) => ({
robotId: member.robotId || '',
devices: Object.entries(member.devices || {}).sort(([a], [b]) => a.localeCompare(b))
}))
}))
)
const resourcesChanged = (assignments: ScanApi.RuntimeAssignment[]) => {
const changed = assignmentSignature(assignments) !== assignmentSignature(form.runtimeAssignments)
form.runtimeAssignments = assignments
if (changed) markDirty()
}
const fixtureRequirementChanged = () => {
if (!form.requireFixture) {
form.fixtureId = undefined
form.fixtureConfirmed = false
}
markDirty()
}
const applySchema = (inputConfig: any, flowData: any, values: Record<string, any> = {}) => {
const graph = normalizeFlowResourceSchema(readJson(flowData, {}))
const allFields = parameterFields(inputConfig, graph)
frameworkNeeded.value = allFields.some(field => field.name === 'fixtureFrameworkUrls') || graph.nodes?.some(node => node.properties?.action === 'SCANNER_FRAMEWORK_IMPORT')
fields.value = allFields.filter(field => ![SCANNER_PARAMETER_RUN_KEY, 'fixtureFrameworkUrls'].includes(field.name))
const settings = scannerTaskParameters(graph, values)
scannerSettings.value = { visible: settings.visible, available: settings.available }
Object.assign(form.scannerParameters, settings.values)
2026-10-22 16:18:37 +08:00
roles.value = getResourceRoles(graph)
form.runParams = parameterDefaults(fields.value, values)
}
let pageGeneration = 0
let activeRefresh: Promise<void> | undefined
const refresh = async (replaceForm = false, refreshVersions = true) => {
2026-10-22 16:18:37 +08:00
if (activeRefresh) {
await activeRefresh
if (!replaceForm) return
}
const work = async () => {
const generation = pageGeneration
const result = await ScanApi.getDetail(taskId.value)
if (generation !== pageGeneration) return
const previousRevision = detail.value?.config.revision
const previousStartedAt = detail.value?.config.startedAt
2026-10-22 16:18:37 +08:00
detail.value = result
if (props.embedded) emit('summary-change', { status: result.task.status, completed: result.units.filter(u => u.status === 'SUCCEEDED').length, total: result.units.length })
2026-10-22 16:18:37 +08:00
if (
replaceForm ||
(!dirty.value && previousRevision !== result.config.revision) ||
(result.config.startedAt && previousStartedAt !== result.config.startedAt)
2026-10-22 16:18:37 +08:00
) {
const config = result.config
Object.assign(form, {
testCaseId: config.selectedTestCaseId,
versionId: config.versionId || '',
changeReason: '',
sampleReceived: config.sampleReceived,
fixtureId: config.fixtureId,
fixtureConfirmed: config.fixtureConfirmed,
lengthMm: config.lengthMm,
widthMm: config.widthMm,
heightMm: config.heightMm,
weightKg: config.weightKg,
requireFixture: config.requireFixture,
runtimeAssignments: JSON.parse(JSON.stringify(config.runtimeAssignments || [])),
robotId: config.robotId || ''
})
Object.assign(schedule, {
reservationMode: config.reservationMode || 'IMMEDIATE',
expectedMinutes: config.expectedMinutes || 60,
plannedStartAt: config.plannedStartAt,
plannedEndAt: config.plannedEndAt,
laboratoryId: config.laboratoryId,
requireLaboratory: !!config.requireLaboratory
})
recommendations.value = result.recommendations || []
applySchema(result.inputConfig, result.flowData, config.runParams || {})
planSnapshot.value = config.runParams?._executionPlan
executionMode.value = planSnapshot.value ? 'plan' : 'single'
if(planSnapshot.value) { fields.value = []; scannerSettings.value = { visible: false, available: false }; form.runParams = {} }
2026-10-22 16:18:37 +08:00
dirty.value = false
if (replaceForm) {
resourceRevision.value++
if(refreshVersions && executionMode.value === 'single') await loadVersions(false)
2026-10-22 16:18:37 +08:00
}
}
}
const pending = work()
activeRefresh = pending
try {
await pending
} finally {
if (activeRefresh === pending) activeRefresh = undefined
}
}
const manualRefresh = async () => {
if (dirty.value && !locked.value) {
try {
await ElMessageBox.confirm('重新加载会放弃未保存的准备配置,是否继续?', '刷新任务')
} catch {
return
}
}
await refresh(true)
}
defineExpose({ refresh: manualRefresh })
2026-10-22 16:18:37 +08:00
let versionRequest = 0
const loadVersions = async (selectPublished = false) => {
const currentCase = cases.value.find((item) => String(item.id) === form.testCaseId)
const itemId = currentCase?.detectItemId
if (!itemId) {
const config = detail.value?.config
versions.value =
config?.selectedTestCaseId === form.testCaseId && config?.versionId
? [
{
id: config.versionId,
versionNo: config.versionNo,
publishNote: '本任务保存的发布版本'
}
]
: []
return
}
const request = ++versionRequest
versionLoading.value = true
try {
const [list, detection] = await Promise.all([flowVersionList(itemId), getDetect(itemId)])
if (request !== versionRequest) return
versions.value = list.data || []
if (selectPublished || !form.versionId) {
form.versionId = detection.data?.publishedVersionId || ''
if (form.versionId) await changeVersion()
}
} finally {
if (request === versionRequest) versionLoading.value = false
}
}
const changeCase = async () => {
form.versionId = ''
form.runtimeAssignments = []
form.runParams = {}
form.fixtureConfirmed = false
fields.value = []
roles.value = []
versions.value = []
markDirty()
await loadVersions(true)
}
const changeVersion = async () => {
if (!form.versionId) return
const id = form.versionId
versionLoading.value = true
try {
const result = await flowVersionDetail(id)
if (id !== form.versionId) return
applySchema(result.data?.config, result.data?.flowData)
form.runtimeAssignments = []
resourceRevision.value++
markDirty()
} finally {
if (id === form.versionId) versionLoading.value = false
}
}
let fixtureRequest = 0
2026-10-22 16:18:37 +08:00
const recommendFixtures = async () => {
const request = ++fixtureRequest
2026-10-22 16:18:37 +08:00
fixtureLoading.value = true
try {
const result = await ScanApi.fixtureOptions({
2026-10-22 16:18:37 +08:00
taskId: taskId.value,
lengthMm: form.lengthMm,
widthMm: form.widthMm,
heightMm: form.heightMm,
weightKg: form.weightKg
2026-10-22 16:18:37 +08:00
})
if (request === fixtureRequest) recommendations.value = result
} catch {
if (request === fixtureRequest) recommendations.value = []
2026-10-22 16:18:37 +08:00
} finally {
if (request === fixtureRequest) fixtureLoading.value = false
2026-10-22 16:18:37 +08:00
}
}
const fixtureRangeVisible = ref(false)
const fixtureRangeName = ref('')
const fixtureRange = reactive({
fixtureId: '' as ScanApi.Id,
maxLengthMm: undefined as number | undefined,
maxWidthMm: undefined as number | undefined,
maxHeightMm: undefined as number | undefined,
maxWeightKg: undefined as number | undefined
})
const openFixtureRange = (fixture: ScanApi.FixtureOption) => {
Object.assign(fixtureRange, {
fixtureId: fixture.id,
maxLengthMm: fixture.maxLengthMm,
maxWidthMm: fixture.maxWidthMm,
maxHeightMm: fixture.maxHeightMm,
maxWeightKg: fixture.maxWeightKg
})
fixtureRangeName.value = fixture.fixtureName
fixtureRangeVisible.value = true
}
const saveFixtureRange = () =>
action(async () => {
if (!fixtureRange.maxLengthMm || !fixtureRange.maxWidthMm || !fixtureRange.maxHeightMm)
throw new Error('请填写完整的夹具适用尺寸')
await ScanApi.updateFixtureRange({
...fixtureRange,
maxLengthMm: fixtureRange.maxLengthMm,
maxWidthMm: fixtureRange.maxWidthMm,
maxHeightMm: fixtureRange.maxHeightMm
})
form.fixtureConfirmed = false
markDirty()
fixtureRangeVisible.value = false
await recommendFixtures()
message.success('夹具适用范围已更新,请重新确认装夹')
})
const save = async () => {
if (locked.value || !detail.value) return
if (!form.testCaseId || !form.versionId) throw new Error('请选择有效测试用例和已发布版本')
if (caseChanged.value && !form.changeReason.trim()) throw new Error('更换测试用例必须填写原因')
const resourceError = assignmentEditor.value?.validate()
if (resourceError) throw new Error(resourceError)
const runParams = materializeParams(fields.value, form.runParams)
const planRequest = executionMode.value === 'plan' ? planSetup.value?.getValue() : {}
if(executionMode.value === 'plan' && !planRequest?.executionPlanId) throw new Error('请选择执行方案')
if(scannerSettings.value.available) {
validateScannerParameters(form.scannerParameters, true)
runParams[SCANNER_PARAMETER_RUN_KEY] = { ...form.scannerParameters }
}
2026-10-22 16:18:37 +08:00
await ScanApi.prepare({
...planRequest,
2026-10-22 16:18:37 +08:00
...schedule,
taskId: taskId.value,
expectedRevision: detail.value.config.revision,
testCaseId: form.testCaseId,
versionId: form.versionId,
changeReason: form.changeReason.trim(),
sampleReceived: form.sampleReceived,
fixtureId: form.fixtureId,
fixtureConfirmed: form.fixtureConfirmed,
lengthMm: form.lengthMm,
widthMm: form.widthMm,
heightMm: form.heightMm,
weightKg: form.weightKg,
requireFixture: form.requireFixture,
runParams,
runtimeAssignments: form.runtimeAssignments,
robotId:
form.runtimeAssignments.flatMap((item) => item.members).find((member) => member.robotId)
?.robotId ||
form.robotId ||
undefined
})
dirty.value = false
await refresh(true)
}
const action = async (work: () => Promise<void>) => {
if (busy.value) return
busy.value = true
try {
await work()
} catch (error: any) {
if (!['cancel', 'close'].includes(error))
message.error(error?.message || '操作失败,请刷新状态后重试')
} finally {
busy.value = false
}
}
const savePreparation = () =>
action(async () => {
await save()
message.success('准备配置已保存')
})
const runPrecheck = () =>
action(async () => {
if (dirty.value) await save()
precheckResult.value = await ScanApi.precheck(taskId.value)
message[precheckResult.value.passed ? 'success' : 'warning'](
precheckResult.value.passed ? '预检通过,可以开始逐件执行' : '预检存在阻断项,请按提示处理'
)
if (precheckResult.value.passed) activeTab.value = 'units'
})
const cancelTask = () =>
action(async () => {
const result = await ElMessageBox.prompt(
'取消会停止当前执行,并结束尚未执行的样件。请填写原因。',
'取消扫描任务',
{ inputValidator: (value) => !!value?.trim() || '请填写原因' }
)
await ScanApi.cancel(taskId.value, result.value)
await refresh(true)
})
const confirmStop = () =>
action(async () => {
const result = await ElMessageBox.prompt(
'将重新发送停止指令,收到设备确认后才能释放占用。请填写处理说明。',
'确认设备停止',
{ inputValidator: (value) => !!value?.trim() || '请填写说明' }
)
await ScanApi.confirmStop(taskId.value, result.value)
await refresh(true)
})
const pauseTask = () =>
action(async () => {
await ScanApi.pause(taskId.value)
await refresh(true)
message.success('已提交暂停')
})
const resumeTask = () =>
action(async () => {
await ScanApi.resume(taskId.value)
await refresh(true)
message.success('已提交恢复')
})
const startVisible = ref(false)
const startUnit = ref<ScanApi.ScanUnit>()
const startForm = reactive({
physicalSerial: '',
reason: '',
loadedConfirmed: false,
idempotencyKey: ''
})
const canStart = (unit: ScanApi.ScanUnit) =>
!terminal.value &&
!unit.attempts?.some(attempt => String(attempt.id) === String(unit.currentExecutionId) && attempt.executionType === 'SUPPLEMENT') &&
2026-10-22 16:18:37 +08:00
!detail.value?.config.stopPending &&
String(nextRunnableUnit(detail.value?.units || [])?.id) === String(unit.id)
const supplementChanged = async (id?: ScanApi.Id) => {
await refresh(true)
if (id != null) selectedAttemptId.value = String(id)
activeTab.value = 'units'
}
2026-10-22 16:18:37 +08:00
const releasePreparation = () =>
action(async () => {
const result = await ElMessageBox.prompt(
'确认所有设备已停止且样件已卸下。释放后可以修改准备配置。请填写说明。',
'释放准备占用',
{ inputValidator: (v) => !!v?.trim() || '请填写说明' }
)
await ScanApi.releaseResources(taskId.value, result.value.trim())
await refresh(true)
})
const extendSchedule = (end: string) =>
action(async () => {
if (dirty.value) throw new Error('请先保存准备配置,再延期')
await ScanApi.extendResources(taskId.value, end)
await refresh(true)
message.success('资源时段已延长')
})
const openStart = (unit: ScanApi.ScanUnit) =>
action(async () => {
if (!detail.value || dirty.value) throw new Error('请先保存准备配置并预检')
await ScanApi.acquireResources(taskId.value, detail.value.config.revision)
await refresh(true)
startUnit.value = unit
Object.assign(startForm, {
physicalSerial: unit.physicalSerial || '',
reason: '',
loadedConfirmed: false,
idempotencyKey: generateUUID()
2026-10-22 16:18:37 +08:00
})
startVisible.value = true
})
const submitStart = () =>
action(async () => {
if (!startUnit.value || !detail.value || !startForm.loadedConfirmed) return
if (dirty.value) throw new Error('准备配置尚未保存,请先保存并预检后再执行')
if (startUnit.value.attemptNo && !startForm.reason.trim()) throw new Error('重试必须填写原因')
await ScanApi.startUnit({
taskId: taskId.value,
unitId: startUnit.value.id,
expectedRevision: detail.value.config.revision,
loadedConfirmed: true,
idempotencyKey: startForm.idempotencyKey,
physicalSerial: startForm.physicalSerial.trim(),
reason: startForm.reason.trim()
})
startVisible.value = false
await refresh(true)
if (startUnit.value)
selectUnit(
detail.value.units.find((unit) => String(unit.id) === String(startUnit.value?.id)) ||
startUnit.value
)
activeTab.value = 'units'
message.success('本件已提交执行')
})
const beforeAttachment = (file: File) => {
if (!file.size) {
message.warning('文件不能为空')
2026-10-22 16:18:37 +08:00
return false
}
return true
}
const safeFileUrl = (value: string) => {
try {
const url = new URL(value, location.origin)
return ['http:', 'https:'].includes(url.protocol) ? url.href : undefined
} catch {
return undefined
}
}
const uploadAttachment = async (options: any) => {
uploading.value = true
try {
const body = new FormData()
body.append('file', options.file)
body.append('directory', `scan-task/${taskId.value}`)
const uploaded: any = await FileApi.updateFile(body)
const fileUrl = uploaded.data ?? uploaded
if (typeof fileUrl !== 'string') throw new Error('上传未返回有效文件地址')
await ScanApi.addAttachment({
taskId: taskId.value,
fileName: options.file.name,
fileUrl,
fileType: options.file.type || options.file.name.split('.').pop()
})
detail.value!.attachments = await ScanApi.getAttachments(taskId.value)
message.success('技术资料已关联任务')
} catch (error: any) {
message.error(error.message || '上传失败')
} finally {
uploading.value = false
}
}
const removeAttachment = async (attachment: ScanApi.ScanAttachment) => {
try {
await ElMessageBox.confirm(`删除本任务资料“${attachment.fileName}”?`, '删除资料')
await ScanApi.deleteAttachment(taskId.value, attachment.id)
detail.value!.attachments = await ScanApi.getAttachments(taskId.value)
} catch (error: any) {
if (!['cancel', 'close'].includes(error)) message.error(error.message || '删除失败')
}
}
const logVisible = ref(false)
const logSelection = ref<Partial<LabExecutionVO>>()
const logExecution = computed(
() =>
detail.value?.units
.flatMap((unit) => unit.attempts || [])
.find((attempt) => String(attempt.id) === String(logSelection.value?.id)) ||
logSelection.value
)
const openLogs = (execution: Partial<LabExecutionVO>) => {
logSelection.value = execution
logVisible.value = true
}
let timer: ReturnType<typeof setInterval> | undefined
let pollingSuspended = false
let catalogLoaded=false,catalogPending:Promise<void>|undefined
const loadCatalog=async()=>{
if(!detail.value||locked.value||catalogLoaded||catalogPending||!props.active||activeTab.value!=='prepare')return
const generation=pageGeneration
catalogLoading.value=true
const pending=(async()=>{
try{
const found:any[]=[];let pageNum=1
while(true){const result:any=await getTestCaseList({pageNum,pageSize:100});if(generation!==pageGeneration)return;const rows=result.rows||[];found.push(...rows);if(!rows.length||found.length>=(result.total??found.length))break;pageNum++}
if(generation!==pageGeneration)return
cases.value=found;catalogLoaded=true;await loadVersions()
}catch(error:any){if(generation===pageGeneration)message.warning(error.message||'用例目录加载失败,可刷新重试;已保存配置仍可查看')}
finally{if(generation===pageGeneration)catalogLoading.value=false}
})()
catalogPending=pending
try{await pending}finally{if(catalogPending===pending)catalogPending=undefined}
}
2026-10-22 16:18:37 +08:00
const initialize = async () => {
logVisible.value = false
logSelection.value = undefined
pageGeneration++
versionRequest++
catalogLoaded=false;catalogPending=undefined;catalogLoading.value=false
2026-10-22 16:18:37 +08:00
dirty.value = false
selectedUnitId.value = ''
selectedAttemptId.value = ''
loading.value = true
try {
// Frozen task history is readable even when the operator cannot browse the native catalog.
cases.value = []
await refresh(true,false)
2026-10-22 16:18:37 +08:00
activeTab.value = detail.value?.config.startedAt || terminal.value ? 'units' : 'prepare'
loading.value=false
if(!locked.value)void loadCatalog()
else await loadVersions()
2026-10-22 16:18:37 +08:00
} catch (error: any) {
message.warning(
error.message || '用例目录加载失败;已保存的任务记录仍可查看,请检查用例读取权限。'
)
} finally {
loading.value = false
}
}
onMounted(() => {
initialize().catch(() => {})
timer = setInterval(() => {
if (props.active && !pollingSuspended && !document.hidden && !busy.value && scanTaskPollInterval(detail.value)) {
2026-10-22 16:18:37 +08:00
refresh().catch(() => {})
}
}, 5000)
2026-10-22 16:18:37 +08:00
})
onActivated(() => { pollingSuspended = false })
onDeactivated(() => { pollingSuspended = true })
watch([()=>props.active,activeTab],()=>{if(props.active&&!pollingSuspended){void loadCatalog()}})
2026-10-22 16:18:37 +08:00
watch(() => route.params.id, initialize)
onBeforeRouteLeave(async () => {
if (dirty.value && !locked.value) {
try {
await ElMessageBox.confirm('准备配置尚未保存,是否离开?', '未保存的修改')
return true
} catch {
return false
}
}
return true
})
onUnmounted(() => {
pageGeneration++
versionRequest++
clearInterval(timer)
})
</script>
<style scoped>
.fixture-option { height: auto; min-height: 36px; line-height: 20px; padding-top: 6px; padding-bottom: 6px; }
.fixture-option-reason { font-size: 12px; line-height: 18px; white-space: normal; max-width: 620px; }
2026-10-22 16:18:37 +08:00
.task-title {
display: block;
max-width: 70vw;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
font-size: 16px;
font-weight: 600;
2026-10-22 16:18:37 +08:00
}
.scan-task-header, .scan-task-content { border-radius: 6px; }
.scan-task-embedded { border: 0; box-shadow: none; margin-bottom: 0; background: transparent; overflow: visible; }
.scan-task-embedded :deep(.el-card__body) { overflow: visible; }
.preparation-layout { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 24px; }
.preparation-column { min-width: 0; }
.scan-preparation :deep(.el-row) { margin-left: 0 !important; margin-right: 0 !important; }
@media (max-width: 991px) { .preparation-layout { grid-template-columns: minmax(0, 1fr); gap: 12px; } }
.scan-task-embedded .task-summary { width: 100%; margin: 0; }
.scan-task-embedded.scan-task-header :deep(.el-card__body) { justify-content: flex-end; }
.scan-task-embedded.scan-task-header :deep(.el-alert) { margin-bottom: 12px; }
.scan-task-embedded.scan-task-content :deep(h3) { font-size: 15px; font-weight: 600; margin: 12px 0 18px; }
.scan-task-header :deep(.el-card__body) { display: flex; flex-wrap: wrap; justify-content: space-between; align-items: center; gap: 8px 12px; }
.scan-task-header :deep(.el-page-header) { flex: 1; min-width: 240px; }
.scan-task-header :deep(.el-page-header__left) { flex-shrink: 0; white-space: nowrap; }
.scan-task-header :deep(.el-page-header__content) { min-width: 0; }
.scan-task-header :deep(.el-card__body > .el-alert), .scan-task-header :deep(.el-card__body > .el-steps) { flex-basis: 100%; }
.scan-task-header .task-title { max-width: min(420px, 65vw); }
.scan-task-header :deep(.el-alert) { font-size: 12px; }
.scan-task-content :deep(.el-tabs__header) { margin-bottom: 14px; }
.scan-task-content :deep(.el-tabs__item) { height: 44px; }
.summary-count { font-size: 12px; color: var(--el-text-color-secondary); }
2026-10-22 16:18:37 +08:00
.task-metadata {
display: grid;
grid-template-columns: minmax(0, 1fr);
gap: 14px;
2026-10-22 16:18:37 +08:00
}
.task-metadata > div {
min-width: 0;
display: flex;
flex-direction: column;
gap: 6px;
}
.task-metadata span {
font-size: 12px;
color: var(--el-text-color-secondary);
}
.task-metadata strong,
.task-metadata code {
overflow-wrap: anywhere;
2026-10-22 16:18:37 +08:00
font-size: 13px;
font-weight: 400;
}
.summary-spacer {
flex: 1;
}
.section-heading,
.selected-unit-heading {
display: flex;
justify-content: space-between;
align-items: center;
gap: 12px;
flex-wrap: wrap;
}
.section-heading h3,
.sample-queue h3,
.selected-unit-heading h3 {
margin: 0 0 8px;
font-size: 14px;
2026-10-22 16:18:37 +08:00
}
.section-heading > span {
font-size: 13px;
color: var(--el-text-color-secondary);
}
.batch-progress {
padding: 0 0 14px;
margin-bottom: 14px;
border-bottom: 1px solid var(--el-border-color-lighter);
2026-10-22 16:18:37 +08:00
}
.execution-layout {
display: grid;
grid-template-columns: 180px minmax(0, 1fr);
gap: 16px;
margin: 0 0 16px;
2026-10-22 16:18:37 +08:00
}
.execution-layout.single-unit { grid-template-columns: minmax(0, 1fr); }
2026-10-22 16:18:37 +08:00
.sample-queue {
min-width: 0;
2026-10-22 16:18:37 +08:00
max-height: 640px;
overflow: auto;
padding-right: 2px;
2026-10-22 16:18:37 +08:00
}
.sample-card {
display: block;
width: 100%;
text-align: left;
padding: 10px;
2026-10-22 16:18:37 +08:00
margin-bottom: 10px;
border: 1px solid var(--el-border-color-light);
border-radius: 5px;
2026-10-22 16:18:37 +08:00
background: var(--el-bg-color);
cursor: pointer;
color: var(--el-text-color-primary);
transition: border-color .15s, background-color .15s;
2026-10-22 16:18:37 +08:00
}
.sample-card:hover,
.sample-card.selected {
border-color: var(--el-color-primary);
background: var(--el-color-primary-light-9);
}
.sample-card.selected { box-shadow: inset 3px 0 0 var(--el-color-primary); }
2026-10-22 16:18:37 +08:00
.sample-card-heading {
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px;
}
.sample-card-code,
.sample-card-caption {
display: block;
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
font-size: 12px;
margin-top: 8px;
}
.sample-card-caption {
color: var(--el-text-color-secondary);
}
.selected-execution {
min-width: 0;
}
.selected-unit-heading {
padding-bottom: 12px;
margin-bottom: 12px;
2026-10-22 16:18:37 +08:00
border-bottom: 1px solid var(--el-border-color-lighter);
}
.selected-unit-heading > div {
min-width: 0;
}
.selected-unit-heading h3 {
overflow-wrap: anywhere;
}
.selected-unit-actions {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 10px;
min-width: 0;
max-width: 100%;
2026-10-22 16:18:37 +08:00
}
.selected-unit-actions > [role='status'] { flex-basis: 100%; line-height: 1.65; }
.selected-unit-actions :deep(.el-button + .el-button) { margin-left: 0; }
2026-10-22 16:18:37 +08:00
.attempt-select {
width: 300px;
max-width: 100%;
2026-10-22 16:18:37 +08:00
}
.execution-record-context { display: flex; align-items: center; flex-wrap: wrap; gap: 10px; margin: 0 0 12px; font-size: 12px; color: var(--el-text-color-secondary); }
2026-10-22 16:18:37 +08:00
.execution-history {
margin-top: 20px;
}
@media (max-width: 1000px) {
.task-metadata {
grid-template-columns: 1fr;
gap: 12px;
}
.execution-layout {
grid-template-columns: 1fr;
gap: 16px;
}
.sample-queue {
display: flex;
gap: 10px;
overflow-x: auto;
padding: 0 0 8px;
}
.sample-queue h3 {
display: none;
}
.sample-card {
min-width: 220px;
width: 220px;
margin-bottom: 0;
}
}
.task-summary {
display: flex;
flex-wrap: wrap;
gap: 12px;
align-items: center;
margin: 0;
}
@media (max-width: 780px) {
.task-metadata { grid-template-columns: minmax(0, 1fr); gap: 12px; }
.task-title { max-width: 65vw; font-size: 16px; }
2026-10-22 16:18:37 +08:00
}
.dimensions {
display: flex;
gap: 8px;
width: 100%;
}
.dimensions :deep(.el-input-number) {
width: 30%;
}
.hint {
color: var(--el-text-color-secondary);
font-size: 12px;
line-height: 1.6;
}
.actions {
display: flex;
align-items: center;
flex-wrap: wrap;
gap: 12px;
margin-top: 24px;
padding-top: 16px;
border-top: 1px solid var(--el-border-color-lighter);
}
.resource-snapshot {
padding: 12px;
margin-bottom: 12px;
background: var(--el-fill-color-light);
line-height: 1.8;
}
</style>