Files
SupplierSystem/miniprogram/components/product-trace-panel/index.js
T
Ubuntu deb3e72750
CI / server typecheck + tests (push) Canceled after 0s
CI / web typecheck + tests + miniprogram syntax (push) Canceled after 0s
CI / eslint (观察项,C7 骨架) (push) Canceled after 0s
CI / npm audit (critical 硬拦) (push) Canceled after 0s
chore: 以 AI 生鲜配送系统 当前版本作为 SupplierSystem 起点
来源仓库:jxc/ai-fresh-delivery
来源提交:f0b1a180e2deb7e4673b9d1c8542619f7bc0f73d
快照树:  09f679334ff38f0ff25e907961c94a8223bcaedd(与来源 HEAD 工作树逐字节一致,3801 个文件)

按约定本仓库不带任何历史提交:来源仓库的历史中含真实凭据
(生产 SSH 私钥 deploy/id_rsa_tencent、server/.env、.env.tencent/.env.production/.env.gitea、
deploy/小程序AppSecret.txt,其中 MP_APPSECRET / S3 AccessKey 经哈希比对与线上同值),
整包推送会把这些凭据永久带入本仓库,故只取「当前版本」的单提交快照。
供应商系统后续开发自本提交开始。
2026-10-08 17:35:43 +08:00

380 lines
12 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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] });
},
},
});