diff --git a/miniprogram/components/customer-trace-panel/index.js b/miniprogram/components/customer-trace-panel/index.js new file mode 100644 index 0000000..46e9773 --- /dev/null +++ b/miniprogram/components/customer-trace-panel/index.js @@ -0,0 +1,310 @@ +const config = require('../../config'); +const { fetchCustomerTraceOrders, fetchCustomerTraceOrder } = require('../../utils/request'); +const { beginPanelShow, endPanelShow } = require('../../utils/panelShowGate'); + +function pad(n) { + return String(n).padStart(2, '0'); +} + +function chinaDay(offsetDays = 0) { + const now = new Date(Date.now() + 8 * 3600 * 1000 + offsetDays * 86400 * 1000); + return `${now.getUTCFullYear()}-${pad(now.getUTCMonth() + 1)}-${pad(now.getUTCDate())}`; +} + +function absolutizeMediaUrl(url) { + const raw = String(url || '').trim(); + if (!raw) return raw; + if (/^https?:\/\//i.test(raw)) return raw; + 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 isImageUrl(url) { + return /\.(png|jpe?g|webp|gif|bmp|avif)(?:[?#]|$)/i.test(String(url || '')); +} + +/** 链路阶段 → 表格列(服务端节点标题:入库 / 分拣 / 配送拍照 / 送达) */ +const STAGE_COLUMNS = [ + { key: 'inbound', label: '入库', match: (title) => title.includes('入库') }, + { key: 'picking', label: '分拣', match: (title) => title.includes('分拣') }, + { key: 'loading', label: '配送拍照', match: (title) => title.includes('配送') || title.includes('补拍') }, + { key: 'delivery', label: '送达', match: (title) => title.includes('送达') }, +]; + +/** 详情接口原始字段 → 面板数据(展示口径与原两页逐字一致) */ +function mapDetail(data) { + const raw = data && typeof data === 'object' ? data : {}; + const items = (raw.items || []).map((item) => { + // 链路节点由服务端给出(入库 / 分拣 / 配送拍照 / 送达),照片跟随节点 ⇒ 天然按阶段区分 + // 表格只展示图片(2026-10-24 开发者:时间无需展示),不再取节点时间 + const stages = STAGE_COLUMNS.map((col) => { + const node = (item.timeline || []).find((candidate) => + col.match(String(candidate && candidate.title ? candidate.title : '')) + ); + const photos = node + ? (node.photos || []) + .filter((photo) => photo && photo.url) + .map((photo) => absolutizeMediaUrl(photo.url)) + : []; + return { + key: col.key, + label: col.label, + photos, + }; + }); + const reports = (item.quality_reports || []).map((report) => ({ + label: report.report_label || report.report_type || '报告', + files: (report.file_urls || []).map((url) => { + const clean = String(url || '').split(/[?#]/)[0]; + const matched = clean.match(/\.([a-z0-9]{1,8})$/i); + return { + url: absolutizeMediaUrl(url), + image: isImageUrl(url), + ext: matched ? matched[1].toUpperCase() : 'FILE', + }; + }), + })); + return { + trace_code: item.trace_code, + item_name: item.item_name, + actual_qty: item.actual_qty == null ? '-' : item.actual_qty, + unit: item.unit || '', + stages, + reports, + }; + }); + return { order: raw.order || null, items }; +} + +Component({ + options: { + addGlobalClass: true, + }, + + properties: { + embedded: { + type: Boolean, + value: false, + }, + }, + + lifetimes: { + attached() { + this.onPanelShow(); + }, + }, + + pageLifetimes: { + show() { + this.onPanelShow(); + }, + }, + + data: { + loading: false, + orders: [], + total: 0, + dateFrom: chinaDay(-6), + dateTo: chinaDay(0), + keyword: '', + expandedCode: '', + detailLoadingCode: '', + detailError: '', + emptyText: '暂无溯源订单', + }, + + methods: { + async onPanelShow() { + if (!beginPanelShow(this)) return; + try { + await this.loadOrders(); + } finally { + endPanelShow(this); + } + }, + + decorateOrders(rows, expandedCode) { + const cache = this._detailCache || {}; + const code = String(expandedCode || ''); + return (rows || this.data.orders || []).map((row) => { + const open = Boolean(code) && row.order_code === code; + return { + ...row, + open, + detail: open ? cache[row.order_code] || null : null, + }; + }); + }, + + async loadOrders() { + if (this.data.loading) return; + this.setData({ loading: true }); + try { + const result = await fetchCustomerTraceOrders({ + q: this.data.keyword, + date_from: this.data.keyword ? '' : this.data.dateFrom, + date_to: this.data.keyword ? '' : this.data.dateTo, + limit: 50, + offset: 0, + }); + const rows = (result.data || []).map((row) => ({ + ...row, + delivery_date: row.delivery_date || '-', + customer_name: row.customer_name || '-', + })); + const expandedCode = rows.some((row) => row.order_code === this.data.expandedCode) + ? this.data.expandedCode + : ''; + this.setData({ + orders: this.decorateOrders(rows, expandedCode), + total: Number(result.total) || rows.length, + expandedCode, + detailError: expandedCode ? this.data.detailError : '', + }); + } catch (error) { + wx.showToast({ title: error.message || '加载失败', icon: 'none' }); + this.setData({ orders: [], total: 0 }); + } finally { + this.setData({ loading: false }); + } + }, + + onKeywordInput(e) { + this.setData({ keyword: String((e.detail && e.detail.value) || '').trim() }); + }, + + onSearch() { + this.loadOrders(); + }, + + onDateFromChange(e) { + this.setData({ dateFrom: e.detail.value, keyword: '' }); + this.loadOrders(); + }, + + onDateToChange(e) { + this.setData({ dateTo: e.detail.value, keyword: '' }); + this.loadOrders(); + }, + + async onOrderTap(e) { + const code = String( + (e.currentTarget && e.currentTarget.dataset && e.currentTarget.dataset.code) || '' + ).trim(); + if (!code) return; + if (this.data.expandedCode === code) { + this.setData({ + expandedCode: '', + detailError: '', + orders: this.decorateOrders(this.data.orders, ''), + }); + return; + } + this.setData({ + expandedCode: code, + detailError: '', + orders: this.decorateOrders(this.data.orders, code), + }); + if (!(this._detailCache && this._detailCache[code])) { + await this.loadDetail(code); + } + }, + + async loadDetail(code) { + const key = String(code || '').trim(); + if (!key || this.data.detailLoadingCode) return; + this.setData({ detailLoadingCode: key, detailError: '' }); + try { + const payload = await fetchCustomerTraceOrder(key); + this._detailCache = this._detailCache || {}; + this._detailCache[key] = mapDetail(payload && payload.data); + } catch (error) { + const message = (error && error.message) || '加载失败'; + this.setData({ detailError: message }); + wx.showToast({ title: message, icon: 'none' }); + } finally { + this.setData({ + detailLoadingCode: '', + orders: this.decorateOrders(this.data.orders, this.data.expandedCode), + }); + } + }, + + detailOf(code) { + const key = String(code || '').trim(); + return (this._detailCache && this._detailCache[key]) || null; + }, + + previewNodePhoto(e) { + const ds = (e.currentTarget && e.currentTarget.dataset) || {}; + const detail = this.detailOf(ds.code); + if (!detail) return; + const stageIndex = Number(ds.stage) || 0; + const itemIndex = Number(ds.item) || 0; + const photoIndex = Number(ds.index) || 0; + // 聚合**整单同一个阶段**的所有图片:预览里左右滑就能看其它商品的同阶段照片 + const urls = []; + let current = ''; + (detail.items || []).forEach((sku, skuIdx) => { + const stage = sku && sku.stages ? sku.stages[stageIndex] : null; + if (!stage || !stage.photos || !stage.photos.length) return; + stage.photos.forEach((url, idx) => { + if (skuIdx === itemIndex && idx === photoIndex) current = url; + urls.push(url); + }); + }); + if (!urls.length) return; + wx.previewImage({ urls, current: current || urls[0] }); + }, + + previewReportImage(e) { + const ds = (e.currentTarget && e.currentTarget.dataset) || {}; + const detail = this.detailOf(ds.code); + const item = detail && detail.items[Number(ds.item) || 0]; + const report = item && item.reports[Number(ds.report) || 0]; + if (!report) return; + const images = report.files.filter((file) => file.image).map((file) => file.url); + if (!images.length) return; + wx.previewImage({ + urls: images, + current: images[Number(ds.index) || 0] || images[0], + }); + }, + + openReportFile(e) { + const ds = (e.currentTarget && e.currentTarget.dataset) || {}; + const detail = this.detailOf(ds.code); + const item = detail && detail.items[Number(ds.item) || 0]; + const report = item && item.reports[Number(ds.report) || 0]; + const file = report && report.files[Number(ds.index) || 0]; + if (!file || file.image) return; + wx.showLoading({ title: '打开中…', mask: true }); + wx.downloadFile({ + url: file.url, + success(res) { + if (res.statusCode !== 200) { + wx.hideLoading(); + wx.showToast({ title: '文件下载失败', icon: 'none' }); + return; + } + wx.openDocument({ + filePath: res.tempFilePath, + complete() { + wx.hideLoading(); + }, + }); + }, + fail() { + wx.hideLoading(); + wx.showToast({ title: '文件下载失败', icon: 'none' }); + }, + }); + }, + + /** 展开区吞掉点击,避免点到空白处把卡片收起来 */ + noop() {}, + }, +}); diff --git a/miniprogram/components/customer-trace-panel/index.json b/miniprogram/components/customer-trace-panel/index.json new file mode 100644 index 0000000..467ce29 --- /dev/null +++ b/miniprogram/components/customer-trace-panel/index.json @@ -0,0 +1,3 @@ +{ + "component": true +} diff --git a/miniprogram/components/customer-trace-panel/index.wxml b/miniprogram/components/customer-trace-panel/index.wxml new file mode 100644 index 0000000..956037d --- /dev/null +++ b/miniprogram/components/customer-trace-panel/index.wxml @@ -0,0 +1,138 @@ + + + + + {{dateFrom}} + + 至 + + {{dateTo}} + + + + + + + + + 共 {{total}} 条 + + 加载中… + {{emptyText}} + + + + {{item.customer_name}} + + {{item.delivery_date}} + + + + + {{item.order_code}} + 商品 {{item.item_count}} 项 + + + + 加载中… + {{detailError}} + + 暂无溯源商品 + + + 商品 + 实收 + 报告 + 入库 + 分拣 + 配送拍照 + 送达 + + + + {{sku.item_name}} + {{sku.actual_qty}} {{sku.unit}} + + + + + {{report.label}} + + + + {{file.ext}} + + + + + - + + + + + + + - + + + + + + + + + diff --git a/miniprogram/components/customer-trace-panel/index.wxss b/miniprogram/components/customer-trace-panel/index.wxss new file mode 100644 index 0000000..91b7299 --- /dev/null +++ b/miniprogram/components/customer-trace-panel/index.wxss @@ -0,0 +1,262 @@ +/* 客户溯源面板:订单列表 + 详情就地展开(2026-10-24,替换原两个二级页) */ +.customer-trace-panel { + min-height: 100vh; + background: #f5f7f6; + padding: 20rpx; + box-sizing: border-box; +} + +.customer-trace-panel.is-embedded { + min-height: 0; + background: transparent; + padding: 8rpx var(--xd-module-grid-side, 16rpx) calc(170rpx + env(safe-area-inset-bottom)); +} + +.filter-card { + background: #fff; + border-radius: 16rpx; + padding: 20rpx; + margin-bottom: 16rpx; +} + +.date-row { + display: flex; + align-items: center; + gap: 12rpx; +} + +.date-pill { + background: #f3f6f4; + color: #1f2937; + border-radius: 10rpx; + padding: 10rpx 16rpx; + font-size: 26rpx; +} + +.date-sep { + color: #9ca3af; + font-size: 24rpx; +} + +.search-row { + display: flex; + align-items: center; + gap: 12rpx; + margin-top: 16rpx; +} + +.search-input { + flex: 1; + background: #f3f6f4; + border-radius: 10rpx; + padding: 12rpx 16rpx; + font-size: 26rpx; +} + +.search-btn { + margin: 0 !important; + background: #059669 !important; + color: #fff !important; + border-radius: 10rpx !important; +} + +.list-summary { + color: #6b7280; + font-size: 24rpx; + padding: 4rpx 8rpx 14rpx; +} + +.tip { + text-align: center; + color: #9ca3af; + font-size: 26rpx; + padding: 80rpx 0; +} + +.order-card { + background: #fff; + border-radius: 16rpx; + padding: 22rpx; + margin-bottom: 14rpx; +} + +.order-card.is-open { + border: 1rpx solid #d1fae5; +} + +.order-head { + display: flex; + align-items: center; + justify-content: space-between; +} + +.order-head-right { + display: flex; + align-items: center; + gap: 12rpx; +} + +.order-customer { + font-size: 30rpx; + font-weight: 600; + color: #111827; +} + +.order-date { + font-size: 24rpx; + color: #6b7280; +} + +/* 展开态指示:纯 CSS 箭头(不新增可见文字),向下=可展开、向上=可收起 */ +.order-caret { + width: 14rpx; + height: 14rpx; + border-right: 3rpx solid #9ca3af; + border-bottom: 3rpx solid #9ca3af; + transform: rotate(45deg); + transition: transform 0.2s ease; +} + +.order-caret.is-open { + transform: rotate(-135deg); +} + +.order-meta { + display: flex; + align-items: center; + justify-content: space-between; + margin-top: 12rpx; +} + +.order-code { + font-size: 22rpx; + color: #6b7280; + font-family: monospace; +} + +.order-count { + font-size: 24rpx; + color: #059669; +} + +.order-detail { + margin-top: 18rpx; + border-top: 1rpx solid #f0f2f1; + padding-top: 8rpx; +} + +/* ── 商品表:整屏铺满、超出隐藏,一行一个商品 ── */ +.trace-table { + margin-top: 14rpx; + width: 100%; + border: 1rpx solid #eef4f1; + border-radius: 12rpx; + overflow: hidden; +} + +.trace-tr { + display: flex; + align-items: stretch; + border-top: 1rpx solid #f0f2f1; +} + +.trace-thead { + border-top: none; + background: #f6faf8; +} + +.trace-th, +.trace-td { + box-sizing: border-box; + padding: 10rpx 6rpx; + font-size: 21rpx; + color: #1f2937; + display: flex; + flex-direction: column; + align-items: flex-start; + justify-content: center; + overflow: hidden; + white-space: normal; + word-break: break-all; +} + +.trace-th { + font-size: 18rpx; + font-weight: 600; + color: #6b7280; + line-height: 1.25; +} + +.trace-td.col-name { + font-weight: 600; + font-size: 23rpx; + line-height: 1.35; + color: #111827; +} + +.col-name { + width: 22%; +} + +.col-qty { + width: 12%; + font-size: 19rpx; + color: #059669; +} + +.col-reports { + width: 14%; +} + +.col-stage { + width: 13%; +} + +.stage-time { + font-size: 17rpx; + color: #9ca3af; + line-height: 1.35; +} + +.thumb-row { + display: flex; + flex-wrap: wrap; + gap: 4rpx; +} + +.thumb { + width: 52rpx; + height: 52rpx; + border-radius: 6rpx; + background: #f3f4f6; +} + +.report-item { + width: 100%; + margin-bottom: 6rpx; +} + +.report-label { + display: block; + font-size: 16rpx; + color: #6b7280; + line-height: 1.35; +} + +.report-files { + display: flex; + flex-wrap: wrap; + gap: 4rpx; + margin-top: 3rpx; +} + +/* 文档类报告:用扩展名标签区分(PDF / DOC / XLS…),点击调用 openDocument */ +.report-doc { + padding: 1rpx 5rpx; + border-radius: 4rpx; + border: 1rpx solid #a7f3d0; + background: #ecfdf5; + color: #047857; + font-size: 15rpx; + line-height: 1.4; +} diff --git a/miniprogram/modules/registry.js b/miniprogram/modules/registry.js index c930467..29470d3 100644 --- a/miniprogram/modules/registry.js +++ b/miniprogram/modules/registry.js @@ -217,6 +217,14 @@ const MOBILE_MODULES = [ handler: 'goProductTrace', homeEmbed: 'product-trace-panel', }, + { + id: 'customer-trace', + title: '商品溯源', + subtitle: '查看您订单的商品、实收、照片与报告', + page: '/pages/home/home', + roles: ['order_customer'], + homeEmbed: 'customer-trace-panel', + }, { id: 'mall', title: '下单', diff --git a/miniprogram/pages/home/home.js b/miniprogram/pages/home/home.js index 2f32d14..261bd85 100644 --- a/miniprogram/pages/home/home.js +++ b/miniprogram/pages/home/home.js @@ -40,6 +40,7 @@ const HOME_PANEL_SELECTORS = { 'prep-amend-review': '#prepAmendHomePanel', 'order-entry': '#orderEntryHomePanel', mall: '#mallHomePanel', + 'customer-trace': '#customerTraceHomePanel', }; function pxToRpx(px, windowWidth) { @@ -138,6 +139,7 @@ function pickExclusiveHomeProgress(flags) { function pickDefaultHomeModule(workspaceIds, workspaceMods) { const order = ['mall', + 'customer-trace', 'purchase', 'admin-purchase', 'delivery', diff --git a/miniprogram/pages/home/home.json b/miniprogram/pages/home/home.json index 03ff256..1bb062f 100644 --- a/miniprogram/pages/home/home.json +++ b/miniprogram/pages/home/home.json @@ -24,6 +24,7 @@ "admin-preparations-panel": "/components/admin-preparations-panel/index", "order-entry-panel": "/components/order-entry-panel/index", "mall-panel": "/components/mall-panel/index", + "customer-trace-panel": "/components/customer-trace-panel/index", "van-icon": "@vant/weapp/icon/index", "van-tag": "@vant/weapp/tag/index", "van-button": "@vant/weapp/button/index", diff --git a/miniprogram/pages/home/home.wxml b/miniprogram/pages/home/home.wxml index e395634..e6752c9 100644 --- a/miniprogram/pages/home/home.wxml +++ b/miniprogram/pages/home/home.wxml @@ -438,6 +438,12 @@ embedded="{{true}}" style="--xd-module-grid-side: {{moduleGridSide}};" /> + diff --git a/miniprogram/utils/request.js b/miniprogram/utils/request.js index 4b3d41e..0fd7ce4 100644 --- a/miniprogram/utils/request.js +++ b/miniprogram/utils/request.js @@ -1431,8 +1431,26 @@ function saveMallAddress(address) { return request('/mobile/mall/address', { method: 'PUT', data: { address } }).then((body) => (body && body.data) || {}); } + +/** 下单客户溯源(order_customer):订单维度,只返回展示字段。 */ +function fetchCustomerTraceOrders(params = {}) { + const parts = []; + if (params.q) parts.push(`q=${encodeURIComponent(params.q)}`); + if (params.date_from) parts.push(`date_from=${encodeURIComponent(params.date_from)}`); + if (params.date_to) parts.push(`date_to=${encodeURIComponent(params.date_to)}`); + if (params.limit) parts.push(`limit=${encodeURIComponent(params.limit)}`); + if (params.offset) parts.push(`offset=${encodeURIComponent(params.offset)}`); + const qs = parts.length ? `?${parts.join('&')}` : ''; + return request(`/mobile/customer-trace/orders${qs}`); +} +function fetchCustomerTraceOrder(orderCode) { + return request(`/mobile/customer-trace/orders/${encodeURIComponent(orderCode || '')}`); +} + module.exports = { request, + fetchCustomerTraceOrders, + fetchCustomerTraceOrder, fetchMallBootstrap, fetchMallProducts, submitMallOrder, diff --git a/server/src/routes/mobile.ts b/server/src/routes/mobile.ts index 26fdf85..d1b8125 100644 --- a/server/src/routes/mobile.ts +++ b/server/src/routes/mobile.ts @@ -14,12 +14,14 @@ import mobileAdminRoutes from './mobile/mobileAdminRoutes'; import mobileUiPreferenceRoutes from './mobile/mobileUiPreferenceRoutes'; import mobileWeighOtaRoutes from './mobile/mobileWeighOtaRoutes'; import mobileMallRoutes from './mobile/mobileMallRoutes'; +import mobileCustomerTraceRoutes from './mobile/mobileCustomerTraceRoutes'; const router = Router(); router.use(mobileNotifyRoutes); router.use(mobileAuthRoutes); router.use(mobileMallRoutes); +router.use(mobileCustomerTraceRoutes); router.use(mobileBadgeRoutes); router.use(mobileDeliveryRoutes); router.use(mobileSupplierRoutes); diff --git a/server/src/routes/mobile/mobileCustomerTraceRoutes.ts b/server/src/routes/mobile/mobileCustomerTraceRoutes.ts new file mode 100644 index 0000000..2469617 --- /dev/null +++ b/server/src/routes/mobile/mobileCustomerTraceRoutes.ts @@ -0,0 +1,65 @@ +import { Router, Response } from 'express'; +import { authMiddleware, type AuthRequest } from '../../middleware/auth'; +import { loadTenantContext } from '../../services/tenantScope'; +import { requireMobileRoles } from './mobileShared'; +import { searchCustomerTraceOrders, getCustomerTraceOrder } from '../../services/customerTraceService'; +import { + resolveOrderCustomerTraceAccess, + canViewCustomerTraceReports, +} from '../../services/customerTraceAccessService'; + +/** 小程序 · 下单客户商品溯源:只允许 order_customer,只能看自己绑定客户的订单。 */ +const router = Router(); + +router.get('/customer-trace/orders', authMiddleware, async (req: AuthRequest, res: Response) => { + try { + requireMobileRoles(req, ['order_customer']); + const ctx = await loadTenantContext(req.userId); + if (!ctx) return res.status(401).json({ error: 'invalid_token', error_description: '请先登录' }); + const access = await resolveOrderCustomerTraceAccess(req.userId); + const result = await searchCustomerTraceOrders({ + branchCode: ctx.branchCode || null, + customerScope: access.customerScope, + q: String(req.query?.q || ''), + dateFrom: String(req.query?.date_from || ''), + dateTo: String(req.query?.date_to || ''), + limit: Number(req.query?.limit) || 20, + offset: Number(req.query?.offset) || 0, + }); + return res.json({ data: result.rows, total: result.total }); + } catch (error: any) { + return res.status(error?.status || 500).json({ + error: error?.code || 'server_error', + error_description: error?.message || '加载溯源订单失败', + }); + } +}); + +router.get('/customer-trace/orders/:orderCode', authMiddleware, async (req: AuthRequest, res: Response) => { + try { + requireMobileRoles(req, ['order_customer']); + const ctx = await loadTenantContext(req.userId); + if (!ctx) return res.status(401).json({ error: 'invalid_token', error_description: '请先登录' }); + const access = await resolveOrderCustomerTraceAccess(req.userId); + const data = await getCustomerTraceOrder({ + orderCode: String(req.params.orderCode || ''), + branchCode: ctx.branchCode || null, + customerScope: access.customerScope, + }); + if (!data) { + return res.status(404).json({ error: 'not_found', error_description: '未找到该订单的溯源记录' }); + } + const reportsAllowed = canViewCustomerTraceReports(access, data.order.customer_code); + if (!reportsAllowed) { + data.items = data.items.map((item) => ({ ...item, quality_reports: [] })); + } + return res.json({ data: { ...data, reports_allowed: reportsAllowed } }); + } catch (error: any) { + return res.status(error?.status || 500).json({ + error: error?.code || 'server_error', + error_description: error?.message || '加载溯源详情失败', + }); + } +}); + +export default router; diff --git a/server/src/services/customerTraceAccessService.ts b/server/src/services/customerTraceAccessService.ts new file mode 100644 index 0000000..79d0b97 --- /dev/null +++ b/server/src/services/customerTraceAccessService.ts @@ -0,0 +1,39 @@ +import { pool } from '../db'; + +export type CustomerTraceAccess = { + customerScope: string[]; + reportCustomerCodes: Set; + reportsEnabled: boolean; +}; + +/** + * 下单客户溯源范围:只认 customer_portal_users 自己绑定,不读 customer_trace_users。 + * 无绑定 ⇒ 空集 + 报告关闭(fail closed)。 + */ +export async function resolveOrderCustomerTraceAccess( + userId: string | undefined +): Promise { + if (!userId) return { customerScope: [], reportCustomerCodes: new Set(), reportsEnabled: false }; + const rows = await pool.query( + `SELECT DISTINCT customer_code FROM customer_portal_users + WHERE user_id = $1 AND COALESCE(status, 1) = 1`, + [userId] + ); + const scope = rows.rows + .map((row) => String(row.customer_code || '').trim()) + .filter(Boolean); + // 供应商 profiles 没有 trace_reports_enabled(主系统才有);下单客户默认允许看自己订单的报告。 + return { + customerScope: scope, + reportCustomerCodes: new Set(scope), + reportsEnabled: scope.length > 0, + }; +} + +export function canViewCustomerTraceReports( + access: CustomerTraceAccess, + customerCode: string | null | undefined +): boolean { + const owner = String(customerCode || '').trim(); + return Boolean(owner) && access.reportsEnabled && access.reportCustomerCodes.has(owner); +} diff --git a/server/src/services/customerTraceService.ts b/server/src/services/customerTraceService.ts new file mode 100644 index 0000000..872f1e9 --- /dev/null +++ b/server/src/services/customerTraceService.ts @@ -0,0 +1,315 @@ +import { pool } from '../db'; +import { buildTraceKey, getProductTrace } from './productTraceService'; + +/** + * 客户溯源 · 订单维度(2026-10-24 开发者确认)。 + * + * 与内部 `/trace/search` 的“批次行”不同:客户看到的是**一张订单一行**, + * 展开后每个商品一行,展示字段沿用当前溯源详情(供应商/产地/实收/入库/链路照片)。 + * + * 权限:`customerScope` 由调用方(traceRoutes)从 `customer_trace_users` 解析; + * `undefined` = 内部账号不收窄;`[]` = 无可见客户(fail closed,不打库)。 + */ + +export type CustomerTraceOrderRow = { + order_code: string; + delivery_date: string | null; + item_count: number; + customer_name: string | null; +}; + +export type CustomerTraceOrderDetail = { + order: { + order_code: string; + delivery_date: string | null; + customer_code: string | null; + customer_name: string | null; + }; + delivery_person?: { + person_code: string | null; + person_name: string | null; + health_cert: { + cert_url: string; + expires_at: string | null; + expired: boolean; + } | null; + } | null; + items: Array<{ + trace_code: string; + item_name: string; + sku_code: string | null; + origin: string | null; + supplier_name: string | null; + actual_qty: number | null; + unit: string | null; + inbound_at: string | null; + quality_rating: string | null; + /** 内部账号专属:公开溯源页地址;客户账号不返回该字段 */ + public_url?: string | null; + quality_reports: Array<{ + report_label: string | null; + report_type: string | null; + tested_at: string | null; + valid_to: string | null; + file_urls: string[]; + }>; + timeline: Array<{ + at: string | null; + title: string; + detail?: string; + photos?: Array<{ url: string; time: string | null; source: string }>; + }>; + }>; +}; + +const trimText = (value: unknown) => String(value ?? '').trim(); +const todayYmd = () => + new Intl.DateTimeFormat('en-CA', { timeZone: 'Asia/Shanghai' }).format(new Date()); + +const ORDER_DAY_SQL = `NULLIF(TRIM(o.delivery_date::text), '')::date`; + +/** 日期轴:配送日(默认)与下单日(中国时区自然日) */ +export type CustomerTraceDateField = 'delivery_date' | 'created_at'; + +function orderDaySql(field?: CustomerTraceDateField | null): string { + if (field === 'created_at') return `(o.created_at AT TIME ZONE 'Asia/Shanghai')::date`; + return ORDER_DAY_SQL; +} + +function buildOrderWhere(input: { + branchCode?: string | null; + customerScope?: string[] | null; + q?: string; + from?: string | null; + to?: string | null; + dateField?: CustomerTraceDateField | null; +}): { whereSql: string; params: unknown[] } { + const params: unknown[] = []; + const where: string[] = [ + 'o.deleted_at IS NULL', + 'COALESCE(oi.is_returned, false) = false', + 'NULLIF(TRIM(oi.sku_code), \'\') IS NOT NULL', + ]; + const branch = trimText(input.branchCode); + if (branch) { + params.push(branch); + where.push(`o.branch_code IS NOT DISTINCT FROM $${params.length}::text`); + } + if (Array.isArray(input.customerScope)) { + params.push(input.customerScope); + where.push(`o.customer_code = ANY($${params.length}::text[])`); + } + const q = trimText(input.q); + if (q) { + params.push(`%${q.replace(/[%_]/g, '\\$&')}%`); + where.push(`( + o.order_code ILIKE $${params.length}::text + OR COALESCE(oi.item_name, '') ILIKE $${params.length}::text + OR COALESCE(s.sku_name, '') ILIKE $${params.length}::text + )`); + } + const from = trimText(input.from); + const to = trimText(input.to); + const daySql = orderDaySql(input.dateField); + if (from && to) { + params.push(from, to); + where.push(`${daySql} >= $${params.length - 1}::date`); + where.push(`${daySql} <= $${params.length}::date`); + } else if (!q) { + // 无关键词且无显式区间 ⇒ 默认今天(与现有溯源页默认一致) + params.push(todayYmd()); + where.push(`${daySql} = $${params.length}::date`); + } + return { whereSql: where.join(' AND '), params }; +} + +export async function searchCustomerTraceOrders(input: { + branchCode?: string | null; + customerScope?: string[] | null; + q?: string; + dateFrom?: string | null; + dateTo?: string | null; + dateField?: CustomerTraceDateField | null; + limit?: number; + offset?: number; +}): Promise<{ rows: CustomerTraceOrderRow[]; total: number }> { + if (Array.isArray(input.customerScope) && input.customerScope.length === 0) { + return { rows: [], total: 0 }; + } + const limit = Math.min(Math.max(Number(input.limit) || 20, 1), 100); + const offset = Math.max(0, Math.floor(Number(input.offset) || 0)); + const { whereSql, params } = buildOrderWhere({ + branchCode: input.branchCode, + customerScope: input.customerScope, + q: input.q, + from: input.dateFrom, + to: input.dateTo, + dateField: input.dateField, + }); + const fromSql = `FROM orders o + INNER JOIN order_items oi ON oi.order_code = o.order_code + LEFT JOIN skus s ON s.sku_code = oi.sku_code + LEFT JOIN customers c ON c.customer_code = o.customer_code`; + + const countResult = await pool.query( + `SELECT COUNT(DISTINCT o.order_code)::int AS cnt ${fromSql} WHERE ${whereSql}`, + params + ); + const total = Number(countResult.rows[0]?.cnt) || 0; + if (total === 0) return { rows: [], total: 0 }; + + const listParams = [...params, limit, offset]; + const result = await pool.query( + `SELECT o.order_code, + to_char(${ORDER_DAY_SQL}, 'YYYY-MM-DD') AS delivery_date, + COUNT(DISTINCT oi.sku_code)::int AS item_count, + MAX(c.company_name) AS customer_name + ${fromSql} + WHERE ${whereSql} + GROUP BY o.order_code, ${ORDER_DAY_SQL} + ORDER BY ${ORDER_DAY_SQL} DESC NULLS LAST, o.order_code DESC + LIMIT $${listParams.length - 1}::int OFFSET $${listParams.length}::int`, + listParams + ); + return { + rows: result.rows.map((row) => ({ + order_code: String(row.order_code), + delivery_date: row.delivery_date != null ? String(row.delivery_date) : null, + item_count: Number(row.item_count) || 0, + customer_name: row.customer_name != null ? String(row.customer_name) : null, + })), + total, + }; +} + +/** 订单详情:只返回当前溯源页会展示的字段(不下发公开链接/采购价/内部日志)。 */ +export async function getCustomerTraceOrder(input: { + orderCode: string; + branchCode?: string | null; + customerScope?: string[] | null; + requestHost?: string | null; + /** 内部账号(有 product_trace)才返回 public_url;客户账号必须为 false */ + includeInternalFields?: boolean; +}): Promise { + if (Array.isArray(input.customerScope) && input.customerScope.length === 0) return null; + const orderCode = trimText(input.orderCode); + if (!orderCode) return null; + + const params: unknown[] = [orderCode]; + const where: string[] = ['o.order_code = $1::text', 'o.deleted_at IS NULL']; + const branch = trimText(input.branchCode); + if (branch) { + params.push(branch); + where.push(`o.branch_code IS NOT DISTINCT FROM $${params.length}::text`); + } + if (Array.isArray(input.customerScope)) { + params.push(input.customerScope); + where.push(`o.customer_code = ANY($${params.length}::text[])`); + } + const orderRow = ( + await pool.query( + `SELECT o.order_code, + to_char(${ORDER_DAY_SQL}, 'YYYY-MM-DD') AS delivery_date, + o.customer_code, + c.company_name + FROM orders o + LEFT JOIN customers c ON c.customer_code = o.customer_code + WHERE ${where.join(' AND ')} + LIMIT 1`, + params + ) + ).rows[0]; + if (!orderRow) return null; + + const itemRows = ( + await pool.query( + `SELECT oi.sku_code, oi.item_name, + i.inbound_batch_no + FROM order_items oi + LEFT JOIN LATERAL ( + SELECT i2.inbound_batch_no + FROM inspections i2 + WHERE i2.order_code = oi.order_code + AND i2.sku_code IS NOT DISTINCT FROM oi.sku_code + AND NULLIF(TRIM(i2.inbound_batch_no), '') IS NOT NULL + ORDER BY i2.inspection_time DESC NULLS LAST + LIMIT 1 + ) i ON true + WHERE oi.order_code = $1::text + AND COALESCE(oi.is_returned, false) = false + ORDER BY oi.sort_order ASC NULLS LAST, oi.id ASC + LIMIT 100`, + [orderCode] + ) + ).rows; + + const items: CustomerTraceOrderDetail['items'] = []; + for (const row of itemRows) { + const skuCode = trimText(row.sku_code); + if (!skuCode) continue; + const batchNo = trimText(row.inbound_batch_no); + const traceCode = batchNo || buildTraceKey(orderCode, skuCode); + try { + const detail = await getProductTrace({ + batchNo: traceCode, + mode: 'internal', + branchCode: input.branchCode || null, + requestHost: input.requestHost || null, + }); + items.push({ + trace_code: detail.trace_code, + item_name: detail.item_name || trimText(row.item_name) || skuCode, + sku_code: detail.sku_code || skuCode, + origin: detail.origin ?? null, + supplier_name: detail.supplier_name ?? null, + actual_qty: detail.actual_qty ?? null, + unit: detail.unit ?? null, + inbound_at: detail.inbound_at ?? null, + quality_rating: detail.quality_rating ?? null, + ...(input.includeInternalFields ? { public_url: detail.public_url || null } : {}), + quality_reports: (detail.quality_reports || []).map((report) => { + const raw = report as Record; + return { + report_label: report.report_label ?? null, + report_type: report.report_type ?? null, + tested_at: typeof raw.tested_at === 'string' ? raw.tested_at : null, + valid_to: typeof raw.valid_to === 'string' ? raw.valid_to : null, + file_urls: report.file_urls || [], + }; + }), + timeline: (detail.timeline || []).map((step) => ({ + at: step.at ?? null, + title: step.title, + detail: step.detail, + photos: (step as { photos?: Array<{ url: string; time: string | null; source: string }> }).photos || [], + })), + }); + } catch { + // 单行取详情失败不拖垮整单:退化为订单行本身的核心信息 + items.push({ + trace_code: traceCode, + item_name: trimText(row.item_name) || skuCode, + sku_code: skuCode, + origin: null, + supplier_name: null, + actual_qty: null, + unit: null, + inbound_at: null, + quality_rating: null, + ...(input.includeInternalFields ? { public_url: null } : {}), + quality_reports: [], + timeline: [], + }); + } + } + + return { + order: { + order_code: String(orderRow.order_code), + delivery_date: orderRow.delivery_date != null ? String(orderRow.delivery_date) : null, + customer_code: orderRow.customer_code != null ? String(orderRow.customer_code) : null, + customer_name: orderRow.company_name != null ? String(orderRow.company_name) : null, + }, + items, + }; +} diff --git a/server/tests/customerTraceAndMall.test.ts b/server/tests/customerTraceAndMall.test.ts new file mode 100644 index 0000000..fb80ad4 --- /dev/null +++ b/server/tests/customerTraceAndMall.test.ts @@ -0,0 +1,36 @@ +import { createRequire } from 'node:module'; +import { readFileSync } from 'node:fs'; +import { describe, expect, it } from 'vitest'; + +const require2 = createRequire(import.meta.url); +const read = (rel: string) => readFileSync(new URL(`../${rel}`, import.meta.url), 'utf8'); +const access = read('src/services/customerTraceAccessService.ts'); +const trace = read('src/services/customerTraceService.ts'); +const routes = read('src/routes/mobile/mobileCustomerTraceRoutes.ts'); +const registry = require2('../../miniprogram/modules/registry.js') as { + buildVisibleModules: (data: Record) => Array<{ id: string }>; +}; + +describe('下单客户商品溯源 + 首页 mall 回归', () => { + it('只认 order_customer + customer_portal_users 自身绑定', () => { + expect(routes).toContain("['order_customer']"); + expect(access).toContain('customer_portal_users'); + expect(access).not.toContain('FROM customer_trace_users'); + expect(access).toContain('COALESCE(status, 1) = 1'); + }); + + it('不返回公开链接/健康证,去掉 includePickingPhotos/staffHealthCertificate', () => { + expect(trace).not.toContain('includePickingPhotos'); + expect(trace).not.toContain('staffHealthCertificateService'); + expect(routes).not.toContain('includeInternalFields'); + expect(trace).toContain('...(input.includeInternalFields ? { public_url'); + }); + + it('小程序 customer-trace 模块仅 order_customer,首页内嵌;mall 在 order_customer 下仍可见', () => { + const mods = registry.buildVisibleModules({ roleType: 'order_customer' }); + expect(mods.map((m) => m.id)).toContain('mall'); + expect(mods.map((m) => m.id)).toContain('customer-trace'); + expect(readFileSync(new URL('../../miniprogram/pages/home/home.wxml', import.meta.url), 'utf8')).toContain("activeHomeModuleId === 'customer-trace'"); + expect(readFileSync(new URL('../../miniprogram/utils/request.js', import.meta.url), 'utf8')).toContain('/mobile/customer-trace/orders'); + }); +});