OrderPage.vue 26.6 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 411 412 413 414 415 416 417 418 419
<!-- 手机单据页(计划员在企微里点链接打开,免登录,靠补货单令牌)。
  定时补货:一个页面走完全流程 —— 待填(历史常备件默认勾选、其他出库件折叠)→ 按钮上挂倒计时 → 确认生成补货单 → 建单中 →
  截图 → 核对截图后点「确认提交」(不过期,提交前先查 DMS 状态;也可以「先不提交」,DMS 草稿保留)→ 提交中 → 已提交;
  倒计时归零按钮变「刷新并重新计算补货数量」(整条链路重新取数,人填的勾选 / 期望保留)。整体填完点一次确认,不逐行保存。
  页面上的每个操作(打开、展开、搜索、勾选、改期望、倒计时归零、确认提交)都上报审计。
  单次补货只看结果和截图(提交在会话里 @机器人 回「确认提交」)。 -->
<script setup lang="ts">
import 'vant/lib/index.css'
import { Button as VanButton, Checkbox as VanCheckbox, Empty as VanEmpty, ImagePreview as VanImagePreview,
  Loading as VanLoading, Search as VanSearch, showConfirmDialog, showFailToast, showSuccessToast,
  Stepper as VanStepper } from 'vant'
import { computed, onMounted, onUnmounted, ref } from 'vue'
import { useRoute } from 'vue-router'
import { publicApi } from '@/api'
import { STAGE } from '@/format'
import './mobile.css'

type Edit = { checked: boolean; expected: number; modified: boolean }
const route = useRoute()
const token = String(route.params.token)
const base = `/api/public/restock/orders/${token}`
const st = ref<any>(null)
const err = ref('')
const edits = ref<Record<string, Edit>>({})
const seq = ref(0)                      // 当前编辑基于第几轮取数(刷新后重置为服务端的值)
const left = ref(0)
const busy = ref(false)
const showOthers = ref(false)
const kw = ref('')
const preview = ref({ show: false, start: 0 })
let deadline = 0
let poll: any = null
let tick: any = null
let expiredSent = false

const BUSY = ['scanning', 'scan_retry', 'refreshing', 'creating', 'screenshotting', 'submitting']

function event(kind: string, detail: Record<string, unknown> = {}) {
  publicApi.post(base + '/events', { kind, detail }).catch(() => {})
}

async function load() {
  try {
    const s = await publicApi.get(base)
    if (s.run.fetch_seq !== seq.value) {                 // 首次 / 刷新后:以服务端的勾选和期望为准
      edits.value = Object.fromEntries(s.lines.map((l: any) => [l.part_no,
        { checked: !!l.checked, expected: l.expected, modified: !!l.modified }]))
      seq.value = s.run.fetch_seq
    }
    if (s.run.status === 'awaiting_confirm') {
      deadline = Date.now() + s.seconds_left * 1000
      if (s.seconds_left > 0) expiredSent = false
    } else deadline = 0
    left.value = Math.max(0, Math.round((deadline - Date.now()) / 1000))
    st.value = s
  } catch (e: any) { err.value = e.message }
  schedule()
}
function schedule() {
  clearTimeout(poll)
  const status = st.value?.run.status
  poll = setTimeout(load, status && BUSY.includes(status) ? 2500 : 15000)
}
onMounted(async () => {
  await load()
  event('open', { status: st.value?.run.status, fetch_seq: seq.value })
  tick = setInterval(() => {
    if (!deadline) return
    left.value = Math.max(0, Math.round((deadline - Date.now()) / 1000))
    if (left.value === 0 && !expiredSent && st.value?.run.status === 'awaiting_confirm') {
      expiredSent = true
      event('expired', { fetch_seq: seq.value })
    }
  }, 500)
})
onUnmounted(() => { clearTimeout(poll); clearInterval(tick) })

const isScheduled = computed(() => st.value?.run.kind === 'scheduled')
const status = computed(() => st.value?.run.status || '')
const editing = computed(() => isScheduled.value && status.value === 'awaiting_confirm')
const submitted = computed(() => st.value?.po?.status === '已提交')
const lines = computed<any[]>(() => st.value?.lines || [])
const stockLines = computed(() => lines.value.filter((l) => l.grp !== 'other'))
const otherLines = computed(() => {
  const k = kw.value.trim().toUpperCase()
  return lines.value.filter((l) => l.grp === 'other' && (!k || l.part_no.includes(k) || (l.name || '').includes(kw.value.trim())))
})
const otherCount = computed(() => lines.value.filter((l) => l.grp === 'other').length)
/** DMS 里还没提交的采购单(含他人创建、本系统建单结果未知的):只提示,不参与计算 */
const drafts = computed<{ items: any[], error?: string, truncated?: boolean }>(() => {
  const d = st.value?.drafts
  return { items: d?.items || [], error: d?.error || '', truncated: !!d?.truncated }
})
const draftText = (l: any) => (l.in_drafts || []).map((d: any) =>
  `${d.order_no || d.doc_no || '草稿'}${d.create_by ? '(' + d.create_by + ')' : ''} ${d.qty ?? '?'} 个${d.unknown ? '(建单结果未知)' : ''}`).join(';')

/** 起订量 / 包装数取整(DMS 只收 ≥ 起订量、包装数整数倍的数量),与云端 planner.pack_up / pack_down 同口径。 */
const packOf = (l: any) => Math.max(Number(l.pack_qty) || 1, 1)
const minOf = (l: any) => Math.max(Number(l.min_qty) || 1, 1)
const packUp = (l: any, want: number) => want <= 0 ? 0 : Math.ceil(Math.max(want, minOf(l)) / packOf(l)) * packOf(l)
function packDown(l: any, cap: number) {
  const q = Math.floor(Math.max(cap, 0) / packOf(l)) * packOf(l)
  return q >= minOf(l) ? q : 0
}
const packText = (l: any) => minOf(l) > 1 && minOf(l) !== packOf(l) ? `起订 ${minOf(l)}、包装 ${packOf(l)}`
  : packOf(l) > 1 ? `包装 ${packOf(l)}` : `起订 ${minOf(l)}`
/** DMS 当日可订为 0 的原因:可订是 DMS 按门店控的量,不是仓库库存,全国仓有货也订不了。 */
function zeroCapNote(l: any) {
  const have = l.stock + l.in_transit
  if (l.storage_limit != null && have >= l.storage_limit)
    return `DMS 当日可订为 0:库存${l.in_transit ? '+在途' : ''} ${have} 已超过 DMS 库存上限 ${l.storage_limit},今天订不了`
  if (l.purchased_today) return `DMS 当日可订为 0:今天已经订过 ${l.purchased_today} 个,可订量用完了`
  return 'DMS 当日可订为 0,今天订不了'
}

/** 页面上实时算补货数(与云端 planner 同口径;最终以确认时服务端重算为准)。 */
function calc(l: any) {
  const e = edits.value[l.part_no]
  if (!editing.value || !e) return { qty: l.final_qty, capped: l.tag === 'capped', note: l.note, tag: l.tag }
  if (l.error) return { qty: 0, capped: false, note: '没查到', tag: 'error' }
  if (!e.checked) return { qty: 0, capped: false, note: '', tag: 'unchecked' }
  const want = Math.max(Math.ceil((e.expected || 0) - (l.stock + l.in_transit)), 0)
  if (want <= 0) return { qty: 0, capped: false, note: '库存够用', tag: 'enough' }
  if (Object.keys(l.wh || {}).length && l.wh_total <= 0) return { qty: 0, capped: false, note: '厂家缺货', tag: 'oos' }
  const qty = packUp(l, want)
  if (l.cap != null && qty > l.cap) {
    const top = packDown(l, l.cap)
    const note = l.cap <= 0 ? zeroCapNote(l)
      : top <= 0 ? `DMS 今天最多还能订 ${l.cap} 个,不够${packText(l)} 的量,今天订不了`
      : `DMS 今天最多还能订 ${l.cap} 个,按 ${top} 订${want > top ? `,差的 ${want - top} 个明天再补` : ''}`
    return { qty: top, capped: true, note, tag: 'capped' }
  }
  return { qty, capped: false, note: qty !== want ? `差 ${want} 个,按${packText(l)} 取整订 ${qty}` : '', tag: 'normal' }
}
const picked = computed(() => lines.value.map((l) => ({ l, c: calc(l) })).filter((x) => x.c.qty > 0))
const totalQty = computed(() => picked.value.reduce((a, x) => a + x.c.qty, 0))
const amount = computed(() => picked.value.reduce((a, x) => a + x.c.qty * (x.l.unit_price || 0), 0))
const sourceLabel = (l: any) => edits.value[l.part_no]?.modified ? '已修改' : (l.default_source === 'last' ? '上次' : '推荐')
const sourceTitle = (l: any) => l.default_source === 'last'
  ? `上次人工修改的值(${l.last_at || ''} ${l.last_by || ''})` : `推荐 = 库存 ${l.stock} + 出库 ${l.outbound_qty}`

function setExpected(l: any, v: number | string) {
  const e = edits.value[l.part_no]
  const before = e.expected
  const after = Math.max(0, Math.round(Number(v) || 0))
  if (after === before) return
  e.expected = after
  e.modified = after !== l.default_expected
  event('edit', { part_no: l.part_no, name: l.name, field: 'expected', before, after, default: l.default_expected,
    source: l.default_source })
}
function toggle(l: any, v: boolean) {
  edits.value[l.part_no].checked = v
  event('toggle', { part_no: l.part_no, name: l.name, grp: l.grp, checked: v })
}
/** 全选 / 全不选(只作用于传入的这一组;不常用配件按当前搜索结果过滤后的可见项)。 */
const checkedCount = (ls: any[]) => ls.filter((l) => edits.value[l.part_no]?.checked).length
const allChecked = (ls: any[]) => ls.length > 0 && checkedCount(ls) === ls.length
const someChecked = (ls: any[]) => checkedCount(ls) > 0 && !allChecked(ls)
function toggleAll(ls: any[], v: boolean, grp: string) {
  for (const l of ls) if (edits.value[l.part_no]) edits.value[l.part_no].checked = v
  event('toggle_all', { grp, checked: v, count: ls.length, keyword: grp === 'other' ? kw.value.trim() : undefined })
}
function reset(l: any) {
  const e = edits.value[l.part_no]
  event('reset', { part_no: l.part_no, before: e.expected, after: l.default_expected })
  e.expected = l.default_expected
  e.modified = false
}
function expand() {
  showOthers.value = !showOthers.value
  if (showOthers.value) event('expand', { count: otherCount.value })
}
let searchTimer: any = null
function onSearch() {
  clearTimeout(searchTimer)
  searchTimer = setTimeout(() => kw.value && event('search', { keyword: kw.value }), 800)
}
const payload = () => ({ lines: Object.entries(edits.value).map(([part_no, e]) => ({ part_no, ...e })) })

async function refresh() {
  busy.value = true
  try { await publicApi.post(base + '/refresh', payload()); showSuccessToast('正在重新取数'); await load() }
  catch (e: any) { showFailToast(e.message) } finally { busy.value = false }
}
async function confirm() {
  await showConfirmDialog({ title: '确认生成补货单',
    message: `共 ${picked.value.length} 项 · ${totalQty.value} 件,约 ¥${amount.value.toFixed(2)}。\n确认后在 DMS 创建采购单(待提交)并截图,核对截图后还要在本页点「确认提交」才会正式提交。`,
    confirmButtonText: '确认' })
  if (left.value <= 0) { showFailToast('已超过有效期,请先刷新'); return }
  busy.value = true
  try { showSuccessToast((await publicApi.post(base + '/confirm', payload())).message); await load() }
  catch (e: any) { showFailToast(e.message); await load() } finally { busy.value = false }
}
async function submit() {
  const po = st.value.po || {}
  try {
    await showConfirmDialog({ title: '确认提交采购单',
      message: `在 DMS 正式提交采购单 ${st.value.run.order_no}(SO)?\n${po.item_num || '-'} 项 · 约 ¥${Number(po.total_amount || 0).toFixed(2)}\n请先核对上面的截图,提交后不能撤回。`,
      confirmButtonText: '确认提交' })
  } catch { return }
  busy.value = true
  try { showSuccessToast((await publicApi.post(base + '/submit')).message); await load() }
  catch (e: any) { showFailToast(e.message); await load() } finally { busy.value = false }
}
async function hold() {
  try {
    await showConfirmDialog({ title: '先不提交',
      message: `采购单 ${st.value.run.order_no} 先不提交?DMS 里这张单会保留「待提交」,需要的话请到 DMS 人工删除或提交。` })
  } catch { return }
  try { showSuccessToast((await publicApi.post(base + '/hold')).message); await load() } catch (e: any) { showFailToast(e.message) }
}
async function cancel() {
  await showConfirmDialog({ title: '今天不订', message: '确定今天的补货不订了吗?' })
  try { showSuccessToast((await publicApi.post(base + '/cancel')).message); await load() } catch (e: any) { showFailToast(e.message) }
}
const tone = computed(() => STAGE[status.value]?.tone || 'info')
const fetchedAt = computed(() => String(st.value?.run.data_fetched_at || '').slice(11, 19))
</script>

<template>
  <div class="m">
    <van-empty v-if="err" image="error" :description="err" />
    <div v-else-if="!st" class="m-loading"><van-loading size="28" /></div>
    <template v-else>
      <header class="m-hero" :class="tone">
        <div class="m-store">{{ st.store.name }} · {{ st.kind_cn }}</div>
        <div class="m-doc">{{ isScheduled ? '今日补货确认' : st.run.doc_no }}</div>
        <div class="m-stage">{{ st.stage_cn }}</div>
        <div v-if="isScheduled" class="m-tip">
          本单出库区间 {{ st.window }}<br>
          共出库 {{ st.summary.total }} 个零件,其中 {{ st.summary.stock_count }} 个为常备件
          <template v-if="fetchedAt"><br>数据取自 {{ fetchedAt }} · 库存与在途以该时刻为准</template>
        </div>
        <div class="m-sum">
          <div><b>{{ picked.length }}</b><span>项</span></div>
          <div><b>{{ totalQty }}</b><span>件</span></div>
          <div><b>¥{{ amount.toFixed(0) }}</b><span>约</span></div>
        </div>
      </header>

      <div v-if="isScheduled && status === 'expired' && !st.run.order_no" class="m-card m-expired">
        已过今天的截单时间({{ st.cutoff }}),这张补货单没有确认,不能再修改,也不会建单;页面上的数量只供参考。
      </div>
      <div v-if="isScheduled && status === 'superseded'" class="m-card m-expired">
        这张清单已作废({{ st.run.message || '已有新的定时补货单' }}),不能再修改,也不会建单;请用群里最新推送的链接。
      </div>
      <div v-if="status === 'terminated'" class="m-card m-expired">
        这张补货单已在后台终止({{ st.run.message || '管理员操作' }}),不再自动重试,不能再修改,也不会建单。
      </div>
      <!-- 截单只提示风险:临近 / 已过截单仍可确认、提交 -->
      <div v-if="st.late_hint" class="m-card m-warnbox">{{ st.late_hint }}</div>
      <div v-if="st.stale_hint" class="m-card m-warnbox">{{ st.stale_hint }}</div>
      <div v-if="status === 'expired' && st.run.order_no && !submitted" class="m-card m-expired">
        这张单当时超时没有确认提交(旧规则),没有提交。DMS 里的 {{ st.run.order_no }} 如果还是「待提交」,请到 DMS 人工删除或提交。
      </div>
      <div v-if="status === 'cancelled' && st.run.order_no && !submitted" class="m-card m-warnbox">
        {{ st.run.message || '已选择先不提交' }}。DMS 里的 {{ st.run.order_no }} 还是「待提交」,需要的话请到 DMS 人工删除或提交。
      </div>
      <div v-if="status === 'awaiting_submit' && st.po?.submit_error" class="m-card m-expired">
        <b>上次提交没成功:</b>{{ st.po.submit_error }}
      </div>
      <div v-if="status === 'error' && st.run.order_no && !submitted" class="m-card m-expired">{{ st.run.message }}</div>
      <div v-if="editing && !st.can_refresh" class="m-card m-expired">
        已经过了今天的截单时间({{ st.cutoff }}),这张补货单不能再刷新或确认了。
      </div>
      <div v-else-if="editing && left === 0" class="m-card m-expired">
        <b>库存数据已过期。</b>上面这批库存 / 在途是 {{ fetchedAt }} 取的,超过 {{ st.valid_seconds }} 秒了。
        这段时间里可能有人手工补过货,在途数可能已经变了。请先刷新,再确认。
      </div>
      <div v-if="st.run.message && editing" class="m-card m-warnbox">{{ st.run.message }}</div>
      <!-- DMS 里所有还没提交的采购单(含他人创建、本系统建单结果未知的):只提示,不参与计算 -->
      <div v-if="isScheduled && (editing || status === 'awaiting_submit') && (drafts.items.length || drafts.error)"
           class="m-card m-warnbox">
        <template v-if="drafts.items.length">
          ⚠️ DMS 里还有 {{ drafts.items.length }} 张没提交的采购单(含他人创建的),不参与本次计算,{{ editing ? '确认' : '提交' }}前请留意别重复订:
          <div v-for="(d, i) in drafts.items" :key="(d.order_no || d.doc_no) + i" class="m-other-order">
            · {{ d.order_no || '(没有采购单号)' }}
            <template v-if="d.doc_no">(本系统 <a v-if="d.link" :href="d.link">{{ d.doc_no }}</a><template v-else>{{ d.doc_no }}</template>)</template>
            {{ d.create_by }} {{ (d.create_time || '').slice(5, 16) }}
            <template v-if="d.lines">· {{ d.lines.length }} 项</template>
            <template v-if="d.note">· {{ d.note }}</template>
          </div>
          <div v-if="drafts.truncated" class="m-other-order">待提交的单比较多,只有前 50 张取了明细,其余没标零件,请到 DMS「采购订单管理」核对</div>
        </template>
        <div v-if="drafts.error" class="m-other-order">ℹ️ {{ drafts.error }}</div>
      </div>

      <!-- 建单结果 -->
      <div v-if="st.run.order_no" class="m-card m-po" :class="{ ok: submitted }">
        <div class="m-label">
          <template v-if="submitted">采购单 · 已提交 ✅</template>
          <template v-else-if="status === 'awaiting_submit' && isScheduled">采购单(待提交)· 请核对截图,没问题点下方「确认提交」</template>
          <template v-else-if="status === 'awaiting_submit'">采购单(待提交)· 等 {{ st.run.triggered_by }} 在群里回「确认」提交</template>
          <template v-else-if="status === 'submitting'">采购单 · 正在 DMS 提交…</template>
          <template v-else>采购单(待提交)</template>
        </div>
        <div class="m-po-no">{{ st.run.order_no }}</div>
        <div v-if="submitted" class="m-po-sub">
          DMS 提交人 {{ st.po.apply_operator || '—' }} · {{ st.po.apply_time || '' }}<br>
          确认人 {{ st.po.submitted_by || '—' }}({{ st.submitted_via_cn }})
        </div>
        <div v-else-if="status === 'awaiting_submit'" class="m-po-sub">不过期 · 提交前会先到 DMS 查这张单的状态</div>
        <div v-if="st.shots_fallback" class="m-fallback">⚠ DMS 页面截图失败,以下截图是用 DMS 接口实际返回的数据渲染的,不是 DMS 原页面</div>
        <div v-if="st.shots.length" class="m-shots">
          <img v-for="(s, i) in st.shots" :key="s.id" :src="s.url" alt="采购单截图" @click="preview = { show: true, start: i }" />
        </div>
      </div>
      <div v-if="status === 'submitting'" class="m-card m-progress"><van-loading size="18" /> 正在 DMS 提交…</div>
      <div v-else-if="['creating', 'screenshotting'].includes(status)" class="m-card m-progress">
        <van-loading size="18" /> {{ status === 'creating' ? '正在 DMS 建单…' : '建单完成,正在截图…' }}
      </div>

      <!-- 单次补货:只读 -->
      <template v-if="!isScheduled">
        <div v-for="l in lines" :key="l.part_no" class="m-card m-line">
          <div class="m-line-head"><div class="m-line-name">{{ l.name || l.part_no }}</div><b class="m-qty">×{{ l.final_qty }}</b></div>
          <div class="m-line-pn">{{ l.part_no }}</div>
          <div class="m-facts"><span>库存 <b>{{ l.stock }}</b></span><span>在途 <b>{{ l.in_transit }}</b></span>
            <span v-if="l.cap != null">当日可订 <b>{{ l.cap }}</b></span></div>
          <div class="m-wh"><span v-for="(qv, w) in (l.wh_cn || l.wh)" :key="w">{{ w }} {{ qv }}</span></div>
          <div v-if="l.note" class="m-note">{{ l.note }}</div>
        </div>
      </template>

      <!-- 定时补货:历史常备件 -->
      <template v-else-if="!['creating', 'screenshotting', 'awaiting_submit', 'submitting', 'done'].includes(status) || !st.run.order_no">
        <div class="m-section">建议补货 <span>历史常备件 {{ stockLines.length }} 项 · 期望默认取「库存 + 出库」(推荐),填过的带上次的值(上次)</span></div>
        <div v-if="editing && stockLines.length" class="m-allbar">
          <van-checkbox :model-value="allChecked(stockLines)" :indeterminate="someChecked(stockLines)" icon-size="18px"
                        @update:model-value="(v: boolean) => toggleAll(stockLines, v, 'stock')">
            全选 <span>已选 {{ checkedCount(stockLines) }} / {{ stockLines.length }}</span></van-checkbox>
        </div>
        <div v-for="l in stockLines" :key="l.part_no" class="m-card m-line" :class="{ off: !edits[l.part_no]?.checked }">
          <div class="m-line-head">
            <van-checkbox v-if="editing" :model-value="edits[l.part_no]?.checked" icon-size="18px" @update:model-value="(v: boolean) => toggle(l, v)">
              <span class="m-line-name">{{ l.name || l.part_no }}</span></van-checkbox>
            <span v-else class="m-line-name">{{ l.name || l.part_no }}</span>
            <b class="m-qty">补 {{ calc(l).qty }}<small v-if="calc(l).capped"> 按上限</small></b>
          </div>
          <div class="m-line-pn">{{ l.part_no }}<span v-if="l.category" class="m-tag">{{ l.category }}</span>
            <span v-if="l.so_hit" class="m-tag">近 {{ st.so_months }} 月补过 {{ l.so_hit.order_count }} 次</span></div>
          <div v-if="l.in_drafts?.length" class="m-draft">⚠ 未提交的采购单里已有:{{ draftText(l) }}</div>
          <div class="m-exp-edit">
            <span class="m-exp-lbl">期望</span>
            <van-stepper v-if="editing && edits[l.part_no]" :model-value="edits[l.part_no].expected" :min="0" integer
                         input-width="48px" button-size="26px" @change="(v: any) => setExpected(l, v)" />
            <b v-else>{{ l.expected }}</b>
            <span class="m-src" :class="sourceLabel(l)" :title="sourceTitle(l)">{{ sourceLabel(l) }}</span>
            <a v-if="editing && edits[l.part_no]?.modified" class="m-reset" @click="reset(l)">恢复默认 {{ l.default_expected }}</a>
          </div>
          <div class="m-facts">
            <span>出库 <b>{{ l.outbound_qty }}</b></span><span>库存 <b>{{ l.stock }}</b></span><span>在途 <b>{{ l.in_transit }}</b></span>
            <span>月均 <b>{{ l.mad ?? '—' }}</b></span><span>可订 <b>{{ l.cap ?? '不限' }}</b></span>
            <span v-if="l.pack_qty > 1 || l.min_qty > 1">{{ packText(l) }}</span>
          </div>
          <div v-if="calc(l).note || l.error" class="m-note">{{ calc(l).note }} {{ l.error }}</div>
        </div>

        <!-- 其他出库件(折叠、默认不勾) -->
        <div v-if="otherCount" class="m-section m-fold" @click="expand">
          当天出库的其他零件 <span>{{ otherCount }} 项 · 默认不补 · 勾选并填期望值即可临时加入</span>
          <i>{{ showOthers ? '▴' : '▾' }}</i>
        </div>
        <template v-if="showOthers">
          <van-search v-model="kw" placeholder="搜索零件号 / 名称" shape="round" @update:model-value="onSearch" />
          <div v-if="editing && otherLines.length" class="m-allbar">
            <van-checkbox :model-value="allChecked(otherLines)" :indeterminate="someChecked(otherLines)" icon-size="18px"
                          @update:model-value="(v: boolean) => toggleAll(otherLines, v, 'other')">
              {{ kw.trim() ? '全选搜索结果' : '全选' }} <span>已选 {{ checkedCount(otherLines) }} / {{ otherLines.length }}</span></van-checkbox>
          </div>
          <div v-for="l in otherLines" :key="l.part_no" class="m-card m-line" :class="{ off: !edits[l.part_no]?.checked }">
            <div class="m-line-head">
              <van-checkbox v-if="editing" :model-value="edits[l.part_no]?.checked" icon-size="18px" @update:model-value="(v: boolean) => toggle(l, v)">
                <span class="m-line-name">{{ l.name || l.part_no }}</span></van-checkbox>
              <span v-else class="m-line-name">{{ l.name || l.part_no }}</span>
              <b class="m-qty">{{ edits[l.part_no]?.checked || !editing ? '补 ' + calc(l).qty : '—' }}</b>
            </div>
            <div class="m-line-pn">{{ l.part_no }}<span v-if="l.category" class="m-tag">{{ l.category }}</span></div>
            <div v-if="l.in_drafts?.length" class="m-draft">⚠ 未提交的采购单里已有:{{ draftText(l) }}</div>
            <div v-if="edits[l.part_no]?.checked" class="m-exp-edit">
              <span class="m-exp-lbl">期望</span>
              <van-stepper v-if="editing" :model-value="edits[l.part_no].expected" :min="0" integer input-width="48px"
                           button-size="26px" @change="(v: any) => setExpected(l, v)" />
              <b v-else>{{ l.expected }}</b>
              <span class="m-src" :class="sourceLabel(l)">{{ sourceLabel(l) }}</span>
            </div>
            <div class="m-facts">
              <span>出库 <b>{{ l.outbound_qty }}</b></span><span>库存 <b>{{ l.stock }}</b></span><span>在途 <b>{{ l.in_transit }}</b></span>
              <span>月均 <b>{{ l.mad ?? '—' }}</b></span><span>可订 <b>{{ l.cap ?? '不限' }}</b></span>
            <span v-if="l.pack_qty > 1 || l.min_qty > 1">{{ packText(l) }}</span>
            </div>
            <div v-if="edits[l.part_no]?.checked && calc(l).note" class="m-note">{{ calc(l).note }}</div>
            <div v-else-if="edits[l.part_no]?.checked && !l.national_queried" class="m-note">没查全国仓(刷新后会查)</div>
          </div>
        </template>
      </template>

      <!-- 底部唯一的按钮:所有状态都在它身上 -->
      <div v-if="isScheduled && status !== 'done' && !['cancelled', 'expired', 'superseded', 'error', 'terminated'].includes(status)" class="m-bar">
        <template v-if="status === 'awaiting_submit'">
          <van-button v-if="st.can_hold" class="m-bar-btn" @click="hold">先不提交</van-button>
          <van-button class="m-bar-btn main" type="primary" :loading="busy" :disabled="!st.can_submit" @click="submit">
            确认提交 {{ st.run.order_no }}</van-button>
        </template>
        <template v-else-if="editing">
          <van-button v-if="st.can_cancel" class="m-bar-btn" @click="cancel">今天不订</van-button>
          <van-button v-if="left > 0" class="m-bar-btn main" type="primary" :loading="busy" :disabled="!st.can_refresh" @click="confirm">
            确认,生成补货单 <span class="m-count">{{ left }} s</span></van-button>
          <van-button v-else class="m-bar-btn main" type="warning" :loading="busy" :disabled="!st.can_refresh" @click="refresh">
            刷新并重新计算补货数量</van-button>
        </template>
        <van-button v-else class="m-bar-btn main" disabled :loading="true">
          {{ ['scanning', 'refreshing', 'scan_retry'].includes(status) ? '正在取数(出库明细 → 库存 / 在途 / 可订)…' : st.stage_cn + '…' }}</van-button>
      </div>
      <van-image-preview v-model:show="preview.show" :images="st.shots.map((s: any) => s.url)" :start-position="preview.start" />
    </template>
  </div>
</template>