RunDetail.vue 29.5 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410
<!-- 补货单详情:清单(分组、出库、库存、在途、月均、可订、默认期望及来源、补货数)、采购单与截图(含兜底标记)、
  审计时间线(聊天原文 / 人和系统的每个动作 / 流程事件 / 取数端任务 / 每次 DMS 接口调用 / 清单快照,逐条可展开、可导出)、
  每轮取数的出库明细原样。定时补货只能在手机单据页确认清单、确认提交;单次补货在所属会话里回「确认提交」提交。
  后台操作:强制终止(取数一直失败、一直自动重试时停下来;建单 / 提交中不能强停)、单次补货作废 / 不提交(保留 DMS 草稿)、
  建单异常人工核实后关闭。都要填原因,写操作日志,并在企微会话里通知。
  审计时间线、取数端任务只给管理员看;普通账号(客户)只看清单和采购单。 -->
<script setup lang="ts">
import { ArrowLeft, Download, Refresh } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { computed, onMounted, onUnmounted, ref, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { api } from '@/api'
import AiTraceDrawer from '@/components/AiTraceDrawer.vue'
import PageHeader from '@/components/PageHeader.vue'
import Pager from '@/components/Pager.vue'
import StatCard from '@/components/StatCard.vue'
import Panel from '@/components/Panel.vue'
import StatusPill from '@/components/StatusPill.vue'
import { usePaged } from '@/composables/usePaged'
import { fmtMoney, fmtShort, fmtTime, GROUP, STAGE, TASK_STATUS, TASK_TYPE, TRIGGER, whLabel } from '@/format'
import { listPath } from '@/nav'
import { session } from '@/session'

const route = useRoute()
const router = useRouter()
const id = computed(() => Number(route.params.id))
const st = ref<any>(null)
const kinds = ref<string[]>(['chat'])   // 默认只看聊天,其余类型按需勾选
const snap = ref<any>(null)
const outboundOpen = ref(false)
const traceOf = ref<number | null>(null)
const isAdmin = computed(() => session.isAdmin)
let t: any = null

const KIND: Record<string, { text: string; type: string }> = {
  chat: { text: '聊天', type: 'primary' }, audit: { text: '操作', type: 'warning' }, event: { text: '流程', type: 'info' },
  task: { text: '取数端任务', type: 'success' }, api: { text: 'DMS 接口', type: '' }, snapshot: { text: '清单快照', type: 'danger' },
}

const tl = usePaged(() => `/api/restock/runs/${id.value}/timeline?kinds=${kinds.value.join(',')}`, { size: 50 })
const outbound = usePaged(() => `/api/restock/runs/${id.value}/outbound`, { size: 50 })
watch(kinds, () => { if (tl.page.value !== 1) tl.page.value = 1; else tl.load() })

async function load(silent = false) {
  try {
    st.value = await api.get('/api/restock/runs/' + id.value)
    if (isAdmin.value) await tl.load(silent)
  } catch (e: any) { if (!silent) ElMessage.error(e.message) }
}
onMounted(() => { load(); t = setInterval(() => load(true), 8000) })
onUnmounted(() => clearInterval(t))

const isScheduled = computed(() => st.value?.run.kind === 'scheduled')
const isPage = computed(() => ['scheduled', 'multi'].includes(st.value?.run.kind))   // 在单据页上确认 / 提交的
const submitted = computed(() => st.value?.po?.status === '已提交')

// 返回:从列表点进来的就退回去(保留原来的页码、筛选和滚动位置),直接打开的回到列表
function back() {
  const from = String((window.history.state as any)?.back || '')
  if (from.startsWith('/runs') && !from.startsWith('/runs/')) router.back()
  else router.push(listPath('/runs'))
}

async function cancel() {
  try { await ElMessageBox.confirm('今天的补货不订了吗?这张补货单会结束。', '今天不订') } catch { return }
  try { ElMessage.success((await api.post(`/api/restock/runs/${id.value}/cancel`)).message); load() } catch (e: any) { ElMessage.error(e.message) }
}
// 后台操作都要填原因:写进操作日志,也会发到企微会话里
async function askReason(title: string, text: string, placeholder: string): Promise<string | null> {
  try {
    const res: any = await ElMessageBox.prompt(text, title, {
      type: 'warning', confirmButtonText: title, inputPlaceholder: placeholder,
      inputValidator: (v: string) => !!(v || '').trim() || '请填写原因',
    })
    return String(res.value).trim()
  } catch { return null }
}
async function terminate() {
  const reason = await askReason('强制终止',
    `终止后这张${st.value.kind_cn}会结束为「已终止」:停止自动重试和正在进行的取数,不会再建单;会在企微会话里通知。要继续补货请重新发起。`,
    '例如:取数端长时间离线,今天改为人工下单')
  if (!reason) return
  try { ElMessage.success((await api.post(`/api/restock/runs/${id.value}/terminate`, { reason })).message); load() } catch (e: any) { ElMessage.error(e.message) }
}
async function voidRun() {
  const draft = st.value.run.status === 'awaiting_submit'
  const reason = await askReason(draft ? '不提交' : '作废',
    draft ? `DMS 里已建好采购单 ${st.value.run.order_no}(待提交)。不提交后这张单结束,DMS 草稿保留「待提交」,需要的话请到 DMS 删除或提交;会在企微会话里通知。`
      : '这张单次补货只报了价,DMS 里没有建单。作废后会话里回「订」不再生效,需要的话请重新发「零件号 数量」;会在企微会话里通知。',
    '例如:计划员说不要了')
  if (!reason) return
  try { ElMessage.success((await api.post(`/api/restock/runs/${id.value}/void`, { reason })).message); load() } catch (e: any) { ElMessage.error(e.message) }
}
async function closeUnknown() {
  let conclusion = ''
  try {
    const res: any = await ElMessageBox.prompt(
      `请先到 DMS「采购订单管理」按备注里的单号 ${st.value.run.doc_no} 核实这张单有没有建成,再填写核实结论。关闭后这个会话恢复可以补货。`,
      '人工核实后关闭', { inputPlaceholder: '例如:DMS 里没有这张单 / 已在 DMS 人工处理', inputValidator: (v: string) => !!(v || '').trim() || '请填写核实结论' })
    conclusion = res.value
  } catch { return }
  try { ElMessage.success((await api.post(`/api/restock/runs/${id.value}/unknown-close`, { conclusion })).message); load() } catch (e: any) { ElMessage.error(e.message) }
}
const shooting = ref(false)
async function retakeSubmitShots() {
  shooting.value = true
  try { ElMessage.success((await api.post(`/api/restock/runs/${id.value}/submit-shots`)).message); load() }
  catch (e: any) { ElMessage.error(e.message) } finally { shooting.value = false }
}
async function openSnap(sid: number) {
  try { snap.value = await api.get(`/api/restock/runs/${id.value}/snapshots/${sid}`) } catch (e: any) { ElMessage.error(e.message) }
}
function openOutbound() {
  outboundOpen.value = true
  outbound.page.value = 1
  outbound.load()
}
async function exportTl() {
  try { await api.download(`/api/restock/runs/${id.value}/timeline.csv`, `审计时间线_${st.value.run.doc_no}.csv`) }
  catch (e: any) { ElMessage.error(e.message) }
}
// 说明列:很多行 note 本身就是 label(如「在途够了」),两个都显示会重复;note 里已经带 label 的只显示 note
const lineNote = (r: any) => (r.label && !(r.note || '').includes(r.label) ? `${r.label} ${r.note || ''}`.trim() : r.note || '')

// 补货清单筛选:关键字(配件码 / 名称)+ 状态
const lineKw = ref('')
const lineView = ref('all')
const VIEWS = [{ v: 'all', t: '全部' }, { v: 'stock', t: '历史常备件' }, { v: 'other', t: '其他出库件' },
  { v: 'order', t: '要订' }, { v: 'skip', t: '不订' }, { v: 'modified', t: '用户改过' }]
// 行着色:用户改过(期望或勾选和默认不一样)浅橙底;没勾选的灰字
const rowClass = ({ row }: any) => [row.changed ? 'row-orange' : '', row.checked ? '' : 'row-grey'].join(' ')
const shownLines = computed(() => {
  const k = lineKw.value.trim().toUpperCase()
  return (st.value?.lines || []).filter((l: any) => {
    if (k && !String(l.part_no || '').toUpperCase().includes(k) && !String(l.name || '').toUpperCase().includes(k)) return false
    if (lineView.value === 'stock' || lineView.value === 'other') return l.grp === lineView.value
    if (lineView.value === 'order') return l.final_qty > 0
    if (lineView.value === 'skip') return !(l.final_qty > 0)
    if (lineView.value === 'modified') return !!l.changed
    return true
  })
})
const filtering = computed(() => !!lineKw.value.trim() || lineView.value !== 'all')
// 按分组分段显示(和手机单据页一致):每段一个小标题,不再每行重复「历史常备件」标签
const GROUP_ORDER = ['stock', 'single', 'multi', 'other']
const shownGroups = computed(() => GROUP_ORDER.map((g) => {
  const rows = shownLines.value.filter((l: any) => l.grp === g)
  return { grp: g, label: GROUP[g] || g, rows, order: rows.filter((l: any) => l.final_qty > 0).length }
}).filter((g) => g.rows.length))
const multiGroup = computed(() => new Set((st.value?.lines || []).map((l: any) => l.grp)).size > 1)

// 用户在单据页改过的零件(期望改了 / 勾选和默认不一样):页面顶部提示
const changedLines = computed(() => (st.value?.lines || []).filter((l: any) => l.changed))
const changeWho = computed(() => {
  const r = st.value?.run || {}
  return r.confirmed_by ? `${r.confirmed_by} ${fmtShort(r.confirmed_at)} 确认时` : '用户在单据页刷新时带上了修改(还没确认),'
})
const CHANGES_SHOWN = 3
const changeBrief = computed(() => changedLines.value.slice(0, CHANGES_SHOWN).map((l: any) => `${l.name || l.part_no} ${l.change_text}`).join(';')
  + (changedLines.value.length > CHANGES_SHOWN ? ` 等 ${changedLines.value.length} 处` : ''))
function onlyChanged() { lineKw.value = ''; lineView.value = 'modified' }
// 说明列的短标签:不订的原因(勾选状态已在勾选列,不重复)
const reasonTag = (r: any) => (r.label && r.tag !== 'unchecked' ? r.label : '')
const reasonText = (r: any) => { const n = r.note || ''; return reasonTag(r) && n.includes(r.label) ? n.replace(r.label, '').replace(/^[::,,\s]+/, '') : n }

const pretty = (v: any) => (v === null || v === undefined || v === '' ? '' : typeof v === 'string' ? v : JSON.stringify(v, null, 2))
</script>

<template>
  <div v-if="st" class="page">
    <PageHeader :title="`${st.kind_cn} ${st.run.doc_no}`">
      <template #badge><StatusPill :tone="STAGE[st.run.status]?.tone || 'info'">{{ STAGE[st.run.status]?.text || st.run.status }}</StatusPill></template>
      <template #back><el-button class="back" size="small" :icon="ArrowLeft" @click="back">返回列表</el-button></template>
      <template #meta>
        {{ TRIGGER[st.run.trigger] || st.run.trigger }} · {{ st.run.triggered_by }} · {{ fmtTime(st.run.created_at) }}
        <template v-if="isScheduled"> · 出库 {{ st.window }} · 第 {{ st.run.fetch_seq || 0 }} 轮取数 · {{ st.cutoff }} 截单</template>
        <template v-else> · 「{{ st.run.trigger_text }}」</template>
      </template>
      <template v-if="st.can_cancel || st.can_close_unknown || st.can_terminate || st.can_void" #actions>
        <el-button v-if="st.can_cancel" @click="cancel">今天不订</el-button>
        <el-button v-if="st.can_void" @click="voidRun">{{ st.run.status === 'awaiting_submit' ? '不提交(保留 DMS 草稿)' : '作废' }}</el-button>
        <el-button v-if="st.can_terminate && (isScheduled || st.run.status === 'scanning')" type="danger" plain @click="terminate">强制终止</el-button>
        <el-button v-if="st.can_close_unknown" type="warning" @click="closeUnknown">人工核实后关闭</el-button>
      </template>
    </PageHeader>

    <div class="stack">
      <div v-if="st.run.status === 'awaiting_confirm' && isPage" class="notice warn">
        待确认:请在<a :href="st.links.order" target="_blank">手机单据页</a>确认
      </div>
      <div v-if="st.run.status === 'awaiting_submit'" class="notice warn">
        已建单 {{ st.run.order_no }},待确认提交(不过期,提交前会先查 DMS 状态):
        <template v-if="isPage">请在<a :href="st.links.order" target="_blank">手机单据页</a>点「确认提交」</template>
        <template v-else>等会话里 @我 回「确认提交」</template>
      </div>
      <div v-if="st.today_orders?.length && st.run.status === 'awaiting_confirm'" class="notice warn">
        今天已建采购单 {{ st.today_orders.map((o: any) => `${o.order_no}(${o.trigger_cn},${o.stage_cn || ''})`).join('、') }},确认前留意别重复订
      </div>
      <div v-if="st.run.status === 'create_unknown'" class="notice err">
        建单异常:DMS 里可能已经建成,系统正在自动核实,期间这个会话暂停补货操作。{{ st.run.message }}
      </div>
      <div v-if="st.run.message && ['error', 'scan_retry', 'expired', 'awaiting_confirm', 'terminated'].includes(st.run.status)" class="notice err">{{ st.run.message }}</div>
      <div v-if="st.run.status === 'awaiting_submit' && st.po?.submit_error" class="notice err">上次提交失败:{{ st.po.submit_error }}</div>
      <div v-if="isPage && changedLines.length" class="notice warn">
        <span>✏️ {{ changeWho }}改了 <b>{{ changedLines.length }}</b> 处:{{ changeBrief }}
          <el-button link type="primary" size="small" @click="onlyChanged">只看改过的</el-button></span>
      </div>

      <div class="grid grid-4">
        <StatCard label="要订" :value="`${st.summary.order_count} 项 / ${st.summary.order_qty} 件`"
                  :hint="isScheduled ? `常备件 ${st.summary.stock_count} · 其他 ${st.summary.other_count} · 改过 ${st.summary.changed_count ?? st.summary.modified_count}` : ''" />
        <StatCard label="金额" :value="fmtMoney(st.summary.amount)" />
        <StatCard label="确认人" :value="st.run.confirmed_by || '—'"
                  :hint="(st.run.confirmed_at ? fmtShort(st.run.confirmed_at) : '') + (st.run.submitted_by ? ` · 提交确认 ${st.run.submitted_by}(${st.submitted_via_cn})` : '')" />
        <StatCard label="采购单号" :value="st.run.order_no || '—'" :tone="submitted ? 'ok' : st.run.order_no ? 'warn' : undefined"
                  :hint="st.run.order_no ? (st.po?.status || '待提交') : ''" />
      </div>

      <Panel flush title="补货清单" :desc="`在途口径:${st.in_transit_label}。\n期望默认:有上次人工修改用上次,否则推荐 = 库存 + 出库。\n补货 = 期望 −(库存 + 在途),按起订量 / 包装数向上取整,受当日可订上限约束。`">
        <template #extra>
          <el-input v-model="lineKw" size="small" clearable placeholder="筛选配件码 / 名称" class="w-filter" />
          <el-select v-model="lineView" size="small" class="w-view">
            <el-option v-for="o in VIEWS" :key="o.v" :value="o.v" :label="o.t" />
          </el-select>
          <el-button v-if="isScheduled" size="small" @click="openOutbound">出库明细原样</el-button>
          <a :href="st.links.order" target="_blank" class="small">手机单据页</a>
        </template>
        <template v-for="g in (shownGroups.length ? shownGroups : [{ grp: '', label: '', rows: [], order: 0 }])" :key="g.grp">
        <div v-if="multiGroup && g.grp" class="grp-title">{{ g.label }}<span>{{ g.rows.length }} 项 · 要订 {{ g.order }}</span></div>
        <el-table :data="g.rows" :row-class-name="rowClass">
          <el-table-column prop="seq" label="#" width="48" align="center" />
          <el-table-column label="配件码" width="130"><template #default="{ row }"><span class="mono">{{ row.part_no }}</span></template></el-table-column>
          <el-table-column prop="name" label="名称" min-width="130" />
          <el-table-column label="分类 / SO" width="120">
            <template #default="{ row }">{{ row.category || '—' }}<div v-if="row.so_hit" class="small muted">SO {{ row.so_hit.order_count }} 次</div></template>
          </el-table-column>
          <el-table-column prop="outbound_qty" label="出库" width="60" align="right" />
          <el-table-column prop="stock" label="库存" width="60" align="right" />
          <el-table-column prop="in_transit" label="在途" width="60" align="right" />
          <el-table-column label="月均" width="64" align="right"><template #default="{ row }">{{ row.mad ?? '—' }}</template></el-table-column>
          <el-table-column label="可订" width="64" align="right"><template #default="{ row }">{{ row.cap ?? '不限' }}</template></el-table-column>
          <el-table-column label="期望" width="120">
            <template #default="{ row }">
              <div class="exp"><b>{{ row.expected }}</b><el-tag size="small" :type="row.modified ? 'warning' : row.default_source === 'last' ? 'primary' : 'success'">{{ row.source_label }}</el-tag></div>
              <div v-if="row.modified" class="small muted exp-def">默认 {{ row.default_expected }}</div>
            </template>
          </el-table-column>
          <el-table-column label="勾选" width="92" align="center">
            <template #default="{ row }">
              <el-tag v-if="row.check_changed" size="small" type="warning">{{ row.checked ? '手动勾选' : '取消勾选' }}</el-tag>
              <template v-else>{{ row.checked ? '✓' : '' }}</template>
            </template>
          </el-table-column>
          <el-table-column label="补货" width="64" align="right">
            <template #default="{ row }"><b v-if="row.final_qty > 0">{{ row.final_qty }}</b><span v-else class="muted">—</span></template>
          </el-table-column>
          <el-table-column label="关注仓" min-width="140">
            <template #default="{ row }"><span v-for="(q, w) in row.wh" :key="w" class="wh">{{ whLabel(String(w)) }} {{ q }}</span></template>
          </el-table-column>
          <el-table-column label="说明" min-width="170" show-overflow-tooltip>
            <template #default="{ row }">
              <el-tag v-if="reasonTag(row)" size="small" :type="row.orderable ? 'info' : 'warning'" class="reason">{{ reasonTag(row) }}</el-tag>{{ reasonText(row) }}
              <span class="err">{{ row.error }}</span>
            </template>
          </el-table-column>
          <template #empty>{{ filtering ? '没有符合筛选条件的配件' : '暂无数据' }}</template>
        </el-table>
        </template>
        <div v-if="filtering" class="muted small filter-hint">筛选后 {{ shownLines.length }} / {{ st.lines.length }} 项</div>
      </Panel>

      <Panel v-if="st.po" :title="`采购单 ${st.po.order_no}`"
             :desc="submitted ? `已在 DMS 提交:DMS 提交人 ${st.po.apply_operator || '—'},提交时间 ${st.po.apply_time || '—'};确认人 ${st.po.submitted_by || '—'}(${st.submitted_via_cn || '—'})。`
               : '先在 DMS 建「待提交」草稿并截图(详情分页时逐页截全);定时 / 批量补货在单据页确认提交,单次补货在所属会话里回「确认提交」提交。'">
        <template #extra>
          <span class="muted small">订单类型 SO · {{ st.po.item_num }} 项 · {{ fmtMoney(st.po.total_amount) }} · 建单 {{ fmtTime(st.po.created_at) }}</span>
          <StatusPill :tone="submitted ? 'ok' : 'warn'">{{ st.po.status || '待提交' }}</StatusPill>
        </template>
        <div v-if="st.po.mismatch?.length" class="notice err mb-3">回查到的明细与订购内容不一致:{{ st.po.mismatch.join(';') }}</div>
        <div v-if="st.shots_fallback" class="notice err mb-3">
          DMS 页面截图失败({{ st.po.fallback_reason }})。{{ st.shots_fallback === 'image' ? '下面是用 DMS 接口实际返回的数据渲染的兜底截图,不是 DMS 原页面。' : '没能生成兜底图片,已在群里发了文字明细。' }}
        </div>
        <div class="shots">
          <el-image v-for="s in st.shots" :key="s.id" :src="s.url" :preview-src-list="st.shots.map((x: any) => x.url)" fit="contain" class="shot" />
          <span v-if="!st.shots.length" class="muted">没有截图</span>
        </div>
      </Panel>

      <Panel v-if="submitted && st.submit_shots" title="提交后截图(审计留档)"
             desc="DMS 提交成功后系统再截一次:采购订单管理列表(已提交状态、提交人和时间)+ 采购单详情全部页。只在后台留档,不发群里,单据页也不显示。">
        <template #extra>
          <span v-if="st.submit_shots.at" class="muted small">{{ st.submit_shots.error && !st.submit_shots.shots.length ? '最后一次失败' : '截图时间' }} {{ fmtTime(st.submit_shots.at) }}</span>
          <el-button v-if="isAdmin" size="small" :loading="shooting || st.submit_shots.running" :disabled="!st.submit_shots.can_retry"
                     @click="retakeSubmitShots">重新截图</el-button>
        </template>
        <div v-if="st.submit_shots.error" class="notice err mb-3">提交后截图失败:{{ st.submit_shots.error }}</div>
        <div v-if="st.submit_shots.fallback === 'image'" class="notice err mb-3">DMS 页面截图失败,下面是用 DMS 接口实际返回的数据渲染的兜底截图,不是 DMS 原页面。</div>
        <div class="shots">
          <el-image v-for="s in st.submit_shots.shots" :key="s.id" :src="s.url" :preview-src-list="st.submit_shots.shots.map((x: any) => x.url)" fit="contain" class="shot" />
          <span v-if="!st.submit_shots.shots.length" class="muted">{{ st.submit_shots.running ? '正在截图…' : '还没有提交后截图' }}</span>
        </div>
      </Panel>

      <Panel v-if="isAdmin" flush title="审计时间线" desc="这张单从触发到结束的全部留痕:聊天原文、谁做了什么(含页面上每一处修改、IP)、流程、取数端任务、每次 DMS 接口调用(traceId、完整响应可下载)、推给用户 / 用户提交的清单快照。">
        <template #extra>
          <el-checkbox-group v-model="kinds" size="small">
            <el-checkbox-button v-for="(v, k) in KIND" :key="k" :value="k">{{ v.text }}<span v-if="tl.data.value?.counts?.[k]" class="kind-n">{{ tl.data.value.counts[k] }}</span></el-checkbox-button>
          </el-checkbox-group>
          <el-button size="small" :icon="Refresh" :loading="tl.loading.value" @click="tl.load()">刷新</el-button>
          <el-button size="small" :icon="Download" @click="exportTl">导出</el-button>
        </template>
        <el-table :data="tl.rows.value" size="small">
          <el-table-column type="expand">
            <template #default="{ row }">
              <div class="tl-detail">
                <div v-if="row.kind === 'snapshot'"><el-button size="small" @click="openSnap(row.detail.snapshot_id)">查看这版清单</el-button></div>
                <div v-if="row.detail?.log_id"><el-button size="small" @click="traceOf = row.detail.log_id">查看助手处理过程</el-button></div>
                <div v-if="row.kind === 'api' && row.detail.evidence_url"><a :href="row.detail.evidence_url" target="_blank">下载本任务完整接口流水(请求体 + 响应正文)</a></div>
                <div v-if="row.kind === 'task' && row.detail.evidence?.length" class="ev">
                  证据文件:<a v-for="f in row.detail.evidence" :key="f.id" :href="f.url" target="_blank">{{ f.name }}</a>
                </div>
                <pre>{{ pretty(row.detail) }}</pre>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="时间" width="150"><template #default="{ row }"><span class="num">{{ row.ts.slice(5) }}</span></template></el-table-column>
          <el-table-column label="类型" width="100"><template #default="{ row }"><el-tag size="small" :type="(KIND[row.kind].type as any)">{{ KIND[row.kind].text }}</el-tag></template></el-table-column>
          <el-table-column label="标题" min-width="200"><template #default="{ row }"><span :class="{ err: row.level === 'error' }">{{ row.title }}</span></template></el-table-column>
          <el-table-column label="内容" min-width="360"><template #default="{ row }"><span class="pre">{{ row.text }}</span></template></el-table-column>
        </el-table>
        <Pager v-model:page="tl.page.value" v-model:size="tl.size.value" :total="tl.total.value" :sizes="[20, 50, 100, 200]" />
        <AiTraceDrawer :log-id="traceOf" @close="traceOf = null" />
      </Panel>

      <Panel v-if="isAdmin" title="取数端任务">
        <el-table :data="st.tasks || []" size="small">
          <el-table-column label="任务" min-width="140"><template #default="{ row }">{{ TASK_TYPE[row.type] || row.type }}</template></el-table-column>
          <el-table-column label="状态" width="100"><template #default="{ row }"><StatusPill :tone="TASK_STATUS[row.status]?.tone">{{ TASK_STATUS[row.status]?.text || row.status }}</StatusPill></template></el-table-column>
          <el-table-column label="下发" width="110"><template #default="{ row }">{{ fmtShort(row.created_at) }}</template></el-table-column>
          <el-table-column label="完成" width="110"><template #default="{ row }">{{ fmtShort(row.finished_at) }}</template></el-table-column>
          <el-table-column label="说明" min-width="160"><template #default="{ row }"><span class="small">{{ row.error || '—' }}</span></template></el-table-column>
        </el-table>
      </Panel>
    </div>

    <el-dialog v-if="snap" :model-value="!!snap" :title="`清单快照 · ${snap.kind} · ${fmtTime(snap.created_at)}${snap.actor ? ' · ' + snap.actor : ''}`" width="92%" @close="snap = null">
      <div class="small muted mb-3">第 {{ snap.fetch_seq }} 轮取数;{{ snap.data.summary.order_count }} 项 · {{ snap.data.summary.order_qty }} 件 · {{ fmtMoney(snap.data.summary.amount) }}{{ snap.ip ? ' · IP ' + snap.ip : '' }}</div>
      <el-table :data="snap.data.lines" size="small" max-height="520">
        <el-table-column label="分组" width="90"><template #default="{ row }">{{ GROUP[row.grp] }}</template></el-table-column>
        <el-table-column prop="part_no" label="配件码" width="130" />
        <el-table-column prop="name" label="名称" min-width="130" />
        <el-table-column prop="outbound_qty" label="出库" width="60" />
        <el-table-column prop="stock" label="库存" width="60" />
        <el-table-column prop="in_transit" label="在途" width="60" />
        <el-table-column prop="cap" label="可订" width="60" />
        <el-table-column label="默认期望" width="100"><template #default="{ row }">{{ row.default_expected }}({{ row.default_source === 'last' ? '上次' : '推荐' }})</template></el-table-column>
        <el-table-column prop="expected" label="期望" width="60" />
        <el-table-column label="勾选" width="56"><template #default="{ row }">{{ row.checked ? '✓' : '' }}</template></el-table-column>
        <el-table-column prop="final_qty" label="补货" width="60" />
        <el-table-column label="说明" min-width="140"><template #default="{ row }">{{ lineNote(row) }}</template></el-table-column>
      </el-table>
      <template v-if="snap.data.changes?.length">
        <h4>用户改动</h4>
        <pre>{{ pretty(snap.data.changes) }}</pre>
      </template>
    </el-dialog>

    <el-dialog v-model="outboundOpen" :title="`出库明细(第 ${outbound.data.value?.fetch_seq ?? '-'} 轮取数,含非纯)`" width="92%">
      <el-table v-loading="outbound.loading.value" :data="outbound.rows.value" size="small" max-height="520">
        <el-table-column prop="shipment_date" label="出库日" width="150" />
        <el-table-column prop="work_order_no" label="工单号" width="130" />
        <el-table-column prop="shipment_batch_no" label="出库单号" width="160" />
        <el-table-column prop="license_plate" label="车牌" width="100" />
        <el-table-column prop="mfr" label="厂家分类" width="80" />
        <el-table-column prop="part_no" label="零件号" width="130" />
        <el-table-column prop="part_name" label="名称" min-width="130" />
        <el-table-column prop="qty" label="数量" width="60" />
        <el-table-column prop="amount" label="销售金额" width="90" />
        <el-table-column prop="settl_status" label="结算" width="60" />
      </el-table>
      <Pager v-model:page="outbound.page.value" v-model:size="outbound.size.value" :total="outbound.total.value" />
    </el-dialog>
  </div>
  <div v-else class="page"><el-skeleton :rows="10" animated /></div>
</template>

<style scoped>
.back { margin-bottom: 10px; }
.kind-n { margin-left: 4px; opacity: 0.7; font-variant-numeric: tabular-nums; }
.wh { margin-right: 8px; }
.ev a { margin-right: 12px; }
.shots { display: flex; gap: 12px; flex-wrap: wrap; }
.shot { width: 360px; max-width: 100%; height: 220px; border: 1px solid var(--c-border); border-radius: var(--radius-sm); background: var(--c-surface-2); }
.tl-detail { padding: 6px 16px; }
.tl-detail pre, pre { white-space: pre-wrap; word-break: break-all; font-size: 12px; background: var(--c-surface-2); padding: 8px; border-radius: 6px; max-height: 360px; overflow: auto; }
.pre { white-space: pre-wrap; }
.mb-3 { margin-bottom: 12px; }
.w-filter { width: 180px; }
.w-view { width: 130px; }
/* 期望列:数字固定宽度右对齐,来源标签才能上下对齐 */
.exp { display: flex; align-items: center; gap: 6px; }
.exp b { display: inline-block; min-width: 32px; text-align: right; font-variant-numeric: tabular-nums; }
.exp-def { padding-left: 38px; }
.filter-hint { padding: 8px 16px; }
/* 补货清单按分组分段:每段一个小标题 */
.grp-title { padding: 12px 16px 8px; border-top: 1px solid var(--c-border); color: var(--c-text); font-size: 13.5px; font-weight: 600; }
.grp-title:first-child { border-top: 0; }
.grp-title span { margin-left: 8px; color: var(--c-text-3); font-size: 12px; font-weight: 400; }
.reason { margin-right: 6px; }
</style>