文件
hyb-oa/server/src/services/ocr/index.js
T

59 行
1.5 KiB
JavaScript

const { runTencentVatOcr } = require("./tencent");
const { runMockOcr } = require("./mock");
const REQUIRED_OCR_FIELDS_BY_TYPE = {
vat: ["invoiceCode", "invoiceNumber", "invoiceDate", "totalAmount", "sellerName"],
};
function isOcrEnabledForType(config, ocrType) {
if (config.ocrProvider === "mock") {
return ocrType === "vat";
}
return config.ocrProvider === "tencent" && ocrType === "vat";
}
function getMissingRequiredOcrFields(ocrType, normalized) {
const requiredFields = REQUIRED_OCR_FIELDS_BY_TYPE[ocrType] ?? [];
if (!requiredFields.length) {
return [];
}
return requiredFields.filter((field) => {
const value = normalized?.[field];
return value == null || value === "";
});
}
function buildMissingRequiredOcrError(ocrType, normalized) {
const missingFields = getMissingRequiredOcrFields(ocrType, normalized);
if (!missingFields.length) {
return null;
}
return `missing_required_fields:${missingFields.join(",")}`;
}
async function runOcrForInvoice({ config, ocrType, imageBase64 }) {
if (config.ocrProvider === "mock") {
return runMockOcr({ ocrType, imageBase64 });
}
if (config.ocrProvider !== "tencent") {
throw new Error(`Unsupported OCR provider: ${config.ocrProvider}`);
}
if (ocrType !== "vat") {
throw new Error(`Unsupported OCR type: ${ocrType}`);
}
return runTencentVatOcr(config, imageBase64);
}
module.exports = {
buildMissingRequiredOcrError,
getMissingRequiredOcrFields,
isOcrEnabledForType,
runOcrForInvoice,
};