OrderPage.vue
45.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
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
<!-- 手机单据页(计划员在企微里点链接打开,免登录,靠补货单令牌)。
定时补货:一个页面走完全流程 —— 待填(历史常备件默认勾选、其他出库件折叠)→ 按钮上挂倒计时 → 确认生成补货单 → 建单中 →
截图 → 核对截图后点「确认提交」(不过期,提交前先查 DMS 状态;也可以「先不提交」,DMS 草稿保留)→ 提交中 → 已提交;
倒计时归零按钮变「刷新并重新计算补货数量」(整条链路重新取数,人填的勾选 / 期望保留)。整体填完点一次确认,不逐行保存。
页面行为(打开、展开、倒计时归零、下载明细清单)上报审计;勾选 / 改数量不逐次上报,确认建单 / 不订时把最终的勾选和数量
一起提交,后台只留最终修改记录(和系统给的不一样的地方)。
批量补货(会话里一次发多个零件):同一套流程,清单是群里要的零件(MultiLines:可以订的 / 不可以订的两组),可取消勾选、改数量。
和定时补货的不同:链接一发起就能开(群里只发这一次链接),查好的零件自动出现(全部查完才能建单);没有倒计时;
没建单的当天 24 点过期;建单被 DMS 点名拒绝的零件标红,还勾着就不能再建单。
数量只能在「起订量 / 包装数 ~ 当日可订 / 单个零件上限」内按包装数加减,要的和实际订的不一样时行上写清原因。
两种补货都有「刷新库存」按钮(待确认时随时可点):重新取数,本次的勾选 / 期望(数量)全部清空、恢复默认。
采购单提交成功后可下载「采购明细清单」xlsx(后台数据生成,不访问 DMS)。
建单之后(建单中 / 待确认提交 / 已提交)照样显示「本次确认的清单」:当时的勾选、改过的期望 / 数量都在,方便事后核对、排查。
单次补货只看结果和截图(提交在会话里 @机器人 回「确认提交」)。 -->
<script setup lang="ts">
import 'vant/lib/index.css'
import { Button as VanButton, Checkbox as VanCheckbox, Empty as VanEmpty,
Loading as VanLoading, showConfirmDialog, showFailToast, showImagePreview, 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 MultiLines from './MultiLines.vue'
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 openSec = ref<Record<string, boolean>>({ stock: true, other: false }) // 大组:常备件默认展开,其他出库件默认收起
const collapsed = ref<Record<string, boolean>>({}) // 二级分类折叠
const showExplain = ref(false) // 头部「口径说明」
const onlyPicked = ref(true) // 确认后的清单:默认只看已勾选的
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)
const fromServer = (l: any) => ({ checked: !!l.checked, expected: l.expected, modified: !!l.modified })
if (s.run.fetch_seq !== seq.value) { // 首次 / 刷新后:以服务端的勾选和期望为准(刷新会清空本次填写)
edits.value = Object.fromEntries(s.lines.map((l: any) => [l.part_no, fromServer(l)]))
if (!st.value && s.run.confirmed_at && s.run.status !== 'awaiting_confirm') openSec.value.other = true // 看确认的清单:两组都展开
if (!st.value && s.run.kind === 'multi') onlyPicked.value = false // 批量补货:未进订单的也要看得见
seq.value = s.run.fetch_seq
} else if (s.run.kind === 'multi') {
// 批量补货边查边填:刚查好的行(之前是占位行)按服务端默认值填上;人已经改过的行不动
const was = Object.fromEntries((st.value?.lines || []).map((l: any) => [l.part_no, l.tag]))
for (const l of s.lines) {
if (!edits.value[l.part_no] || (was[l.part_no] === 'pending' && l.tag !== 'pending') || l.blocked)
edits.value[l.part_no] = fromServer(l)
}
}
if (s.run.status === 'awaiting_confirm' && s.run.kind !== 'multi') { // 批量补货没有倒计时
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 isMulti = computed(() => st.value?.run.kind === 'multi')
const isPage = computed(() => isScheduled.value || isMulti.value) // 在单据页上确认 / 建单 / 提交的
const status = computed(() => st.value?.run.status || '')
/** 能不能改:定时补货待确认时;批量补货查询中(已查好的行)和待确认时都能改,过了当天没建单就只读 */
const editing = computed(() => isPage.value && !st.value?.stale &&
(status.value === 'awaiting_confirm' || (isMulti.value && status.value === 'scanning')))
const multiExpired = computed(() => isMulti.value && (st.value?.stale || (status.value === 'expired' && !st.value?.run.order_no)))
const queryingLines = computed(() => lines.value.filter((l) => l.tag === 'pending').length)
/** 上次建单被 DMS 点名拒绝、现在还勾着的零件:必须先取消勾选才能再建单 */
const rejectedChecked = computed(() => lines.value.filter((l) => l.ext?.reject && edits.value[l.part_no]?.checked))
/** 已经确认过(建单中 / 待确认提交 / 已提交 / 之后作废等):清单只读,显示当时确认的勾选和改动 */
const confirmedView = computed(() => isPage.value && !!st.value?.run.confirmed_at && status.value !== 'awaiting_confirm')
const fmtTime = (v: any) => String(v || '').slice(5, 16)
const submitted = computed(() => st.value?.po?.status === '已提交')
/** 页头「刷新库存」:待确认时可点(批量补货查询中不显示);放在取数时间旁边,远离底部「确认建单」防误点 */
const showRefresh = computed(() => editing.value && status.value === 'awaiting_confirm' && !!st.value?.can_refresh)
const lines = computed<any[]>(() => st.value?.lines || [])
/** 「自动过滤补货数量为 0 的零件」(补货规则开关):按这次取数时服务端算的数量判断(勾选后会补的数),
* 编辑期望时行不会忽隐忽现;查询失败的照常显示。隐藏的行仍随确认一起提交(数量本就是 0)。 */
const hiddenZero = (l: any) => !!st.value?.hide_zero && !l.error && Number(l.preview_qty ?? l.final_qty) === 0
const visibleLines = computed(() => lines.value.filter((l) => !hiddenZero(l) && (!confirmedView.value || !onlyPicked.value || l.checked)))
const hiddenCount = computed(() => lines.value.filter(hiddenZero).length)
const stockCats = computed<string[]>(() => st.value?.stock_categories || [])
const normCat = (c: any) => { const v = String(c || '').trim(); return (!v || v === '未分类') ? '未分类' : v }
const stockAllLines = computed(() => visibleLines.value.filter((l) => l.grp !== 'other'))
const otherAllLines = computed(() => visibleLines.value.filter((l) => l.grp === 'other'))
const otherCount = computed(() => otherAllLines.value.length)
type SubGroup = { label: string; lines: any[]; showCat?: boolean }
/** 取数时就勾选、但服务端算出补 0 的(到上限 / 库存够 / 缺货)排到本组最后。
* 只看服务端这一轮的结果,页面上勾选 / 改期望不会让行跳动。 */
const isServerZero = (l: any) => !!l.checked && !l.error && Number(l.final_qty) === 0
const sinkZero = (ls: any[]) => [...ls.filter((l) => !isServerZero(l)), ...ls.filter(isServerZero)]
/** 历史常备件按分类二级分组:常备分类子组(按配置顺序)+ 末尾「近N个月SO单」子组(SO命中但分类不在常备分类里的,行上显示原分类) */
const stockGroups = computed<SubGroup[]>(() => {
const cats = stockCats.value
const groups: SubGroup[] = cats.map((c) => ({ label: c, lines: sinkZero(stockAllLines.value.filter((l) => (l.category || '') === c)) }))
.filter((g) => g.lines.length > 0)
const soLines = stockAllLines.value.filter((l) => !cats.includes(l.category || ''))
if (soLines.length > 0) groups.push({ label: `近${st.value?.so_months || 3}个月SO单`, lines: sinkZero(soLines), showCat: true })
return groups
})
/** 其他出库件按分类二级分组:钣喷件 → 未分类 → 其余按出现顺序 */
const otherGroups = computed<SubGroup[]>(() => {
const other = otherAllLines.value
const fixed = ['钣喷件', '未分类']
const groups: SubGroup[] = []
const seen = new Set<string>()
for (const c of fixed) {
const lines = other.filter((l) => normCat(l.category) === c)
if (lines.length > 0) { groups.push({ label: c, lines: sinkZero(lines) }); seen.add(c) }
}
for (const l of other) {
const c = normCat(l.category)
if (fixed.includes(c) || seen.has(c)) continue
seen.add(c)
groups.push({ label: c, lines: sinkZero(other.filter((x) => normCat(x.category) === c)) })
}
return groups
})
/** 两个大组用同一套模板渲染 */
const sections = computed(() => [
{ key: 'stock', title: '历史常备件', badge: '建议补货', lines: stockAllLines.value, groups: stockGroups.value,
desc: '默认勾选 · 期望取「库存 + 出库」,修改过的沿用上次值', empty: '这次没有历史常备件出库' },
{ key: 'other', title: '当天出库的其他零件', badge: '按需补货', lines: otherAllLines.value, groups: otherGroups.value,
desc: '默认不勾选 · 按分类挑选需要补货的零件', empty: '这次没有其他出库的零件' },
])
/** 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 同口径;最终以确认时服务端重算为准)。
* 没勾选的行也照常算出「勾选后会补多少」(off = true,不计入合计、不下单)。 */
function calc(l: any) {
if (l.tag === 'pending') return { qty: 0, capped: false, note: '', tag: 'pending', off: true }
if (l.blocked) return { qty: 0, capped: false, note: l.note || l.label || '', tag: l.tag, off: true }
const e = edits.value[l.part_no]
if (!editing.value || !e) {
if (l.checked) return { qty: l.final_qty, capped: l.tag === 'capped', note: l.note, tag: l.tag, off: false,
rounded: l.grp === 'multi' ? multiNote(l, l.final_qty, l.tag === 'capped').rounded : '' }
return { qty: l.preview_qty ?? 0, capped: false, note: l.preview_note || '', tag: 'unchecked', off: true }
}
return { ...calcQty(l, e.expected), off: !e.checked }
}
/** 批量补货:实际订的和群里要的不一样时,把原因说清(与云端 planner._multi_note 同口径)。
* rounded = 按起订量 / 包装数往上取了整(状态标签用);人自己改成别的数量的不写原因(行上有「已改」)。 */
function multiNote(l: any, qty: number, capped: boolean) {
const req = Number(l.default_expected) || 0
if (qty <= 0 || qty === req) return { note: '', rounded: '' }
if (capped) {
return { rounded: '', note: `你要 ${req} 个,DMS 今天最多还能订 ${l.cap} 个,按 ${qty} 订`
+ (qty !== l.cap ? `(${packText(l)})` : '') + (req > qty ? `,差的 ${req - qty} 个明天再补` : '') }
}
if (qty > req && qty === packUp(l, req)) {
const why = [...(minOf(l) > req ? [`起订量 ${minOf(l)} 个`] : []), ...(packOf(l) > 1 ? [`包装 ${packOf(l)} 个`] : [])]
return { rounded: minOf(l) > req ? '按起订量订' : '按包装取整', note: `你要 ${req} 个,DMS ${why.join('、')},按 ${qty} 订` }
}
return { note: '', rounded: '' }
}
function calcQty(l: any, expected: number) {
const r = calcRaw(l, expected)
if (l.grp !== 'multi' || r.qty <= 0) return r
// 数量已经是按上限取过整的建议量时,按群里要的数量判断,还是算「按上限订」
const capped = r.capped || (l.cap != null && r.qty === packDown(l, l.cap) && packUp(l, Number(l.default_expected) || 0) > l.cap)
const m = multiNote(l, r.qty, capped)
return { ...r, capped, tag: capped ? 'capped' : r.tag, note: m.note || r.note, rounded: m.rounded }
}
function calcRaw(l: any, expected: number): { qty: number; capped: boolean; note: string; tag: string; rounded?: string } {
if (l.error) return { qty: 0, capped: false, note: '没查到', tag: 'error' }
// 批量补货:期望就是要订的数量;定时补货:期望 −(库存 + 在途)
const want = l.grp === 'multi' ? Math.max(Math.round(expected || 0), 0)
: Math.max(Math.ceil((expected || 0) - (l.stock + l.in_transit)), 0)
if (want <= 0) return { qty: 0, capped: false, note: l.grp === 'multi' ? '数量为 0,不订' : '库存够用', 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} 个,不够起订 ${packUp(l, 1)} 个${packOf(l) > 1 ? `(包装 ${packOf(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.off && x.c.qty > 0))
/** 列表里显示、已勾选但补货数为 0 的行(库存够用 / 到 DMS 上限 / 厂家缺货 / 没查到):不计入头部「项」数,单独说明一下 */
const zeroPicked = computed(() => visibleLines.value.filter((l) => { const c = calc(l); return !c.off && c.qty <= 0 }).length)
/** 组摘要:已勾选几项、要补几件(大组 / 二级分类标题上显示,折叠了也看得到) */
function groupStat(ls: any[]) {
let qty = 0
for (const l of ls) { const c = calc(l); if (!c.off) qty += c.qty }
return { checked: checkedCount(ls), qty }
}
/** 勾选了但补 0 的行:右上角用标签说明原因(替代「补 0」) */
const ZERO_BADGE: Record<string, string> = { capped: '今天订不了', oos: '厂家缺货', enough: '库存够用', in_transit_ok: '在途够了', error: '没查到' }
const zeroBadge = (l: any) => { const c = calc(l); return !c.off && c.qty <= 0 ? (ZERO_BADGE[c.tag] || '不用补') : '' }
/** 数据格子里的数字:≥100 取整,其余最多一位小数 */
const fmtNum = (v: any) => v == null || v === '' ? '—' : Number(v) >= 100 ? String(Math.round(Number(v))) : String(Math.round(Number(v) * 10) / 10)
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}`
/** 批量补货数量的可选范围:最小 = ≥ 起订量的最小包装整数倍,最大 = 当日可订和单个零件上限以内最大的包装整数倍,
* 步长 = 包装数(与服务端 planner.qty_range 同口径)。 */
function qtyRange(l: any) {
const step = packOf(l)
const min = packUp(l, 1)
const tops = [l.cap != null ? packDown(l, l.cap) : Infinity, st.value?.max_qty ? packDown(l, st.value.max_qty) : Infinity]
return { min, max: Math.min(...tops), step }
}
/** 判断「改过」的基准:批量补货 = 系统建议的订货量,定时补货 = 默认期望 */
const baseOf = (l: any) => l.base_expected ?? l.default_expected
function setExpected(l: any, v: number | string) {
const e = edits.value[l.part_no]
let after = Math.max(0, Math.round(Number(v) || 0))
if (l.grp === 'multi') { // 手输的数量按包装数向上取整,再夹到可订范围里
const r = qtyRange(l)
const snapped = Math.min(Math.max(packUp(l, after), r.min), r.max)
if (snapped !== after) showFailToast(snapped > after && after >= r.min ? `已按包装 ${r.step} 取整为 ${snapped}`
: after < r.min ? `最少订 ${r.min} 个(${packText(l)})` : `最多订 ${r.max} 个`)
after = snapped
}
e.expected = after
e.modified = after !== baseOf(l)
}
function toggle(l: any, v: boolean) {
edits.value[l.part_no].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) {
for (const l of ls) if (edits.value[l.part_no] && !l.blocked && l.tag !== 'pending') edits.value[l.part_no].checked = v
}
function reset(l: any) {
const e = edits.value[l.part_no]
e.expected = baseOf(l)
e.modified = false
}
function toggleSection(key: string) {
openSec.value[key] = !openSec.value[key]
if (key === 'other' && openSec.value[key]) event('expand', { count: otherCount.value }) // 沿用原来的「展开其他组」埋点
}
const gkey = (prefix: string, label: string) => prefix + ':' + label
function toggleGroup(prefix: string, label: string) {
const k = gkey(prefix, label)
collapsed.value[k] = !collapsed.value[k]
}
const isCollapsed = (prefix: string, label: string) => !!collapsed.value[gkey(prefix, label)]
const payload = () => ({ lines: Object.entries(edits.value).map(([part_no, e]) => ({ part_no, ...e })) })
async function refresh() {
try {
await showConfirmDialog({ title: '刷新库存',
message: isMulti.value ? '重新查全部零件的库存 / 在途 / 可订。\n刷新后本次的勾选和改过的数量会清空,恢复默认,需要重新填。'
: '整条链路重新取数(出库明细 → 库存 / 在途 / 可订),重新计算补货数量并重新倒计时。\n刷新后本次的勾选和改过的期望会清空,恢复默认,需要重新填。',
confirmButtonText: '刷新' })
} catch { return }
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() {
if (rejectedChecked.value.length) {
showFailToast(`${rejectedChecked.value.map((l) => l.part_no).join('、')} 上次被 DMS 拒绝,请先取消勾选`)
return
}
await showConfirmDialog({ title: isMulti.value ? '确认建单' : '确认生成补货单',
message: `共 ${picked.value.length} 项 · ${totalQty.value} 件,约 ¥${amount.value.toFixed(2)}。\n确认后在 DMS 创建采购单(待提交)并截图,核对截图后还要在本页点「确认提交」才会正式提交。`,
confirmButtonText: '确认' })
if (!isMulti.value && 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(isMulti.value ? { title: '不订了', message: '确定这张批量补货不订了吗?DMS 里不会建单。' }
: { title: '今天不订', message: '确定今天的补货不订了吗?' })
try { showSuccessToast((await publicApi.post(base + '/cancel', payload())).message); await load() } catch (e: any) { showFailToast(e.message) }
}
const tone = computed(() => STAGE[status.value]?.tone || 'info')
function sheetClicked() { event('sheet_download', { order_no: st.value?.run.order_no }) }
const fetchedAt = computed(() => String(st.value?.run.data_fetched_at || '').slice(11, 19))
/** 采购单截图预览按设备分流:
* - 触屏手机 / 平板:Vant 全屏预览(黑底、双指 / 双击缩放、左右滑、点一下关闭、返回键关闭),像点普通图片一样,没有工具栏按钮;
* - 电脑(企微桌面端 / 浏览器,有鼠标):el-image 自带查看器,大图不变形。
* 按指针类型判断而不是按宽度,电脑窗口拉窄也还是电脑的预览。 */
const touch = typeof window !== 'undefined' && window.matchMedia('(hover: none) and (pointer: coarse)').matches
const shotUrls = computed<string[]>(() => (st.value?.shots || []).map((x: any) => x.url))
function openShot(i: number) {
if (!touch) return
showImagePreview({ images: shotUrls.value, startPosition: i, showIndex: shotUrls.value.length > 1, closeable: false, loop: false })
}
</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-hero-top"><span class="m-store">{{ st.store.name }} · {{ st.kind_cn }}</span><span class="m-stage">{{ st.stage_cn }}</span></div>
<div class="m-doc">{{ isScheduled ? '今日补货确认' : st.run.doc_no }}</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>
<div v-if="isScheduled" class="m-tip">
出库 {{ st.window }} · {{ st.summary.total }} 个零件(常备 {{ st.summary.stock_count }})
<template v-if="hiddenCount"><br>已按设置隐藏 {{ hiddenCount }} 个补货数量为 0 的零件</template>
<br><template v-if="fetchedAt">数据取自 {{ fetchedAt }}</template>
<button type="button" class="m-explain-btn" :aria-expanded="showExplain" @click="showExplain = !showExplain">口径说明</button>
<button v-if="showRefresh" type="button" class="m-explain-btn" :disabled="busy" @click="refresh">↻ 刷新库存</button>
</div>
<div v-if="isMulti" class="m-tip">
{{ st.run.triggered_by }} 在群里发起 · 共 {{ lines.length }} 项
<template v-if="queryingLines"><br>正在查库存,已查 {{ lines.length - queryingLines }}/{{ lines.length }} 项,查好的会自动出现</template>
<template v-else-if="fetchedAt"><br>数据 {{ fetchedAt.slice(0, 5) }} 查询<template v-if="!st.run.order_no && !st.stale"> · 今天 24 点前有效</template></template>
<button v-if="showRefresh" type="button" class="m-explain-btn" :disabled="busy" @click="refresh">↻ 刷新库存</button>
</div>
<div v-if="isScheduled && showExplain" class="m-explain">
只统计出库区间内的纯牌出库,和 DMS 按自然日导出的出库明细口径不同。<br>
<template v-if="zeroPicked">已勾选的里有 {{ zeroPicked }} 个今天不用订或订不了(库存够用 / 到 DMS 上限 / 厂家缺货),不计入「项要订」。<br></template>
库存与在途以取数时刻为准,超过有效期要先刷新再确认。
</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="isMulti && status === 'superseded'" class="m-card m-expired">
这张批量补货已作废({{ st.run.message || '已有新的批量补货' }}),不能再修改,也不会建单;请用群里最新的链接。
</div>
<div v-if="isMulti && status === 'done' && !st.run.order_no" class="m-card m-warnbox">
这 {{ lines.length }} 项全部不可订,原因见下面每一行;需要的话请在群里重新发「零件号 数量」。</div>
<div v-if="multiExpired" class="m-card m-expired">
这张批量补货是 {{ String(st.run.biz_date).slice(5) }} 的,当天没有建单,链接已过期,不能再修改或建单;需要的话请在群里重新发「零件号 数量」。
</div>
<div v-if="isMulti && status === 'error' && !st.run.order_no" class="m-card m-expired">
查询没成功:{{ st.run.message }}。请在群里重新发一次。</div>
<div v-if="editing && rejectedChecked.length" class="m-card m-expired">
上次建单被 DMS 拒绝:{{ rejectedChecked.map((l: any) => l.part_no).join('、') }}(原因见标红的行)。请先取消勾选这些零件再建单,或点「刷新库存」重新查。
</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 && !isMulti && !st.can_refresh" class="m-card m-expired">
已经过了今天的截单时间({{ st.cutoff }}),这张补货单不能再刷新或确认了。
</div>
<div v-else-if="editing && !isMulti && 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' && isPage">采购单(待提交)· 请核对截图,没问题点下方「确认提交」</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>
<!-- 缩略图统一用 el-image(固定高、宽按比例)。点开:手机走 Vant 全屏预览(openShot),电脑走 el-image 查看器;
两种预览都挂到 body,不受缩略图样式影响,大图不变形 -->
<div v-if="st.shots.length" class="m-shots">
<el-image v-for="(s, i) in st.shots" :key="s.id" :src="s.url" :preview-src-list="touch ? [] : shotUrls"
:initial-index="i" fit="contain" preview-teleported alt="采购单截图" @click="openShot(i)" />
</div>
<!-- 采购明细清单:卡片底部的蓝色小按钮;已提交才能导出,待提交时置灰 -->
<div v-if="st.sheet || (st.run.order_no && !submitted)" class="m-sheet-row">
<a v-if="st.sheet" class="m-sheet-btn" :href="st.sheet.url" :download="st.sheet.name" @click="sheetClicked">⤓ 导出采购明细清单</a>
<span v-else class="m-sheet-btn disabled" aria-disabled="true">⤓ 导出采购明细清单</span>
<span class="m-sheet-name">{{ st.sheet ? st.sheet.name : '提交后才能导出' }}</span>
</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>
<!-- 确认之后:清单只读,保留当时的勾选和改动(默认只看已勾选) -->
<div v-if="confirmedView" class="m-card m-confirmed">
<div class="m-label">本次确认的清单 · {{ st.run.confirmed_by || '—' }} {{ fmtTime(st.run.confirmed_at) }} 确认
<template v-if="st.summary.changed_count">· 改过 {{ st.summary.changed_count }} 处</template></div>
<div class="m-confirmed-sum">已勾选 {{ st.summary.checked_count }} / {{ st.summary.total }} 项 · 订 {{ st.summary.order_count }} 项
{{ st.summary.order_qty }} 件
<button type="button" class="m-toggle-btn" @click="onlyPicked = !onlyPicked">
{{ onlyPicked ? '看全部' : '只看已勾选' }}</button></div>
</div>
<!-- 批量补货:群里要的零件,可取消勾选、改数量 -->
<MultiLines v-if="isMulti" :lines="visibleLines" :edits="edits" :editing="editing" :calc="calc" :qty-range="qtyRange"
:wh-labels="st.wh_labels" @toggle="toggle" @set-qty="setExpected" @reset="reset"
@toggle-all="(ls: any[], v: boolean) => toggleAll(ls, v)" />
<!-- 单次补货:只读 -->
<template v-else-if="!isScheduled && !isMulti">
<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>
<section v-for="sec in sections" :key="sec.key" class="m-grp" :class="['m-grp-' + sec.key, { closed: !openSec[sec.key] }]">
<div class="m-grp-head" role="button" :aria-expanded="!!openSec[sec.key]" @click="toggleSection(sec.key)">
<i class="m-grp-arrow" aria-hidden="true"></i>
<div class="m-grp-title">
<div><b>{{ sec.title }}</b><small>{{ sec.badge }}</small></div>
<div class="m-grp-sum">{{ sec.lines.length }} 项 · 已选 <em>{{ groupStat(sec.lines).checked }}</em>
· 补 <em>{{ groupStat(sec.lines).qty }}</em> 件</div>
</div>
<div v-if="editing && sec.lines.length" class="m-grp-all" @click.stop>
<van-checkbox :model-value="allChecked(sec.lines)" :indeterminate="someChecked(sec.lines)" icon-size="17px"
@update:model-value="(v: boolean) => toggleAll(sec.lines, v)">
全选 {{ checkedCount(sec.lines) }}/{{ sec.lines.length }}</van-checkbox>
</div>
</div>
<div v-show="openSec[sec.key]" class="m-grp-body">
<div class="m-grp-desc">{{ sec.desc }}</div>
<div v-if="!sec.lines.length" class="m-section-empty">{{ sec.empty }}</div>
<div v-for="(g, gi) in sec.groups" :key="g.label + gi" class="m-subgroup"
:class="{ collapsed: isCollapsed(sec.key, g.label) }">
<div class="m-subsection">
<van-checkbox v-if="editing" :model-value="allChecked(g.lines)" :indeterminate="someChecked(g.lines)" icon-size="17px"
@update:model-value="(v: boolean) => toggleAll(g.lines, v)" />
<button type="button" class="m-sub-toggle" :aria-expanded="!isCollapsed(sec.key, g.label)"
@click="toggleGroup(sec.key, g.label)">
<span class="m-sub-title">{{ g.label }}</span>
<span class="m-sub-sum">已选 <em>{{ groupStat(g.lines).checked }}/{{ g.lines.length }}</em>
· 补 <em>{{ groupStat(g.lines).qty }}</em> 件</span>
<i class="m-sub-arrow" aria-hidden="true"></i>
</button>
</div>
<div v-show="!isCollapsed(sec.key, g.label)" class="m-sub-body">
<div v-for="l in g.lines" :key="l.part_no" class="m-ln"
:class="{ off: calc(l).off, zero: !!zeroBadge(l), 'no-cb': !editing }">
<van-checkbox v-if="editing" class="m-ln-cb" :model-value="edits[l.part_no]?.checked" icon-size="18px"
@update:model-value="(v: boolean) => toggle(l, v)" />
<div class="m-ln-id">
<div class="m-ln-name">{{ l.name || l.part_no }}</div>
<div class="m-line-pn">{{ l.part_no }}<span v-if="l.so_hit" class="m-tag">近 {{ st.so_months }} 月补过 {{ l.so_hit.order_count }} 次</span><span
v-if="g.showCat" class="m-tag cat">{{ l.category || '无分类' }}</span></div>
</div>
<div class="m-ln-qty">
<template v-if="zeroBadge(l)">0<small class="m-badge">{{ zeroBadge(l) }}</small></template>
<template v-else-if="calc(l).off">{{ calc(l).qty }}<small>勾选后补</small></template>
<template v-else>补 {{ calc(l).qty }}<small v-if="calc(l).capped">按上限</small></template>
</div>
<div class="m-ln-main">
<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="44px" 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>
<span v-if="!editing && l.modified" class="m-exp-lbl">原 {{ l.default_expected }}</span>
<span v-if="!editing && confirmedView" class="m-tag" :class="{ cat: !l.checked }">{{ l.checked ? '已勾选' : '未勾选' }}</span>
<a v-if="editing && edits[l.part_no]?.modified" class="m-reset" @click="reset(l)">恢复默认 {{ l.default_expected }}</a>
</div>
<div class="m-cells">
<div><span>出库</span><b>{{ fmtNum(l.outbound_qty) }}</b></div>
<div><span>库存</span><b>{{ fmtNum(l.stock) }}</b></div>
<div><span>在途</span><b>{{ fmtNum(l.in_transit) }}</b></div>
<div><span>月均</span><b>{{ fmtNum(l.mad) }}</b></div>
<div><span>可订</span><b>{{ l.cap ?? '不限' }}</b></div>
<div v-if="minOf(l) > 1 && minOf(l) !== packOf(l)"><span>起订/包装</span><b>{{ minOf(l) }}/{{ packOf(l) }}</b></div>
<div v-else><span>包装</span><b>{{ packOf(l) }}</b></div>
</div>
<div v-if="calc(l).note || l.error" class="m-note">{{ calc(l).note }} {{ l.error }}</div>
<div v-else-if="sec.key === 'other' && !l.national_queried && calc(l).qty > 0" class="m-note">没查全国仓(刷新后会查)</div>
</div>
</div>
</div>
</div>
</div>
</section>
</template>
<!-- 底部唯一的按钮:所有状态都在它身上 -->
<div v-if="isPage && !st.stale && status !== 'done' && !['cancelled', 'expired', 'superseded', 'error', 'terminated', 'po_changed', 'po_deleted'].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 && (status === 'awaiting_confirm' || isMulti)">
<!-- 实时合计:滑到下面改数量时也看得到 -->
<div class="m-bar-sum"><span>已选 <b>{{ picked.length }}</b> 项 · <b>{{ totalQty }}</b> 件 · 约 <b>¥{{ isMulti ? amount.toFixed(2) : amount.toFixed(0) }}</b></span></div>
<van-button v-if="st.can_cancel" class="m-bar-btn" @click="cancel">{{ isMulti ? '不订了' : '今天不订' }}</van-button>
<van-button v-if="isMulti" class="m-bar-btn main" type="primary" :loading="busy"
:disabled="status !== 'awaiting_confirm' || !picked.length || !!rejectedChecked.length" @click="confirm">
{{ status === 'scanning' ? `查询中 ${lines.length - queryingLines}/${lines.length},查完才能建单` : '确认建单' }}</van-button>
<van-button v-else-if="left > 0" class="m-bar-btn main" type="primary" :loading="busy" :disabled="!st.can_refresh || !picked.length" @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>
<!-- loading 时 Vant 会隐藏按钮内容,提示文字要走 loading-text 才显示得出来 -->
<van-button v-else class="m-bar-btn main" disabled loading
:loading-text="['scanning', 'refreshing', 'scan_retry'].includes(status)
? (isMulti ? '正在查库存 / 在途 / 可订…' : '正在取数(出库明细 → 库存 / 在途 / 可订)…') : st.stage_cn + '…'" />
</div>
</template>
</div>
</template>