const { searchProductTrace, fetchProductTrace } = require('../../utils/request'); const { ensureMobileRole } = require('../../utils/roleGuard'); const { beginPanelShow, endPanelShow } = require('../../utils/panelShowGate'); const { chinaTodayYmd } = require('../../utils/chinaDate'); const config = require('../../config'); const TRACE_ROLES = ['warehouse', 'inspector', 'purchaser', 'admin', 'operator', 'picker']; function queryDayLabel(ymd) { const today = chinaTodayYmd(); const day = String(ymd || today).trim() || today; if (day === today) return '今天'; const parts = day.split('-'); if (parts.length !== 3) return day; return `${Number(parts[1])}月${Number(parts[2])}日`; } function rangeLabel(from, to) { const a = String(from || '').trim(); const b = String(to || '').trim(); if (!a || !b) return '自定义'; if (a === b) return queryDayLabel(a); return `${queryDayLabel(a)} ~ ${queryDayLabel(b)}`; } function compactRangeText(from, to) { const a = String(from || '').trim(); const b = String(to || '').trim(); if (!a || !b) return ''; const short = (ymd) => { const parts = String(ymd).split('-'); if (parts.length !== 3) return ymd; return `${Number(parts[1])}/${Number(parts[2])}`; }; return `起 ${short(a)} 止 ${short(b)}`; } function resolveQueryRange(preset, dateFrom, dateTo) { const today = chinaTodayYmd(); if (preset !== 'custom') return { from: today, to: today }; const from = String(dateFrom || '').trim() || today; const to = String(dateTo || '').trim() || today; return from <= to ? { from, to } : { from: to, to: from }; } function formatTime(value) { if (!value) return ''; const d = new Date(value); if (Number.isNaN(d.getTime())) return String(value); return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')} ${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}`; } /** 相对 /api/storage 签名路径 → 小程序可加载的绝对地址 */ function absolutizeMediaUrl(url) { const raw = String(url || '').trim(); if (!raw) return raw; if (/^https?:\/\//i.test(raw)) return raw; const apiBase = String(config.apiBase || '').replace(/\/+$/, ''); const origin = apiBase.replace(/\/api$/i, ''); if (raw.startsWith('/')) return `${origin}${raw}`; return `${apiBase}/${raw.replace(/^\/+/, '')}`; } function absolutizeMediaList(list) { return Array.isArray(list) ? list.map(absolutizeMediaUrl) : list; } /** * 照片时间文本:按 `*_meta` 与 URL 数组**同序**取 `time` 并格式化。 * `*_meta` 缺失或为空(旧响应 / 旧缓存)时返回空串,照片照常显示、只是没有时间文字。 */ function photoTimeTextList(meta, urls) { const list = Array.isArray(meta) ? meta : []; const total = Array.isArray(urls) ? urls.length : 0; const out = []; for (let i = 0; i < total; i += 1) { const item = list[i]; out.push(item && item.time ? formatTime(item.time) : ''); } return out; } function absolutizeDetailMedia(detail) { if (!detail || typeof detail !== 'object') return detail; const photos = absolutizeMediaList(detail.photos); const loading_photos = absolutizeMediaList(detail.loading_photos); const direct_delivery_photos = absolutizeMediaList(detail.direct_delivery_photos); const quality_reports = Array.isArray(detail.quality_reports) ? detail.quality_reports.map((r) => ({ ...r, file_urls: Array.isArray(r.file_urls) ? r.file_urls.map(absolutizeMediaUrl) : r.file_urls, })) : detail.quality_reports; return { ...detail, photos, loading_photos, direct_delivery_photos, photos_time_text: photoTimeTextList(detail.photos_meta, photos), loading_photos_time_text: photoTimeTextList(detail.loading_photos_meta, loading_photos), direct_delivery_photos_time_text: photoTimeTextList(detail.direct_delivery_photos_meta, direct_delivery_photos), quality_reports, }; } /** 公开溯源链接:用 config.webBase 自拼绝对地址(后端未配置时返回相对路径 /t/<编码>) */ function buildPublicUrl(code) { const webBase = String(config.webBase || '').replace(/\/$/, ''); const key = String(code || '').trim(); if (!webBase || !key) return ''; return `${webBase}/t/${encodeURIComponent(key)}`; } /** 溯源标识:优先 trace_code,无批次行回退 batch_no */ function traceKey(hit) { return String(hit.trace_code || hit.batch_no || ''); } Component({ options: { addGlobalClass: true, }, properties: { embedded: { type: Boolean, value: false, }, initialCode: { type: String, value: '', }, }, lifetimes: { attached() { this.onPanelShow(); }, }, pageLifetimes: { show() { this.onPanelShow(); }, }, data: { query: '', hits: [], hitTotal: 0, listSummary: '', dateField: 'order_created', datePreset: 'today', dateFrom: '', dateTo: '', customRangeText: '', showRangeModal: false, draftFrom: '', draftTo: '', loading: false, error: '', }, methods: { async onPanelShow() { if (!beginPanelShow(this)) return; try { const ok = await ensureMobileRole(TRACE_ROLES); if (!ok) return; const code = String(this.properties.initialCode || '').trim(); if (code && !this._openedInitialCode) { this._openedInitialCode = code; this.setData({ query: code }); await this.loadHits(); this._openBatches = { [code]: true }; await this.loadDetail(code); this.setData({ hits: this.decorateHits(this.data.hits) }); return; } await this.loadHits(); } finally { endPanelShow(this); } }, onQueryInput(e) { this.setData({ query: e.detail.value }); }, decorateHits(list) { const cache = this._detailCache || {}; const open = this._openBatches || {}; const loadingCode = this._detailLoading || ''; return (list || []).map((hit) => { const code = traceKey(hit); const detail = cache[code] || null; return { ...hit, trace_code: code, // 有批次行看验收入库时间;无批次行(免入库/直送/加菜)inspection_time 为 null,改看配送补拍时间 inspection_time_text: hit.inspection_time_text || formatTime(hit.inspection_time || hit.loading_at), open: Boolean(open[code]), detail_loading: loadingCode === code && !detail, detail, }; }); }, setDateField(e) { const dateField = String(e.currentTarget.dataset.field || 'order_created'); if (dateField === this.data.dateField) return; this._openBatches = {}; this.setData({ dateField }, () => this.loadHits()); }, setDatePreset() { this._openBatches = {}; this.setData({ datePreset: 'today', customRangeText: '' }, () => this.loadHits()); }, stopModalTap() {}, openRangeModal() { const today = chinaTodayYmd(); this.setData({ showRangeModal: true, draftFrom: this.data.dateFrom || today, draftTo: this.data.dateTo || today, }); }, closeRangeModal() { this.setData({ showRangeModal: false }); }, onDraftFromChange(e) { this.setData({ draftFrom: e.detail.value }); }, onDraftToChange(e) { this.setData({ draftTo: e.detail.value }); }, confirmRangeModal() { const range = resolveQueryRange('custom', this.data.draftFrom, this.data.draftTo); this._openBatches = {}; this.setData({ showRangeModal: false, datePreset: 'custom', dateFrom: range.from, dateTo: range.to, customRangeText: compactRangeText(range.from, range.to), }, () => this.loadHits()); }, async onSearch() { await this.loadHits(); }, async loadHits() { const range = resolveQueryRange(this.data.datePreset, this.data.dateFrom, this.data.dateTo); const q = String(this.data.query || '').trim(); const dateField = this.data.dateField === 'inbound' ? 'inbound' : 'order_created'; this.setData({ loading: true, error: '' }); try { const result = await searchProductTrace({ q, date_from: range.from, date_to: range.to, date_field: dateField, limit: 50, }); const hits = result.data || result || []; const list = Array.isArray(hits) ? hits : []; const hitTotal = Number(result.total != null ? result.total : list.length) || 0; const axis = dateField === 'order_created' ? '下单日' : '入库日'; const listSummary = `${rangeLabel(range.from, range.to)} ${axis}批次 共 ${hitTotal} 条`; this.setData({ hits: this.decorateHits(list), hitTotal, listSummary, }); } catch (err) { this.setData({ error: err.message || '搜索失败', hits: [], hitTotal: 0 }); } finally { this.setData({ loading: false }); } }, async loadDetail(code) { const traceCode = String(code || '').trim(); if (!traceCode) return null; const cache = this._detailCache || {}; if (cache[traceCode]) return cache[traceCode]; this._detailLoading = traceCode; this.setData({ hits: this.decorateHits(this.data.hits), error: '' }); try { const result = await fetchProductTrace(traceCode); let detail = result.data || result; if (detail) { detail = absolutizeDetailMedia(detail); detail.public_url = buildPublicUrl(traceCode); detail.inbound_at_text = formatTime(detail.inbound_at); } cache[traceCode] = detail; this._detailCache = cache; return detail; } catch (err) { wx.showToast({ title: err.message || '查询失败', icon: 'none' }); this.setData({ error: err.message || '查询失败' }); return null; } finally { if (this._detailLoading === traceCode) this._detailLoading = ''; this.setData({ hits: this.decorateHits(this.data.hits) }); } }, async toggleExpand(code) { const traceCode = String(code || '').trim(); if (!traceCode) return; const open = { ...(this._openBatches || {}) }; if (open[traceCode]) { delete open[traceCode]; this._openBatches = open; this.setData({ hits: this.decorateHits(this.data.hits) }); return; } open[traceCode] = true; this._openBatches = open; this.setData({ hits: this.decorateHits(this.data.hits) }); await this.loadDetail(traceCode); }, openHit(e) { const code = e.currentTarget.dataset.code; void this.toggleExpand(code); }, async onScan() { wx.scanCode({ onlyFromCamera: false, success: async (res) => { let raw = String(res.result || '').trim(); const match = raw.match(/\/t\/([^/?#]+)/i); if (match) raw = decodeURIComponent(match[1]); this.setData({ query: raw }); const detail = await this.loadDetail(raw); if (!detail) return; const exists = (this.data.hits || []).some((h) => traceKey(h) === raw); if (!exists) { const extra = { trace_code: raw, batch_no: detail.batch_no || raw, item_name: detail.item_name, order_code: detail.order && detail.order.order_code, inspection_time: detail.inbound_at, loading_at: detail.loading_at || null, }; this.setData({ hits: this.decorateHits([extra, ...(this.data.hits || [])]) }); } this._openBatches = { ...(this._openBatches || {}), [raw]: true }; this.setData({ hits: this.decorateHits(this.data.hits) }); }, fail: () => wx.showToast({ title: '扫码取消', icon: 'none' }), }); }, previewPhoto(e) { const url = e.currentTarget.dataset.url; const batch = String(e.currentTarget.dataset.batch || ''); const hit = (this.data.hits || []).find((row) => traceKey(row) === batch); const detail = (hit && hit.detail) || null; const urls = detail ? [].concat(detail.photos || [], detail.loading_photos || [], detail.direct_delivery_photos || []) : []; wx.previewImage({ current: url, urls: urls.length ? urls : [url] }); }, }, });