- T1 资金/库存/报价/自采 P1(BIZ-1/2/3/4/10/13/14) - T2 主系统反向事件墓碑/改派/孤儿处理(BIZ-6/8/9) - T3 选分公司 ticket、trust proxy、角色权限收口(SEC-2/3/4) - T4 缺列/RLS/tenant 名单/FK/迁移执行器(DATA-1..8) - T5 401 登出/分页/映射口径/blob/ZIP 中文名(FE-1..4/BIZ-15) - T6 测试脚本目标守卫/config fail-fast/容器配置(OPS-2..8) - T7 前后端测试与 lint 门禁清零 - T8 应付卡片按关联订单日(口径 A) - T9 存储对象全链路归属校验、敏感列禁写、审计 target_id 超长修复
902 lines
34 KiB
TypeScript
902 lines
34 KiB
TypeScript
import { pool } from '../db';
|
||
import { getTenantDbStore } from './tenantDbContext';
|
||
import { withActiveTenantFallback } from './tenantSchemaFallback';
|
||
import { listQualityReportsForTrace, validityStatusLabel } from './qualityReportService';
|
||
import { signedExistingPhotos } from './inspectionReviewService';
|
||
|
||
export type TraceViewMode = 'internal' | 'public';
|
||
|
||
function trimText(value: unknown): string {
|
||
return String(value || '').trim();
|
||
}
|
||
|
||
/** 无批次行的溯源标识:`订单号::SKU`(内部与公开详情共用) */
|
||
const TRACE_KEY_SEP = '::';
|
||
|
||
/**
|
||
* 从上传文件名解析**拍摄/上传时间**。
|
||
*
|
||
* `buildTimedPhotoBasename` 生成 `<Date.now()>-<随机>.<ext>`,补拍与验收照同规则
|
||
* (`delivery-loading/…` 也走同一函数),故文件名首段即毫秒时间戳。
|
||
* 实测 br002:补拍 694/694、验收 2599/2599 全部可解析;验收照解析值与
|
||
* `inspection_time` 秒级一致。
|
||
*
|
||
* ⚠️ 这是**唯一**可得的补拍时间来源:`picking_items` 无拍摄时间列,
|
||
* `created_at` 是拣货时间(实测与补拍时间差 8 小时且多图相同),不可替代。
|
||
*/
|
||
export function photoTimeFromPath(path: unknown): string | null {
|
||
const name = String(path || '');
|
||
const match = name.match(/(?:^|\/)(\d{13})(?:-|\.)/);
|
||
if (!match) return null;
|
||
const epoch = Number(match[1]);
|
||
if (!Number.isFinite(epoch) || epoch <= 0) return null;
|
||
return new Date(epoch).toISOString();
|
||
}
|
||
|
||
export type TracePhoto = { path: string; url: string; time: string | null };
|
||
|
||
export function buildTraceKey(orderCode: string, skuCode: string): string {
|
||
return `${trimText(orderCode)}${TRACE_KEY_SEP}${trimText(skuCode)}`;
|
||
}
|
||
|
||
export function parseTraceKey(raw: unknown): { orderCode: string; skuCode: string } | null {
|
||
const value = trimText(raw);
|
||
const at = value.indexOf(TRACE_KEY_SEP);
|
||
if (at <= 0) return null;
|
||
const orderCode = value.slice(0, at).trim();
|
||
const skuCode = value.slice(at + TRACE_KEY_SEP.length).trim();
|
||
if (!orderCode || !skuCode) return null;
|
||
return { orderCode, skuCode };
|
||
}
|
||
|
||
/**
|
||
* 照片存在性过滤 + 签名 + 时间。
|
||
*
|
||
* 与验收复核 / 订单详情照片一致:先 `storage.exists` 再签名,**避免文件已删时裂图**。
|
||
* 返回相对签名路径(`/api/storage/...`),由前端按同源或 apiBase 补绝对地址;
|
||
* `time` 取自文件名毫秒时间戳(见 `photoTimeFromPath`)。
|
||
*/
|
||
async function loadTracePhotos(
|
||
photos: unknown,
|
||
bucket: 'inspection-photos' | 'delivery-photos' = 'inspection-photos',
|
||
branchCode?: string | null
|
||
): Promise<TracePhoto[]> {
|
||
const signed = await signedExistingPhotos(photos, bucket, { branchCode: branchCode || null });
|
||
return signed.map((item) => ({
|
||
path: item.path,
|
||
url: item.url,
|
||
time: photoTimeFromPath(item.path),
|
||
}));
|
||
}
|
||
|
||
/** 兼容旧客户端/小程序的纯 URL 数组 */
|
||
function photoUrls(photos: TracePhoto[]): string[] {
|
||
return photos.map((item) => item.url);
|
||
}
|
||
|
||
type TracePhotoSource = {
|
||
loading_photos: TracePhoto[];
|
||
direct_delivery_photos: TracePhoto[];
|
||
};
|
||
|
||
/**
|
||
* 与订单行关联的两类非验收照:配送补拍(`picking_items.loading_photos`,加菜同列)
|
||
* 与直送照(`purchase_orders.direct_delivery_photos`)。
|
||
*
|
||
* 两种"免入库"判定**分别读取、不合并**(供应商免入库 `skip_inbound` 与商品直送
|
||
* `skus.direct_delivery` 是两种货,规则见 supplier-freeze)。
|
||
*/
|
||
async function loadOrderLineTracePhotos(
|
||
orderCode: string,
|
||
skuCode: string,
|
||
branchCode?: string | null
|
||
): Promise<TracePhotoSource> {
|
||
const empty: TracePhotoSource = { loading_photos: [], direct_delivery_photos: [] };
|
||
const order = trimText(orderCode);
|
||
const sku = trimText(skuCode);
|
||
if (!order || !sku) return empty;
|
||
|
||
const params: unknown[] = [order, sku];
|
||
let loadingSql = `
|
||
SELECT pi.loading_photos
|
||
FROM picking_items pi
|
||
WHERE pi.order_code = $1
|
||
AND COALESCE(NULLIF(TRIM(pi.sku_code), ''), (
|
||
SELECT NULLIF(TRIM(oi.sku_code), '') FROM order_items oi WHERE oi.id = pi.order_item_id LIMIT 1
|
||
)) = $2
|
||
AND COALESCE(array_length(pi.loading_photos, 1), 0) > 0`;
|
||
if (branchCode) {
|
||
params.push(branchCode);
|
||
loadingSql += ` AND pi.branch_code IS NOT DISTINCT FROM $${params.length}`;
|
||
}
|
||
const loadingResult = await pool.query(loadingSql, params);
|
||
|
||
const directParams: unknown[] = [order, sku];
|
||
let directSql = `
|
||
SELECT po.direct_delivery_photos
|
||
FROM purchase_orders po
|
||
WHERE po.order_code = $1
|
||
AND NULLIF(TRIM(po.sku_code), '') = $2
|
||
AND COALESCE(array_length(po.direct_delivery_photos, 1), 0) > 0`;
|
||
if (branchCode) {
|
||
directParams.push(branchCode);
|
||
directSql += ` AND po.branch_code IS NOT DISTINCT FROM $${directParams.length}`;
|
||
}
|
||
const directResult = await pool.query(directSql, directParams);
|
||
|
||
const flatten = (rows: Array<Record<string, unknown>>, column: string): string[] => {
|
||
const out: string[] = [];
|
||
const seen = new Set<string>();
|
||
for (const row of rows) {
|
||
const raw = row[column];
|
||
const list = Array.isArray(raw) ? raw : raw != null ? [raw] : [];
|
||
for (const item of list) {
|
||
const path = trimText(item);
|
||
if (!path || seen.has(path)) continue;
|
||
seen.add(path);
|
||
out.push(path);
|
||
}
|
||
}
|
||
return out;
|
||
};
|
||
|
||
return {
|
||
loading_photos: await loadTracePhotos(
|
||
flatten(loadingResult.rows, 'loading_photos'),
|
||
'inspection-photos'
|
||
),
|
||
direct_delivery_photos: await loadTracePhotos(
|
||
flatten(directResult.rows, 'direct_delivery_photos'),
|
||
'delivery-photos'
|
||
),
|
||
};
|
||
}
|
||
|
||
/**
|
||
* 公开溯源页所属的 Web 站点基址。
|
||
*
|
||
* ⚠️ 不回退请求 Host:内部溯源接口的 Host 是 **API 域**(如 test-api),
|
||
* 而 API 域并不服务前端路由(`deploy/nginx.api-proxy.conf` 只反代 `/api/`,
|
||
* `/` 是 `try_files … =404`)。回退 Host 会让二维码与复制出去的公开链
|
||
* 指向 API 域而 404。
|
||
*
|
||
* 未配置时返回空串 → 调用方得到**相对路径** `/t/<code>`,由前端按当前
|
||
* Web 源拼绝对地址(Web 用 `window.location.origin`,小程序用 `config.webBase`)。
|
||
* 生产建议显式配置 `PUBLIC_TRACE_BASE_URL`(或回退 `WEB_PUBLIC_URL`)。
|
||
*/
|
||
function publicBaseUrl(): string {
|
||
const fromEnv = trimText(process.env.PUBLIC_TRACE_BASE_URL || process.env.WEB_PUBLIC_URL);
|
||
if (fromEnv) return fromEnv.replace(/\/+$/, '');
|
||
const cors = trimText(process.env.CORS_ORIGINS).split(',')[0]?.trim();
|
||
if (cors && /^https?:\/\//i.test(cors)) return cors.replace(/\/+$/, '');
|
||
return '';
|
||
}
|
||
|
||
/**
|
||
* `hostHint` 参数保留仅为兼容既有调用点,**不再参与拼接**(见 `publicBaseUrl` 说明)。
|
||
* @deprecated 新调用请直接用 `buildPublicTraceUrl(batchNo)`;hostHint 会被忽略。
|
||
*/
|
||
export function buildPublicTraceUrl(batchNo: string, hostHint?: string | null): string {
|
||
void hostHint;
|
||
const base = publicBaseUrl();
|
||
const code = encodeURIComponent(trimText(batchNo));
|
||
if (!base) return `/t/${code}`;
|
||
return `${base}/t/${code}`;
|
||
}
|
||
|
||
async function loadInventoryByBatch(batchNo: string, branchCode?: string | null) {
|
||
const params: unknown[] = [batchNo];
|
||
let sql = `
|
||
SELECT inv.id, inv.batch_no, inv.sku_code, inv.quantity, inv.available_qty,
|
||
inv.supplier_code, inv.cost_price, inv.production_date, inv.expiry_date,
|
||
inv.branch_code, inv.status, inv.created_at,
|
||
COALESCE(s.sku_name, inv.sku_code) AS sku_name,
|
||
COALESCE(s.origin, '') AS origin,
|
||
COALESCE(s.unit, '') AS sku_unit,
|
||
COALESCE(sup.company_name, inv.supplier_code, '') AS supplier_name
|
||
FROM inventory inv
|
||
LEFT JOIN skus s ON s.sku_code = inv.sku_code
|
||
LEFT JOIN suppliers sup ON sup.supplier_code = inv.supplier_code
|
||
WHERE inv.batch_no = $1`;
|
||
if (branchCode) {
|
||
params.push(branchCode);
|
||
sql += ` AND inv.branch_code IS NOT DISTINCT FROM $${params.length}`;
|
||
}
|
||
sql += ` LIMIT 1`;
|
||
const result = await pool.query(sql, params);
|
||
return result.rows[0] || null;
|
||
}
|
||
|
||
async function loadInspectionByInboundBatch(batchNo: string, branchCode?: string | null) {
|
||
const params: unknown[] = [batchNo];
|
||
let sql = `
|
||
SELECT i.id, i.order_code, i.sku_code, i.item_name, i.supplier_code, i.source_type,
|
||
i.prepare_qty, i.actual_qty, i.unit, i.quality_rating, i.purchase_price,
|
||
i.inspection_photos, i.inspection_time, i.inspector_id, i.branch_code,
|
||
i.inbound_batch_no, i.production_date_month,
|
||
COALESCE(sup.company_name, i.supplier_code, '') AS supplier_name,
|
||
COALESCE(NULLIF(i.item_name, ''), s.sku_name, i.sku_code) AS display_name,
|
||
COALESCE(s.origin, '') AS origin
|
||
FROM inspections i
|
||
LEFT JOIN skus s ON s.sku_code = i.sku_code
|
||
LEFT JOIN suppliers sup ON sup.supplier_code = i.supplier_code
|
||
WHERE i.inbound_batch_no = $1`;
|
||
if (branchCode) {
|
||
params.push(branchCode);
|
||
sql += ` AND i.branch_code IS NOT DISTINCT FROM $${params.length}`;
|
||
}
|
||
sql += ` ORDER BY i.inspection_time DESC NULLS LAST LIMIT 1`;
|
||
const result = await pool.query(sql, params);
|
||
return result.rows[0] || null;
|
||
}
|
||
|
||
/** 与库存管理页口径一致的流水类型中文标签;未收录类型原样展示 */
|
||
const TRACE_LOG_TYPE_LABELS: Record<string, string> = {
|
||
inspection_in: '验收入库',
|
||
stock_in: '独立入库',
|
||
picking_out: '分拣出库',
|
||
delivery_loading_out: '配送核货出库',
|
||
delivery_loading_restore: '发车撤销回补',
|
||
processing_out: '加工出库',
|
||
adjust: '库存调整',
|
||
order_item_return: '退货回冲入库',
|
||
in: '入库',
|
||
out: '出库',
|
||
transfer: '调拨',
|
||
return: '退货',
|
||
};
|
||
|
||
function chinaTodayYmd(): string {
|
||
return new Intl.DateTimeFormat('en-CA', { timeZone: 'Asia/Shanghai' }).format(new Date());
|
||
}
|
||
|
||
function isYmd(value: string): boolean {
|
||
return /^\d{4}-\d{2}-\d{2}$/.test(value);
|
||
}
|
||
|
||
export type TraceSearchDateField = 'inbound' | 'order_created';
|
||
|
||
/** 非法 / 空 → inbound,保证旧客户端与小程序行为不变 */
|
||
export function parseTraceSearchDateField(raw: unknown): TraceSearchDateField {
|
||
return String(raw || '').trim() === 'order_created' ? 'order_created' : 'inbound';
|
||
}
|
||
|
||
export type TraceSearchHit = {
|
||
/** 溯源标识:有批次=批次号;无批次(免入库/直送/加菜)=`订单号::SKU` */
|
||
trace_code: string;
|
||
/** 无批次行为 null(不参与入库日轴) */
|
||
batch_no: string | null;
|
||
/** 是否来自验收入库批次 */
|
||
has_batch: boolean;
|
||
item_name: string;
|
||
order_code: string | null;
|
||
/** 有批次行=验收入库时间;无批次行=null(改看 loading_at) */
|
||
inspection_time: string | null;
|
||
/** 无批次行的配送补拍时间(取自补拍照片文件名时间戳;无照片则 null) */
|
||
loading_at: string | null;
|
||
};
|
||
|
||
export async function searchTraceBatches(input: {
|
||
query?: string;
|
||
/** 中国日 YYYY-MM-DD;无区间且无关键词时默认当天 */
|
||
date?: string;
|
||
dateFrom?: string | null;
|
||
dateTo?: string | null;
|
||
/** 有日期区间时生效;无日期的全历史关键词搜忽略此轴 */
|
||
dateField?: TraceSearchDateField | string | null;
|
||
branchCode?: string | null;
|
||
limit?: number;
|
||
offset?: number;
|
||
}): Promise<{ rows: TraceSearchHit[]; total: number }> {
|
||
const q = trimText(input.query);
|
||
let from = isYmd(trimText(input.dateFrom)) ? trimText(input.dateFrom) : '';
|
||
let to = isYmd(trimText(input.dateTo)) ? trimText(input.dateTo) : '';
|
||
const dateRaw = trimText(input.date);
|
||
if (!from && !to && isYmd(dateRaw)) {
|
||
from = dateRaw;
|
||
to = dateRaw;
|
||
}
|
||
if (from && !to) to = from;
|
||
if (to && !from) from = to;
|
||
if (from && to && from > to) {
|
||
const swap = from;
|
||
from = to;
|
||
to = swap;
|
||
}
|
||
const hasRange = Boolean(from && to);
|
||
if (!hasRange && !q) {
|
||
from = chinaTodayYmd();
|
||
to = from;
|
||
}
|
||
const activeRange = Boolean(from && to);
|
||
const dateField = activeRange ? parseTraceSearchDateField(input.dateField) : 'inbound';
|
||
const useOrderCreated = activeRange && dateField === 'order_created';
|
||
const limit = Math.min(Math.max(Number(input.limit) || (activeRange && !q ? 50 : 20), 1), 100);
|
||
const offset = Math.max(0, Math.floor(Number(input.offset) || 0));
|
||
|
||
const params: unknown[] = [];
|
||
const where: string[] = [
|
||
'i.inbound_batch_no IS NOT NULL',
|
||
`TRIM(i.inbound_batch_no) <> ''`,
|
||
];
|
||
|
||
if (input.branchCode) {
|
||
params.push(input.branchCode);
|
||
where.push(`i.branch_code IS NOT DISTINCT FROM $${params.length}`);
|
||
}
|
||
|
||
if (activeRange) {
|
||
const dayExpr = useOrderCreated
|
||
? `(o.created_at AT TIME ZONE 'Asia/Shanghai')::date`
|
||
: `(i.inspection_time AT TIME ZONE 'Asia/Shanghai')::date`;
|
||
params.push(from);
|
||
const fromIdx = params.length;
|
||
params.push(to);
|
||
const toIdx = params.length;
|
||
where.push(`${dayExpr} >= $${fromIdx}::date AND ${dayExpr} <= $${toIdx}::date`);
|
||
}
|
||
|
||
if (q) {
|
||
params.push(q);
|
||
const batchIdx = params.length;
|
||
params.push(`%${q.replace(/[%_]/g, '\\$&')}%`);
|
||
const likeIdx = params.length;
|
||
where.push(`(
|
||
i.inbound_batch_no = $${batchIdx}
|
||
OR i.order_code ILIKE $${likeIdx}
|
||
OR COALESCE(i.item_name, '') ILIKE $${likeIdx}
|
||
OR COALESCE(i.sku_code, '') ILIKE $${likeIdx}
|
||
)`);
|
||
}
|
||
|
||
if (!activeRange && !q) {
|
||
return { rows: [], total: 0 };
|
||
}
|
||
|
||
// ② 订单维度:按订单号查询时列出**该订单全部未退货商品行**(含免入库/直送/加菜)。
|
||
// 不受日期轴限制(订单号本身即唯一限定)——否则默认"今天入库日"会把
|
||
// 昨天验收的批次全部滤掉,这正是"按订单查不到商品"的根因。
|
||
if (q && isOrderCodeQuery(q)) {
|
||
return searchTraceByOrderCode({ query: q, branchCode: input.branchCode, limit, offset });
|
||
}
|
||
|
||
const fromSql = useOrderCreated
|
||
? `FROM inspections i
|
||
INNER JOIN orders o ON o.order_code = i.order_code
|
||
LEFT JOIN skus s ON s.sku_code = i.sku_code`
|
||
: `FROM inspections i
|
||
LEFT JOIN skus s ON s.sku_code = i.sku_code`;
|
||
const whereSql = where.join(' AND ');
|
||
|
||
const countResult = await pool.query(
|
||
`SELECT COUNT(DISTINCT i.inbound_batch_no)::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 * FROM (
|
||
SELECT DISTINCT ON (i.inbound_batch_no)
|
||
i.inbound_batch_no AS batch_no,
|
||
COALESCE(NULLIF(i.item_name, ''), s.sku_name, i.sku_code, '') AS item_name,
|
||
i.order_code,
|
||
i.inspection_time::text AS inspection_time
|
||
${fromSql}
|
||
WHERE ${whereSql}
|
||
ORDER BY i.inbound_batch_no, i.inspection_time DESC NULLS LAST
|
||
) batches
|
||
ORDER BY inspection_time DESC NULLS LAST
|
||
LIMIT $${listParams.length - 1} OFFSET $${listParams.length}`,
|
||
listParams
|
||
);
|
||
|
||
const rows = result.rows.map((row) => ({
|
||
trace_code: String(row.batch_no),
|
||
batch_no: String(row.batch_no),
|
||
has_batch: true,
|
||
item_name: String(row.item_name || ''),
|
||
order_code: row.order_code ? String(row.order_code) : null,
|
||
inspection_time: row.inspection_time ? String(row.inspection_time) : null,
|
||
loading_at: null,
|
||
}));
|
||
return { rows, total };
|
||
}
|
||
|
||
/** 订单号形态:`ORD_` 前缀(全站订单号约定),用于把"按订单查"与"按批次/品名查"分流 */
|
||
function isOrderCodeQuery(query: string): boolean {
|
||
return /^ORD_/i.test(trimText(query));
|
||
}
|
||
|
||
/**
|
||
* 订单维度溯源列表:一条订单行 = 一条溯源项。
|
||
*
|
||
* - 有验收批次 → `trace_code` = 批次号(已印二维码保持不变)
|
||
* - 无批次(免入库 / 直送 / 加菜)→ `trace_code` = `订单号::SKU`
|
||
*
|
||
* ⚠️ 参数数组必须与 SQL 占位符严格对应:push 了未被引用的参数会让 PG
|
||
* 报 `could not determine data type of parameter $N`(42P18)。
|
||
*/
|
||
async function searchTraceByOrderCode(input: {
|
||
query: string;
|
||
branchCode?: string | null;
|
||
limit: number;
|
||
offset: number;
|
||
}): Promise<{ rows: TraceSearchHit[]; total: number }> {
|
||
const exact = trimText(input.query);
|
||
const like = `%${exact.replace(/[%_]/g, '\\$&')}%`;
|
||
const branch = trimText(input.branchCode);
|
||
|
||
const selectSql = `SELECT oi.order_code, oi.sku_code,
|
||
COALESCE(NULLIF(oi.item_name, ''), s.sku_name, oi.sku_code, '') AS item_name,
|
||
i.inbound_batch_no AS batch_no,
|
||
i.inspection_time::text AS inspection_time,
|
||
l.loading_at
|
||
FROM order_items oi
|
||
INNER JOIN orders o ON o.order_code = oi.order_code
|
||
LEFT JOIN skus s ON s.sku_code = oi.sku_code
|
||
LEFT JOIN LATERAL (
|
||
SELECT i2.inbound_batch_no, i2.inspection_time
|
||
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
|
||
LEFT JOIN LATERAL (
|
||
SELECT (to_timestamp(substring(p from '([0-9]{13})')::bigint / 1000.0))::timestamptz AS loading_at
|
||
FROM picking_items pi
|
||
CROSS JOIN LATERAL unnest(pi.loading_photos) AS p
|
||
WHERE pi.order_code = oi.order_code
|
||
AND COALESCE(NULLIF(TRIM(pi.sku_code), ''), oi.sku_code) = oi.sku_code
|
||
AND substring(p from '([0-9]{13})') IS NOT NULL
|
||
ORDER BY 1 ASC NULLS LAST
|
||
LIMIT 1
|
||
) l ON true`;
|
||
|
||
const countSql = `SELECT COUNT(*)::int AS cnt
|
||
FROM order_items oi
|
||
INNER JOIN orders o ON o.order_code = oi.order_code`;
|
||
|
||
// 先按精确订单号($1)统计
|
||
const exactWhere = ` WHERE o.deleted_at IS NULL
|
||
AND oi.order_code = $1::text
|
||
AND COALESCE(oi.is_returned, false) = false`;
|
||
const exactParams: unknown[] = [exact];
|
||
let exactBranch = '';
|
||
if (branch) {
|
||
exactParams.push(branch);
|
||
exactBranch = ` AND o.branch_code IS NOT DISTINCT FROM $2::text`;
|
||
}
|
||
const exactCount = await pool.query(`${countSql}${exactWhere}${exactBranch}`, exactParams);
|
||
const exactTotal = Number(exactCount.rows[0]?.cnt) || 0;
|
||
|
||
const useFuzzy = exactTotal === 0;
|
||
const params: unknown[] = useFuzzy ? [exact, like] : [exact];
|
||
let branchWhere = '';
|
||
if (branch) {
|
||
params.push(branch);
|
||
branchWhere = ` AND o.branch_code IS NOT DISTINCT FROM $${params.length}::text`;
|
||
}
|
||
const matchClause = useFuzzy ? `oi.order_code ILIKE $2::text` : `oi.order_code = $1::text`;
|
||
|
||
// 模糊兜底(前缀不完整/不确定)时才需要总数
|
||
let total = exactTotal;
|
||
if (useFuzzy) {
|
||
const countResult = await pool.query(
|
||
`${countSql} WHERE o.deleted_at IS NULL
|
||
AND ${matchClause}
|
||
AND COALESCE(oi.is_returned, false) = false${branchWhere}`,
|
||
params
|
||
);
|
||
total = Number(countResult.rows[0]?.cnt) || 0;
|
||
if (total === 0) return { rows: [], total: 0 };
|
||
}
|
||
|
||
const listParams = [...params, input.limit, input.offset];
|
||
const result = await pool.query(
|
||
`${selectSql}
|
||
WHERE o.deleted_at IS NULL
|
||
AND ${matchClause}
|
||
AND COALESCE(oi.is_returned, false) = false${branchWhere}
|
||
ORDER BY oi.order_code ASC, oi.sort_order ASC NULLS LAST, oi.id ASC
|
||
LIMIT $${listParams.length - 1} OFFSET $${listParams.length}`,
|
||
listParams
|
||
);
|
||
|
||
return { rows: result.rows.map(mapOrderDimensionRow), total };
|
||
}
|
||
|
||
function mapOrderDimensionRow(row: Record<string, unknown>): TraceSearchHit {
|
||
const orderCode = trimText(row.order_code);
|
||
const skuCode = trimText(row.sku_code);
|
||
const batchNo = trimText(row.batch_no);
|
||
const hasBatch = Boolean(batchNo);
|
||
return {
|
||
trace_code: hasBatch ? batchNo : buildTraceKey(orderCode, skuCode),
|
||
batch_no: hasBatch ? batchNo : null,
|
||
has_batch: hasBatch,
|
||
item_name: trimText(row.item_name),
|
||
order_code: orderCode || null,
|
||
inspection_time: row.inspection_time ? String(row.inspection_time) : null,
|
||
loading_at: row.loading_at ? new Date(String(row.loading_at)).toISOString() : null,
|
||
};
|
||
}
|
||
|
||
export async function getProductTrace(input: {
|
||
batchNo: string;
|
||
mode: TraceViewMode;
|
||
branchCode?: string | null;
|
||
requestHost?: string | null;
|
||
}) {
|
||
const batchNo = trimText(input.batchNo);
|
||
if (!batchNo) {
|
||
throw Object.assign(new Error('缺少溯源码'), { status: 400, code: 'invalid_request' });
|
||
}
|
||
|
||
// 公开且当前无 ALS:先 public,再扫 active tenant(阶段 4)
|
||
if (input.mode === 'public' && !getTenantDbStore()?.schemaName) {
|
||
const hit = await withActiveTenantFallback(async () => {
|
||
try {
|
||
return await getProductTraceInCurrentSchema(input);
|
||
} catch (error: any) {
|
||
if (error?.status === 404 || error?.code === 'not_found') return null;
|
||
// public 无业务表时继续扫 tenant_*
|
||
if (
|
||
error?.code === '42P01' ||
|
||
/relation ["'].*["'] does not exist/i.test(String(error?.message || ''))
|
||
) {
|
||
return null;
|
||
}
|
||
throw error;
|
||
}
|
||
});
|
||
if (!hit) {
|
||
throw Object.assign(new Error('未找到该溯源码对应的批次'), { status: 404, code: 'not_found' });
|
||
}
|
||
return hit;
|
||
}
|
||
|
||
return getProductTraceInCurrentSchema(input);
|
||
}
|
||
|
||
async function getProductTraceInCurrentSchema(input: {
|
||
batchNo: string;
|
||
mode: TraceViewMode;
|
||
branchCode?: string | null;
|
||
requestHost?: string | null;
|
||
}) {
|
||
const batchNo = trimText(input.batchNo);
|
||
|
||
// 公开查询不按分公司过滤(批次号全局足够稀疏);内部可按分公司收紧
|
||
const branchForLookup = input.mode === 'public' ? null : input.branchCode || null;
|
||
|
||
// ① 无批次行(免入库 / 直送 / 加菜):标识为 `订单号::SKU`
|
||
const keyParts = parseTraceKey(batchNo);
|
||
const inv = keyParts ? null : await loadInventoryByBatch(batchNo, branchForLookup);
|
||
const insp = keyParts ? null : await loadInspectionByInboundBatch(batchNo, branchForLookup);
|
||
|
||
let orderItemId: string | null = null;
|
||
let orderCode = trimText(insp?.order_code);
|
||
let skuCode = trimText(insp?.sku_code || inv?.sku_code);
|
||
let itemName = trimText(insp?.display_name || inv?.sku_name || skuCode) || '商品';
|
||
let supplierName = trimText(insp?.supplier_name || inv?.supplier_name) || '-';
|
||
let supplierCode = trimText(insp?.supplier_code || inv?.supplier_code);
|
||
/** 无批次行取自主数据(订单行/商品),批次行沿用验收入库口径 */
|
||
let lineUnit = '';
|
||
let lineOrigin = '';
|
||
|
||
if (keyParts) {
|
||
// 无批次行:以订单行本身为准(没有 inspections / inventory 记录)
|
||
const params: unknown[] = [keyParts.orderCode, keyParts.skuCode];
|
||
let sql = `
|
||
SELECT oi.id, oi.order_code, oi.sku_code, oi.item_name, oi.supplier_code,
|
||
COALESCE(s.sku_name, oi.item_name, oi.sku_code) AS sku_name,
|
||
COALESCE(s.origin, '') AS origin,
|
||
COALESCE(s.unit, '') AS sku_unit,
|
||
COALESCE(sup.company_name, '') AS supplier_name
|
||
FROM order_items oi
|
||
LEFT JOIN skus s ON s.sku_code = oi.sku_code
|
||
LEFT JOIN suppliers sup ON sup.supplier_code = oi.supplier_code
|
||
WHERE oi.order_code = $1
|
||
AND oi.sku_code IS NOT DISTINCT FROM $2
|
||
AND COALESCE(oi.is_returned, false) = false`;
|
||
if (branchForLookup) {
|
||
params.push(branchForLookup);
|
||
sql += ` AND oi.branch_code IS NOT DISTINCT FROM $${params.length}`;
|
||
}
|
||
sql += ` ORDER BY oi.sort_order ASC NULLS LAST, oi.id ASC LIMIT 1`;
|
||
const itemResult = await pool.query(sql, params);
|
||
const row = itemResult.rows[0];
|
||
if (!row) {
|
||
throw Object.assign(new Error('未找到该溯源码对应的商品'), { status: 404, code: 'not_found' });
|
||
}
|
||
orderItemId = String(row.id);
|
||
orderCode = trimText(row.order_code);
|
||
skuCode = trimText(row.sku_code) || keyParts.skuCode;
|
||
itemName = trimText(row.sku_name || row.item_name || skuCode) || '商品';
|
||
supplierName = trimText(row.supplier_name) || '-';
|
||
supplierCode = trimText(row.supplier_code);
|
||
lineUnit = trimText(row.sku_unit);
|
||
lineOrigin = trimText(row.origin);
|
||
}
|
||
|
||
if (!keyParts && !inv && !insp) {
|
||
throw Object.assign(new Error('未找到该溯源码对应的批次'), { status: 404, code: 'not_found' });
|
||
}
|
||
|
||
const origin = keyParts ? lineOrigin || null : trimText(insp?.origin || inv?.origin) || null;
|
||
|
||
let order: Record<string, unknown> | null = null;
|
||
let fulfillment: Record<string, unknown> | null = null;
|
||
if (orderCode) {
|
||
const orderRow = await pool.query(
|
||
`SELECT o.order_code, o.customer_code, c.company_name, o.delivery_date::text AS delivery_date,
|
||
o.order_status, o.branch_code
|
||
FROM orders o
|
||
LEFT JOIN customers c ON c.customer_code = o.customer_code
|
||
WHERE o.order_code = $1
|
||
AND o.deleted_at IS NULL
|
||
LIMIT 1`,
|
||
[orderCode]
|
||
);
|
||
if (orderRow.rows[0]) {
|
||
order = orderRow.rows[0];
|
||
}
|
||
|
||
// 履约必须按**订单行**取:同一订单同 SKU 可能多行(实测存在 23 组),
|
||
// 用 `sku_code IS NOT DISTINCT FROM … OR item_name IS NOT DISTINCT FROM …`
|
||
// 会在参数为 NULL 时命中订单首行(把别的商品的供应商/履约挂到本行)。
|
||
const fulfill = orderItemId
|
||
? await pool.query(
|
||
`SELECT f.order_item_id, f.supplier_preparation_id, f.purchase_code,
|
||
sp.supplier_code AS prep_supplier_code, sp.prepare_status,
|
||
po.purchase_code AS po_code, po.purchase_status
|
||
FROM order_items oi
|
||
LEFT JOIN order_item_fulfillments f ON f.order_item_id = oi.id
|
||
LEFT JOIN supplier_preparations sp ON sp.id = f.supplier_preparation_id
|
||
LEFT JOIN purchase_orders po ON po.purchase_code = f.purchase_code
|
||
WHERE oi.id = $1
|
||
LIMIT 1`,
|
||
[orderItemId]
|
||
)
|
||
: await pool.query(
|
||
`SELECT f.order_item_id, f.supplier_preparation_id, f.purchase_code,
|
||
sp.supplier_code AS prep_supplier_code, sp.prepare_status,
|
||
po.purchase_code AS po_code, po.purchase_status
|
||
FROM order_items oi
|
||
LEFT JOIN order_item_fulfillments f ON f.order_item_id = oi.id
|
||
LEFT JOIN supplier_preparations sp ON sp.id = f.supplier_preparation_id
|
||
LEFT JOIN purchase_orders po ON po.purchase_code = f.purchase_code
|
||
WHERE oi.order_code = $1
|
||
AND (
|
||
(NULLIF(TRIM($2), '') IS NOT NULL AND oi.sku_code IS NOT DISTINCT FROM $2)
|
||
OR (NULLIF(TRIM($2), '') IS NULL AND NULLIF(TRIM($3), '') IS NOT NULL
|
||
AND oi.item_name IS NOT DISTINCT FROM $3)
|
||
)
|
||
ORDER BY oi.sort_order ASC NULLS LAST, oi.id ASC
|
||
LIMIT 1`,
|
||
[orderCode, skuCode, itemName]
|
||
);
|
||
if (fulfill) {
|
||
const rows = (fulfill as { rows: Array<Record<string, unknown>> }).rows;
|
||
if (rows[0]) fulfillment = rows[0];
|
||
if (!orderItemId && rows[0]?.order_item_id) orderItemId = String(rows[0].order_item_id);
|
||
}
|
||
}
|
||
|
||
const logs = await pool.query(
|
||
`SELECT id, batch_no, sku_code, operation_type, quantity, before_qty, after_qty,
|
||
related_order_code, remark, created_at::text AS created_at
|
||
FROM inventory_logs
|
||
WHERE batch_no = $1
|
||
ORDER BY created_at ASC
|
||
LIMIT 200`,
|
||
[batchNo]
|
||
);
|
||
|
||
let processing: Record<string, unknown> | null = null;
|
||
if (insp?.id) {
|
||
const proc = await pool.query(
|
||
`SELECT id, process_status, process_photos, processing_inspection_photos, completed_at
|
||
FROM processing_tasks
|
||
WHERE inspection_id = $1
|
||
ORDER BY created_at DESC NULLS LAST
|
||
LIMIT 1`,
|
||
[insp.id]
|
||
);
|
||
if (proc.rows[0]) processing = proc.rows[0];
|
||
}
|
||
|
||
const host = input.requestHost || null;
|
||
// 照片一律相对签名路径(与验收复核一致),经同源 /api 访问,避免管理端 Vite/反代下绝对 Host 裂图。
|
||
// 小程序端自行把相对路径补成 apiBase 绝对地址。
|
||
// 三源**分源返回、不合并**:验收照 / 配送补拍(含加菜核货照)/ 直送照语义不同。
|
||
const inspectionPhotos = await loadTracePhotos(insp?.inspection_photos, 'inspection-photos', branchForLookup);
|
||
const orderLinePhotos = await loadOrderLineTracePhotos(orderCode, skuCode, branchForLookup);
|
||
const publicUrl = buildPublicTraceUrl(batchNo, host);
|
||
|
||
// 行级时间:与界面筛选/展示一致,一律取**真实发生时间**。
|
||
// 无批次行没有验收,只有补拍时间;验收行沿用验收入库时间。
|
||
const inspectionAt = inspectionPhotos[0]?.time || (insp?.inspection_time ? String(insp.inspection_time) : null);
|
||
const loadingTimes = [...orderLinePhotos.loading_photos, ...orderLinePhotos.direct_delivery_photos]
|
||
.map((item) => item.time)
|
||
.filter((value): value is string => Boolean(value))
|
||
.sort();
|
||
const loadingAt = loadingTimes[0] || null;
|
||
|
||
const isSelfPurchase =
|
||
Boolean(fulfillment?.purchase_code || fulfillment?.po_code) &&
|
||
!fulfillment?.supplier_preparation_id;
|
||
const displaySupplierName = isSelfPurchase ? '自采' : supplierName;
|
||
|
||
const qualityReportsRaw = await listQualityReportsForTrace({
|
||
batchNo,
|
||
preparationId: fulfillment?.supplier_preparation_id
|
||
? String(fulfillment.supplier_preparation_id)
|
||
: null,
|
||
purchaseCode: fulfillment?.purchase_code || fulfillment?.po_code
|
||
? String(fulfillment.purchase_code || fulfillment.po_code)
|
||
: null,
|
||
skuCode,
|
||
orderCode: orderCode || null,
|
||
mode: input.mode,
|
||
// 报告文件 URL 同样用相对路径,避免管理端裂链
|
||
requestHost: null,
|
||
});
|
||
const quality_reports =
|
||
input.mode === 'public'
|
||
? qualityReportsRaw.map((r) => ({
|
||
report_type: r.report_type,
|
||
report_label: r.report_label,
|
||
validity_status: r.validity_status,
|
||
validity_label: validityStatusLabel(r.validity_status),
|
||
file_urls: r.file_urls,
|
||
}))
|
||
: qualityReportsRaw.map((r) => ({
|
||
...r,
|
||
validity_label: validityStatusLabel(r.validity_status),
|
||
}));
|
||
|
||
const timeline: Array<{ at: string | null; title: string; detail?: string }> = [];
|
||
if (orderCode) {
|
||
timeline.push({
|
||
at: null,
|
||
title: '关联订单',
|
||
detail: orderCode + (order?.company_name ? ` · ${order.company_name}` : ''),
|
||
});
|
||
}
|
||
if (fulfillment?.purchase_code || fulfillment?.po_code) {
|
||
timeline.push({
|
||
at: null,
|
||
title: '自采履约',
|
||
detail: String(fulfillment.purchase_code || fulfillment.po_code),
|
||
});
|
||
} else if (fulfillment?.supplier_preparation_id) {
|
||
timeline.push({
|
||
at: null,
|
||
title: '供应商备货',
|
||
});
|
||
}
|
||
if (inspectionAt) {
|
||
timeline.push({
|
||
at: inspectionAt,
|
||
title: '验收入库',
|
||
detail: `实收 ${Number(insp.actual_qty) || 0} ${insp.unit || ''} · ${insp.quality_rating || ''}`,
|
||
});
|
||
}
|
||
// 公开页只展示对外节点;库存流水(adjust / 出库等)仅内部溯源可见
|
||
if (input.mode !== 'public') {
|
||
for (const log of logs.rows) {
|
||
if (String(log.operation_type) === 'inspection_in') continue;
|
||
const opType = String(log.operation_type);
|
||
timeline.push({
|
||
at: log.created_at ? String(log.created_at) : null,
|
||
title: TRACE_LOG_TYPE_LABELS[opType] || opType,
|
||
detail: `数量 ${Number(log.quantity) || 0}` + (log.related_order_code ? ` · 订单 ${log.related_order_code}` : ''),
|
||
});
|
||
}
|
||
}
|
||
|
||
if (input.mode === 'public') {
|
||
// ⚠️ 公开模式字段白名单:只给「溯源」需要的对外节点。
|
||
// 禁止加回 available_qty(剩余库存量)与 outbound_count(出库次数)——它们是内部经营数据,
|
||
// 配合 actual_qty 即可推算本批已走多少;与上方「库存流水仅内部溯源可见」是同一口径。
|
||
// 公开页 src/pages/inventory/PublicTrace.tsx 从未渲染过这两个字段(仅类型声明)。
|
||
// 2026-09-24 经开发者确认移除。
|
||
return {
|
||
mode: 'public' as const,
|
||
trace_code: batchNo,
|
||
public_url: publicUrl,
|
||
item_name: itemName,
|
||
origin,
|
||
supplier_name: displaySupplierName,
|
||
inbound_at: inspectionAt,
|
||
actual_qty: insp?.actual_qty != null ? Number(insp.actual_qty) : null,
|
||
unit: trimText(insp?.unit || inv?.sku_unit || lineUnit) || null,
|
||
quality_rating: trimText(insp?.quality_rating) || null,
|
||
// 时间为真实发生时间:验收照取文件名时间戳(与 inspection_time 一致),
|
||
// 补拍取文件名时间戳(唯一来源,见 photoTimeFromPath)
|
||
photos: photoUrls(inspectionPhotos),
|
||
photos_meta: inspectionPhotos,
|
||
loading_photos: photoUrls(orderLinePhotos.loading_photos),
|
||
loading_photos_meta: orderLinePhotos.loading_photos,
|
||
direct_delivery_photos: photoUrls(orderLinePhotos.direct_delivery_photos),
|
||
direct_delivery_photos_meta: orderLinePhotos.direct_delivery_photos,
|
||
loading_at: loadingAt,
|
||
quality_reports,
|
||
timeline: timeline
|
||
.filter((t) => t.title !== '关联订单')
|
||
.map((t) => ({
|
||
at: t.at,
|
||
title: t.title,
|
||
detail: t.detail,
|
||
})),
|
||
};
|
||
}
|
||
|
||
return {
|
||
mode: 'internal' as const,
|
||
trace_code: batchNo,
|
||
public_url: publicUrl,
|
||
batch_no: keyParts ? null : batchNo,
|
||
item_name: itemName,
|
||
sku_code: skuCode || null,
|
||
order_item_id: orderItemId,
|
||
origin,
|
||
supplier_code: isSelfPurchase ? null : supplierCode || null,
|
||
supplier_name: displaySupplierName,
|
||
source_type: insp?.source_type || null,
|
||
inbound_at: inspectionAt,
|
||
actual_qty: insp?.actual_qty != null ? Number(insp.actual_qty) : null,
|
||
prepare_qty: insp?.prepare_qty != null ? Number(insp.prepare_qty) : null,
|
||
unit: trimText(insp?.unit || inv?.sku_unit || lineUnit) || null,
|
||
quality_rating: trimText(insp?.quality_rating) || null,
|
||
purchase_price: insp?.purchase_price != null ? Number(insp.purchase_price) : null,
|
||
inventory: inv
|
||
? {
|
||
quantity: Number(inv.quantity) || 0,
|
||
available_qty: Number(inv.available_qty) || 0,
|
||
cost_price: Number(inv.cost_price) || 0,
|
||
production_date: inv.production_date,
|
||
expiry_date: inv.expiry_date,
|
||
branch_code: inv.branch_code,
|
||
status: inv.status,
|
||
}
|
||
: null,
|
||
order: order
|
||
? {
|
||
order_code: order.order_code,
|
||
customer_code: order.customer_code,
|
||
company_name: order.company_name,
|
||
delivery_date: order.delivery_date,
|
||
order_status: order.order_status,
|
||
}
|
||
: null,
|
||
fulfillment,
|
||
processing: processing
|
||
? {
|
||
id: processing.id,
|
||
process_status: processing.process_status,
|
||
completed_at: processing.completed_at,
|
||
}
|
||
: null,
|
||
photos: photoUrls(inspectionPhotos),
|
||
photos_meta: inspectionPhotos,
|
||
loading_photos: photoUrls(orderLinePhotos.loading_photos),
|
||
loading_photos_meta: orderLinePhotos.loading_photos,
|
||
direct_delivery_photos: photoUrls(orderLinePhotos.direct_delivery_photos),
|
||
direct_delivery_photos_meta: orderLinePhotos.direct_delivery_photos,
|
||
loading_at: loadingAt,
|
||
quality_reports,
|
||
logs: logs.rows,
|
||
timeline,
|
||
};
|
||
}
|