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

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

228 lines
7.6 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { callWithImage as callArkWithImage, hasRuntimeConfig as hasArkRuntimeConfig } from './llmService';
import { resolvePrompt } from './promptRegistryService';
export interface PrepackagedOcrResult {
product_name: string | null;
brand: string | null;
production_month: string | null;
raw_text?: string | null;
}
export interface PrepackagedScanPayload {
ocr_product_name: string | null;
ocr_brand: string | null;
ocr_production_month: string | null;
name_matched: boolean;
brand_matched: boolean;
label_matched: boolean;
photo_filename: string;
scanned_at: string;
expected_name: string;
expected_brand: string;
}
export function normalizeLabelText(text: string): string {
return String(text || '')
.replace(/[\s·•\-_/\\()()\[\]【】《》,,.。::;;]/g, '')
.toLowerCase();
}
export function normalizeProductionMonth(raw: string | null | undefined): string | null {
if (!raw) return null;
const text = String(raw).trim();
const match = text.match(/(\d{4})\D{0,3}(\d{1,2})/);
if (!match) return null;
const month = Number(match[2]);
if (month < 1 || month > 12) return null;
return `${match[1]}-${String(month).padStart(2, '0')}`;
}
function parseJson(text: string): Record<string, unknown> | null {
const s = text.trim();
const start = s.indexOf('{');
const end = s.lastIndexOf('}');
if (start < 0 || end <= start) return null;
try {
return JSON.parse(s.slice(start, end + 1));
} catch {
return null;
}
}
/** 期望文字是否出现在 OCR 结果中(支持互相包含) */
export function labelTextMatches(
expected: string,
...sources: Array<string | null | undefined>
): boolean {
const expectedNorm = normalizeLabelText(expected);
if (!expectedNorm || expectedNorm.length < 2) return false;
for (const source of sources) {
if (!source) continue;
const sourceNorm = normalizeLabelText(source);
if (!sourceNorm || sourceNorm.length < 2) continue;
if (sourceNorm === expectedNorm) return true;
if (sourceNorm.includes(expectedNorm)) return true;
if (expectedNorm.includes(sourceNorm)) return true;
}
return false;
}
export function evaluatePrepackagedLabelMatch(input: {
expectedName: string;
expectedBrand: string;
ocrProductName: string | null;
ocrBrand: string | null;
ocrRawText?: string | null;
}): { labelMatched: boolean; nameMatched: boolean; brandMatched: boolean } {
const combined = [input.ocrProductName, input.ocrBrand, input.ocrRawText]
.filter(Boolean)
.join('');
const nameMatched = labelTextMatches(input.expectedName, input.ocrProductName, combined);
const brandMatched = input.expectedBrand
? labelTextMatches(input.expectedBrand, input.ocrBrand, input.ocrProductName, combined)
: false;
return {
labelMatched: nameMatched && brandMatched,
nameMatched,
brandMatched,
};
}
export async function scanPrepackagedLabel(
imageBase64: string,
branchCode?: string | null
): Promise<PrepackagedOcrResult> {
if (!(await hasArkRuntimeConfig({ branchCode: branchCode || undefined }))) {
return { product_name: null, brand: null, production_month: null, raw_text: null };
}
try {
const prompt = await resolvePrompt('inspection.prepackaged.ocr', { branchCode });
const raw = await callArkWithImage(prompt.systemPrompt, imageBase64, {
branchCode: branchCode || undefined,
});
if (!raw) return { product_name: null, brand: null, production_month: null, raw_text: null };
const parsed = parseJson(raw);
if (!parsed) return { product_name: null, brand: null, production_month: null, raw_text: raw };
return {
brand: parsed.brand ? String(parsed.brand).trim() : null,
product_name: parsed.product_name ? String(parsed.product_name).trim() : null,
production_month: normalizeProductionMonth(
parsed.production_month ? String(parsed.production_month) : null
),
raw_text: parsed.raw_text ? String(parsed.raw_text) : raw,
};
} catch {
return { product_name: null, brand: null, production_month: null, raw_text: null };
}
}
export async function buildPrepackagedScan(input: {
skuCode: string;
expectedName: string;
expectedBrand: string;
photoFilename: string;
imageBase64: string;
branchCode?: string | null;
}): Promise<PrepackagedScanPayload> {
const ocr = await scanPrepackagedLabel(input.imageBase64, input.branchCode);
const match = evaluatePrepackagedLabelMatch({
expectedName: input.expectedName,
expectedBrand: input.expectedBrand,
ocrProductName: ocr.product_name,
ocrBrand: ocr.brand,
ocrRawText: ocr.raw_text,
});
return {
ocr_product_name: ocr.product_name,
ocr_brand: ocr.brand,
ocr_production_month: ocr.production_month,
name_matched: match.nameMatched,
brand_matched: match.brandMatched,
label_matched: match.labelMatched,
photo_filename: input.photoFilename,
scanned_at: new Date().toISOString(),
expected_name: input.expectedName,
expected_brand: input.expectedBrand,
};
}
export function readPrepackagedScan(details: unknown): PrepackagedScanPayload | null {
if (!details || typeof details !== 'object' || Array.isArray(details)) return null;
const scan = (details as { prepackaged_scan?: unknown }).prepackaged_scan;
if (!scan || typeof scan !== 'object' || Array.isArray(scan)) return null;
const obj = scan as Record<string, unknown>;
const labelMatched =
obj.label_matched === true ||
(obj.name_matched === true && obj.brand_matched === true);
return {
ocr_product_name: obj.ocr_product_name ? String(obj.ocr_product_name) : null,
ocr_brand: obj.ocr_brand ? String(obj.ocr_brand) : null,
ocr_production_month: obj.ocr_production_month ? String(obj.ocr_production_month) : null,
name_matched: obj.name_matched === true,
brand_matched: obj.brand_matched === true,
label_matched: labelMatched,
photo_filename: String(obj.photo_filename || ''),
scanned_at: String(obj.scanned_at || ''),
expected_name: String(obj.expected_name || ''),
expected_brand: String(obj.expected_brand || ''),
};
}
export function mergeProcessingDetails(
existing: unknown,
patch: Record<string, unknown>
): Record<string, unknown> {
const base =
existing && typeof existing === 'object' && !Array.isArray(existing)
? { ...(existing as Record<string, unknown>) }
: {};
return { ...base, ...patch };
}
export async function validatePrepackagedInspection(input: {
skuCode: string;
expectedName: string;
expectedBrand?: string | null;
productionDateMonth: string;
processingDetails?: unknown;
}): Promise<{ ok: boolean; message?: string }> {
const month = normalizeProductionMonth(input.productionDateMonth);
if (!month) {
return { ok: false, message: '请选择预包装商品生产日期(按月)' };
}
const expectedBrand = String(input.expectedBrand || '').trim();
if (!expectedBrand) {
return { ok: false, message: '该预包装商品未维护品牌,请先在商品管理中填写品牌' };
}
const scan = readPrepackagedScan(input.processingDetails);
if (!scan) {
return { ok: false, message: '请先拍摄包装照片并完成识别' };
}
if (!scan.label_matched) {
const parts: string[] = [];
if (!scan.name_matched) {
parts.push(`商品名「${scan.ocr_product_name || '未识别'}」与系统「${input.expectedName}」不对应`);
}
if (!scan.brand_matched) {
parts.push(`品牌「${scan.ocr_brand || '未识别'}」与系统「${expectedBrand}」不对应`);
}
return {
ok: false,
message: `${parts.join(';')},不能验收通过`,
};
}
return { ok: true };
}