Web 溯源详情:检验报告移到链路右侧(有报告才两列,无报告链路整宽),图片报告出缩略图可放大;订单行改为客户名称在前、短号在后,链接仍指向完整单号。小程序溯源面板:报告紧跟链路,报告附件缩略图/文档打开,公开链接改复制按钮,链路补时间。
501 lines
17 KiB
JavaScript
501 lines
17 KiB
JavaScript
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;
|
||
// 内联 base64 照片(实测有 `data:image/jpeg;base64,…`)原样透传,否则会拼成 `${apiBase}/data:...` 而裂图
|
||
if (/^data:/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;
|
||
}
|
||
|
||
/** 报告附件:图片直接预览;PDF/Word/Excel/PPT 下载后 openDocument */
|
||
const REPORT_IMAGE_RE = /\.(png|jpe?g|webp|gif|bmp|avif)(?:[?#]|$)/i;
|
||
const REPORT_DOC_EXTS = ['pdf', 'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx'];
|
||
const REPORT_EXT_LABEL = {
|
||
pdf: 'PDF',
|
||
doc: 'WORD',
|
||
docx: 'WORD',
|
||
xls: 'EXCEL',
|
||
xlsx: 'EXCEL',
|
||
ppt: 'PPT',
|
||
pptx: 'PPT',
|
||
};
|
||
|
||
function reportFileMeta(url) {
|
||
const clean = String(url || '').split(/[?#]/)[0];
|
||
const match = clean.match(/\.([a-z0-9]{1,8})$/i);
|
||
const ext = match ? match[1].toLowerCase() : '';
|
||
return {
|
||
url,
|
||
ext,
|
||
ext_label: REPORT_EXT_LABEL[ext] || (ext ? ext.toUpperCase() : 'FILE'),
|
||
is_image: REPORT_IMAGE_RE.test(url),
|
||
can_open_doc: REPORT_DOC_EXTS.includes(ext),
|
||
};
|
||
}
|
||
|
||
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) => {
|
||
// `file_urls` 里可能是空串(旧无前缀 key 不再签发给空 URL)——过滤掉,否则会渲染出一个点不动的「查看文档」
|
||
const urls = Array.isArray(r.file_urls) ? r.file_urls.map(absolutizeMediaUrl).filter(Boolean) : [];
|
||
return {
|
||
...r,
|
||
file_urls: urls,
|
||
files: urls.map((url) => reportFileMeta(url)),
|
||
};
|
||
})
|
||
: 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 || '');
|
||
}
|
||
|
||
/**
|
||
* 溯源面板的订单号**展示**缩写:`ORD_{入口}_{YYYYMMDD}_{分公司}_{4位}` → `ORD_{YYYYMMDD}`。
|
||
* 只用于详情面板展示;接口参数与存储仍用完整单号。非标准值原样返回。
|
||
*/
|
||
function shortenOrderCode(orderCode) {
|
||
const raw = String(orderCode == null ? '' : orderCode);
|
||
const parts = raw.split('_');
|
||
if (parts.length !== 5) return raw;
|
||
if (parts[0] !== 'ORD' || !/^\d{8}$/.test(parts[2]) || !/^\d{4}$/.test(parts[4])) return raw;
|
||
return `ORD_${parts[2]}`;
|
||
}
|
||
|
||
/** 链路节点时间文本:wxml 不能调函数,故在 js 里预算 */
|
||
function withTimelineTimeText(detail) {
|
||
if (!detail || typeof detail !== 'object') return detail;
|
||
const timeline = Array.isArray(detail.timeline) ? detail.timeline : [];
|
||
return {
|
||
...detail,
|
||
order_code_text: detail.order && detail.order.order_code ? shortenOrderCode(detail.order.order_code) : '',
|
||
timeline: timeline.map((step) => ({
|
||
...step,
|
||
at_text: step && step.at ? formatTime(step.at) : '',
|
||
})),
|
||
};
|
||
}
|
||
|
||
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);
|
||
detail = withTimelineTimeText(detail);
|
||
}
|
||
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' }),
|
||
});
|
||
},
|
||
|
||
onCopyPublicLink(e) {
|
||
const url = String((e.currentTarget.dataset || {}).url || '').trim();
|
||
if (!url) return;
|
||
wx.setClipboardData({ data: url });
|
||
},
|
||
|
||
/** 定位可点击的报告附件(图片/文档共用) */
|
||
findReportFile(e) {
|
||
const ds = e.currentTarget.dataset || {};
|
||
const batch = String(ds.batch || '');
|
||
const hit = (this.data.hits || []).find((row) => traceKey(row) === batch);
|
||
const detail = (hit && hit.detail) || null;
|
||
const reports = detail && Array.isArray(detail.quality_reports) ? detail.quality_reports : [];
|
||
const report = reports[Number(ds.report)] || null;
|
||
const files = report && Array.isArray(report.files) ? report.files : [];
|
||
return { files, file: files[Number(ds.file)] || null };
|
||
},
|
||
|
||
/** 图片报告:点击看大图(同一条报告的多张图可左右滑) */
|
||
previewReportFile(e) {
|
||
const { files, file } = this.findReportFile(e);
|
||
if (!file || !file.is_image) return;
|
||
const images = files.filter((item) => item && item.is_image);
|
||
if (!images.length) return;
|
||
wx.previewImage({
|
||
urls: images.map((item) => item.url),
|
||
current: file.url,
|
||
});
|
||
},
|
||
|
||
/** 文档报告:下载后调系统阅读器(pdf/doc/docx/xls/xlsx/ppt/pptx) */
|
||
openReportFile(e) {
|
||
const { file } = this.findReportFile(e);
|
||
if (!file) return;
|
||
if (!file.can_open_doc) {
|
||
wx.showToast({ title: '该文件暂不支持预览', icon: 'none' });
|
||
return;
|
||
}
|
||
wx.showLoading({ title: '打开中' });
|
||
wx.downloadFile({
|
||
url: file.url,
|
||
success: (res) => {
|
||
wx.hideLoading();
|
||
if (res.statusCode !== 200) {
|
||
wx.showToast({ title: '文件下载失败', icon: 'none' });
|
||
return;
|
||
}
|
||
wx.openDocument({
|
||
filePath: res.tempFilePath,
|
||
fileType: file.ext,
|
||
showMenu: true,
|
||
fail: () => wx.showToast({ title: '无法预览该文档', icon: 'none' }),
|
||
});
|
||
},
|
||
fail: () => {
|
||
wx.hideLoading();
|
||
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] });
|
||
},
|
||
},
|
||
});
|