- 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 超长修复
3967 lines
136 KiB
TypeScript
3967 lines
136 KiB
TypeScript
import type { PoolClient } from 'pg';
|
||
import { pool } from '../db';
|
||
import { callWithImage as callArkWithImage, callWithFile, hasRuntimeConfig as hasArkRuntimeConfig } from './llmService';
|
||
import { resolvePrompt } from './promptRegistryService';
|
||
import { isQualityReportHardGateEnabled, getQuarantineValidDays } from './qualityReportGateConfigService';
|
||
import { assertOwnedStoragePaths, tryBuildSignedStoragePathForCtx } from './storageObjectOwnership';
|
||
import { saveBase64Upload } from './storageUploadService';
|
||
import { getStorageProvider } from './storageProvider';
|
||
import { safeStorageFileName } from './storageBucketConfig';
|
||
import { getTenantDbStore } from './tenantDbContext';
|
||
import { orderCodeActiveExistsSql } from './orderTrashScope';
|
||
import {
|
||
LEGACY_QUALITY_REPORT_TYPE_LABELS,
|
||
getQualityReportTypes,
|
||
} from './qualityReportTypeConfigService';
|
||
|
||
/** 报告类型 code(可配置目录;历史含 annual) */
|
||
export type QualityReportType = string;
|
||
export type ValidityStatus = 'in_range' | 'expired' | 'not_yet' | 'unknown';
|
||
export type QualityReportSourceParty = 'supplier' | 'self_purchase' | 'admin';
|
||
/** line=按行;leaf_category=肉类末级分类共用;produce_day=蔬果同供应商同日共用 */
|
||
export type QualityReportShareMode = 'line' | 'leaf_category' | 'produce_day' | 'manual';
|
||
|
||
export const QUALITY_REPORT_STATUS = { active: 10, voided: 20 } as const;
|
||
|
||
const TYPE_CODE_RE = /^[a-z][a-z0-9_]{0,31}$/;
|
||
|
||
const IMAGE_EXTS = new Set(['jpg', 'jpeg', 'png', 'webp', 'gif']);
|
||
/** 检验报告页采购员虚拟键:`p:` + purchaser_code;旧值 `__SELF__` 仍表示全部自采 */
|
||
export const QUALITY_REPORT_SELF_SUPPLIER_KEY = '__SELF__';
|
||
export const QUALITY_REPORT_PURCHASER_PREFIX = 'p:';
|
||
const SELF_SUPPLIER_KEY = QUALITY_REPORT_SELF_SUPPLIER_KEY;
|
||
|
||
export function qualityReportPurchaserPartyKey(purchaserCode: string): string {
|
||
return `${QUALITY_REPORT_PURCHASER_PREFIX}${trimText(purchaserCode).slice(0, 48)}`;
|
||
}
|
||
|
||
export function parseQualityReportPurchaserCode(
|
||
party: string | null | undefined
|
||
): string | null {
|
||
const raw = trimText(party);
|
||
if (!raw.startsWith(QUALITY_REPORT_PURCHASER_PREFIX)) return null;
|
||
return raw.slice(QUALITY_REPORT_PURCHASER_PREFIX.length) || null;
|
||
}
|
||
|
||
export function isQualityReportSelfSupplier(code: string | null | undefined): boolean {
|
||
const raw = trimText(code);
|
||
return raw === SELF_SUPPLIER_KEY || parseQualityReportPurchaserCode(raw) != null;
|
||
}
|
||
|
||
function trimText(value: unknown): string {
|
||
return String(value || '').trim();
|
||
}
|
||
|
||
function normalizeReportType(raw: unknown): QualityReportType {
|
||
const v = trimText(raw).toLowerCase();
|
||
if (TYPE_CODE_RE.test(v)) return v;
|
||
return 'other';
|
||
}
|
||
|
||
export function shareModeForReportType(type: QualityReportType | string | null | undefined): QualityReportShareMode {
|
||
const t = normalizeReportType(type);
|
||
if (t === 'quarantine' || t === 'inspection' || t === 'annual' || t === 'batch') return 'leaf_category';
|
||
if (t === 'pesticide') return 'produce_day';
|
||
return 'line';
|
||
}
|
||
|
||
export function buildQualityReportShareKey(input: {
|
||
shareMode: QualityReportShareMode;
|
||
supplierCode?: string | null;
|
||
deliveryDate?: string | null;
|
||
categoryCode?: string | null;
|
||
preparationId?: string | null;
|
||
purchaseCode?: string | null;
|
||
skuCode?: string | null;
|
||
}): string {
|
||
const supplier = trimText(input.supplierCode) || SELF_SUPPLIER_KEY;
|
||
const day = trimText(input.deliveryDate) || shanghaiToday();
|
||
if (input.shareMode === 'leaf_category') {
|
||
const cat = trimText(input.categoryCode) || '_';
|
||
return `lc|${supplier}|${day}|${cat}`;
|
||
}
|
||
if (input.shareMode === 'produce_day') {
|
||
return `pd|${supplier}|${day}`;
|
||
}
|
||
if (trimText(input.preparationId)) return `ln|prep:${trimText(input.preparationId)}`;
|
||
return `ln|po:${trimText(input.purchaseCode)}:${trimText(input.skuCode) || ''}`;
|
||
}
|
||
|
||
/** 当日清单「报告」列:SKU 直连 + 叶子分类/农残日共用 */
|
||
export type DayItemCoverageHit = {
|
||
reportId: string;
|
||
skuCode: string | null;
|
||
categoryCode: string | null;
|
||
shareMode: QualityReportShareMode | null;
|
||
};
|
||
|
||
export function countReportsCoveringDayItem(
|
||
item: { sku_code: string | null; category_code?: string | null },
|
||
hits: DayItemCoverageHit[]
|
||
): number {
|
||
const ids = new Set<string>();
|
||
const sku = trimText(item.sku_code) || null;
|
||
const cat = trimText(item.category_code) || null;
|
||
for (const h of hits) {
|
||
const rid = trimText(h.reportId);
|
||
if (!rid) continue;
|
||
if (sku && h.skuCode && h.skuCode === sku) {
|
||
ids.add(rid);
|
||
continue;
|
||
}
|
||
if (h.shareMode === 'manual') continue;
|
||
if (h.shareMode === 'produce_day') {
|
||
ids.add(rid);
|
||
continue;
|
||
}
|
||
if (h.shareMode === 'leaf_category' && cat && h.categoryCode && h.categoryCode === cat) {
|
||
ids.add(rid);
|
||
}
|
||
}
|
||
return ids.size;
|
||
}
|
||
|
||
/** Web 当日报告勾选:与 countReportsCoveringDayItem 同一套共用,不另写谓词 */
|
||
export function skuCodesCoveredByDayReport(
|
||
report: {
|
||
id?: string | null;
|
||
sku_code?: string | null;
|
||
category_code?: string | null;
|
||
share_mode?: string | null;
|
||
share_key?: string | null;
|
||
linked_sku_codes?: string[] | null;
|
||
},
|
||
dayItems: Array<{ sku_code: string | null; category_code?: string | null }>
|
||
): string[] {
|
||
const reportId = trimText(report.id) || 'report';
|
||
const staging = isPrepInlineStagingShareKey(report.share_key);
|
||
const rawMode = trimText(report.share_mode);
|
||
const shareMode = (
|
||
staging
|
||
? 'line'
|
||
: rawMode === 'leaf_category' ||
|
||
rawMode === 'produce_day' ||
|
||
rawMode === 'line' ||
|
||
rawMode === 'manual'
|
||
? rawMode
|
||
: null
|
||
) as QualityReportShareMode | null;
|
||
const skuHits = new Set<string>();
|
||
const ownSku = trimText(report.sku_code);
|
||
if (ownSku) skuHits.add(ownSku);
|
||
for (const raw of report.linked_sku_codes || []) {
|
||
const sku = trimText(raw);
|
||
if (sku) skuHits.add(sku);
|
||
}
|
||
const cat = trimText(report.category_code) || null;
|
||
const hits: DayItemCoverageHit[] = [...skuHits].map((sku) => ({
|
||
reportId,
|
||
skuCode: sku,
|
||
categoryCode: cat,
|
||
shareMode,
|
||
}));
|
||
if (!hits.length) {
|
||
hits.push({
|
||
reportId,
|
||
skuCode: null,
|
||
categoryCode: cat,
|
||
shareMode,
|
||
});
|
||
}
|
||
const out: string[] = [];
|
||
const seen = new Set<string>();
|
||
for (const it of dayItems) {
|
||
const sku = trimText(it.sku_code);
|
||
if (!sku || seen.has(sku)) continue;
|
||
if (countReportsCoveringDayItem({ sku_code: sku, category_code: it.category_code }, hits) < 1) {
|
||
continue;
|
||
}
|
||
seen.add(sku);
|
||
out.push(sku);
|
||
}
|
||
return out;
|
||
}
|
||
|
||
/** 供货录入行内覆盖:检疫仍认映射;农残不认 produce_day 扩散到其它 SKU */
|
||
export const PREP_INLINE_STAGING_SHARE_PREFIX = 'st|';
|
||
|
||
export function isPrepInlineStagingShareKey(shareKey: string | null | undefined): boolean {
|
||
return trimText(shareKey).startsWith(PREP_INLINE_STAGING_SHARE_PREFIX);
|
||
}
|
||
|
||
export type PrepInlineHit = {
|
||
id: string;
|
||
sku_code: string | null;
|
||
product_name: string;
|
||
category_code: string | null;
|
||
};
|
||
|
||
export function proposePrepInlineHits(input: {
|
||
reportType: string | null | undefined;
|
||
sourcePrepId: string;
|
||
sourceSkuCode: string | null;
|
||
sourceCategoryCode: string | null;
|
||
dayItems: PrepInlineHit[];
|
||
aiNames: string[];
|
||
}): PrepInlineHit[] {
|
||
const sourceId = trimText(input.sourcePrepId);
|
||
const reportType = normalizeReportType(input.reportType);
|
||
const byId = new Map(input.dayItems.map((it) => [it.id, it]));
|
||
const picked = new Map<string, PrepInlineHit>();
|
||
const take = (hit: PrepInlineHit | undefined) => {
|
||
if (!hit || picked.has(hit.id)) return;
|
||
picked.set(hit.id, hit);
|
||
};
|
||
take(byId.get(sourceId) || input.dayItems.find((it) => it.id === sourceId));
|
||
if (!picked.size && sourceId) {
|
||
take({
|
||
id: sourceId,
|
||
sku_code: input.sourceSkuCode,
|
||
product_name: '',
|
||
category_code: input.sourceCategoryCode,
|
||
});
|
||
}
|
||
const shareMode = shareModeForReportType(reportType);
|
||
if (shareMode === 'leaf_category') {
|
||
const cat = trimText(input.sourceCategoryCode);
|
||
for (const it of input.dayItems) {
|
||
if (cat && trimText(it.category_code) === cat) take(it);
|
||
}
|
||
return [...picked.values()];
|
||
}
|
||
if (reportType === 'pesticide') {
|
||
const matched = matchDayItemsByProductNames(
|
||
input.aiNames,
|
||
input.dayItems.map((it) => ({
|
||
sku_code: it.sku_code,
|
||
product_name: it.product_name,
|
||
specification: null,
|
||
unit: null,
|
||
prepare_qty: 0,
|
||
prep_count: 1,
|
||
matched_report_count: 0,
|
||
category_code: it.category_code,
|
||
}))
|
||
);
|
||
const skuSet = new Set(matched.skuCodes);
|
||
for (const it of input.dayItems) {
|
||
if (it.sku_code && skuSet.has(it.sku_code)) take(it);
|
||
}
|
||
}
|
||
return [...picked.values()];
|
||
}
|
||
|
||
export function intersectPrepInlineHits(
|
||
candidates: PrepInlineHit[],
|
||
selectedIds: string[] | null | undefined
|
||
): PrepInlineHit[] {
|
||
const allowed = new Set(candidates.map((c) => c.id));
|
||
const out: PrepInlineHit[] = [];
|
||
const seen = new Set<string>();
|
||
for (const raw of selectedIds || []) {
|
||
const id = trimText(raw);
|
||
if (!id || !allowed.has(id) || seen.has(id)) continue;
|
||
seen.add(id);
|
||
const hit = candidates.find((c) => c.id === id);
|
||
if (hit) out.push(hit);
|
||
}
|
||
return out;
|
||
}
|
||
|
||
export function isPrepInlineReportCovered(input: {
|
||
prepId: string;
|
||
skuCode: string | null;
|
||
reportType: string | null | undefined;
|
||
mapped:
|
||
| {
|
||
share_mode?: string | null;
|
||
share_key?: string | null;
|
||
preparation_id?: string | null;
|
||
sku_code?: string | null;
|
||
source?: string | null;
|
||
linked_sku_codes?: string[] | null;
|
||
}
|
||
| null
|
||
| undefined;
|
||
}): boolean {
|
||
const mapped = input.mapped;
|
||
if (!mapped) return false;
|
||
if (isPrepInlineStagingShareKey(mapped.share_key)) return false;
|
||
if (normalizeReportType(input.reportType) !== 'pesticide') return true;
|
||
if (mapped.share_mode === 'manual' || mapped.source === 'library') return true;
|
||
const prepId = String(mapped.preparation_id || '');
|
||
const sku = String(mapped.sku_code || '');
|
||
if (prepId && prepId === String(input.prepId || '')) return true;
|
||
if (input.skuCode && sku && sku === input.skuCode) return true;
|
||
if (input.skuCode && (mapped.linked_sku_codes || []).includes(input.skuCode)) return true;
|
||
return false;
|
||
}
|
||
|
||
export function qualityReportShareHint(type: QualityReportType | string | null | undefined): string {
|
||
const mode = shareModeForReportType(type);
|
||
if (mode === 'leaf_category') return '同供应商、同配送日、同末级分类共用一张';
|
||
if (mode === 'produce_day') return '同供应商、同配送日蔬果共用一张';
|
||
return '本行单独上传';
|
||
}
|
||
|
||
export function qualityReportTypeLabel(
|
||
type: QualityReportType | string | null | undefined,
|
||
customLabel?: string | null
|
||
): string {
|
||
if (trimText(customLabel)) return trimText(customLabel);
|
||
const t = normalizeReportType(type);
|
||
return LEGACY_QUALITY_REPORT_TYPE_LABELS[t] || t;
|
||
}
|
||
|
||
/** 上传前:类型须在分公司目录内(或兼容历史 annual) */
|
||
export async function assertReportTypeAllowed(
|
||
typeRaw: unknown,
|
||
branchCode?: string | null
|
||
): Promise<{ code: string; label: string }> {
|
||
const code = normalizeReportType(typeRaw);
|
||
const types = await getQualityReportTypes(branchCode);
|
||
const hit = types.find((t) => t.code === code);
|
||
if (hit) return hit;
|
||
if (code === 'annual') {
|
||
return { code: 'annual', label: LEGACY_QUALITY_REPORT_TYPE_LABELS.annual };
|
||
}
|
||
throw Object.assign(new Error(`不支持的报告类型:${code}`), { status: 400, code: 'invalid_report_type' });
|
||
}
|
||
|
||
function parseDateOnly(raw: unknown): string | null {
|
||
if (raw instanceof Date && !Number.isNaN(raw.getTime())) {
|
||
const y = raw.getUTCFullYear();
|
||
const m = String(raw.getUTCMonth() + 1).padStart(2, '0');
|
||
const d = String(raw.getUTCDate()).padStart(2, '0');
|
||
return `${y}-${m}-${d}`;
|
||
}
|
||
const s = trimText(raw);
|
||
if (!s) return null;
|
||
const m = /^(\d{4})-(\d{2})-(\d{2})/.exec(s);
|
||
if (m) return `${m[1]}-${m[2]}-${m[3]}`;
|
||
const m2 = /^(\d{4})[/.年](\d{1,2})[/.月](\d{1,2})/.exec(s);
|
||
if (m2) {
|
||
return `${m2[1]}-${m2[2].padStart(2, '0')}-${m2[3].padStart(2, '0')}`;
|
||
}
|
||
return null;
|
||
}
|
||
|
||
export function computeValidityStatus(input: {
|
||
compareAt: string | null;
|
||
validFrom?: string | null;
|
||
validTo?: string | null;
|
||
testedAt?: string | null;
|
||
}): ValidityStatus {
|
||
const compareAt = parseDateOnly(input.compareAt);
|
||
if (!compareAt) return 'unknown';
|
||
|
||
let from = parseDateOnly(input.validFrom);
|
||
let to = parseDateOnly(input.validTo);
|
||
const tested = parseDateOnly(input.testedAt);
|
||
|
||
if (!from && !to && tested) {
|
||
from = tested;
|
||
to = tested;
|
||
}
|
||
if (!from && to) from = to;
|
||
if (!to && from) to = from;
|
||
if (!from || !to) return 'unknown';
|
||
|
||
if (compareAt < from) return 'not_yet';
|
||
if (compareAt > to) return 'expired';
|
||
return 'in_range';
|
||
}
|
||
|
||
/** 日历加天(中午锚点,避免时区边界) */
|
||
export function addCalendarDays(isoDate: string, days: number): string {
|
||
const base = parseDateOnly(isoDate);
|
||
if (!base) return isoDate;
|
||
const d = new Date(`${base}T12:00:00Z`);
|
||
d.setUTCDate(d.getUTCDate() + days);
|
||
return d.toISOString().slice(0, 10);
|
||
}
|
||
|
||
/**
|
||
* 检疫报告有效窗口:
|
||
* days=1 → 仅检验日;days=2 → 检验日及次日。
|
||
*/
|
||
export function applyQuarantineValidWindow(
|
||
testedAt: string | null | undefined,
|
||
days: 1 | 2
|
||
): { valid_from: string; valid_to: string } | null {
|
||
const tested = parseDateOnly(testedAt);
|
||
if (!tested) return null;
|
||
return {
|
||
valid_from: tested,
|
||
valid_to: days === 1 ? tested : addCalendarDays(tested, 1),
|
||
};
|
||
}
|
||
|
||
function shanghaiToday(): string {
|
||
return new Intl.DateTimeFormat('en-CA', {
|
||
timeZone: 'Asia/Shanghai',
|
||
year: 'numeric',
|
||
month: '2-digit',
|
||
day: '2-digit',
|
||
}).format(new Date());
|
||
}
|
||
|
||
export interface CategoryQualityRequirement {
|
||
requires: boolean;
|
||
report_type: QualityReportType;
|
||
report_label: string;
|
||
category_code: string | null;
|
||
}
|
||
|
||
export async function resolveCategoryQualityRequirement(
|
||
input: {
|
||
branchCode?: string | null;
|
||
categoryCode?: string | null;
|
||
skuCode?: string | null;
|
||
},
|
||
client: PoolClient | typeof pool = pool
|
||
): Promise<CategoryQualityRequirement> {
|
||
const branch = trimText(input.branchCode);
|
||
let categoryCode = trimText(input.categoryCode) || null;
|
||
|
||
if (!categoryCode && trimText(input.skuCode)) {
|
||
const sku = await client.query(
|
||
`SELECT COALESCE(
|
||
NULLIF(TRIM(s.category_code), ''),
|
||
(SELECT NULLIF(TRIM(pc.parent_code), '')
|
||
FROM product_catalog pc
|
||
WHERE pc.item_type = 'product' AND pc.code = s.sku_code
|
||
AND ($1::text = '' OR pc.branch_code IS NOT DISTINCT FROM $1)
|
||
LIMIT 1)
|
||
) AS category_code
|
||
FROM skus s
|
||
WHERE s.sku_code = $2
|
||
LIMIT 1`,
|
||
[branch, trimText(input.skuCode)]
|
||
);
|
||
categoryCode = trimText(sku.rows[0]?.category_code) || null;
|
||
}
|
||
|
||
if (!categoryCode) {
|
||
return { requires: false, report_type: 'other', report_label: qualityReportTypeLabel('other'), category_code: null };
|
||
}
|
||
|
||
const cat = await client.query(
|
||
`SELECT requires_quality_report, quality_report_type, quality_report_label
|
||
FROM (
|
||
SELECT requires_quality_report, quality_report_type, quality_report_label, 1 AS pri
|
||
FROM product_catalog
|
||
WHERE item_type = 'category' AND code = $1
|
||
AND ($2::text = '' OR branch_code IS NOT DISTINCT FROM $2)
|
||
UNION ALL
|
||
SELECT requires_quality_report, quality_report_type, quality_report_label, 2 AS pri
|
||
FROM categories
|
||
WHERE category_code = $1
|
||
AND ($2::text = '' OR branch_code IS NOT DISTINCT FROM $2)
|
||
) t
|
||
ORDER BY pri
|
||
LIMIT 1`,
|
||
[categoryCode, branch]
|
||
);
|
||
const row = cat.rows[0];
|
||
if (!row || row.requires_quality_report !== true) {
|
||
return {
|
||
requires: false,
|
||
report_type: 'other',
|
||
report_label: qualityReportTypeLabel('other'),
|
||
category_code: categoryCode,
|
||
};
|
||
}
|
||
const reportType = normalizeReportType(row.quality_report_type);
|
||
return {
|
||
requires: true,
|
||
report_type: reportType,
|
||
report_label: qualityReportTypeLabel(reportType, row.quality_report_label),
|
||
category_code: categoryCode,
|
||
};
|
||
}
|
||
|
||
async function resolveCompareAt(input: {
|
||
orderCode?: string | null;
|
||
preparationId?: string | null;
|
||
purchaseCode?: string | null;
|
||
}): Promise<string> {
|
||
if (trimText(input.orderCode)) {
|
||
const o = await pool.query(
|
||
`SELECT to_char(delivery_date::date, 'YYYY-MM-DD') AS d
|
||
FROM orders WHERE order_code = $1 LIMIT 1`,
|
||
[trimText(input.orderCode)]
|
||
);
|
||
if (o.rows[0]?.d) return String(o.rows[0].d);
|
||
}
|
||
if (trimText(input.preparationId)) {
|
||
const p = await pool.query(
|
||
`SELECT to_char(COALESCE(o.delivery_date, sp.prepare_time, sp.created_at)::date, 'YYYY-MM-DD') AS d
|
||
FROM supplier_preparations sp
|
||
LEFT JOIN orders o ON o.order_code = sp.order_code
|
||
WHERE sp.id = $1
|
||
LIMIT 1`,
|
||
[trimText(input.preparationId)]
|
||
);
|
||
if (p.rows[0]?.d) return String(p.rows[0].d);
|
||
}
|
||
if (trimText(input.purchaseCode)) {
|
||
const p = await pool.query(
|
||
`SELECT to_char(COALESCE(o.delivery_date, po.created_at)::date, 'YYYY-MM-DD') AS d
|
||
FROM purchase_orders po
|
||
LEFT JOIN orders o ON o.order_code = po.order_code
|
||
WHERE po.purchase_code = $1
|
||
LIMIT 1`,
|
||
[trimText(input.purchaseCode)]
|
||
);
|
||
if (p.rows[0]?.d) return String(p.rows[0].d);
|
||
}
|
||
return shanghaiToday();
|
||
}
|
||
|
||
async function parseReportDatesWithAi(
|
||
imageBase64: string,
|
||
branchCode?: string | null,
|
||
reportHint?: { code?: string | null; label?: string | null } | null
|
||
): Promise<{
|
||
tested_at: string | null;
|
||
valid_from: string | null;
|
||
valid_to: string | null;
|
||
valid_days: number | null;
|
||
ai_raw: Record<string, unknown> | null;
|
||
}> {
|
||
if (!imageBase64 || !(await hasArkRuntimeConfig({ branchCode }))) {
|
||
return { tested_at: null, valid_from: null, valid_to: null, valid_days: null, ai_raw: null };
|
||
}
|
||
const prompt = await resolvePrompt('quality.report.dates', { branchCode });
|
||
const typeCode = trimText(reportHint?.code);
|
||
const typeLabel = trimText(reportHint?.label) || typeCode;
|
||
const typeClause =
|
||
typeCode || typeLabel
|
||
? `\n当前上传类型为:${typeLabel || '未知'}${typeCode ? `(${typeCode})` : ''}。请按该类型报告的常见版式识别日期字段,不要编造。`
|
||
: '';
|
||
try {
|
||
const text = await callArkWithImage(
|
||
`${prompt.systemPrompt}${typeClause}`,
|
||
imageBase64,
|
||
{ branchCode }
|
||
); if (!text) {
|
||
return { tested_at: null, valid_from: null, valid_to: null, valid_days: null, ai_raw: null };
|
||
}
|
||
const jsonMatch = text.match(/\{[\s\S]*\}/);
|
||
const raw = jsonMatch ? (JSON.parse(jsonMatch[0]) as Record<string, unknown>) : { text };
|
||
let tested_at = parseDateOnly(raw.tested_at);
|
||
let valid_from = parseDateOnly(raw.valid_from);
|
||
let valid_to = parseDateOnly(raw.valid_to);
|
||
const validDays = Number(raw.valid_days);
|
||
const days = Number.isFinite(validDays) && validDays > 0 ? Math.floor(validDays) : null;
|
||
if (!valid_to && tested_at && days) {
|
||
const d = new Date(`${tested_at}T00:00:00Z`);
|
||
d.setUTCDate(d.getUTCDate() + days);
|
||
valid_to = d.toISOString().slice(0, 10);
|
||
if (!valid_from) valid_from = tested_at;
|
||
}
|
||
return { tested_at, valid_from, valid_to, valid_days: days, ai_raw: raw };
|
||
} catch {
|
||
return { tested_at: null, valid_from: null, valid_to: null, valid_days: null, ai_raw: null };
|
||
}
|
||
}
|
||
|
||
function nullText(value: unknown): string | null {
|
||
const t = trimText(value);
|
||
return t || null;
|
||
}
|
||
|
||
/** 库模式:元数据 + 日期;认不出一律 null,不编造 */
|
||
async function parseReportMetaWithAi(
|
||
imageBase64: string,
|
||
branchCode?: string | null,
|
||
reportHint?: { code?: string | null; label?: string | null } | null
|
||
): Promise<QualityReportParsedMeta> {
|
||
const empty = emptyParsedMeta();
|
||
if (!imageBase64 || !(await hasArkRuntimeConfig({ branchCode }))) return empty;
|
||
try {
|
||
const prompt = await resolvePrompt('quality.report.meta', { branchCode });
|
||
const typeCode = trimText(reportHint?.code);
|
||
const typeLabel = trimText(reportHint?.label) || typeCode;
|
||
const typeClause =
|
||
typeCode || typeLabel
|
||
? `\n当前上传类型为:${typeLabel || '未知'}${typeCode ? `(${typeCode})` : ''}。请按该类型报告版式提取字段,认不出填 null,不要编造。`
|
||
: '';
|
||
const text = await callArkWithImage(
|
||
`${prompt.systemPrompt}${typeClause}`,
|
||
imageBase64,
|
||
{ branchCode }
|
||
);
|
||
if (!text) return empty;
|
||
const jsonMatch = text.match(/\{[\s\S]*\}/);
|
||
if (!jsonMatch) return empty;
|
||
const raw = JSON.parse(jsonMatch[0]) as Record<string, unknown>;
|
||
return parsedMetaFromAiRaw(raw);
|
||
} catch {
|
||
return empty;
|
||
}
|
||
}
|
||
|
||
function parseUploadPayload(photo: string): { content: string; ext: string } | null {
|
||
const trimmed = trimText(photo);
|
||
if (!trimmed) return null;
|
||
const dataUrl = /^data:([^;]+);base64,(.+)$/i.exec(trimmed);
|
||
if (dataUrl) {
|
||
const mime = dataUrl[1].toLowerCase();
|
||
let ext = 'jpg';
|
||
if (mime.includes('png')) ext = 'png';
|
||
else if (mime.includes('webp')) ext = 'webp';
|
||
else if (mime.includes('pdf')) ext = 'pdf';
|
||
else if (mime.includes('jpeg') || mime.includes('jpg')) ext = 'jpg';
|
||
return { content: dataUrl[2], ext };
|
||
}
|
||
if (trimmed.length > 200 && /^[A-Za-z0-9+/=\s]+$/.test(trimmed)) {
|
||
return { content: trimmed.replace(/\s+/g, ''), ext: 'jpg' };
|
||
}
|
||
return null;
|
||
}
|
||
|
||
/**
|
||
* 解析一个上传项,两种口径都认:
|
||
* - data URL / 裸 base64:旧口径,走 2MB JSON 通道,仅小文件可用;
|
||
* - `quality-reports` 桶内对象路径:新口径,文件先经 multer 通道上传(单文件 10MB)再由服务端读回。
|
||
*
|
||
* 见 docs/design/20260921-quality-report-upload-multer-channel.md
|
||
*/
|
||
async function resolveMatchUploadEntry(
|
||
entry: string
|
||
): Promise<{ content: string; ext: string; storedPath?: string } | null> {
|
||
const inline = parseUploadPayload(entry);
|
||
if (inline) return inline;
|
||
let safe: string;
|
||
try {
|
||
safe = safeStorageFileName(trimText(entry));
|
||
} catch {
|
||
return null;
|
||
}
|
||
if (!safe) return null;
|
||
// T9:客户端给的桶内旧 key 先做归属反查(调用者分支 RLS),跨分支 key 直接 403,不读他租户对象
|
||
await assertOwnedStoragePaths(
|
||
{ branchCode: getTenantDbStore()?.branchCode || null },
|
||
'quality-reports',
|
||
[safe]
|
||
);
|
||
const obj = await getStorageProvider().getObject('quality-reports', safe);
|
||
if (!obj?.buffer?.length) return null;
|
||
const ext = (safe.split('.').pop() || 'jpg').toLowerCase();
|
||
return { content: obj.buffer.toString('base64'), ext, storedPath: safe };
|
||
}
|
||
|
||
export interface QualityReportRow {
|
||
id: string;
|
||
branch_code: string | null;
|
||
report_type: string;
|
||
report_label: string | null;
|
||
preparation_id: string | null;
|
||
purchase_code: string | null;
|
||
order_code: string | null;
|
||
sku_code: string | null;
|
||
supplier_code: string | null;
|
||
batch_no: string | null;
|
||
file_paths: string[];
|
||
status: number;
|
||
source_party: string;
|
||
tested_at: string | null;
|
||
valid_from: string | null;
|
||
valid_to: string | null;
|
||
compare_at: string | null;
|
||
validity_status: ValidityStatus;
|
||
uploaded_at: string | null;
|
||
uploaded_by?: string | null;
|
||
share_mode?: string | null;
|
||
share_key?: string | null;
|
||
category_code?: string | null;
|
||
delivery_date?: string | null;
|
||
file_urls?: string[];
|
||
/** 是否为共用解析命中(非本行上传) */
|
||
shared?: boolean;
|
||
is_library?: boolean;
|
||
report_date?: string | null;
|
||
product_name?: string | null;
|
||
produced_at?: string | null;
|
||
testing_org?: string | null;
|
||
inspected_org?: string | null;
|
||
specification?: string | null;
|
||
/** 解析来源:备货直传 / 库报告 / 共用键 / 自采单直传 */
|
||
source?: 'prep' | 'library' | 'shared' | 'self_purchase';
|
||
linked_sku_codes?: string[];
|
||
}
|
||
|
||
function mapReportRow(row: Record<string, unknown>, absoluteHost?: string | null): QualityReportRow {
|
||
const paths = Array.isArray(row.file_paths) ? row.file_paths.map(String).filter(Boolean) : [];
|
||
const file_urls = paths.map((filename) => {
|
||
// T9F-5:未迁移的无前缀旧 key 不再同步签发,给空 URL 避免列表 500。
|
||
const path = tryBuildSignedStoragePathForCtx(undefined, 'quality-reports', filename);
|
||
if (!path) return '';
|
||
if (absoluteHost) return `${String(absoluteHost).replace(/\/+$/, '')}${path}`;
|
||
return path;
|
||
});
|
||
return {
|
||
id: String(row.id),
|
||
branch_code: row.branch_code != null ? String(row.branch_code) : null,
|
||
report_type: String(row.report_type || 'other'),
|
||
report_label: row.report_label != null ? String(row.report_label) : null,
|
||
preparation_id: row.preparation_id != null ? String(row.preparation_id) : null,
|
||
purchase_code: row.purchase_code != null ? String(row.purchase_code) : null,
|
||
order_code: row.order_code != null ? String(row.order_code) : null,
|
||
sku_code: row.sku_code != null ? String(row.sku_code) : null,
|
||
supplier_code: row.supplier_code != null ? String(row.supplier_code) : null,
|
||
batch_no: row.batch_no != null ? String(row.batch_no) : null,
|
||
file_paths: paths,
|
||
status: Number(row.status) || 10,
|
||
source_party: String(row.source_party || 'supplier'),
|
||
tested_at: parseDateOnly(row.tested_at),
|
||
valid_from: parseDateOnly(row.valid_from),
|
||
valid_to: parseDateOnly(row.valid_to),
|
||
compare_at: parseDateOnly(row.compare_at),
|
||
validity_status: (trimText(row.validity_status) as ValidityStatus) || 'unknown',
|
||
uploaded_at: row.uploaded_at ? String(row.uploaded_at) : null,
|
||
uploaded_by: row.uploaded_by != null ? String(row.uploaded_by) : null,
|
||
share_mode: row.share_mode != null ? String(row.share_mode) : null,
|
||
share_key: row.share_key != null ? String(row.share_key) : null,
|
||
category_code: row.category_code != null ? String(row.category_code) : null,
|
||
delivery_date: parseDateOnly(row.delivery_date),
|
||
file_urls,
|
||
is_library: row.is_library === true || row.is_library === 't' || row.is_library === 1,
|
||
report_date: parseDateOnly(row.report_date),
|
||
product_name: row.product_name != null ? String(row.product_name).trim() || null : null,
|
||
produced_at: parseDateOnly(row.produced_at),
|
||
testing_org: row.testing_org != null ? String(row.testing_org).trim() || null : null,
|
||
inspected_org: row.inspected_org != null ? String(row.inspected_org).trim() || null : null,
|
||
specification: row.specification != null ? String(row.specification).trim() || null : null,
|
||
linked_sku_codes: Array.isArray(row.linked_sku_codes)
|
||
? row.linked_sku_codes.map((v) => String(v || '').trim()).filter(Boolean)
|
||
: [],
|
||
};
|
||
}
|
||
|
||
async function loadPrepReportContext(
|
||
preparationId: string,
|
||
client: PoolClient | typeof pool = pool
|
||
): Promise<{
|
||
preparationId: string;
|
||
purchaseCode: null;
|
||
orderCode: string | null;
|
||
skuCode: string | null;
|
||
supplierCode: string | null;
|
||
branchCode: string | null;
|
||
categoryCode: string | null;
|
||
deliveryDate: string;
|
||
reportType: QualityReportType;
|
||
requires: boolean;
|
||
shareMode: QualityReportShareMode;
|
||
shareKey: string;
|
||
} | null> {
|
||
const prep = await client.query(
|
||
`SELECT sp.id, sp.order_code, sp.sku_code, sp.supplier_code, sp.branch_code,
|
||
COALESCE(
|
||
NULLIF(TRIM(oi.category_code), ''),
|
||
NULLIF(TRIM(s.category_code), '')
|
||
) AS category_code,
|
||
to_char(COALESCE(o.delivery_date, sp.prepare_time, sp.created_at)::date, 'YYYY-MM-DD') AS delivery_date
|
||
FROM supplier_preparations sp
|
||
LEFT JOIN orders o ON o.order_code = sp.order_code
|
||
LEFT JOIN order_items oi ON oi.order_code = sp.order_code AND oi.sku_code IS NOT DISTINCT FROM sp.sku_code
|
||
LEFT JOIN skus s ON s.sku_code = sp.sku_code
|
||
WHERE sp.id = $1
|
||
LIMIT 1`,
|
||
[preparationId]
|
||
);
|
||
const row = prep.rows[0];
|
||
if (!row) return null;
|
||
const categoryCode = row.category_code ? String(row.category_code) : null;
|
||
const skuCode = row.sku_code ? String(row.sku_code) : null;
|
||
const branchCode = row.branch_code ? String(row.branch_code) : null;
|
||
const supplierCode = row.supplier_code ? String(row.supplier_code) : null;
|
||
const deliveryDate = row.delivery_date ? String(row.delivery_date) : shanghaiToday();
|
||
const req = await resolveCategoryQualityRequirement(
|
||
{ branchCode, categoryCode, skuCode },
|
||
client
|
||
);
|
||
const reportType = req.requires ? req.report_type : 'other';
|
||
const shareMode = shareModeForReportType(reportType);
|
||
const shareKey = buildQualityReportShareKey({
|
||
shareMode,
|
||
supplierCode,
|
||
deliveryDate,
|
||
categoryCode,
|
||
preparationId,
|
||
});
|
||
return {
|
||
preparationId,
|
||
purchaseCode: null,
|
||
orderCode: row.order_code ? String(row.order_code) : null,
|
||
skuCode,
|
||
supplierCode,
|
||
branchCode,
|
||
categoryCode,
|
||
deliveryDate,
|
||
reportType,
|
||
requires: req.requires,
|
||
shareMode,
|
||
shareKey,
|
||
};
|
||
}
|
||
|
||
async function loadPurchaseReportContext(
|
||
purchaseCode: string,
|
||
skuCodeHint?: string | null,
|
||
client: PoolClient | typeof pool = pool
|
||
): Promise<{
|
||
preparationId: null;
|
||
purchaseCode: string;
|
||
orderCode: string | null;
|
||
skuCode: string | null;
|
||
supplierCode: string | null;
|
||
branchCode: string | null;
|
||
categoryCode: string | null;
|
||
deliveryDate: string;
|
||
reportType: QualityReportType;
|
||
requires: boolean;
|
||
shareMode: QualityReportShareMode;
|
||
shareKey: string;
|
||
} | null> {
|
||
const po = await client.query(
|
||
`SELECT po.purchase_code, po.order_code, po.sku_code, po.branch_code,
|
||
NULLIF(TRIM(po.purchaser_code), '') AS purchaser_code,
|
||
COALESCE(NULLIF(TRIM(oi.category_code), ''), NULLIF(TRIM(s.category_code), '')) AS category_code,
|
||
to_char(COALESCE(o.delivery_date, po.created_at)::date, 'YYYY-MM-DD') AS delivery_date
|
||
FROM purchase_orders po
|
||
LEFT JOIN orders o ON o.order_code = po.order_code
|
||
LEFT JOIN order_items oi ON oi.order_code = po.order_code AND oi.sku_code IS NOT DISTINCT FROM po.sku_code
|
||
LEFT JOIN skus s ON s.sku_code = po.sku_code
|
||
WHERE po.purchase_code = $1
|
||
LIMIT 1`,
|
||
[purchaseCode]
|
||
);
|
||
const row = po.rows[0];
|
||
if (!row) return null;
|
||
const categoryCode = row.category_code ? String(row.category_code) : null;
|
||
const skuCode = trimText(skuCodeHint) || (row.sku_code ? String(row.sku_code) : null);
|
||
const branchCode = row.branch_code ? String(row.branch_code) : null;
|
||
const deliveryDate = row.delivery_date ? String(row.delivery_date) : shanghaiToday();
|
||
const partyKey = row.purchaser_code
|
||
? qualityReportPurchaserPartyKey(String(row.purchaser_code))
|
||
: SELF_SUPPLIER_KEY;
|
||
const req = await resolveCategoryQualityRequirement(
|
||
{ branchCode, categoryCode, skuCode },
|
||
client
|
||
);
|
||
const reportType = req.requires ? req.report_type : 'other';
|
||
const shareMode = shareModeForReportType(reportType);
|
||
const shareKey = buildQualityReportShareKey({
|
||
shareMode,
|
||
supplierCode: partyKey,
|
||
deliveryDate,
|
||
categoryCode,
|
||
purchaseCode,
|
||
skuCode,
|
||
});
|
||
return {
|
||
preparationId: null,
|
||
purchaseCode,
|
||
orderCode: row.order_code ? String(row.order_code) : null,
|
||
skuCode,
|
||
supplierCode: partyKey,
|
||
branchCode,
|
||
categoryCode,
|
||
deliveryDate,
|
||
reportType,
|
||
requires: req.requires,
|
||
shareMode,
|
||
shareKey,
|
||
};
|
||
}
|
||
|
||
async function getActiveByShareKey(
|
||
shareKey: string,
|
||
client: PoolClient | typeof pool = pool,
|
||
reportType?: string | null
|
||
): Promise<QualityReportRow | null> {
|
||
if (!trimText(shareKey)) return null;
|
||
const type = trimText(reportType);
|
||
const result = type
|
||
? await client.query(
|
||
`SELECT * FROM quality_reports
|
||
WHERE share_key = $1 AND report_type = $2 AND status = $3
|
||
ORDER BY uploaded_at DESC
|
||
LIMIT 1`,
|
||
[shareKey, type, QUALITY_REPORT_STATUS.active]
|
||
)
|
||
: await client.query(
|
||
`SELECT * FROM quality_reports
|
||
WHERE share_key = $1 AND status = $2
|
||
ORDER BY uploaded_at DESC
|
||
LIMIT 1`,
|
||
[shareKey, QUALITY_REPORT_STATUS.active]
|
||
);
|
||
return result.rows[0] ? mapReportRow(result.rows[0]) : null;
|
||
}
|
||
|
||
async function voidPrepLinksForReport(
|
||
reportId: string,
|
||
client: PoolClient | typeof pool = pool
|
||
): Promise<void> {
|
||
const id = trimText(reportId);
|
||
if (!id) return;
|
||
await client.query(
|
||
`UPDATE quality_report_prep_links
|
||
SET status = $2, updated_at = NOW()
|
||
WHERE quality_report_id = $1::uuid AND status = $3`,
|
||
[id, QUALITY_REPORT_STATUS.voided, QUALITY_REPORT_STATUS.active]
|
||
);
|
||
}
|
||
|
||
async function voidPrepLinksForPrepType(
|
||
preparationId: string,
|
||
reportType: string,
|
||
client: PoolClient | typeof pool = pool
|
||
): Promise<void> {
|
||
const prepId = trimText(preparationId);
|
||
const type = normalizeReportType(reportType);
|
||
if (!prepId) return;
|
||
await client.query(
|
||
`UPDATE quality_report_prep_links
|
||
SET status = $3, updated_at = NOW()
|
||
WHERE preparation_id = $1::uuid AND report_type = $2 AND status = $4`,
|
||
[prepId, type, QUALITY_REPORT_STATUS.voided, QUALITY_REPORT_STATUS.active]
|
||
);
|
||
}
|
||
|
||
async function findPrepIdsForLibraryMatch(input: {
|
||
supplierCode: string;
|
||
deliveryDate: string;
|
||
skuCode?: string | null;
|
||
reportType: QualityReportType;
|
||
branchCode?: string | null;
|
||
client?: PoolClient | typeof pool;
|
||
exactSkuOnly?: boolean;
|
||
}): Promise<string[]> {
|
||
const supplierCode = trimText(input.supplierCode);
|
||
const deliveryDate = parseDateOnly(input.deliveryDate);
|
||
const skuCode = trimText(input.skuCode);
|
||
if (!supplierCode || !deliveryDate || !skuCode) return [];
|
||
|
||
const db = input.client || pool;
|
||
const params: unknown[] = [supplierCode, deliveryDate];
|
||
const filters: string[] = [
|
||
'sp.supplier_code = $1',
|
||
`o.delivery_date::date = $2::date`,
|
||
'COALESCE(sp.is_history_repair, false) = false',
|
||
`(
|
||
sp.order_code IS NULL
|
||
OR TRIM(sp.order_code) = ''
|
||
OR ${orderCodeActiveExistsSql('sp.order_code')}
|
||
)`,
|
||
];
|
||
const branchCode = trimText(input.branchCode);
|
||
if (branchCode) {
|
||
params.push(branchCode);
|
||
filters.push(`(
|
||
sp.branch_code = $${params.length}
|
||
OR (
|
||
(sp.branch_code IS NULL OR TRIM(sp.branch_code) = '')
|
||
AND o.branch_code = $${params.length}
|
||
)
|
||
)`);
|
||
}
|
||
|
||
const result = await db.query(
|
||
`SELECT
|
||
sp.id::text AS id,
|
||
NULLIF(TRIM(sp.sku_code), '') AS sku_code,
|
||
COALESCE(
|
||
NULLIF(TRIM(oi.category_code), ''),
|
||
NULLIF(TRIM(s.category_code), '')
|
||
) AS category_code,
|
||
sp.branch_code
|
||
FROM supplier_preparations sp
|
||
INNER JOIN orders o ON o.order_code = sp.order_code
|
||
LEFT JOIN order_items oi ON oi.order_code = sp.order_code AND oi.sku_code IS NOT DISTINCT FROM sp.sku_code
|
||
LEFT JOIN skus s ON s.sku_code = sp.sku_code
|
||
WHERE ${filters.join(' AND ')}`,
|
||
params
|
||
);
|
||
|
||
const shareMode = shareModeForReportType(input.reportType);
|
||
const wantedType = normalizeReportType(input.reportType);
|
||
const ids = new Set<string>();
|
||
for (const row of result.rows) {
|
||
const id = String(row.id);
|
||
const rowSku = row.sku_code != null ? String(row.sku_code) : '';
|
||
if (rowSku && rowSku === skuCode) {
|
||
ids.add(id);
|
||
continue;
|
||
}
|
||
if (input.exactSkuOnly || shareMode === 'line') continue;
|
||
const req = await resolveCategoryQualityRequirement(
|
||
{
|
||
branchCode: row.branch_code != null ? String(row.branch_code) : input.branchCode || null,
|
||
categoryCode: row.category_code != null ? String(row.category_code) : null,
|
||
skuCode: rowSku || null,
|
||
},
|
||
db
|
||
);
|
||
if (!req.requires || normalizeReportType(req.report_type) !== wantedType) continue;
|
||
if (shareMode === 'produce_day') {
|
||
ids.add(id);
|
||
continue;
|
||
}
|
||
const hitCat = result.rows.find((r) => String(r.sku_code || '') === skuCode);
|
||
const hitCategory = hitCat?.category_code != null ? String(hitCat.category_code) : '';
|
||
const rowCategory = row.category_code != null ? String(row.category_code) : '';
|
||
if (hitCategory && rowCategory && hitCategory === rowCategory) ids.add(id);
|
||
}
|
||
return [...ids];
|
||
}
|
||
|
||
export async function linkLibraryReportToPreps(input: {
|
||
reportId: string;
|
||
reportType: string;
|
||
supplierCode: string;
|
||
deliveryDate: string;
|
||
skuCode?: string | null;
|
||
branchCode?: string | null;
|
||
linkSource?: 'auto_match' | 'manual_rematch' | 'admin_link';
|
||
linkedBy?: string | null;
|
||
exactSkuOnly?: boolean;
|
||
client?: PoolClient | typeof pool;
|
||
}): Promise<number> {
|
||
const reportId = trimText(input.reportId);
|
||
const skuCode = trimText(input.skuCode);
|
||
if (!reportId || !skuCode) return 0;
|
||
const db = input.client || pool;
|
||
const reportType = normalizeReportType(input.reportType);
|
||
const reportCheck = await db.query(
|
||
`SELECT id FROM quality_reports
|
||
WHERE id = $1::uuid
|
||
AND status = $2
|
||
AND is_library = true
|
||
AND preparation_id IS NULL
|
||
AND purchase_code IS NULL
|
||
AND supplier_code = $3
|
||
AND report_type = $4
|
||
LIMIT 1`,
|
||
[reportId, QUALITY_REPORT_STATUS.active, trimText(input.supplierCode), reportType]
|
||
);
|
||
if (!reportCheck.rowCount) return 0;
|
||
const prepIds = await findPrepIdsForLibraryMatch({
|
||
supplierCode: input.supplierCode,
|
||
deliveryDate: input.deliveryDate,
|
||
skuCode,
|
||
reportType,
|
||
branchCode: input.branchCode,
|
||
exactSkuOnly: input.exactSkuOnly,
|
||
client: db,
|
||
});
|
||
if (!prepIds.length) return 0;
|
||
|
||
for (const prepId of prepIds) {
|
||
await voidPrepLinksForPrepType(prepId, reportType, db);
|
||
await db.query(
|
||
`INSERT INTO quality_report_prep_links (
|
||
quality_report_id, preparation_id, report_type, link_source, linked_by, status
|
||
) VALUES ($1::uuid, $2::uuid, $3, $4, $5, $6)`,
|
||
[
|
||
reportId,
|
||
prepId,
|
||
reportType,
|
||
input.linkSource || 'auto_match',
|
||
input.linkedBy || null,
|
||
QUALITY_REPORT_STATUS.active,
|
||
]
|
||
);
|
||
}
|
||
return prepIds.length;
|
||
}
|
||
|
||
export async function getActiveQualityReportForPrep(
|
||
preparationId: string,
|
||
client: PoolClient | typeof pool = pool
|
||
): Promise<QualityReportRow | null> {
|
||
const ctx = await loadPrepReportContext(preparationId, client);
|
||
if (!ctx) return null;
|
||
|
||
if (ctx.shareMode !== 'line') {
|
||
const shared = await getActiveByShareKey(ctx.shareKey, client, ctx.reportType);
|
||
if (shared) {
|
||
return {
|
||
...shared,
|
||
shared: shared.preparation_id !== preparationId,
|
||
source: shared.preparation_id === preparationId ? 'prep' : 'shared',
|
||
};
|
||
}
|
||
}
|
||
|
||
const result = await client.query(
|
||
`SELECT * FROM quality_reports
|
||
WHERE preparation_id = $1 AND status = $2
|
||
ORDER BY uploaded_at DESC
|
||
LIMIT 1`,
|
||
[preparationId, QUALITY_REPORT_STATUS.active]
|
||
);
|
||
return result.rows[0] ? mapReportRow(result.rows[0]) : null;
|
||
}
|
||
|
||
export async function listQualityReportsForPrep(
|
||
preparationId: string,
|
||
options?: { includeVoided?: boolean }
|
||
): Promise<{ reports: QualityReportRow[]; history: QualityReportRow[] }> {
|
||
return resolveReportsForPrep(preparationId, options);
|
||
}
|
||
|
||
export async function resolveReportsForPrep(
|
||
preparationId: string,
|
||
options?: { includeVoided?: boolean }
|
||
): Promise<{ reports: QualityReportRow[]; history: QualityReportRow[] }> {
|
||
const prepId = trimText(preparationId);
|
||
if (!prepId) return { reports: [], history: [] };
|
||
const includeVoided = options?.includeVoided !== false;
|
||
const statuses = includeVoided
|
||
? [QUALITY_REPORT_STATUS.active, QUALITY_REPORT_STATUS.voided]
|
||
: [QUALITY_REPORT_STATUS.active];
|
||
|
||
const direct = await pool.query(
|
||
`SELECT * FROM quality_reports
|
||
WHERE preparation_id = $1 AND status = ANY($2::int[])
|
||
ORDER BY status ASC, uploaded_at DESC NULLS LAST`,
|
||
[prepId, statuses]
|
||
);
|
||
const linked = await pool.query(
|
||
`SELECT qr.*, l.status AS link_status
|
||
FROM quality_report_prep_links l
|
||
JOIN quality_reports qr ON qr.id = l.quality_report_id
|
||
WHERE l.preparation_id = $1::uuid AND l.status = ANY($2::int[])
|
||
AND qr.is_library = true
|
||
ORDER BY l.status ASC, qr.uploaded_at DESC NULLS LAST`,
|
||
[prepId, statuses]
|
||
);
|
||
|
||
const seen = new Set<string>();
|
||
const reports: QualityReportRow[] = [];
|
||
const history: QualityReportRow[] = [];
|
||
const activeTypes = new Set<string>();
|
||
|
||
const pushRow = (row: QualityReportRow, source: 'prep' | 'library' | 'shared') => {
|
||
if (seen.has(row.id)) return;
|
||
seen.add(row.id);
|
||
const tagged = { ...row, source };
|
||
if (row.status === QUALITY_REPORT_STATUS.active) {
|
||
if (activeTypes.has(row.report_type) && source !== 'prep') return;
|
||
if (source === 'prep') {
|
||
const idx = reports.findIndex((r) => r.report_type === row.report_type && r.source !== 'prep');
|
||
if (idx >= 0) reports.splice(idx, 1);
|
||
}
|
||
activeTypes.add(row.report_type);
|
||
reports.push(tagged);
|
||
} else if (includeVoided) {
|
||
history.push(tagged);
|
||
}
|
||
};
|
||
|
||
for (const row of direct.rows) {
|
||
pushRow(mapReportRow(row), 'prep');
|
||
}
|
||
for (const row of linked.rows) {
|
||
const mapped = mapReportRow(row);
|
||
const linkVoided = Number(row.link_status) === QUALITY_REPORT_STATUS.voided;
|
||
if (linkVoided && mapped.status === QUALITY_REPORT_STATUS.active) {
|
||
mapped.status = QUALITY_REPORT_STATUS.voided;
|
||
}
|
||
pushRow(mapped, 'library');
|
||
}
|
||
|
||
const ctx = await loadPrepReportContext(prepId);
|
||
if (ctx) {
|
||
const shareTypes: QualityReportType[] = ['quarantine', 'inspection', 'annual', 'batch', 'pesticide'];
|
||
for (const reportType of shareTypes) {
|
||
if (activeTypes.has(reportType)) continue;
|
||
const shareMode = shareModeForReportType(reportType);
|
||
if (shareMode === 'line') continue;
|
||
const shareKey = buildQualityReportShareKey({
|
||
shareMode,
|
||
supplierCode: ctx.supplierCode,
|
||
deliveryDate: ctx.deliveryDate,
|
||
categoryCode: ctx.categoryCode,
|
||
preparationId: prepId,
|
||
});
|
||
const shared = await getActiveByShareKey(shareKey, pool, reportType);
|
||
if (shared && shared.preparation_id !== prepId) {
|
||
pushRow({ ...shared, shared: true }, 'shared');
|
||
}
|
||
}
|
||
}
|
||
|
||
reports.sort((a, b) => String(b.uploaded_at || '').localeCompare(String(a.uploaded_at || '')));
|
||
history.sort((a, b) => String(b.uploaded_at || '').localeCompare(String(a.uploaded_at || '')));
|
||
return { reports, history };
|
||
}
|
||
|
||
export async function getActiveQualityReportForPurchase(
|
||
purchaseCode: string,
|
||
skuCode?: string | null,
|
||
client: PoolClient | typeof pool = pool
|
||
): Promise<QualityReportRow | null> {
|
||
const ctx = await loadPurchaseReportContext(purchaseCode, skuCode, client);
|
||
if (!ctx) return null;
|
||
|
||
if (ctx.shareMode !== 'line') {
|
||
const shared = await getActiveByShareKey(ctx.shareKey, client);
|
||
if (shared) {
|
||
return {
|
||
...shared,
|
||
shared: shared.purchase_code !== purchaseCode || shared.sku_code !== ctx.skuCode,
|
||
};
|
||
}
|
||
}
|
||
|
||
if (ctx.skuCode) {
|
||
const linked = await client.query(
|
||
`SELECT * FROM quality_reports
|
||
WHERE status = $1
|
||
AND is_library = true
|
||
AND supplier_code = $2
|
||
AND (
|
||
sku_code = $3
|
||
OR (linked_sku_codes IS NOT NULL AND $3 = ANY(linked_sku_codes))
|
||
)
|
||
AND COALESCE(report_date::date, delivery_date::date) = $4::date
|
||
ORDER BY uploaded_at DESC
|
||
LIMIT 1`,
|
||
[QUALITY_REPORT_STATUS.active, ctx.supplierCode, ctx.skuCode, ctx.deliveryDate]
|
||
);
|
||
if (linked.rows[0]) {
|
||
return {
|
||
...mapReportRow(linked.rows[0]),
|
||
shared: true,
|
||
};
|
||
}
|
||
}
|
||
|
||
const result = await client.query(
|
||
`SELECT * FROM quality_reports
|
||
WHERE purchase_code = $1
|
||
AND status = $2
|
||
AND COALESCE(sku_code, '') = COALESCE($3, '')
|
||
ORDER BY uploaded_at DESC
|
||
LIMIT 1`,
|
||
[purchaseCode, QUALITY_REPORT_STATUS.active, trimText(skuCode) || null]
|
||
);
|
||
return result.rows[0] ? mapReportRow(result.rows[0]) : null;
|
||
}
|
||
|
||
export async function listQualityReportsForTrace(input: {
|
||
batchNo?: string | null;
|
||
preparationId?: string | null;
|
||
purchaseCode?: string | null;
|
||
skuCode?: string | null;
|
||
orderCode?: string | null;
|
||
mode?: 'internal' | 'public';
|
||
requestHost?: string | null;
|
||
}): Promise<QualityReportRow[]> {
|
||
const params: unknown[] = [QUALITY_REPORT_STATUS.active];
|
||
const orParts: string[] = [];
|
||
|
||
if (trimText(input.batchNo)) {
|
||
params.push(trimText(input.batchNo));
|
||
orParts.push(`batch_no = $${params.length}`);
|
||
}
|
||
if (trimText(input.preparationId)) {
|
||
params.push(trimText(input.preparationId));
|
||
orParts.push(`preparation_id = $${params.length}`);
|
||
}
|
||
if (trimText(input.purchaseCode)) {
|
||
params.push(trimText(input.purchaseCode));
|
||
let part = `purchase_code = $${params.length}`;
|
||
if (trimText(input.skuCode)) {
|
||
params.push(trimText(input.skuCode));
|
||
part += ` AND COALESCE(sku_code, '') = COALESCE($${params.length}, '')`;
|
||
}
|
||
orParts.push(`(${part})`);
|
||
}
|
||
if (!orParts.length && trimText(input.orderCode) && trimText(input.skuCode)) {
|
||
params.push(trimText(input.orderCode), trimText(input.skuCode));
|
||
orParts.push(
|
||
`(order_code = $${params.length - 1} AND sku_code IS NOT DISTINCT FROM $${params.length})`
|
||
);
|
||
}
|
||
if (!orParts.length) return [];
|
||
|
||
const result = await pool.query(
|
||
`SELECT * FROM quality_reports
|
||
WHERE status = $1 AND (${orParts.join(' OR ')})
|
||
ORDER BY uploaded_at DESC
|
||
LIMIT 20`,
|
||
params
|
||
);
|
||
|
||
// 若按备货行查且无结果,尝试共用键 / 库链 / 多类型解析
|
||
if (!result.rows.length && trimText(input.preparationId)) {
|
||
const resolved = await resolveReportsForPrep(trimText(input.preparationId)!, {
|
||
includeVoided: false,
|
||
});
|
||
if (resolved.reports.length) {
|
||
const host = input.mode === 'public' ? null : input.requestHost;
|
||
if (!host) return resolved.reports;
|
||
return resolved.reports.map((row) => ({
|
||
...row,
|
||
file_urls: (row.file_urls || []).map((u) =>
|
||
String(u).startsWith('http') ? String(u) : `${String(host).replace(/\/+$/, '')}${u}`
|
||
),
|
||
}));
|
||
}
|
||
const shared = await getActiveQualityReportForPrep(trimText(input.preparationId));
|
||
if (shared?.id) {
|
||
const full = await pool.query(`SELECT * FROM quality_reports WHERE id = $1 LIMIT 1`, [shared.id]);
|
||
if (full.rows[0]) {
|
||
const host = input.mode === 'public' ? null : input.requestHost;
|
||
return [mapReportRow(full.rows[0], host)];
|
||
}
|
||
}
|
||
}
|
||
|
||
const host = input.mode === 'public' ? null : input.requestHost;
|
||
const seen = new Set<string>();
|
||
const rows: QualityReportRow[] = [];
|
||
for (const row of result.rows) {
|
||
const id = String(row.id);
|
||
if (seen.has(id)) continue;
|
||
seen.add(id);
|
||
rows.push(mapReportRow(row, host));
|
||
}
|
||
return rows;
|
||
}
|
||
|
||
export async function mapQualityReportsByPrepIds(
|
||
prepIds: string[]
|
||
): Promise<Record<string, QualityReportRow>> {
|
||
const ids = [...new Set(prepIds.map(String).filter(Boolean))];
|
||
if (!ids.length) return {};
|
||
const out: Record<string, QualityReportRow> = {};
|
||
// 批量拉上下文
|
||
const meta = await pool.query(
|
||
`SELECT sp.id::text AS id, sp.order_code, sp.sku_code, sp.supplier_code, sp.branch_code,
|
||
COALESCE(
|
||
NULLIF(TRIM(oi.category_code), ''),
|
||
NULLIF(TRIM(s.category_code), '')
|
||
) AS category_code,
|
||
to_char(COALESCE(o.delivery_date, sp.prepare_time, sp.created_at)::date, 'YYYY-MM-DD') AS delivery_date
|
||
FROM supplier_preparations sp
|
||
LEFT JOIN orders o ON o.order_code = sp.order_code
|
||
LEFT JOIN order_items oi ON oi.order_code = sp.order_code AND oi.sku_code IS NOT DISTINCT FROM sp.sku_code
|
||
LEFT JOIN skus s ON s.sku_code = sp.sku_code
|
||
WHERE sp.id = ANY($1::uuid[])`,
|
||
[ids]
|
||
);
|
||
const shareKeys: string[] = [];
|
||
const ctxById = new Map<string, { shareKey: string; shareMode: QualityReportShareMode }>();
|
||
for (const row of meta.rows) {
|
||
const id = String(row.id);
|
||
const categoryCode = row.category_code ? String(row.category_code) : null;
|
||
const skuCode = row.sku_code ? String(row.sku_code) : null;
|
||
const branchCode = row.branch_code ? String(row.branch_code) : null;
|
||
const req = await resolveCategoryQualityRequirement({
|
||
branchCode,
|
||
categoryCode,
|
||
skuCode,
|
||
});
|
||
const reportType = req.requires ? req.report_type : 'other';
|
||
const shareMode = shareModeForReportType(reportType);
|
||
const shareKey = buildQualityReportShareKey({
|
||
shareMode,
|
||
supplierCode: row.supplier_code ? String(row.supplier_code) : null,
|
||
deliveryDate: row.delivery_date ? String(row.delivery_date) : shanghaiToday(),
|
||
categoryCode,
|
||
preparationId: id,
|
||
});
|
||
ctxById.set(id, { shareKey, shareMode });
|
||
if (shareMode !== 'line') shareKeys.push(shareKey);
|
||
}
|
||
|
||
const sharedRows =
|
||
shareKeys.length > 0
|
||
? await pool.query(
|
||
`SELECT DISTINCT ON (share_key) *
|
||
FROM quality_reports
|
||
WHERE share_key = ANY($1::text[]) AND status = $2
|
||
ORDER BY share_key, uploaded_at DESC`,
|
||
[[...new Set(shareKeys)], QUALITY_REPORT_STATUS.active]
|
||
)
|
||
: { rows: [] as any[] };
|
||
const byShare = new Map<string, any>();
|
||
for (const row of sharedRows.rows) {
|
||
byShare.set(String(row.share_key), row);
|
||
}
|
||
|
||
const lineRows = await pool.query(
|
||
`SELECT DISTINCT ON (preparation_id) *
|
||
FROM quality_reports
|
||
WHERE preparation_id = ANY($1::uuid[]) AND status = $2
|
||
ORDER BY preparation_id, uploaded_at DESC`,
|
||
[ids, QUALITY_REPORT_STATUS.active]
|
||
);
|
||
const byPrep = new Map<string, any>();
|
||
for (const row of lineRows.rows) {
|
||
byPrep.set(String(row.preparation_id), row);
|
||
}
|
||
|
||
for (const id of ids) {
|
||
const ctx = ctxById.get(id);
|
||
if (ctx && ctx.shareMode !== 'line' && byShare.has(ctx.shareKey)) {
|
||
const row = byShare.get(ctx.shareKey);
|
||
out[id] = {
|
||
...mapReportRow(row),
|
||
shared: String(row.preparation_id || '') !== id,
|
||
};
|
||
continue;
|
||
}
|
||
if (byPrep.has(id)) out[id] = mapReportRow(byPrep.get(id));
|
||
}
|
||
|
||
const missing = ids.filter((id) => !out[id]);
|
||
if (missing.length) {
|
||
const linkedRows = await pool.query(
|
||
`SELECT DISTINCT ON (l.preparation_id) qr.*, l.preparation_id::text AS link_prep_id
|
||
FROM quality_report_prep_links l
|
||
JOIN quality_reports qr ON qr.id = l.quality_report_id
|
||
WHERE l.preparation_id = ANY($1::uuid[])
|
||
AND l.status = $2
|
||
AND qr.status = $2
|
||
ORDER BY l.preparation_id, qr.uploaded_at DESC`,
|
||
[missing, QUALITY_REPORT_STATUS.active]
|
||
);
|
||
for (const row of linkedRows.rows) {
|
||
const id = String(row.link_prep_id);
|
||
if (!out[id]) {
|
||
out[id] = { ...mapReportRow(row), source: 'library' };
|
||
}
|
||
}
|
||
}
|
||
return out;
|
||
}
|
||
|
||
export async function mapQualityReportLinksByPrepIds(
|
||
prepIds: string[]
|
||
): Promise<Record<string, QualityReportRow>> {
|
||
const ids = [...new Set(prepIds.map(String).filter(Boolean))];
|
||
if (!ids.length) return {};
|
||
const linkedRows = await pool.query(
|
||
`SELECT DISTINCT ON (l.preparation_id) qr.*, l.preparation_id::text AS link_prep_id
|
||
FROM quality_report_prep_links l
|
||
JOIN quality_reports qr ON qr.id = l.quality_report_id
|
||
WHERE l.preparation_id = ANY($1::uuid[])
|
||
AND l.status = $2
|
||
AND qr.status = $2
|
||
ORDER BY l.preparation_id, qr.uploaded_at DESC`,
|
||
[ids, QUALITY_REPORT_STATUS.active]
|
||
);
|
||
const out: Record<string, QualityReportRow> = {};
|
||
for (const row of linkedRows.rows) {
|
||
const id = String(row.link_prep_id);
|
||
if (!out[id]) out[id] = { ...mapReportRow(row), source: 'library' };
|
||
}
|
||
return out;
|
||
}
|
||
|
||
async function listSupplierDayReportPrepItems(input: {
|
||
supplierCode: string | null;
|
||
deliveryDate: string;
|
||
branchCode?: string | null;
|
||
reportType: string;
|
||
}): Promise<PrepInlineHit[]> {
|
||
const supplierCode = trimText(input.supplierCode);
|
||
const deliveryDate = parseDateOnly(input.deliveryDate) || shanghaiToday();
|
||
const reportType = normalizeReportType(input.reportType);
|
||
if (!supplierCode) return [];
|
||
const params: unknown[] = [supplierCode, deliveryDate];
|
||
const filters: string[] = [
|
||
'sp.supplier_code = $1',
|
||
`o.delivery_date::date = $2::date`,
|
||
'COALESCE(sp.is_history_repair, false) = false',
|
||
];
|
||
const branchCode = trimText(input.branchCode);
|
||
if (branchCode) {
|
||
params.push(branchCode);
|
||
filters.push(`(
|
||
sp.branch_code = $${params.length}
|
||
OR (
|
||
(sp.branch_code IS NULL OR TRIM(sp.branch_code) = '')
|
||
AND o.branch_code = $${params.length}
|
||
)
|
||
)`);
|
||
}
|
||
const result = await pool.query(
|
||
`SELECT sp.id::text AS id,
|
||
NULLIF(TRIM(sp.sku_code), '') AS sku_code,
|
||
COALESCE(
|
||
NULLIF(TRIM(sp.item_name), ''),
|
||
NULLIF(TRIM(s.sku_name), ''),
|
||
NULLIF(TRIM(sp.sku_code), ''),
|
||
'未命名商品'
|
||
) AS product_name,
|
||
COALESCE(
|
||
NULLIF(TRIM(oi.category_code), ''),
|
||
NULLIF(TRIM(s.category_code), '')
|
||
) AS category_code,
|
||
COALESCE(NULLIF(TRIM(sp.branch_code), ''), NULLIF(TRIM(o.branch_code), '')) AS branch_code
|
||
FROM supplier_preparations sp
|
||
LEFT JOIN orders o ON o.order_code = sp.order_code
|
||
LEFT JOIN order_items oi ON oi.order_code = sp.order_code AND oi.sku_code IS NOT DISTINCT FROM sp.sku_code
|
||
LEFT JOIN skus s ON s.sku_code = sp.sku_code
|
||
WHERE ${filters.join(' AND ')}`,
|
||
params
|
||
);
|
||
const out: PrepInlineHit[] = [];
|
||
for (const row of result.rows) {
|
||
const req = await resolveCategoryQualityRequirement({
|
||
branchCode: row.branch_code ? String(row.branch_code) : null,
|
||
categoryCode: row.category_code ? String(row.category_code) : null,
|
||
skuCode: row.sku_code ? String(row.sku_code) : null,
|
||
});
|
||
if (!req.requires || normalizeReportType(req.report_type) !== reportType) continue;
|
||
out.push({
|
||
id: String(row.id),
|
||
sku_code: row.sku_code ? String(row.sku_code) : null,
|
||
product_name: String(row.product_name || '未命名商品'),
|
||
category_code: row.category_code ? String(row.category_code) : null,
|
||
});
|
||
}
|
||
return out;
|
||
}
|
||
|
||
async function insertPrepReportLinks(input: {
|
||
reportId: string;
|
||
prepIds: string[];
|
||
reportType: string;
|
||
linkedBy?: string | null;
|
||
}): Promise<void> {
|
||
const reportId = trimText(input.reportId);
|
||
const reportType = normalizeReportType(input.reportType);
|
||
if (!reportId) return;
|
||
const seen = new Set<string>();
|
||
for (const raw of input.prepIds) {
|
||
const prepId = trimText(raw);
|
||
if (!prepId || seen.has(prepId)) continue;
|
||
seen.add(prepId);
|
||
await voidPrepLinksForPrepType(prepId, reportType);
|
||
await pool.query(
|
||
`INSERT INTO quality_report_prep_links (
|
||
quality_report_id, preparation_id, report_type, link_source, linked_by, status
|
||
) VALUES ($1::uuid, $2::uuid, $3, $4, $5, $6)`,
|
||
[reportId, prepId, reportType, 'auto_match', input.linkedBy || null, QUALITY_REPORT_STATUS.active]
|
||
);
|
||
}
|
||
}
|
||
|
||
export async function uploadQualityReport(input: {
|
||
preparationId?: string | null;
|
||
purchaseCode?: string | null;
|
||
files: string[];
|
||
uploadedBy?: string | null;
|
||
sourceParty: QualityReportSourceParty;
|
||
branchCode?: string | null;
|
||
replacePaths?: string[] | null;
|
||
reportType?: string | null;
|
||
matchPesticideToDayPreps?: boolean;
|
||
deferPrepCoverage?: boolean;
|
||
}): Promise<QualityReportRow & { proposed_hits?: PrepInlineHit[]; candidate_hits?: PrepInlineHit[]; pending_confirm?: boolean }> {
|
||
const prepId = trimText(input.preparationId) || null;
|
||
const purchaseCode = trimText(input.purchaseCode) || null;
|
||
if (!prepId && !purchaseCode) {
|
||
throw Object.assign(new Error('缺少备货或自采单号'), { status: 400 });
|
||
}
|
||
if (!input.files?.length && !input.replacePaths?.length) {
|
||
throw Object.assign(new Error('请上传报告文件'), { status: 400 });
|
||
}
|
||
|
||
let orderCode: string | null = null;
|
||
let skuCode: string | null = null;
|
||
let supplierCode: string | null = null;
|
||
let branchCode = trimText(input.branchCode) || null;
|
||
let categoryCode: string | null = null;
|
||
let deliveryDate = shanghaiToday();
|
||
let shareMode: QualityReportShareMode = 'line';
|
||
let shareKey = '';
|
||
|
||
if (prepId) {
|
||
const ctx = await loadPrepReportContext(prepId);
|
||
if (!ctx) throw Object.assign(new Error('备货单不存在'), { status: 404 });
|
||
orderCode = ctx.orderCode;
|
||
skuCode = ctx.skuCode;
|
||
supplierCode = ctx.supplierCode;
|
||
branchCode = branchCode || ctx.branchCode;
|
||
categoryCode = ctx.categoryCode;
|
||
deliveryDate = ctx.deliveryDate;
|
||
shareMode = ctx.shareMode;
|
||
shareKey = ctx.shareKey;
|
||
} else if (purchaseCode) {
|
||
const ctx = await loadPurchaseReportContext(purchaseCode);
|
||
if (!ctx) throw Object.assign(new Error('自采单不存在'), { status: 404 });
|
||
orderCode = ctx.orderCode;
|
||
skuCode = ctx.skuCode;
|
||
supplierCode = ctx.supplierCode;
|
||
branchCode = branchCode || ctx.branchCode;
|
||
categoryCode = ctx.categoryCode;
|
||
deliveryDate = ctx.deliveryDate;
|
||
shareMode = ctx.shareMode;
|
||
shareKey = ctx.shareKey;
|
||
}
|
||
|
||
const req = await resolveCategoryQualityRequirement({
|
||
branchCode,
|
||
categoryCode,
|
||
skuCode,
|
||
});
|
||
// 允许未勾选分类也上传;显式传入类型优先,否则用分类默认
|
||
const reportType = input.reportType
|
||
? normalizeReportType(input.reportType)
|
||
: req.requires
|
||
? req.report_type
|
||
: 'other';
|
||
let reportLabel =
|
||
reportType === 'other' && req.requires && trimText(req.report_label)
|
||
? trimText(req.report_label)
|
||
: qualityReportTypeLabel(reportType, req.report_label);
|
||
// 未要求报告时仍按类型算共用(补传场景),否则用 other→line
|
||
shareMode = shareModeForReportType(reportType);
|
||
shareKey = buildQualityReportShareKey({
|
||
shareMode,
|
||
supplierCode,
|
||
deliveryDate,
|
||
categoryCode,
|
||
preparationId: prepId,
|
||
purchaseCode,
|
||
skuCode,
|
||
});
|
||
|
||
try {
|
||
const allowed = await assertReportTypeAllowed(reportType, branchCode);
|
||
if (!(reportType === 'other' && req.requires && trimText(req.report_label))) {
|
||
reportLabel = allowed.label;
|
||
}
|
||
} catch (e) {
|
||
// 分类要求的类型若已从目录删除,仍允许按该 code 上传(避免门禁卡死)
|
||
if (!(req.requires && normalizeReportType(req.report_type) === reportType)) throw e;
|
||
}
|
||
|
||
const savedPaths: string[] = [];
|
||
let firstImageBase64: string | null = null;
|
||
let firstPdfBase64: string | null = null;
|
||
for (const file of input.files || []) {
|
||
const parsed = await resolveMatchUploadEntry(file);
|
||
if (!parsed) continue;
|
||
const filename =
|
||
parsed.storedPath ||
|
||
(await saveBase64Upload(
|
||
'quality-reports',
|
||
parsed.content,
|
||
parsed.ext,
|
||
branchCode ? { objectPrefix: branchCode } : undefined
|
||
));
|
||
savedPaths.push(filename);
|
||
const ext = parsed.ext.toLowerCase();
|
||
if (!firstImageBase64 && IMAGE_EXTS.has(ext)) {
|
||
firstImageBase64 = parsed.content;
|
||
} else if (!firstPdfBase64 && ext === 'pdf') {
|
||
firstPdfBase64 = parsed.content;
|
||
}
|
||
}
|
||
const filePaths = [...(input.replacePaths || []).map(String).filter(Boolean), ...savedPaths];
|
||
if (!filePaths.length) {
|
||
throw Object.assign(new Error('未解析到有效文件'), { status: 400 });
|
||
}
|
||
|
||
const compareAt = await resolveCompareAt({
|
||
orderCode,
|
||
preparationId: prepId,
|
||
purchaseCode,
|
||
});
|
||
|
||
let tested_at: string | null = null;
|
||
let valid_from: string | null = null;
|
||
let valid_to: string | null = null;
|
||
let ai_raw: Record<string, unknown> | null = null;
|
||
let ai_parsed_at: string | null = null;
|
||
|
||
const deferPrepCoverage = Boolean(input.deferPrepCoverage && prepId);
|
||
const pesticideInline = Boolean(
|
||
!deferPrepCoverage && input.matchPesticideToDayPreps && prepId && reportType === 'pesticide'
|
||
);
|
||
|
||
if (firstImageBase64) {
|
||
if (deferPrepCoverage || pesticideInline) {
|
||
const meta = await parseReportMetaWithAi(firstImageBase64, branchCode, {
|
||
code: reportType,
|
||
label: reportLabel,
|
||
});
|
||
tested_at = meta.tested_at;
|
||
valid_from = meta.valid_from;
|
||
valid_to = meta.valid_to;
|
||
ai_raw = meta.ai_raw;
|
||
ai_parsed_at = new Date().toISOString();
|
||
} else {
|
||
const parsed = await parseReportDatesWithAi(firstImageBase64, branchCode, {
|
||
code: reportType,
|
||
label: reportLabel,
|
||
});
|
||
tested_at = parsed.tested_at;
|
||
valid_from = parsed.valid_from;
|
||
valid_to = parsed.valid_to;
|
||
ai_raw = parsed.ai_raw;
|
||
ai_parsed_at = new Date().toISOString();
|
||
}
|
||
} else if (firstPdfBase64 && deferPrepCoverage) {
|
||
const meta = await parseMatchUploadMeta(firstPdfBase64, 'pdf', branchCode, {
|
||
code: reportType,
|
||
label: reportLabel,
|
||
});
|
||
tested_at = meta.tested_at;
|
||
valid_from = meta.valid_from;
|
||
valid_to = meta.valid_to;
|
||
ai_raw = meta.ai_raw;
|
||
ai_parsed_at = new Date().toISOString();
|
||
}
|
||
|
||
// 检疫:按分公司配置的 1/2 天窗口覆盖有效期(有检验日才套用)
|
||
if (reportType === 'quarantine') {
|
||
const days = await getQuarantineValidDays(branchCode);
|
||
const window = applyQuarantineValidWindow(tested_at || valid_from, days);
|
||
if (window) {
|
||
valid_from = window.valid_from;
|
||
valid_to = window.valid_to;
|
||
if (!tested_at) tested_at = window.valid_from;
|
||
}
|
||
}
|
||
|
||
const validity_status = computeValidityStatus({
|
||
compareAt,
|
||
validFrom: valid_from,
|
||
validTo: valid_to,
|
||
testedAt: tested_at,
|
||
});
|
||
|
||
let pesticideLinkPrepIds: string[] = [];
|
||
let proposedHits: PrepInlineHit[] = [];
|
||
let candidateHits: PrepInlineHit[] = [];
|
||
if (deferPrepCoverage && prepId) {
|
||
const dayItems = await listSupplierDayReportPrepItems({
|
||
supplierCode,
|
||
deliveryDate,
|
||
branchCode,
|
||
reportType,
|
||
});
|
||
candidateHits = dayItems;
|
||
proposedHits = proposePrepInlineHits({
|
||
reportType,
|
||
sourcePrepId: prepId,
|
||
sourceSkuCode: skuCode,
|
||
sourceCategoryCode: categoryCode,
|
||
dayItems,
|
||
aiNames: extractAiProductNames(ai_raw),
|
||
});
|
||
shareMode = 'line';
|
||
shareKey = `${PREP_INLINE_STAGING_SHARE_PREFIX}${prepId}`;
|
||
const staleStaging = await pool.query(
|
||
`SELECT id FROM quality_reports
|
||
WHERE share_key = $1 AND status = $2`,
|
||
[shareKey, QUALITY_REPORT_STATUS.active]
|
||
);
|
||
for (const row of staleStaging.rows) {
|
||
await voidQualityReport(String(row.id));
|
||
}
|
||
} else if (pesticideInline && prepId) {
|
||
const dayItems = await listSupplierDayReportPrepItems({
|
||
supplierCode,
|
||
deliveryDate,
|
||
branchCode,
|
||
reportType: 'pesticide',
|
||
});
|
||
const names = extractAiProductNames(ai_raw);
|
||
const matched = matchDayItemsByProductNames(
|
||
names,
|
||
dayItems.map((it) => ({
|
||
sku_code: it.sku_code,
|
||
product_name: it.product_name,
|
||
specification: null,
|
||
unit: null,
|
||
prepare_qty: 0,
|
||
prep_count: 1,
|
||
matched_report_count: 0,
|
||
category_code: it.category_code,
|
||
}))
|
||
);
|
||
const skuSet = new Set(matched.skuCodes);
|
||
if (skuCode) skuSet.add(skuCode);
|
||
pesticideLinkPrepIds = dayItems
|
||
.filter((it) => it.sku_code && skuSet.has(it.sku_code))
|
||
.map((it) => it.id);
|
||
if (!pesticideLinkPrepIds.includes(prepId)) pesticideLinkPrepIds.unshift(prepId);
|
||
shareMode = 'manual';
|
||
const supplierKey = trimText(supplierCode) || SELF_SUPPLIER_KEY;
|
||
const skuPart = [...skuSet].sort().join(',') || '_';
|
||
shareKey = `mn|${supplierKey}|${deliveryDate}|${skuPart}`;
|
||
}
|
||
|
||
let existing: QualityReportRow | null = null;
|
||
if (!deferPrepCoverage && shareMode !== 'line' && shareKey) {
|
||
const shared = await pool.query(
|
||
`SELECT * FROM quality_reports
|
||
WHERE share_key = $1 AND report_type = $2 AND status = $3
|
||
ORDER BY uploaded_at DESC LIMIT 1`,
|
||
[shareKey, reportType, QUALITY_REPORT_STATUS.active]
|
||
);
|
||
existing = shared.rows[0] ? mapReportRow(shared.rows[0]) : null;
|
||
}
|
||
if (!existing && prepId) {
|
||
const direct = await pool.query(
|
||
`SELECT * FROM quality_reports
|
||
WHERE preparation_id = $1 AND report_type = $2 AND status = $3
|
||
ORDER BY uploaded_at DESC LIMIT 1`,
|
||
[prepId, reportType, QUALITY_REPORT_STATUS.active]
|
||
);
|
||
const row = direct.rows[0] ? mapReportRow(direct.rows[0]) : null;
|
||
if (!(pesticideInline && row?.share_mode === 'produce_day')) {
|
||
existing = row;
|
||
}
|
||
}
|
||
if (!deferPrepCoverage && !existing && purchaseCode) {
|
||
const direct = await pool.query(
|
||
`SELECT * FROM quality_reports
|
||
WHERE purchase_code = $1 AND report_type = $2 AND status = $3
|
||
AND COALESCE(sku_code, '') = COALESCE($4, '')
|
||
ORDER BY uploaded_at DESC LIMIT 1`,
|
||
[purchaseCode, reportType, QUALITY_REPORT_STATUS.active, trimText(skuCode) || null]
|
||
);
|
||
existing = direct.rows[0] ? mapReportRow(direct.rows[0]) : null;
|
||
}
|
||
|
||
if (!deferPrepCoverage && existing?.id) {
|
||
await voidQualityReport(existing.id);
|
||
}
|
||
if (!deferPrepCoverage && prepId) {
|
||
await voidPrepLinksForPrepType(prepId, reportType);
|
||
}
|
||
|
||
// T9:INSERT file_paths 前校验归属(跨分支 key ⇒ 403,不落库)
|
||
await assertOwnedStoragePaths({ branchCode }, 'quality-reports', filePaths);
|
||
|
||
const result = await pool.query(
|
||
`INSERT INTO quality_reports (
|
||
branch_code, report_type, report_label, preparation_id, purchase_code,
|
||
order_code, sku_code, supplier_code, file_paths, status, source_party,
|
||
uploaded_by, tested_at, valid_from, valid_to, compare_at, validity_status,
|
||
ai_raw, ai_parsed_at, share_mode, share_key, category_code, delivery_date
|
||
) VALUES (
|
||
$1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14,$15,$16::date,$17,$18::jsonb,$19,
|
||
$20,$21,$22,$23::date
|
||
) RETURNING *`,
|
||
[
|
||
branchCode,
|
||
reportType,
|
||
reportLabel,
|
||
prepId,
|
||
purchaseCode,
|
||
orderCode,
|
||
skuCode,
|
||
supplierCode,
|
||
filePaths,
|
||
QUALITY_REPORT_STATUS.active,
|
||
input.sourceParty,
|
||
input.uploadedBy || null,
|
||
tested_at,
|
||
valid_from,
|
||
valid_to,
|
||
compareAt,
|
||
validity_status,
|
||
ai_raw ? JSON.stringify(ai_raw) : null,
|
||
ai_parsed_at,
|
||
shareMode,
|
||
shareKey,
|
||
categoryCode,
|
||
deliveryDate,
|
||
]
|
||
);
|
||
|
||
const saved = mapReportRow(result.rows[0]);
|
||
if (pesticideInline && saved.id && pesticideLinkPrepIds.length) {
|
||
await insertPrepReportLinks({
|
||
reportId: saved.id,
|
||
prepIds: pesticideLinkPrepIds,
|
||
reportType,
|
||
linkedBy: input.uploadedBy || null,
|
||
});
|
||
}
|
||
if (deferPrepCoverage) {
|
||
return { ...saved, proposed_hits: proposedHits, candidate_hits: candidateHits, pending_confirm: true };
|
||
}
|
||
return saved;
|
||
}
|
||
|
||
export async function confirmPrepInlineQualityReport(input: {
|
||
reportId: string;
|
||
supplierCode: string;
|
||
uploadedBy?: string | null;
|
||
prepIds?: string[] | null;
|
||
}): Promise<QualityReportRow & { proposed_hits: PrepInlineHit[] }> {
|
||
const reportId = trimText(input.reportId);
|
||
const supplierCode = trimText(input.supplierCode);
|
||
if (!reportId) throw Object.assign(new Error('缺少报告 id'), { status: 400 });
|
||
const current = await pool.query(
|
||
`SELECT * FROM quality_reports WHERE id = $1::uuid AND status = $2 LIMIT 1`,
|
||
[reportId, QUALITY_REPORT_STATUS.active]
|
||
);
|
||
const row = current.rows[0];
|
||
if (!row) throw Object.assign(new Error('报告不存在或已作废'), { status: 404 });
|
||
if (trimText(row.supplier_code) !== supplierCode) {
|
||
throw Object.assign(new Error('无权确认该报告'), { status: 403 });
|
||
}
|
||
if (!isPrepInlineStagingShareKey(row.share_key)) {
|
||
throw Object.assign(new Error('该报告已确认'), { status: 409 });
|
||
}
|
||
const prepId = trimText(row.preparation_id);
|
||
if (!prepId) throw Object.assign(new Error('缺少备货 id'), { status: 400 });
|
||
const ctx = await loadPrepReportContext(prepId);
|
||
if (!ctx) throw Object.assign(new Error('备货单不存在'), { status: 404 });
|
||
if (trimText(ctx.supplierCode) !== supplierCode) {
|
||
throw Object.assign(new Error('无权确认该报告'), { status: 403 });
|
||
}
|
||
const reportType = normalizeReportType(row.report_type);
|
||
const dayItems = await listSupplierDayReportPrepItems({
|
||
supplierCode,
|
||
deliveryDate: ctx.deliveryDate,
|
||
branchCode: ctx.branchCode,
|
||
reportType,
|
||
});
|
||
const proposedHits = intersectPrepInlineHits(dayItems, input.prepIds);
|
||
if (!proposedHits.length) {
|
||
throw Object.assign(new Error('请选择商品'), { status: 400 });
|
||
}
|
||
let shareMode: QualityReportShareMode = shareModeForReportType(reportType);
|
||
if (reportType === 'pesticide') shareMode = 'manual';
|
||
const skuCodes = [...new Set(proposedHits.map((h) => trimText(h.sku_code)).filter(Boolean))].sort();
|
||
const shareKey =
|
||
shareMode === 'manual'
|
||
? `mn|${trimText(ctx.supplierCode) || SELF_SUPPLIER_KEY}|${ctx.deliveryDate}|${skuCodes.join(',') || '_'}`
|
||
: buildQualityReportShareKey({
|
||
shareMode,
|
||
supplierCode: ctx.supplierCode,
|
||
deliveryDate: ctx.deliveryDate,
|
||
categoryCode: ctx.categoryCode,
|
||
preparationId: prepId,
|
||
skuCode: ctx.skuCode,
|
||
});
|
||
if (shareMode !== 'produce_day' && shareKey) {
|
||
const others = await pool.query(
|
||
`SELECT id FROM quality_reports
|
||
WHERE share_key = $1 AND report_type = $2 AND status = $3 AND id <> $4::uuid`,
|
||
[shareKey, reportType, QUALITY_REPORT_STATUS.active, reportId]
|
||
);
|
||
for (const other of others.rows) {
|
||
await voidQualityReport(String(other.id));
|
||
}
|
||
}
|
||
await pool.query(
|
||
`UPDATE quality_reports
|
||
SET share_mode = $2, share_key = $3, category_code = $4, updated_at = NOW()
|
||
WHERE id = $1::uuid`,
|
||
[reportId, shareMode, shareKey, ctx.categoryCode]
|
||
);
|
||
await insertPrepReportLinks({
|
||
reportId,
|
||
prepIds: proposedHits.map((h) => h.id),
|
||
reportType,
|
||
linkedBy: input.uploadedBy || null,
|
||
});
|
||
const refreshed = await pool.query(`SELECT * FROM quality_reports WHERE id = $1::uuid LIMIT 1`, [reportId]);
|
||
return { ...mapReportRow(refreshed.rows[0] || row), proposed_hits: proposedHits };
|
||
}
|
||
|
||
export async function updateQualityReportValidity(input: {
|
||
id: string;
|
||
testedAt?: string | null;
|
||
validFrom?: string | null;
|
||
validTo?: string | null;
|
||
compareAt?: string | null;
|
||
}): Promise<QualityReportRow> {
|
||
const current = await pool.query(`SELECT * FROM quality_reports WHERE id = $1 LIMIT 1`, [input.id]);
|
||
const row = current.rows[0];
|
||
if (!row) throw Object.assign(new Error('报告不存在'), { status: 404 });
|
||
|
||
const tested_at =
|
||
input.testedAt !== undefined ? parseDateOnly(input.testedAt) : parseDateOnly(row.tested_at);
|
||
const valid_from =
|
||
input.validFrom !== undefined ? parseDateOnly(input.validFrom) : parseDateOnly(row.valid_from);
|
||
const valid_to =
|
||
input.validTo !== undefined ? parseDateOnly(input.validTo) : parseDateOnly(row.valid_to);
|
||
const compare_at =
|
||
input.compareAt !== undefined
|
||
? parseDateOnly(input.compareAt) || shanghaiToday()
|
||
: parseDateOnly(row.compare_at) || shanghaiToday();
|
||
|
||
const validity_status = computeValidityStatus({
|
||
compareAt: compare_at,
|
||
validFrom: valid_from,
|
||
validTo: valid_to,
|
||
testedAt: tested_at,
|
||
});
|
||
|
||
const updated = await pool.query(
|
||
`UPDATE quality_reports SET
|
||
tested_at = $2, valid_from = $3, valid_to = $4, compare_at = $5::date,
|
||
validity_status = $6, updated_at = NOW()
|
||
WHERE id = $1
|
||
RETURNING *`,
|
||
[input.id, tested_at, valid_from, valid_to, compare_at, validity_status]
|
||
);
|
||
return mapReportRow(updated.rows[0]);
|
||
}
|
||
|
||
/** 台账作废:status=20,列表默认不再展示 */
|
||
export async function voidQualityReport(id: string): Promise<QualityReportRow> {
|
||
const reportId = trimText(id);
|
||
if (!reportId) {
|
||
throw Object.assign(new Error('缺少报告 id'), { status: 400 });
|
||
}
|
||
const updated = await pool.query(
|
||
`UPDATE quality_reports
|
||
SET status = $2, updated_at = NOW()
|
||
WHERE id = $1::uuid AND status = $3
|
||
RETURNING *`,
|
||
[reportId, QUALITY_REPORT_STATUS.voided, QUALITY_REPORT_STATUS.active]
|
||
);
|
||
if (!updated.rows[0]) {
|
||
throw Object.assign(new Error('报告不存在或已作废'), { status: 404 });
|
||
}
|
||
await voidPrepLinksForReport(reportId);
|
||
return mapReportRow(updated.rows[0]);
|
||
}
|
||
|
||
/**
|
||
* 供应商取消「备货行内上传待确认」报告:归属 + 暂存态校验后作废。
|
||
*
|
||
* 归属校验必须落在 service 层——路由层不得内嵌 SQL(见 tests/routeLayerBoundary.test.ts 棘轮);
|
||
* 行为/错误码与原先路由内联查询一致(404 not_found / 409 not_staging)。
|
||
*/
|
||
export async function discardSupplierStagingQualityReport(
|
||
id: string,
|
||
supplierCode: string
|
||
): Promise<QualityReportRow> {
|
||
const reportId = trimText(id);
|
||
const code = trimText(supplierCode);
|
||
if (!reportId) {
|
||
throw Object.assign(new Error('缺少报告 id'), { status: 400 });
|
||
}
|
||
const owned = await pool.query(
|
||
`SELECT id, share_key FROM quality_reports
|
||
WHERE id = $1::uuid AND supplier_code = $2 AND status = $3
|
||
LIMIT 1`,
|
||
[reportId, code, QUALITY_REPORT_STATUS.active]
|
||
);
|
||
if (!owned.rows[0]) {
|
||
throw Object.assign(new Error('报告不存在或无权操作'), { status: 404, code: 'not_found' });
|
||
}
|
||
if (!isPrepInlineStagingShareKey(owned.rows[0].share_key)) {
|
||
throw Object.assign(new Error('只能取消未确认的报告'), { status: 409, code: 'not_staging' });
|
||
}
|
||
return voidQualityReport(reportId);
|
||
}
|
||
|
||
export async function bindQualityReportBatchNo(input: {
|
||
preparationId?: string | null;
|
||
purchaseCode?: string | null;
|
||
skuCode?: string | null;
|
||
orderCode?: string | null;
|
||
supplierCode?: string | null;
|
||
batchNo: string;
|
||
client?: PoolClient;
|
||
}): Promise<void> {
|
||
const client = input.client || pool;
|
||
const batchNo = trimText(input.batchNo);
|
||
if (!batchNo) return;
|
||
|
||
if (trimText(input.preparationId)) {
|
||
await client.query(
|
||
`UPDATE quality_reports SET batch_no = $2, updated_at = NOW()
|
||
WHERE status = $3 AND (batch_no IS NULL OR batch_no = '')
|
||
AND (
|
||
preparation_id = $1
|
||
OR id IN (
|
||
SELECT quality_report_id FROM quality_report_prep_links
|
||
WHERE preparation_id = $1::uuid AND status = $3
|
||
)
|
||
)`,
|
||
[trimText(input.preparationId), batchNo, QUALITY_REPORT_STATUS.active]
|
||
);
|
||
return;
|
||
}
|
||
if (trimText(input.purchaseCode)) {
|
||
await client.query(
|
||
`UPDATE quality_reports SET batch_no = $2, updated_at = NOW()
|
||
WHERE purchase_code = $1
|
||
AND status = $3
|
||
AND ($4::text IS NULL OR sku_code IS NOT DISTINCT FROM $4)
|
||
AND (batch_no IS NULL OR batch_no = '')`,
|
||
[
|
||
trimText(input.purchaseCode),
|
||
batchNo,
|
||
QUALITY_REPORT_STATUS.active,
|
||
trimText(input.skuCode) || null,
|
||
]
|
||
);
|
||
return;
|
||
}
|
||
if (trimText(input.orderCode) && trimText(input.skuCode)) {
|
||
await client.query(
|
||
`UPDATE quality_reports SET batch_no = $3, updated_at = NOW()
|
||
WHERE order_code = $1
|
||
AND sku_code IS NOT DISTINCT FROM $2
|
||
AND ($4::text IS NULL OR COALESCE(supplier_code, '') = COALESCE($4, ''))
|
||
AND status = $5
|
||
AND (batch_no IS NULL OR batch_no = '')`,
|
||
[
|
||
trimText(input.orderCode),
|
||
trimText(input.skuCode),
|
||
batchNo,
|
||
trimText(input.supplierCode) || null,
|
||
QUALITY_REPORT_STATUS.active,
|
||
]
|
||
);
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 硬闸门用的「有效报告」解析。
|
||
*
|
||
* ⚠️ 必须排除未确认的行内上传(`share_key` 以 `st|` 开头):supplier 上传后要点确认单确定覆盖范围,
|
||
* 未确认前不算已覆盖——与 `isPrepInlineReportCovered` 同一口径。否则小程序在上传后、确认前异常退出,
|
||
* 会留下一条 active 的 staging 报告把闸门放行,而工作台同时显示「未覆盖」。
|
||
* 见 docs/design/20260921-quality-report-hard-gate-exclude-staging.md
|
||
* (`linked` 分支无需加:它要求 `is_library = true`,而行内上传不写该列,默认 false。)
|
||
*/
|
||
export async function resolveReportForHardGate(input: {
|
||
preparationId: string;
|
||
reportType: string;
|
||
client?: PoolClient | typeof pool;
|
||
}): Promise<QualityReportRow | null> {
|
||
const prepId = trimText(input.preparationId);
|
||
const reportType = normalizeReportType(input.reportType);
|
||
if (!prepId) return null;
|
||
const db = input.client || pool;
|
||
|
||
const direct = await db.query(
|
||
`SELECT * FROM quality_reports
|
||
WHERE preparation_id = $1 AND report_type = $2 AND status = $3
|
||
AND COALESCE(share_key, '') NOT LIKE $4
|
||
ORDER BY uploaded_at DESC LIMIT 1`,
|
||
[prepId, reportType, QUALITY_REPORT_STATUS.active, `${PREP_INLINE_STAGING_SHARE_PREFIX}%`]
|
||
);
|
||
if (direct.rows[0]) {
|
||
const mapped = mapReportRow(direct.rows[0]);
|
||
mapped.source = 'prep';
|
||
return mapped;
|
||
}
|
||
|
||
const linked = await db.query(
|
||
`SELECT qr.*
|
||
FROM quality_report_prep_links l
|
||
JOIN quality_reports qr ON qr.id = l.quality_report_id
|
||
WHERE l.preparation_id = $1::uuid
|
||
AND l.report_type = $2
|
||
AND l.status = $3
|
||
AND qr.status = $3
|
||
AND qr.is_library = true
|
||
ORDER BY qr.uploaded_at DESC LIMIT 1`,
|
||
[prepId, reportType, QUALITY_REPORT_STATUS.active]
|
||
);
|
||
if (linked.rows[0]) {
|
||
const mapped = mapReportRow(linked.rows[0]);
|
||
mapped.source = 'library';
|
||
return mapped;
|
||
}
|
||
|
||
const ctx = await loadPrepReportContext(prepId, db);
|
||
if (ctx) {
|
||
const shareMode = shareModeForReportType(reportType);
|
||
if (shareMode !== 'line') {
|
||
const shareKey = buildQualityReportShareKey({
|
||
shareMode,
|
||
supplierCode: ctx.supplierCode,
|
||
deliveryDate: ctx.deliveryDate,
|
||
categoryCode: ctx.categoryCode,
|
||
preparationId: prepId,
|
||
});
|
||
const shared = await getActiveByShareKey(shareKey, db, reportType);
|
||
if (shared) {
|
||
shared.source = 'shared';
|
||
shared.shared = shared.preparation_id !== prepId;
|
||
return shared;
|
||
}
|
||
}
|
||
}
|
||
return null;
|
||
}
|
||
|
||
export async function assertQualityReportHardGate(input: {
|
||
branchCode?: string | null;
|
||
categoryCode?: string | null;
|
||
skuCode?: string | null;
|
||
preparationId?: string | null;
|
||
purchaseCode?: string | null;
|
||
orderCode?: string | null;
|
||
supplierCode?: string | null;
|
||
/** inbound=验收入库;complete_supply=完成供货 */
|
||
phase?: 'inbound' | 'complete_supply';
|
||
client?: PoolClient;
|
||
}): Promise<void> {
|
||
const enabled = await isQualityReportHardGateEnabled(input.branchCode);
|
||
if (!enabled) return;
|
||
|
||
const req = await resolveCategoryQualityRequirement(
|
||
{
|
||
branchCode: input.branchCode,
|
||
categoryCode: input.categoryCode,
|
||
skuCode: input.skuCode,
|
||
},
|
||
input.client || pool
|
||
);
|
||
if (!req.requires) return;
|
||
|
||
let report: QualityReportRow | null = null;
|
||
const db = input.client || pool;
|
||
if (trimText(input.preparationId)) {
|
||
report = await resolveReportForHardGate({
|
||
preparationId: trimText(input.preparationId),
|
||
reportType: req.report_type,
|
||
client: db,
|
||
});
|
||
} else if (trimText(input.purchaseCode)) {
|
||
report = await getActiveQualityReportForPurchase(
|
||
trimText(input.purchaseCode),
|
||
input.skuCode,
|
||
db
|
||
);
|
||
} else if (trimText(input.orderCode) && trimText(input.skuCode)) {
|
||
// 同 resolveReportForHardGate:未确认的行内上传(st|)不算已覆盖
|
||
const found = await db.query(
|
||
`SELECT * FROM quality_reports
|
||
WHERE order_code = $1
|
||
AND sku_code IS NOT DISTINCT FROM $2
|
||
AND ($3::text IS NULL OR COALESCE(supplier_code, '') = COALESCE($3, ''))
|
||
AND status = $4
|
||
AND COALESCE(share_key, '') NOT LIKE $5
|
||
ORDER BY uploaded_at DESC
|
||
LIMIT 1`,
|
||
[
|
||
trimText(input.orderCode),
|
||
trimText(input.skuCode),
|
||
trimText(input.supplierCode) || null,
|
||
QUALITY_REPORT_STATUS.active,
|
||
`${PREP_INLINE_STAGING_SHARE_PREFIX}%`,
|
||
]
|
||
);
|
||
report = found.rows[0] ? mapReportRow(found.rows[0]) : null;
|
||
}
|
||
|
||
if (!report || report.validity_status !== 'in_range') {
|
||
const label = req.report_label;
|
||
const action = input.phase === 'complete_supply' ? '完成供货' : '入库';
|
||
const reason = !report
|
||
? `该分类需上传有效期内的${label}后方可${action}`
|
||
: report.validity_status === 'expired'
|
||
? `${label}已过期,请重新上传有效报告后再${action}`
|
||
: report.validity_status === 'not_yet'
|
||
? `${label}尚未生效,请核对日期后再${action}`
|
||
: `${label}日期未识别或未在有效期,请补录有效期后再${action}`;
|
||
throw Object.assign(new Error(reason), { status: 409, code: 'quality_report_required' });
|
||
}
|
||
}
|
||
|
||
export function validityStatusLabel(status: ValidityStatus | string | null | undefined): string {
|
||
switch (trimText(status)) {
|
||
case 'in_range':
|
||
return '在期内';
|
||
case 'expired':
|
||
return '已过期';
|
||
case 'not_yet':
|
||
return '未生效';
|
||
default:
|
||
return '待识别';
|
||
}
|
||
}
|
||
|
||
export type QualityReportLedgerItem = QualityReportRow & {
|
||
validity_label: string;
|
||
related_batch_nos: string[];
|
||
share_hint?: string;
|
||
};
|
||
|
||
async function resolveRelatedBatchNos(
|
||
reports: QualityReportRow[]
|
||
): Promise<Map<string, string[]>> {
|
||
const out = new Map<string, string[]>();
|
||
if (!reports.length) return out;
|
||
|
||
const prepIds = [
|
||
...new Set(reports.map((r) => trimText(r.preparation_id)).filter(Boolean)),
|
||
];
|
||
const shareKeys = [
|
||
...new Set(reports.map((r) => trimText(r.share_key)).filter(Boolean)),
|
||
];
|
||
|
||
const prepBatchMap = new Map<string, string[]>();
|
||
if (prepIds.length) {
|
||
const prepBatches = await pool.query(
|
||
`SELECT sp.id::text AS prep_id,
|
||
array_agg(DISTINCT NULLIF(TRIM(i.inbound_batch_no), ''))
|
||
FILTER (WHERE NULLIF(TRIM(i.inbound_batch_no), '') IS NOT NULL) AS batches
|
||
FROM supplier_preparations sp
|
||
LEFT JOIN inspections i
|
||
ON i.order_code = sp.order_code
|
||
AND i.sku_code IS NOT DISTINCT FROM sp.sku_code
|
||
WHERE sp.id = ANY($1::uuid[])
|
||
GROUP BY sp.id`,
|
||
[prepIds]
|
||
);
|
||
for (const row of prepBatches.rows) {
|
||
prepBatchMap.set(
|
||
String(row.prep_id),
|
||
Array.isArray(row.batches) ? row.batches.map(String).filter(Boolean) : []
|
||
);
|
||
}
|
||
}
|
||
|
||
const shareBatchMap = new Map<string, string[]>();
|
||
if (shareKeys.length) {
|
||
const shareBatches = await pool.query(
|
||
`SELECT qr.share_key,
|
||
array_agg(DISTINCT b.batch_no) FILTER (WHERE b.batch_no IS NOT NULL) AS batches
|
||
FROM quality_reports qr
|
||
LEFT JOIN LATERAL (
|
||
SELECT NULLIF(TRIM(qr.batch_no), '') AS batch_no
|
||
UNION
|
||
SELECT NULLIF(TRIM(i.inbound_batch_no), '')
|
||
FROM supplier_preparations sp
|
||
JOIN inspections i
|
||
ON i.order_code = sp.order_code
|
||
AND i.sku_code IS NOT DISTINCT FROM sp.sku_code
|
||
WHERE sp.id = qr.preparation_id
|
||
) b ON TRUE
|
||
WHERE qr.status = $1
|
||
AND qr.share_key = ANY($2::text[])
|
||
GROUP BY qr.share_key`,
|
||
[QUALITY_REPORT_STATUS.active, shareKeys]
|
||
);
|
||
for (const row of shareBatches.rows) {
|
||
shareBatchMap.set(
|
||
String(row.share_key),
|
||
Array.isArray(row.batches) ? row.batches.map(String).filter(Boolean) : []
|
||
);
|
||
}
|
||
}
|
||
|
||
for (const r of reports) {
|
||
const set = new Set<string>();
|
||
if (trimText(r.batch_no)) set.add(trimText(r.batch_no));
|
||
const prepId = trimText(r.preparation_id);
|
||
if (prepId) {
|
||
for (const b of prepBatchMap.get(prepId) || []) set.add(b);
|
||
}
|
||
const sk = trimText(r.share_key);
|
||
if (sk) {
|
||
for (const b of shareBatchMap.get(sk) || []) set.add(b);
|
||
}
|
||
out.set(r.id, [...set].slice(0, 20));
|
||
}
|
||
return out;
|
||
}
|
||
|
||
function toLedgerItem(
|
||
row: QualityReportRow,
|
||
related: string[],
|
||
shareHint?: string
|
||
): QualityReportLedgerItem {
|
||
return {
|
||
...row,
|
||
validity_label: validityStatusLabel(row.validity_status),
|
||
related_batch_nos: related,
|
||
share_hint: shareHint,
|
||
};
|
||
}
|
||
|
||
/** Web 检验报告台账 */
|
||
export async function listQualityReportsLedger(input: {
|
||
dateFrom?: string | null;
|
||
dateTo?: string | null;
|
||
supplierCode?: string | null;
|
||
batchNo?: string | null;
|
||
validityStatus?: string | null;
|
||
q?: string | null;
|
||
libraryOnly?: boolean;
|
||
includeVoided?: boolean;
|
||
requestHost?: string | null;
|
||
limit?: number;
|
||
}): Promise<QualityReportLedgerItem[]> {
|
||
const params: unknown[] = input.includeVoided
|
||
? [[QUALITY_REPORT_STATUS.active, QUALITY_REPORT_STATUS.voided]]
|
||
: [QUALITY_REPORT_STATUS.active];
|
||
const where: string[] = input.includeVoided ? ['status = ANY($1::int[])'] : ['status = $1'];
|
||
|
||
if (input.libraryOnly) {
|
||
where.push(`is_library = true`);
|
||
}
|
||
|
||
const dateFrom = trimText(input.dateFrom);
|
||
if (dateFrom) {
|
||
params.push(dateFrom);
|
||
where.push(
|
||
`COALESCE(report_date, delivery_date, uploaded_at::date) >= $${params.length}::date`
|
||
);
|
||
}
|
||
const dateTo = trimText(input.dateTo);
|
||
if (dateTo) {
|
||
params.push(dateTo);
|
||
where.push(
|
||
`COALESCE(report_date, delivery_date, uploaded_at::date) <= $${params.length}::date`
|
||
);
|
||
}
|
||
const supplierCode = trimText(input.supplierCode);
|
||
if (supplierCode) {
|
||
params.push(supplierCode);
|
||
where.push(`supplier_code = $${params.length}`);
|
||
}
|
||
const batchNo = trimText(input.batchNo);
|
||
if (batchNo) {
|
||
params.push(batchNo);
|
||
where.push(
|
||
`(batch_no = $${params.length} OR EXISTS (
|
||
SELECT 1 FROM supplier_preparations sp
|
||
JOIN inspections i ON i.order_code = sp.order_code
|
||
AND i.sku_code IS NOT DISTINCT FROM sp.sku_code
|
||
WHERE sp.id = quality_reports.preparation_id
|
||
AND NULLIF(TRIM(i.inbound_batch_no), '') = $${params.length}
|
||
))`
|
||
);
|
||
}
|
||
const validityStatus = trimText(input.validityStatus);
|
||
if (validityStatus) {
|
||
params.push(validityStatus);
|
||
where.push(`validity_status = $${params.length}`);
|
||
}
|
||
const q = trimText(input.q);
|
||
if (q) {
|
||
params.push(`%${q}%`);
|
||
where.push(
|
||
`(report_label ILIKE $${params.length}
|
||
OR share_key ILIKE $${params.length}
|
||
OR category_code ILIKE $${params.length}
|
||
OR CAST(preparation_id AS text) ILIKE $${params.length}
|
||
OR COALESCE(batch_no, '') ILIKE $${params.length}
|
||
OR COALESCE(supplier_code, '') ILIKE $${params.length}
|
||
OR COALESCE(product_name, '') ILIKE $${params.length}
|
||
OR COALESCE(testing_org, '') ILIKE $${params.length}
|
||
OR COALESCE(inspected_org, '') ILIKE $${params.length}
|
||
OR COALESCE(specification, '') ILIKE $${params.length})`
|
||
);
|
||
}
|
||
|
||
const limit = Math.min(Math.max(Number(input.limit) || 100, 1), 300);
|
||
params.push(limit);
|
||
|
||
const result = await pool.query(
|
||
`SELECT * FROM quality_reports
|
||
WHERE ${where.join(' AND ')}
|
||
ORDER BY uploaded_at DESC NULLS LAST
|
||
LIMIT $${params.length}`,
|
||
params
|
||
);
|
||
|
||
const host = input.requestHost || null;
|
||
const rows = result.rows.map((r) => mapReportRow(r, host));
|
||
const relatedMap = await resolveRelatedBatchNos(rows);
|
||
return rows.map((r) =>
|
||
toLedgerItem(r, relatedMap.get(r.id) || [], qualityReportShareHint(r.report_type))
|
||
);
|
||
}
|
||
|
||
export type SupplierQualityPendingGroup = {
|
||
share_key: string;
|
||
share_hint: string;
|
||
report_type: string;
|
||
report_label: string;
|
||
delivery_date: string | null;
|
||
category_code: string | null;
|
||
item_names: string[];
|
||
preparation_id: string;
|
||
prep_count: number;
|
||
};
|
||
|
||
/** 供应商小程序:已上传台账 + 待上传共用组 */
|
||
export async function listSupplierQualityReportWorkbench(input: {
|
||
supplierCode: string;
|
||
requestHost?: string | null;
|
||
daysBack?: number;
|
||
}): Promise<{
|
||
uploaded: QualityReportLedgerItem[];
|
||
pending: SupplierQualityPendingGroup[];
|
||
}> {
|
||
const supplierCode = trimText(input.supplierCode);
|
||
if (!supplierCode) return { uploaded: [], pending: [] };
|
||
|
||
const daysBack = Math.min(Math.max(Number(input.daysBack) || 14, 1), 60);
|
||
const host = input.requestHost || null;
|
||
|
||
const uploadedResult = await pool.query(
|
||
`SELECT * FROM quality_reports
|
||
WHERE status = $1
|
||
AND supplier_code = $2
|
||
AND COALESCE(uploaded_at, created_at) >= (NOW() - ($3::text || ' days')::interval)
|
||
ORDER BY uploaded_at DESC NULLS LAST
|
||
LIMIT 100`,
|
||
[QUALITY_REPORT_STATUS.active, supplierCode, String(daysBack)]
|
||
);
|
||
const uploadedRows = uploadedResult.rows.map((r) => mapReportRow(r, host));
|
||
const relatedMap = await resolveRelatedBatchNos(uploadedRows);
|
||
const uploaded = uploadedRows.map((r) =>
|
||
toLedgerItem(r, relatedMap.get(r.id) || [], qualityReportShareHint(r.report_type))
|
||
);
|
||
|
||
const activePreps = await pool.query(
|
||
`SELECT sp.id::text AS id, sp.order_code, sp.sku_code, sp.supplier_code, sp.branch_code,
|
||
sp.item_name,
|
||
COALESCE(
|
||
NULLIF(TRIM(oi.category_code), ''),
|
||
NULLIF(TRIM(s.category_code), '')
|
||
) AS category_code,
|
||
COALESCE(NULLIF(TRIM(sp.item_name), ''), NULLIF(TRIM(oi.item_name), ''), NULLIF(TRIM(s.sku_name), '')) AS sku_name,
|
||
to_char(COALESCE(o.delivery_date, sp.prepare_time, sp.created_at)::date, 'YYYY-MM-DD') AS delivery_date
|
||
FROM supplier_preparations sp
|
||
LEFT JOIN orders o ON o.order_code = sp.order_code
|
||
LEFT JOIN order_items oi ON oi.order_code = sp.order_code AND oi.sku_code IS NOT DISTINCT FROM sp.sku_code
|
||
LEFT JOIN skus s ON s.sku_code = sp.sku_code
|
||
WHERE sp.supplier_code = $1
|
||
AND COALESCE(sp.is_stockout, false) = false
|
||
AND COALESCE(sp.transferred_to_purchase, false) = false
|
||
AND sp.prepare_status < 40
|
||
AND COALESCE(sp.prepare_time, sp.created_at) >= (NOW() - ($2::text || ' days')::interval)
|
||
ORDER BY sp.created_at DESC
|
||
LIMIT 200`,
|
||
[supplierCode, String(daysBack)]
|
||
);
|
||
|
||
const reportByPrep = await mapQualityReportsByPrepIds(
|
||
activePreps.rows.map((r) => String(r.id))
|
||
);
|
||
|
||
const pendingMap = new Map<string, SupplierQualityPendingGroup>();
|
||
for (const row of activePreps.rows) {
|
||
const prepId = String(row.id);
|
||
if (reportByPrep[prepId]) continue;
|
||
|
||
const req = await resolveCategoryQualityRequirement({
|
||
branchCode: row.branch_code ? String(row.branch_code) : null,
|
||
skuCode: row.sku_code ? String(row.sku_code) : null,
|
||
categoryCode: row.category_code ? String(row.category_code) : null,
|
||
});
|
||
if (!req.requires) continue;
|
||
|
||
const shareMode = shareModeForReportType(req.report_type);
|
||
const shareKey = buildQualityReportShareKey({
|
||
shareMode,
|
||
supplierCode,
|
||
deliveryDate: row.delivery_date ? String(row.delivery_date) : null,
|
||
categoryCode: row.category_code ? String(row.category_code) : null,
|
||
preparationId: prepId,
|
||
skuCode: row.sku_code ? String(row.sku_code) : null,
|
||
});
|
||
|
||
const existing = pendingMap.get(shareKey);
|
||
const itemName = String(row.sku_name || row.item_name || row.sku_code || prepId);
|
||
if (existing) {
|
||
existing.prep_count += 1;
|
||
if (!existing.item_names.includes(itemName) && existing.item_names.length < 8) {
|
||
existing.item_names.push(itemName);
|
||
}
|
||
continue;
|
||
}
|
||
pendingMap.set(shareKey, {
|
||
share_key: shareKey,
|
||
share_hint: qualityReportShareHint(req.report_type),
|
||
report_type: req.report_type || 'other',
|
||
report_label: req.report_label || qualityReportTypeLabel(req.report_type),
|
||
delivery_date: parseDateOnly(row.delivery_date),
|
||
category_code: row.category_code ? String(row.category_code) : null,
|
||
item_names: [itemName],
|
||
preparation_id: prepId,
|
||
prep_count: 1,
|
||
});
|
||
}
|
||
|
||
return { uploaded, pending: [...pendingMap.values()] };
|
||
}
|
||
|
||
/**
|
||
* 报告上传首页角标:近 14 天待上传共用组数。
|
||
* 复用 workbench 口径,避免漏掉直传/分享键/库报告链接三种已覆盖情况。
|
||
*/
|
||
export async function countSupplierPendingQualityReports(supplierCode: string): Promise<number> {
|
||
const workbench = await listSupplierQualityReportWorkbench({ supplierCode, daysBack: 14 });
|
||
return workbench.pending.length;
|
||
}
|
||
|
||
/** 独立报告库:按供应商 + 业务日上传(不计硬门禁) */
|
||
export async function uploadLibraryQualityReport(input: {
|
||
supplierCode: string;
|
||
reportDate?: string | null;
|
||
reportType?: string | null;
|
||
reportLabel?: string | null;
|
||
files: string[];
|
||
branchCode?: string | null;
|
||
uploadedBy?: string | null;
|
||
sourceParty?: string;
|
||
/** 录单挂接:写入库行,便于按商品检索 */
|
||
skuCode?: string | null;
|
||
productName?: string | null;
|
||
}): Promise<QualityReportRow> {
|
||
const supplierCode = trimText(input.supplierCode);
|
||
if (!supplierCode) {
|
||
throw Object.assign(new Error('请选择供应商'), { status: 400 });
|
||
}
|
||
const reportDate = parseDateOnly(input.reportDate) || shanghaiToday();
|
||
const reportType = normalizeReportType(input.reportType || 'other');
|
||
const allowed = await assertReportTypeAllowed(reportType, input.branchCode);
|
||
const reportLabel =
|
||
trimText(input.reportLabel) || allowed.label || qualityReportTypeLabel(reportType);
|
||
const skuCode = trimText(input.skuCode) || null;
|
||
const productNameHint = trimText(input.productName) || null;
|
||
|
||
const savedPaths: string[] = [];
|
||
let firstImageBase64: string | null = null;
|
||
for (const file of input.files || []) {
|
||
const parsed = parseUploadPayload(file);
|
||
if (!parsed) continue;
|
||
const filename = await saveBase64Upload(
|
||
'quality-reports',
|
||
parsed.content,
|
||
parsed.ext,
|
||
input.branchCode ? { objectPrefix: String(input.branchCode) } : undefined
|
||
);
|
||
savedPaths.push(filename);
|
||
if (!firstImageBase64 && IMAGE_EXTS.has(parsed.ext.toLowerCase())) {
|
||
firstImageBase64 = parsed.content;
|
||
}
|
||
}
|
||
if (!savedPaths.length) {
|
||
throw Object.assign(new Error('未解析到有效文件'), { status: 400 });
|
||
}
|
||
|
||
let product_name: string | null = null;
|
||
let produced_at: string | null = null;
|
||
let testing_org: string | null = null;
|
||
let inspected_org: string | null = null;
|
||
let specification: string | null = null;
|
||
let tested_at: string | null = null;
|
||
let valid_from: string | null = null;
|
||
let valid_to: string | null = null;
|
||
let ai_raw: Record<string, unknown> | null = null;
|
||
let ai_parsed_at: string | null = null;
|
||
|
||
if (firstImageBase64) {
|
||
const meta = await parseReportMetaWithAi(firstImageBase64, input.branchCode, {
|
||
code: reportType,
|
||
label: reportLabel,
|
||
});
|
||
product_name = meta.product_name;
|
||
produced_at = meta.produced_at;
|
||
testing_org = meta.testing_org;
|
||
inspected_org = meta.inspected_org;
|
||
specification = meta.specification;
|
||
tested_at = meta.tested_at;
|
||
valid_from = meta.valid_from;
|
||
valid_to = meta.valid_to;
|
||
ai_raw = meta.ai_raw;
|
||
ai_parsed_at = new Date().toISOString();
|
||
}
|
||
if (!product_name && productNameHint) {
|
||
product_name = productNameHint;
|
||
}
|
||
|
||
const validity_status = computeValidityStatus({
|
||
compareAt: reportDate,
|
||
validFrom: valid_from,
|
||
validTo: valid_to,
|
||
testedAt: tested_at,
|
||
});
|
||
|
||
// T9:INSERT file_paths 前校验归属(跨分支 key ⇒ 403,不落库)
|
||
await assertOwnedStoragePaths({ branchCode: input.branchCode || null }, 'quality-reports', savedPaths);
|
||
|
||
const result = await pool.query(
|
||
`INSERT INTO quality_reports (
|
||
branch_code, report_type, report_label, preparation_id, purchase_code,
|
||
order_code, sku_code, supplier_code, file_paths, status, source_party,
|
||
uploaded_by, tested_at, valid_from, valid_to, compare_at, validity_status,
|
||
ai_raw, ai_parsed_at, is_library, report_date, delivery_date,
|
||
product_name, produced_at, testing_org, inspected_org, specification
|
||
) VALUES (
|
||
$1,$2,$3,NULL,NULL,NULL,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13::date,$14,
|
||
$15::jsonb,$16,true,$17::date,$17::date,$18,$19::date,$20,$21,$22
|
||
) RETURNING *`,
|
||
[
|
||
input.branchCode || null,
|
||
reportType,
|
||
reportLabel,
|
||
skuCode,
|
||
supplierCode,
|
||
savedPaths,
|
||
QUALITY_REPORT_STATUS.active,
|
||
input.sourceParty || 'library',
|
||
input.uploadedBy || null,
|
||
tested_at,
|
||
valid_from,
|
||
valid_to,
|
||
reportDate,
|
||
validity_status,
|
||
ai_raw ? JSON.stringify(ai_raw) : null,
|
||
ai_parsed_at,
|
||
reportDate,
|
||
product_name,
|
||
produced_at,
|
||
testing_org,
|
||
inspected_org,
|
||
specification,
|
||
]
|
||
);
|
||
|
||
return mapReportRow(result.rows[0]);
|
||
}
|
||
|
||
export async function listLibraryQualityReports(input: {
|
||
supplierCode?: string | null;
|
||
reportDate?: string | null;
|
||
dateFrom?: string | null;
|
||
dateTo?: string | null;
|
||
q?: string | null;
|
||
includeVoided?: boolean;
|
||
requestHost?: string | null;
|
||
limit?: number;
|
||
}): Promise<QualityReportLedgerItem[]> {
|
||
return listQualityReportsLedger({
|
||
supplierCode: input.supplierCode,
|
||
dateFrom: input.reportDate || input.dateFrom,
|
||
dateTo: input.reportDate || input.dateTo,
|
||
q: input.q,
|
||
libraryOnly: true,
|
||
includeVoided: input.includeVoided,
|
||
requestHost: input.requestHost,
|
||
limit: input.limit ?? 100,
|
||
});
|
||
}
|
||
|
||
// ---------------------------------------------------------------------------
|
||
// 检验报告页:按当日供货或自采商品匹配上传(库报告,不计硬门禁)
|
||
// 不写 preparation_id / purchase_code / order_code;非 line 类型可回写 share_key 供一对多覆盖
|
||
// ---------------------------------------------------------------------------
|
||
|
||
export type QualityReportDayItem = {
|
||
sku_code: string | null;
|
||
product_name: string;
|
||
specification: string | null;
|
||
unit: string | null;
|
||
prepare_qty: number;
|
||
prep_count: number;
|
||
matched_report_count: number;
|
||
category_code?: string | null;
|
||
};
|
||
|
||
function normalizeMatchName(value: unknown): string {
|
||
return trimText(value)
|
||
.toLowerCase()
|
||
.replace(/[\s\u3000]+/g, '')
|
||
.replace(/[()()【】\[\]「」『』《》<>]/g, '')
|
||
.replace(/[·•..]/g, '');
|
||
}
|
||
|
||
/** 全等,或较短一方至少 2 字且被包含。避免「瓜」命中「丝瓜」。 */
|
||
export function productNamesMatch(
|
||
aiName: string | null | undefined,
|
||
itemName: string | null | undefined
|
||
): boolean {
|
||
const a = normalizeMatchName(aiName);
|
||
const b = normalizeMatchName(itemName);
|
||
if (!a || !b) return false;
|
||
if (a === b) return true;
|
||
if (a.length >= 2 && b.includes(a)) return true;
|
||
if (b.length >= 2 && a.includes(b)) return true;
|
||
return false;
|
||
}
|
||
|
||
export function extractAiProductNames(raw: Record<string, unknown> | null | undefined): string[] {
|
||
if (!raw) return [];
|
||
const out: string[] = [];
|
||
const push = (v: unknown) => {
|
||
if (Array.isArray(v)) {
|
||
for (const x of v) push(x);
|
||
return;
|
||
}
|
||
const s = trimText(v);
|
||
if (!s) return;
|
||
for (const part of s.split(/[,,、;;|/]+/)) {
|
||
const t = trimText(part);
|
||
if (t) out.push(t);
|
||
}
|
||
};
|
||
push(raw.product_names);
|
||
push(raw.product_name);
|
||
const seen = new Set<string>();
|
||
const unique: string[] = [];
|
||
for (const name of out) {
|
||
const key = normalizeMatchName(name);
|
||
if (!key || seen.has(key)) continue;
|
||
seen.add(key);
|
||
unique.push(name);
|
||
}
|
||
return unique;
|
||
}
|
||
|
||
type QualityReportParsedMeta = {
|
||
product_name: string | null;
|
||
product_names: string[];
|
||
produced_at: string | null;
|
||
testing_org: string | null;
|
||
inspected_org: string | null;
|
||
specification: string | null;
|
||
tested_at: string | null;
|
||
valid_from: string | null;
|
||
valid_to: string | null;
|
||
ai_raw: Record<string, unknown> | null;
|
||
};
|
||
|
||
function emptyParsedMeta(): QualityReportParsedMeta {
|
||
return {
|
||
product_name: null,
|
||
product_names: [],
|
||
produced_at: null,
|
||
testing_org: null,
|
||
inspected_org: null,
|
||
specification: null,
|
||
tested_at: null,
|
||
valid_from: null,
|
||
valid_to: null,
|
||
ai_raw: null,
|
||
};
|
||
}
|
||
|
||
function parsedMetaFromAiRaw(raw: Record<string, unknown>): QualityReportParsedMeta {
|
||
let tested_at = parseDateOnly(raw.tested_at);
|
||
let valid_from = parseDateOnly(raw.valid_from);
|
||
let valid_to = parseDateOnly(raw.valid_to);
|
||
const validDays = Number(raw.valid_days);
|
||
const days = Number.isFinite(validDays) && validDays > 0 ? Math.floor(validDays) : null;
|
||
if (!valid_to && tested_at && days) {
|
||
const d = new Date(`${tested_at}T00:00:00Z`);
|
||
d.setUTCDate(d.getUTCDate() + days);
|
||
valid_to = d.toISOString().slice(0, 10);
|
||
if (!valid_from) valid_from = tested_at;
|
||
}
|
||
const product_names = extractAiProductNames(raw);
|
||
return {
|
||
product_name: product_names[0] || nullText(raw.product_name),
|
||
product_names,
|
||
produced_at: parseDateOnly(raw.produced_at),
|
||
testing_org: nullText(raw.testing_org),
|
||
inspected_org: nullText(raw.inspected_org),
|
||
specification: nullText(raw.specification),
|
||
tested_at,
|
||
valid_from,
|
||
valid_to,
|
||
ai_raw: raw,
|
||
};
|
||
}
|
||
|
||
export function matchDayItemsByProductNames(
|
||
names: string[],
|
||
items: QualityReportDayItem[]
|
||
): { skuCodes: string[]; productName: string | null; match_status: 'matched' | 'unmatched' } {
|
||
const skuCodes: string[] = [];
|
||
const seenSku = new Set<string>();
|
||
let firstName: string | null = null;
|
||
for (const name of names) {
|
||
const hits = items.filter(
|
||
(it) =>
|
||
productNamesMatch(name, it.product_name) || productNamesMatch(name, it.sku_code)
|
||
);
|
||
if (hits.length !== 1) continue;
|
||
const sku = trimText(hits[0].sku_code);
|
||
if (!sku || seenSku.has(sku)) continue;
|
||
seenSku.add(sku);
|
||
skuCodes.push(sku);
|
||
if (!firstName) firstName = hits[0].product_name || name;
|
||
}
|
||
if (!skuCodes.length) {
|
||
return {
|
||
skuCodes: [],
|
||
productName: names[0] || null,
|
||
match_status: 'unmatched',
|
||
};
|
||
}
|
||
return { skuCodes, productName: firstName, match_status: 'matched' };
|
||
}
|
||
|
||
function matchDayItemSku(
|
||
meta: { product_name: string | null; product_names?: string[]; produced_at?: string | null },
|
||
items: QualityReportDayItem[]
|
||
): { skuCodes: string[]; sku_code: string | null; product_name: string | null; match_status: 'matched' | 'unmatched' } {
|
||
const names = [
|
||
...((meta.product_names || []).map(trimText).filter(Boolean)),
|
||
...(meta.product_name ? [meta.product_name] : []),
|
||
];
|
||
const unique = extractAiProductNames({
|
||
product_names: names,
|
||
product_name: meta.product_name,
|
||
});
|
||
const matched = matchDayItemsByProductNames(unique, items);
|
||
return {
|
||
skuCodes: matched.skuCodes,
|
||
sku_code: matched.skuCodes[0] || null,
|
||
product_name: matched.productName,
|
||
match_status: matched.match_status,
|
||
};
|
||
}
|
||
|
||
/** match-upload:图走视觉;PDF 走方舟文档理解(File API / file_url),失败则留空可手改挂接 */
|
||
async function parseMatchUploadMeta(
|
||
contentBase64: string,
|
||
ext: string,
|
||
branchCode?: string | null,
|
||
reportHint?: { code?: string | null; label?: string | null } | null
|
||
): Promise<QualityReportParsedMeta> {
|
||
const empty = emptyParsedMeta();
|
||
const lower = ext.toLowerCase();
|
||
if (IMAGE_EXTS.has(lower)) {
|
||
return parseReportMetaWithAi(contentBase64, branchCode, reportHint);
|
||
}
|
||
if (lower !== 'pdf') return empty;
|
||
if (!contentBase64 || !(await hasArkRuntimeConfig({ branchCode }))) {
|
||
console.warn('[quality-report] PDF skipped: LLM not configured');
|
||
return empty;
|
||
}
|
||
try {
|
||
const prompt = await resolvePrompt('quality.report.meta', { branchCode });
|
||
const typeCode = trimText(reportHint?.code);
|
||
const typeLabel = trimText(reportHint?.label) || typeCode;
|
||
const typeClause =
|
||
typeCode || typeLabel
|
||
? `\n当前上传类型为:${typeLabel || '未知'}${typeCode ? `(${typeCode})` : ''}。请按该类型报告版式提取字段,认不出填 null,不要编造。`
|
||
: '';
|
||
const dataUrl = contentBase64.startsWith('data:')
|
||
? contentBase64
|
||
: `data:application/pdf;base64,${contentBase64}`;
|
||
const text = await callWithFile(`${prompt.systemPrompt}${typeClause}`, dataUrl, {
|
||
branchCode,
|
||
filename: 'quality-report.pdf',
|
||
mime: 'application/pdf',
|
||
});
|
||
if (!text) {
|
||
console.warn('[quality-report] PDF AI returned empty');
|
||
return empty;
|
||
}
|
||
const jsonMatch = text.match(/\{[\s\S]*\}/);
|
||
if (!jsonMatch) {
|
||
console.warn('[quality-report] PDF AI response had no JSON:', text.slice(0, 200));
|
||
return empty;
|
||
}
|
||
const raw = JSON.parse(jsonMatch[0]) as Record<string, unknown>;
|
||
return parsedMetaFromAiRaw(raw);
|
||
} catch (error) {
|
||
console.warn('[quality-report] PDF AI parse failed:', error instanceof Error ? error.message : error);
|
||
return empty;
|
||
}
|
||
}
|
||
|
||
function mapDayItemRows(rows: Array<Record<string, unknown>>): QualityReportDayItem[] {
|
||
return rows.map((row) => ({
|
||
sku_code: row.sku_code != null ? String(row.sku_code) : null,
|
||
product_name: String(row.product_name || '未命名商品'),
|
||
specification: row.specification != null ? String(row.specification) : null,
|
||
unit: row.unit != null ? String(row.unit) : null,
|
||
prepare_qty: Number(row.prepare_qty) || 0,
|
||
prep_count: Number(row.prep_count) || 0,
|
||
matched_report_count: 0,
|
||
category_code: row.category_code != null ? String(row.category_code).trim() || null : null,
|
||
}));
|
||
}
|
||
|
||
function coverageHitsFromRows(rows: Array<Record<string, unknown>>): DayItemCoverageHit[] {
|
||
return rows.map((row) => ({
|
||
reportId: String(row.report_id || ''),
|
||
skuCode: row.sku_code != null ? String(row.sku_code).trim() || null : null,
|
||
categoryCode: row.category_code != null ? String(row.category_code).trim() || null : null,
|
||
shareMode: (row.share_mode != null
|
||
? String(row.share_mode).trim()
|
||
: '') as QualityReportShareMode | '',
|
||
})).map((h) => ({
|
||
...h,
|
||
shareMode:
|
||
h.shareMode === 'leaf_category' ||
|
||
h.shareMode === 'produce_day' ||
|
||
h.shareMode === 'line' ||
|
||
h.shareMode === 'manual'
|
||
? h.shareMode
|
||
: null,
|
||
}));
|
||
}
|
||
|
||
async function stampLibraryReportShare(input: {
|
||
reportId: string;
|
||
reportType: string;
|
||
supplierCode: string;
|
||
deliveryDate: string;
|
||
skuCode: string | null;
|
||
dayItems: QualityReportDayItem[];
|
||
}): Promise<void> {
|
||
const skuCode = trimText(input.skuCode);
|
||
if (!skuCode) return;
|
||
const shareMode = shareModeForReportType(input.reportType);
|
||
if (shareMode === 'line') return;
|
||
const hit = input.dayItems.find((it) => it.sku_code === skuCode);
|
||
const categoryCode = hit?.category_code || null;
|
||
const shareKey = buildQualityReportShareKey({
|
||
shareMode,
|
||
supplierCode: input.supplierCode,
|
||
deliveryDate: input.deliveryDate,
|
||
categoryCode,
|
||
skuCode,
|
||
});
|
||
await pool.query(
|
||
`UPDATE quality_reports
|
||
SET share_mode = $2,
|
||
share_key = $3,
|
||
category_code = $4,
|
||
updated_at = NOW()
|
||
WHERE id = $1::uuid
|
||
AND is_library = true
|
||
AND preparation_id IS NULL
|
||
AND purchase_code IS NULL`,
|
||
[input.reportId, shareMode, shareKey, categoryCode]
|
||
);
|
||
}
|
||
|
||
async function persistLibraryLinkedSkus(input: {
|
||
reportId: string;
|
||
skuCodes: string[];
|
||
reportType: string;
|
||
supplierCode: string;
|
||
deliveryDate: string;
|
||
dayItems: QualityReportDayItem[];
|
||
branchCode?: string | null;
|
||
}): Promise<{ skuCode: string | null; productName: string | null }> {
|
||
const allowed = new Set(
|
||
input.dayItems.map((it) => trimText(it.sku_code)).filter(Boolean)
|
||
);
|
||
const skus = [...new Set(input.skuCodes.map(trimText).filter((s) => allowed.has(s)))];
|
||
const skuCode = skus[0] || null;
|
||
const productName = skuCode
|
||
? input.dayItems.find((it) => it.sku_code === skuCode)?.product_name || null
|
||
: null;
|
||
const multi = skus.length > 1;
|
||
await pool.query(
|
||
`UPDATE quality_reports
|
||
SET sku_code = $2,
|
||
product_name = COALESCE($3, product_name),
|
||
linked_sku_codes = $4::text[],
|
||
updated_at = NOW()
|
||
WHERE id = $1::uuid
|
||
AND is_library = true
|
||
AND preparation_id IS NULL
|
||
AND purchase_code IS NULL`,
|
||
[input.reportId, skuCode, productName, skus.length ? skus : null]
|
||
);
|
||
await voidPrepLinksForReport(input.reportId);
|
||
if (skuCode && !isQualityReportSelfSupplier(input.supplierCode)) {
|
||
for (const sku of skus) {
|
||
await linkLibraryReportToPreps({
|
||
reportId: input.reportId,
|
||
reportType: input.reportType,
|
||
supplierCode: input.supplierCode,
|
||
deliveryDate: input.deliveryDate,
|
||
skuCode: sku,
|
||
branchCode: input.branchCode,
|
||
linkSource: 'manual_rematch',
|
||
exactSkuOnly: multi,
|
||
});
|
||
}
|
||
}
|
||
const typeMode = shareModeForReportType(input.reportType);
|
||
if (skuCode && typeMode === 'produce_day') {
|
||
await stampLibraryReportShare({
|
||
reportId: input.reportId,
|
||
reportType: input.reportType,
|
||
supplierCode: input.supplierCode,
|
||
deliveryDate: input.deliveryDate,
|
||
skuCode,
|
||
dayItems: input.dayItems,
|
||
});
|
||
} else if (multi && skuCode) {
|
||
const shareKey = `mn|${trimText(input.supplierCode)}|${input.deliveryDate}|${skus.join(',')}`;
|
||
await pool.query(
|
||
`UPDATE quality_reports
|
||
SET share_mode = 'manual',
|
||
share_key = $2,
|
||
category_code = NULL,
|
||
updated_at = NOW()
|
||
WHERE id = $1::uuid`,
|
||
[input.reportId, shareKey.slice(0, 200)]
|
||
);
|
||
} else if (skuCode) {
|
||
await stampLibraryReportShare({
|
||
reportId: input.reportId,
|
||
reportType: input.reportType,
|
||
supplierCode: input.supplierCode,
|
||
deliveryDate: input.deliveryDate,
|
||
skuCode,
|
||
dayItems: input.dayItems,
|
||
});
|
||
} else {
|
||
await pool.query(
|
||
`UPDATE quality_reports
|
||
SET share_mode = NULL, share_key = NULL, category_code = NULL, updated_at = NOW()
|
||
WHERE id = $1::uuid AND is_library = true AND preparation_id IS NULL AND purchase_code IS NULL`,
|
||
[input.reportId]
|
||
);
|
||
}
|
||
return { skuCode, productName };
|
||
}
|
||
|
||
async function attachDayItemReportCoverage(
|
||
items: QualityReportDayItem[],
|
||
input: {
|
||
supplierCode: string;
|
||
deliveryDate: string;
|
||
branchCode?: string | null;
|
||
isSelf: boolean;
|
||
purchaserCode?: string | null;
|
||
}
|
||
): Promise<void> {
|
||
if (!items.length) return;
|
||
const supplierCode = trimText(input.supplierCode);
|
||
const deliveryDate = input.deliveryDate;
|
||
const branchCode = trimText(input.branchCode);
|
||
const purchaserCode = trimText(input.purchaserCode);
|
||
let hits: DayItemCoverageHit[] = [];
|
||
|
||
if (input.isSelf) {
|
||
const params: unknown[] = [supplierCode, QUALITY_REPORT_STATUS.active, deliveryDate];
|
||
let purchaserSql = '';
|
||
if (purchaserCode) {
|
||
params.push(purchaserCode);
|
||
purchaserSql = `AND po.purchaser_code = $${params.length}`;
|
||
}
|
||
const result = await pool.query(
|
||
`SELECT qr.id::text AS report_id,
|
||
NULLIF(TRIM(qr.sku_code), '') AS sku_code,
|
||
NULLIF(TRIM(qr.category_code), '') AS category_code,
|
||
NULLIF(TRIM(qr.share_mode), '') AS share_mode
|
||
FROM quality_reports qr
|
||
WHERE qr.status = $2
|
||
AND qr.supplier_code = $1
|
||
AND COALESCE(qr.report_date::date, qr.delivery_date::date) = $3::date
|
||
UNION
|
||
SELECT qr.id::text,
|
||
NULLIF(TRIM(po.sku_code), '') AS sku_code,
|
||
COALESCE(
|
||
NULLIF(TRIM(oi.category_code), ''),
|
||
NULLIF(TRIM(s.category_code), ''),
|
||
NULLIF(TRIM(qr.category_code), '')
|
||
) AS category_code,
|
||
NULLIF(TRIM(qr.share_mode), '') AS share_mode
|
||
FROM quality_reports qr
|
||
JOIN purchase_orders po ON po.purchase_code = qr.purchase_code
|
||
INNER JOIN orders o ON o.order_code = po.order_code
|
||
LEFT JOIN order_items oi ON oi.order_code = po.order_code AND oi.sku_code IS NOT DISTINCT FROM po.sku_code
|
||
LEFT JOIN skus s ON s.sku_code = po.sku_code
|
||
WHERE qr.status = $2
|
||
AND COALESCE(NULLIF(TRIM(po.supplier_code), ''), '') = ''
|
||
AND po.purchase_status <> 40
|
||
AND o.delivery_date::date = $3::date
|
||
AND ${orderCodeActiveExistsSql('po.order_code')}
|
||
${purchaserSql}
|
||
UNION
|
||
SELECT qr.id::text,
|
||
NULLIF(TRIM(x.sku), '') AS sku_code,
|
||
NULL::text AS category_code,
|
||
'manual'::text AS share_mode
|
||
FROM quality_reports qr
|
||
CROSS JOIN LATERAL unnest(COALESCE(qr.linked_sku_codes, ARRAY[]::text[])) AS x(sku)
|
||
WHERE qr.status = $2
|
||
AND qr.supplier_code = $1
|
||
AND COALESCE(qr.report_date::date, qr.delivery_date::date) = $3::date`,
|
||
params
|
||
);
|
||
hits = coverageHitsFromRows(result.rows);
|
||
} else {
|
||
const params: unknown[] = [supplierCode, QUALITY_REPORT_STATUS.active, deliveryDate];
|
||
let branchSql = '';
|
||
if (branchCode) {
|
||
params.push(branchCode);
|
||
branchSql = `AND (
|
||
sp.branch_code = $4
|
||
OR (
|
||
(sp.branch_code IS NULL OR TRIM(sp.branch_code) = '')
|
||
AND o.branch_code = $4
|
||
)
|
||
)`;
|
||
}
|
||
const result = await pool.query(
|
||
`SELECT qr.id::text AS report_id,
|
||
NULLIF(TRIM(qr.sku_code), '') AS sku_code,
|
||
NULLIF(TRIM(qr.category_code), '') AS category_code,
|
||
NULLIF(TRIM(qr.share_mode), '') AS share_mode
|
||
FROM quality_reports qr
|
||
WHERE qr.status = $2
|
||
AND qr.is_library = true
|
||
AND qr.preparation_id IS NULL
|
||
AND qr.purchase_code IS NULL
|
||
AND qr.supplier_code = $1
|
||
AND COALESCE(qr.report_date::date, qr.delivery_date::date) = $3::date
|
||
UNION
|
||
SELECT qr.id::text,
|
||
NULLIF(TRIM(sp.sku_code), '') AS sku_code,
|
||
COALESCE(
|
||
NULLIF(TRIM(oi.category_code), ''),
|
||
NULLIF(TRIM(s.category_code), ''),
|
||
NULLIF(TRIM(qr.category_code), '')
|
||
) AS category_code,
|
||
NULLIF(TRIM(qr.share_mode), '') AS share_mode
|
||
FROM quality_reports qr
|
||
JOIN supplier_preparations sp ON sp.id = qr.preparation_id
|
||
JOIN orders o ON o.order_code = sp.order_code
|
||
LEFT JOIN order_items oi ON oi.order_code = sp.order_code AND oi.sku_code IS NOT DISTINCT FROM sp.sku_code
|
||
LEFT JOIN skus s ON s.sku_code = sp.sku_code
|
||
WHERE qr.status = $2
|
||
AND COALESCE(qr.is_library, false) = false
|
||
AND sp.supplier_code = $1
|
||
AND o.delivery_date::date = $3::date
|
||
AND COALESCE(sp.is_history_repair, false) = false
|
||
${branchSql}
|
||
UNION
|
||
SELECT qr.id::text,
|
||
NULLIF(TRIM(sp.sku_code), '') AS sku_code,
|
||
COALESCE(
|
||
NULLIF(TRIM(oi.category_code), ''),
|
||
NULLIF(TRIM(s.category_code), ''),
|
||
NULLIF(TRIM(qr.category_code), '')
|
||
) AS category_code,
|
||
NULLIF(TRIM(qr.share_mode), '') AS share_mode
|
||
FROM quality_report_prep_links l
|
||
JOIN quality_reports qr ON qr.id = l.quality_report_id
|
||
JOIN supplier_preparations sp ON sp.id = l.preparation_id
|
||
JOIN orders o ON o.order_code = sp.order_code
|
||
LEFT JOIN order_items oi ON oi.order_code = sp.order_code AND oi.sku_code IS NOT DISTINCT FROM sp.sku_code
|
||
LEFT JOIN skus s ON s.sku_code = sp.sku_code
|
||
WHERE l.status = $2
|
||
AND qr.status = $2
|
||
AND sp.supplier_code = $1
|
||
AND o.delivery_date::date = $3::date
|
||
AND COALESCE(sp.is_history_repair, false) = false
|
||
${branchSql}
|
||
UNION
|
||
SELECT qr.id::text,
|
||
NULLIF(TRIM(x.sku), '') AS sku_code,
|
||
NULL::text AS category_code,
|
||
'manual'::text AS share_mode
|
||
FROM quality_reports qr
|
||
CROSS JOIN LATERAL unnest(COALESCE(qr.linked_sku_codes, ARRAY[]::text[])) AS x(sku)
|
||
WHERE qr.status = $2
|
||
AND qr.is_library = true
|
||
AND qr.preparation_id IS NULL
|
||
AND qr.purchase_code IS NULL
|
||
AND qr.supplier_code = $1
|
||
AND COALESCE(qr.report_date::date, qr.delivery_date::date) = $3::date`,
|
||
params
|
||
);
|
||
hits = coverageHitsFromRows(result.rows);
|
||
}
|
||
|
||
for (const it of items) {
|
||
it.matched_report_count = countReportsCoveringDayItem(it, hits);
|
||
}
|
||
}
|
||
|
||
export async function listQualityReportDayItems(input: {
|
||
supplierCode: string;
|
||
deliveryDate: string;
|
||
branchCode?: string | null;
|
||
}): Promise<QualityReportDayItem[]> {
|
||
const supplierCode = trimText(input.supplierCode);
|
||
const deliveryDate = parseDateOnly(input.deliveryDate);
|
||
if (!supplierCode) {
|
||
throw Object.assign(new Error('请选择供应商'), { status: 400 });
|
||
}
|
||
if (!deliveryDate) {
|
||
throw Object.assign(new Error('请选择业务日'), { status: 400 });
|
||
}
|
||
|
||
const purchaserCode = parseQualityReportPurchaserCode(supplierCode);
|
||
const isSelf = isQualityReportSelfSupplier(supplierCode);
|
||
const branchCode = trimText(input.branchCode);
|
||
|
||
if (isSelf) {
|
||
const params: unknown[] = [deliveryDate];
|
||
const filters: string[] = [
|
||
`COALESCE(NULLIF(TRIM(po.supplier_code), ''), '') = ''`,
|
||
`o.delivery_date::date = $1::date`,
|
||
`po.purchase_status <> 40`,
|
||
`${orderCodeActiveExistsSql('po.order_code')}`,
|
||
];
|
||
if (purchaserCode) {
|
||
params.push(purchaserCode);
|
||
filters.push(`po.purchaser_code = $${params.length}`);
|
||
}
|
||
if (branchCode) {
|
||
params.push(branchCode);
|
||
filters.push(`(
|
||
po.branch_code = $${params.length}
|
||
OR (
|
||
(po.branch_code IS NULL OR TRIM(po.branch_code) = '')
|
||
AND o.branch_code = $${params.length}
|
||
)
|
||
)`);
|
||
}
|
||
const result = await pool.query(
|
||
`WITH po_rows AS (
|
||
SELECT
|
||
NULLIF(TRIM(po.sku_code), '') AS sku_code,
|
||
COALESCE(
|
||
NULLIF(TRIM(s.sku_name), ''),
|
||
NULLIF(TRIM(po.sku_code), ''),
|
||
'未命名商品'
|
||
) AS product_name,
|
||
NULLIF(TRIM(s.spec), '') AS specification,
|
||
COALESCE(
|
||
NULLIF(TRIM(s.unit), ''),
|
||
'个'
|
||
) AS unit,
|
||
COALESCE(po.actual_qty, po.purchase_qty, 0)::float8 AS prepare_qty,
|
||
COALESCE(
|
||
NULLIF(TRIM(oi.category_code), ''),
|
||
NULLIF(TRIM(s.category_code), '')
|
||
) AS category_code
|
||
FROM purchase_orders po
|
||
INNER JOIN orders o ON o.order_code = po.order_code
|
||
LEFT JOIN order_items oi ON oi.order_code = po.order_code AND oi.sku_code IS NOT DISTINCT FROM po.sku_code
|
||
LEFT JOIN skus s ON s.sku_code = po.sku_code
|
||
WHERE ${filters.join(' AND ')}
|
||
)
|
||
SELECT
|
||
sku_code,
|
||
MAX(product_name) AS product_name,
|
||
NULLIF(TRIM(MAX(specification)), '') AS specification,
|
||
NULLIF(TRIM(MAX(unit)), '') AS unit,
|
||
COALESCE(SUM(prepare_qty), 0)::float8 AS prepare_qty,
|
||
COUNT(*)::int AS prep_count,
|
||
NULLIF(TRIM(MAX(category_code)), '') AS category_code
|
||
FROM po_rows
|
||
GROUP BY COALESCE(sku_code, 'name:' || product_name), sku_code
|
||
ORDER BY MAX(product_name) ASC`,
|
||
params
|
||
);
|
||
const items = mapDayItemRows(result.rows);
|
||
await attachDayItemReportCoverage(items, {
|
||
supplierCode,
|
||
deliveryDate,
|
||
branchCode,
|
||
isSelf: true,
|
||
purchaserCode,
|
||
});
|
||
return items;
|
||
}
|
||
|
||
const params: unknown[] = [supplierCode, deliveryDate];
|
||
const filters: string[] = [
|
||
'sp.supplier_code = $1',
|
||
`o.delivery_date::date = $2::date`,
|
||
'COALESCE(sp.is_history_repair, false) = false',
|
||
`(
|
||
sp.order_code IS NULL
|
||
OR TRIM(sp.order_code) = ''
|
||
OR ${orderCodeActiveExistsSql('sp.order_code')}
|
||
)`,
|
||
];
|
||
if (branchCode) {
|
||
params.push(branchCode);
|
||
filters.push(`(
|
||
sp.branch_code = $${params.length}
|
||
OR (
|
||
(sp.branch_code IS NULL OR TRIM(sp.branch_code) = '')
|
||
AND o.branch_code = $${params.length}
|
||
)
|
||
)`);
|
||
}
|
||
|
||
const result = await pool.query(
|
||
`WITH prep_rows AS (
|
||
SELECT
|
||
NULLIF(TRIM(sp.sku_code), '') AS sku_code,
|
||
COALESCE(
|
||
NULLIF(TRIM(sp.item_name), ''),
|
||
NULLIF(TRIM(s.sku_name), ''),
|
||
NULLIF(TRIM(sp.sku_code), ''),
|
||
'未命名商品'
|
||
) AS product_name,
|
||
NULLIF(TRIM(s.spec), '') AS specification,
|
||
COALESCE(
|
||
NULLIF(TRIM(sp.unit), ''),
|
||
NULLIF(TRIM(s.unit), ''),
|
||
'个'
|
||
) AS unit,
|
||
COALESCE(sp.prepare_qty, 0)::float8 AS prepare_qty,
|
||
COALESCE(
|
||
NULLIF(TRIM(oi.category_code), ''),
|
||
NULLIF(TRIM(s.category_code), '')
|
||
) AS category_code
|
||
FROM supplier_preparations sp
|
||
INNER JOIN orders o ON o.order_code = sp.order_code
|
||
LEFT JOIN order_items oi ON oi.order_code = sp.order_code AND oi.sku_code IS NOT DISTINCT FROM sp.sku_code
|
||
LEFT JOIN skus s ON s.sku_code = sp.sku_code
|
||
WHERE ${filters.join(' AND ')}
|
||
)
|
||
SELECT
|
||
sku_code,
|
||
MAX(product_name) AS product_name,
|
||
NULLIF(TRIM(MAX(specification)), '') AS specification,
|
||
NULLIF(TRIM(MAX(unit)), '') AS unit,
|
||
COALESCE(SUM(prepare_qty), 0)::float8 AS prepare_qty,
|
||
COUNT(*)::int AS prep_count,
|
||
NULLIF(TRIM(MAX(category_code)), '') AS category_code
|
||
FROM prep_rows
|
||
GROUP BY COALESCE(sku_code, 'name:' || product_name), sku_code
|
||
ORDER BY MAX(product_name) ASC`,
|
||
params
|
||
);
|
||
|
||
const items = mapDayItemRows(result.rows);
|
||
await attachDayItemReportCoverage(items, {
|
||
supplierCode,
|
||
deliveryDate,
|
||
branchCode,
|
||
isSelf: false,
|
||
});
|
||
return items;
|
||
}
|
||
|
||
export async function matchUploadQualityReports(input: {
|
||
supplierCode: string;
|
||
reportDate: string;
|
||
files: string[];
|
||
branchCode?: string | null;
|
||
uploadedBy?: string | null;
|
||
requestHost?: string | null;
|
||
reportType?: string | null;
|
||
}): Promise<{
|
||
items: QualityReportDayItem[];
|
||
reports: Array<QualityReportLedgerItem & { match_status: 'matched' | 'unmatched' }>;
|
||
}> {
|
||
const supplierCode = trimText(input.supplierCode);
|
||
const reportDate = parseDateOnly(input.reportDate);
|
||
if (!supplierCode) {
|
||
throw Object.assign(new Error('请选择供应商'), { status: 400 });
|
||
}
|
||
if (!reportDate) {
|
||
throw Object.assign(new Error('请选择业务日'), { status: 400 });
|
||
}
|
||
const files = (input.files || []).map(String).filter(Boolean);
|
||
if (!files.length) {
|
||
throw Object.assign(new Error('请选择报告文件'), { status: 400 });
|
||
}
|
||
if (files.length > 20) {
|
||
throw Object.assign(new Error('单次最多上传 20 个文件'), { status: 400 });
|
||
}
|
||
|
||
const dayItems = await listQualityReportDayItems({
|
||
supplierCode,
|
||
deliveryDate: reportDate,
|
||
branchCode: input.branchCode,
|
||
});
|
||
|
||
const allowed = await assertReportTypeAllowed(input.reportType || 'other', input.branchCode);
|
||
const reportType = allowed.code;
|
||
const reportLabel = allowed.label;
|
||
const reportHint = { code: reportType, label: reportLabel };
|
||
const created: Array<QualityReportLedgerItem & { match_status: 'matched' | 'unmatched' }> = [];
|
||
|
||
for (const file of files) {
|
||
const parsed = await resolveMatchUploadEntry(file);
|
||
if (!parsed) continue;
|
||
// 已由 multer 通道落存储的对象直接用其路径;旧 data URL 口径仍按原样保存
|
||
const filename =
|
||
parsed.storedPath ||
|
||
(await saveBase64Upload(
|
||
'quality-reports',
|
||
parsed.content,
|
||
parsed.ext,
|
||
input.branchCode ? { objectPrefix: String(input.branchCode) } : undefined
|
||
));
|
||
const meta = await parseMatchUploadMeta(parsed.content, parsed.ext, input.branchCode, reportHint);
|
||
const matched = matchDayItemSku(meta, dayItems);
|
||
const product_name = matched.product_name || meta.product_name;
|
||
const sku_code = matched.sku_code;
|
||
const validity_status = computeValidityStatus({
|
||
compareAt: reportDate,
|
||
validFrom: meta.valid_from,
|
||
validTo: meta.valid_to,
|
||
testedAt: meta.tested_at,
|
||
});
|
||
const ai_parsed_at = meta.ai_raw ? new Date().toISOString() : null;
|
||
|
||
const isSelf = isQualityReportSelfSupplier(supplierCode);
|
||
// T9:INSERT file_paths 前校验归属(跨分支 key ⇒ 403,不落库)
|
||
await assertOwnedStoragePaths({ branchCode: input.branchCode || null }, 'quality-reports', [filename]);
|
||
const result = await pool.query(
|
||
`INSERT INTO quality_reports (
|
||
branch_code, report_type, report_label, preparation_id, purchase_code,
|
||
order_code, sku_code, supplier_code, file_paths, status, source_party,
|
||
uploaded_by, tested_at, valid_from, valid_to, compare_at, validity_status,
|
||
ai_raw, ai_parsed_at, is_library, report_date, delivery_date,
|
||
product_name, produced_at, testing_org, inspected_org, specification
|
||
) VALUES (
|
||
$1,$22,$2,NULL,NULL,NULL,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12::date,$13,
|
||
$14::jsonb,$15,true,$16::date,$16::date,$17,$18::date,$19,$20,$21
|
||
) RETURNING *`,
|
||
[
|
||
input.branchCode || null,
|
||
reportLabel,
|
||
sku_code,
|
||
supplierCode,
|
||
[filename],
|
||
QUALITY_REPORT_STATUS.active,
|
||
isSelf ? 'self_purchase' : 'library',
|
||
input.uploadedBy || null,
|
||
meta.tested_at,
|
||
meta.valid_from,
|
||
meta.valid_to,
|
||
reportDate,
|
||
validity_status,
|
||
meta.ai_raw ? JSON.stringify(meta.ai_raw) : null,
|
||
ai_parsed_at,
|
||
reportDate,
|
||
product_name,
|
||
meta.produced_at,
|
||
meta.testing_org,
|
||
meta.inspected_org,
|
||
meta.specification,
|
||
reportType,
|
||
]
|
||
);
|
||
const row = mapReportRow(result.rows[0], input.requestHost);
|
||
if (matched.skuCodes.length) {
|
||
await persistLibraryLinkedSkus({
|
||
reportId: row.id,
|
||
skuCodes: matched.skuCodes,
|
||
reportType,
|
||
supplierCode,
|
||
deliveryDate: reportDate,
|
||
dayItems,
|
||
branchCode: input.branchCode,
|
||
});
|
||
const refreshed = await pool.query(
|
||
`SELECT * FROM quality_reports WHERE id = $1::uuid LIMIT 1`,
|
||
[row.id]
|
||
);
|
||
const mapped = mapReportRow(refreshed.rows[0] || result.rows[0], input.requestHost);
|
||
created.push({
|
||
...toLedgerItem({ ...mapped, source: 'library' }, [], undefined),
|
||
match_status: 'matched',
|
||
});
|
||
} else {
|
||
created.push({
|
||
...toLedgerItem({ ...row, source: 'library' }, [], undefined),
|
||
match_status: 'unmatched',
|
||
});
|
||
}
|
||
}
|
||
|
||
if (!created.length) {
|
||
throw Object.assign(new Error('未解析到有效文件'), { status: 400 });
|
||
}
|
||
|
||
const refreshedItems = await listQualityReportDayItems({
|
||
supplierCode,
|
||
deliveryDate: reportDate,
|
||
branchCode: input.branchCode,
|
||
});
|
||
|
||
return { items: refreshedItems, reports: created };
|
||
}
|
||
|
||
/** 仅允许改挂库报告(is_library 且无备货/自采外键) */
|
||
export async function rematchLibraryQualityReport(input: {
|
||
id: string;
|
||
skuCode?: string | null;
|
||
skuCodes?: string[] | null;
|
||
supplierCode?: string | null;
|
||
reportDate?: string | null;
|
||
branchCode?: string | null;
|
||
requestHost?: string | null;
|
||
}): Promise<QualityReportLedgerItem & { match_status: 'matched' | 'unmatched' }> {
|
||
const reportId = trimText(input.id);
|
||
if (!reportId) {
|
||
throw Object.assign(new Error('缺少报告 id'), { status: 400 });
|
||
}
|
||
|
||
const existing = await pool.query(
|
||
`SELECT * FROM quality_reports
|
||
WHERE id = $1::uuid AND status = $2
|
||
LIMIT 1`,
|
||
[reportId, QUALITY_REPORT_STATUS.active]
|
||
);
|
||
const row0 = existing.rows[0];
|
||
if (!row0) {
|
||
throw Object.assign(new Error('报告不存在或已作废'), { status: 404 });
|
||
}
|
||
const isLibrary = row0.is_library === true || row0.is_library === 't' || row0.is_library === 1;
|
||
if (!isLibrary || row0.preparation_id || row0.purchase_code) {
|
||
throw Object.assign(new Error('仅可改挂报告库中的匹配关系'), {
|
||
status: 403,
|
||
code: 'forbidden',
|
||
});
|
||
}
|
||
|
||
const supplierCode = trimText(row0.supplier_code);
|
||
const reportDate =
|
||
parseDateOnly(input.reportDate) ||
|
||
parseDateOnly(row0.report_date) ||
|
||
parseDateOnly(row0.delivery_date) ||
|
||
shanghaiToday();
|
||
const dayItems = await listQualityReportDayItems({
|
||
supplierCode,
|
||
deliveryDate: reportDate,
|
||
branchCode: input.branchCode || (row0.branch_code != null ? String(row0.branch_code) : null),
|
||
});
|
||
|
||
const reportType = String(row0.report_type || 'other');
|
||
let skuCodes: string[] = [];
|
||
if (input.skuCodes !== undefined) {
|
||
skuCodes = (input.skuCodes || []).map((s) => trimText(s)).filter(Boolean);
|
||
} else if (input.skuCode === undefined) {
|
||
const existingLinked = Array.isArray(row0.linked_sku_codes)
|
||
? row0.linked_sku_codes.map((v: unknown) => String(v || '').trim()).filter(Boolean)
|
||
: [];
|
||
skuCodes = existingLinked.length
|
||
? existingLinked
|
||
: row0.sku_code != null
|
||
? [String(row0.sku_code)]
|
||
: [];
|
||
} else if (input.skuCode != null && trimText(input.skuCode)) {
|
||
skuCodes = [trimText(input.skuCode)];
|
||
}
|
||
|
||
const persisted = await persistLibraryLinkedSkus({
|
||
reportId,
|
||
skuCodes,
|
||
reportType,
|
||
supplierCode,
|
||
deliveryDate: reportDate,
|
||
dayItems,
|
||
branchCode: input.branchCode || (row0.branch_code != null ? String(row0.branch_code) : null),
|
||
});
|
||
const refreshed = await pool.query(
|
||
`SELECT * FROM quality_reports WHERE id = $1::uuid LIMIT 1`,
|
||
[reportId]
|
||
);
|
||
if (!refreshed.rows[0]) {
|
||
throw Object.assign(new Error('改挂失败'), { status: 409 });
|
||
}
|
||
const mapped = mapReportRow(refreshed.rows[0], input.requestHost);
|
||
mapped.source = 'library';
|
||
return {
|
||
...toLedgerItem(mapped, [], qualityReportShareHint(reportType)),
|
||
match_status: persisted.skuCode ? 'matched' : 'unmatched',
|
||
};
|
||
}
|
||
|
||
/** 修改报告类型:库报告改类型后按新类型重新挂链;备货直传需无同类型冲突 */
|
||
export async function updateQualityReportType(input: {
|
||
id: string;
|
||
reportType: string;
|
||
branchCode?: string | null;
|
||
requestHost?: string | null;
|
||
}): Promise<QualityReportLedgerItem & { match_status?: 'matched' | 'unmatched' }> {
|
||
const reportId = trimText(input.id);
|
||
if (!reportId) {
|
||
throw Object.assign(new Error('缺少报告 id'), { status: 400 });
|
||
}
|
||
const allowed = await assertReportTypeAllowed(input.reportType, input.branchCode);
|
||
const nextType = allowed.code;
|
||
const nextLabel = allowed.label;
|
||
|
||
const existing = await pool.query(
|
||
`SELECT * FROM quality_reports WHERE id = $1::uuid AND status = $2 LIMIT 1`,
|
||
[reportId, QUALITY_REPORT_STATUS.active]
|
||
);
|
||
const row0 = existing.rows[0];
|
||
if (!row0) {
|
||
throw Object.assign(new Error('报告不存在或已作废'), { status: 404 });
|
||
}
|
||
|
||
const currentType = normalizeReportType(row0.report_type);
|
||
if (currentType === nextType) {
|
||
const mapped = mapReportRow(row0, input.requestHost);
|
||
const isLibrary = row0.is_library === true || row0.is_library === 't' || row0.is_library === 1;
|
||
mapped.source = isLibrary ? 'library' : row0.preparation_id ? 'prep' : 'library';
|
||
return {
|
||
...toLedgerItem(mapped, [], qualityReportShareHint(nextType)),
|
||
match_status: row0.sku_code ? 'matched' : 'unmatched',
|
||
};
|
||
}
|
||
|
||
const isLibrary = row0.is_library === true || row0.is_library === 't' || row0.is_library === 1;
|
||
const prepId = row0.preparation_id != null ? String(row0.preparation_id) : null;
|
||
|
||
if (isLibrary && !row0.preparation_id && !row0.purchase_code) {
|
||
const updated = await pool.query(
|
||
`UPDATE quality_reports
|
||
SET report_type = $2,
|
||
report_label = $3,
|
||
updated_at = NOW()
|
||
WHERE id = $1::uuid
|
||
AND is_library = true
|
||
AND preparation_id IS NULL
|
||
AND purchase_code IS NULL
|
||
AND status = $4
|
||
RETURNING *`,
|
||
[reportId, nextType, nextLabel, QUALITY_REPORT_STATUS.active]
|
||
);
|
||
if (!updated.rows[0]) {
|
||
throw Object.assign(new Error('修改类型失败'), { status: 409 });
|
||
}
|
||
await voidPrepLinksForReport(reportId);
|
||
const skuCode = updated.rows[0].sku_code != null ? String(updated.rows[0].sku_code).trim() || null : null;
|
||
const supplierCode = trimText(updated.rows[0].supplier_code);
|
||
const reportDate =
|
||
parseDateOnly(updated.rows[0].report_date) ||
|
||
parseDateOnly(updated.rows[0].delivery_date) ||
|
||
shanghaiToday();
|
||
if (skuCode && !isQualityReportSelfSupplier(supplierCode)) {
|
||
await linkLibraryReportToPreps({
|
||
reportId,
|
||
reportType: nextType,
|
||
supplierCode,
|
||
deliveryDate: reportDate,
|
||
skuCode,
|
||
branchCode: input.branchCode || (row0.branch_code != null ? String(row0.branch_code) : null),
|
||
linkSource: 'manual_rematch',
|
||
});
|
||
}
|
||
if (skuCode) {
|
||
const dayItems = await listQualityReportDayItems({
|
||
supplierCode,
|
||
deliveryDate: reportDate,
|
||
branchCode: input.branchCode || (row0.branch_code != null ? String(row0.branch_code) : null),
|
||
});
|
||
await stampLibraryReportShare({
|
||
reportId,
|
||
reportType: nextType,
|
||
supplierCode,
|
||
deliveryDate: reportDate,
|
||
skuCode,
|
||
dayItems,
|
||
});
|
||
}
|
||
const mapped = mapReportRow(updated.rows[0], input.requestHost);
|
||
mapped.source = 'library';
|
||
return {
|
||
...toLedgerItem(mapped, [], qualityReportShareHint(nextType)),
|
||
match_status: skuCode ? 'matched' : 'unmatched',
|
||
};
|
||
}
|
||
|
||
if (prepId) {
|
||
const conflict = await pool.query(
|
||
`SELECT id FROM quality_reports
|
||
WHERE preparation_id = $1::uuid
|
||
AND report_type = $2
|
||
AND status = $3
|
||
AND id <> $4::uuid
|
||
LIMIT 1`,
|
||
[prepId, nextType, QUALITY_REPORT_STATUS.active, reportId]
|
||
);
|
||
if (conflict.rowCount) {
|
||
throw Object.assign(new Error('该备货行已有同类型有效报告,请先作废后再改类型'), {
|
||
status: 409,
|
||
code: 'type_conflict',
|
||
});
|
||
}
|
||
|
||
const ctx = await loadPrepReportContext(prepId);
|
||
if (!ctx) throw Object.assign(new Error('备货单不存在'), { status: 404 });
|
||
|
||
const shareMode = shareModeForReportType(nextType);
|
||
const shareKey = buildQualityReportShareKey({
|
||
shareMode,
|
||
supplierCode: ctx.supplierCode,
|
||
deliveryDate: ctx.deliveryDate,
|
||
categoryCode: ctx.categoryCode,
|
||
preparationId: prepId,
|
||
});
|
||
|
||
const updated = await pool.query(
|
||
`UPDATE quality_reports
|
||
SET report_type = $2,
|
||
report_label = $3,
|
||
share_mode = $4,
|
||
share_key = $5,
|
||
updated_at = NOW()
|
||
WHERE id = $1::uuid
|
||
AND preparation_id IS NOT NULL
|
||
AND status = $6
|
||
RETURNING *`,
|
||
[reportId, nextType, nextLabel, shareMode, shareKey, QUALITY_REPORT_STATUS.active]
|
||
);
|
||
if (!updated.rows[0]) {
|
||
throw Object.assign(new Error('修改类型失败'), { status: 409 });
|
||
}
|
||
const mapped = mapReportRow(updated.rows[0], input.requestHost);
|
||
mapped.source = 'prep';
|
||
return toLedgerItem(mapped, [], qualityReportShareHint(nextType));
|
||
}
|
||
|
||
throw Object.assign(new Error('仅可修改库报告或备货直传的报告类型'), {
|
||
status: 403,
|
||
code: 'forbidden',
|
||
});
|
||
}
|
||
|
||
export async function listReportsForSupplierDay(input: {
|
||
supplierCode: string;
|
||
deliveryDate: string;
|
||
branchCode?: string | null;
|
||
includeVoided?: boolean;
|
||
requestHost?: string | null;
|
||
limit?: number;
|
||
}): Promise<{
|
||
items: QualityReportDayItem[];
|
||
reports: Array<
|
||
QualityReportLedgerItem & {
|
||
source?: 'prep' | 'library' | 'shared' | 'self_purchase';
|
||
covered_sku_codes?: string[];
|
||
}
|
||
>;
|
||
}> {
|
||
const supplierCode = trimText(input.supplierCode);
|
||
const deliveryDate = parseDateOnly(input.deliveryDate);
|
||
if (!supplierCode) {
|
||
throw Object.assign(new Error('请选择供应商'), { status: 400 });
|
||
}
|
||
if (!deliveryDate) {
|
||
throw Object.assign(new Error('请选择业务日'), { status: 400 });
|
||
}
|
||
|
||
const items = await listQualityReportDayItems({
|
||
supplierCode,
|
||
deliveryDate,
|
||
branchCode: input.branchCode,
|
||
});
|
||
|
||
const statuses = input.includeVoided
|
||
? [QUALITY_REPORT_STATUS.active, QUALITY_REPORT_STATUS.voided]
|
||
: [QUALITY_REPORT_STATUS.active];
|
||
const limit = Math.min(Math.max(Number(input.limit) || 200, 1), 300);
|
||
const host = input.requestHost || null;
|
||
|
||
const libRows = await pool.query(
|
||
`SELECT * FROM quality_reports
|
||
WHERE is_library = true
|
||
AND supplier_code = $1
|
||
AND COALESCE(report_date::date, delivery_date::date, uploaded_at::date) = $2::date
|
||
AND status = ANY($3::int[])
|
||
ORDER BY uploaded_at DESC NULLS LAST
|
||
LIMIT $4`,
|
||
[supplierCode, deliveryDate, statuses, limit]
|
||
);
|
||
const isSelf = isQualityReportSelfSupplier(supplierCode);
|
||
const prepRows = isSelf
|
||
? { rows: [] as Record<string, unknown>[] }
|
||
: await pool.query(
|
||
`SELECT qr.*
|
||
FROM quality_reports qr
|
||
JOIN supplier_preparations sp ON sp.id = qr.preparation_id
|
||
JOIN orders o ON o.order_code = sp.order_code
|
||
WHERE COALESCE(qr.is_library, false) = false
|
||
AND sp.supplier_code = $1
|
||
AND o.delivery_date::date = $2::date
|
||
AND qr.status = ANY($3::int[])
|
||
AND COALESCE(sp.is_history_repair, false) = false
|
||
${
|
||
trimText(input.branchCode)
|
||
? `AND (
|
||
sp.branch_code = $5
|
||
OR (
|
||
(sp.branch_code IS NULL OR TRIM(sp.branch_code) = '')
|
||
AND o.branch_code = $5
|
||
)
|
||
)`
|
||
: ''
|
||
}
|
||
ORDER BY qr.uploaded_at DESC NULLS LAST
|
||
LIMIT $4`,
|
||
trimText(input.branchCode)
|
||
? [supplierCode, deliveryDate, statuses, limit, trimText(input.branchCode)]
|
||
: [supplierCode, deliveryDate, statuses, limit]
|
||
);
|
||
const purchaseRows = isSelf
|
||
? await pool.query(
|
||
`SELECT qr.*
|
||
FROM quality_reports qr
|
||
JOIN purchase_orders po ON po.purchase_code = qr.purchase_code
|
||
INNER JOIN orders o ON o.order_code = po.order_code
|
||
WHERE COALESCE(NULLIF(TRIM(po.supplier_code), ''), '') = ''
|
||
AND po.purchase_status <> 40
|
||
AND o.delivery_date::date = $1::date
|
||
AND qr.status = ANY($2::int[])
|
||
AND ${orderCodeActiveExistsSql('po.order_code')}
|
||
${
|
||
parseQualityReportPurchaserCode(supplierCode)
|
||
? `AND po.purchaser_code = $4`
|
||
: ''
|
||
}
|
||
ORDER BY qr.uploaded_at DESC NULLS LAST
|
||
LIMIT $3`,
|
||
parseQualityReportPurchaserCode(supplierCode)
|
||
? [deliveryDate, statuses, limit, parseQualityReportPurchaserCode(supplierCode)]
|
||
: [deliveryDate, statuses, limit]
|
||
)
|
||
: { rows: [] as Record<string, unknown>[] };
|
||
|
||
const seen = new Set<string>();
|
||
const reports: Array<
|
||
QualityReportLedgerItem & { source?: 'prep' | 'library' | 'shared' | 'self_purchase' }
|
||
> = [];
|
||
const push = (raw: Record<string, unknown>, source: 'prep' | 'library' | 'self_purchase') => {
|
||
const mapped = mapReportRow(raw, host);
|
||
if (seen.has(mapped.id)) return;
|
||
seen.add(mapped.id);
|
||
mapped.source = source;
|
||
reports.push({
|
||
...toLedgerItem(mapped, [], qualityReportShareHint(mapped.report_type)),
|
||
source,
|
||
});
|
||
};
|
||
for (const row of libRows.rows) push(row, 'library');
|
||
for (const row of prepRows.rows) push(row, 'prep');
|
||
for (const row of purchaseRows.rows) push(row, 'self_purchase');
|
||
reports.sort((a, b) => String(b.uploaded_at || '').localeCompare(String(a.uploaded_at || '')));
|
||
return {
|
||
items,
|
||
reports: reports.map((r) => ({
|
||
...r,
|
||
covered_sku_codes: skuCodesCoveredByDayReport(r, items),
|
||
})),
|
||
};
|
||
}
|