Merge pull request #243 from yunyingk/mac15/invoices-flatten-and-conflict-trace
Add normalized invoice fields, first-class invoices CLI, and CLI-attributed conflict diagnosis
This commit is contained in:
10 files changed
+605
-9
No files matched your search
@@ -184,7 +184,11 @@ seal-use contacts children <departmentId> [--corp <corpId>]
|
||||
seal-use contacts users <departmentId> [--corp <corpId>]
|
||||
seal-use contacts sync-time [--corp <corpId>]
|
||||
seal-use data expenses [--search <text>] [--start-date <ISO|ms>] [--end-date <ISO|ms>] [--offset <n>] [--limit <n>] [--corp <corpId>]
|
||||
seal-use data invoices [--search <text>] [--start-date <ISO|ms>] [--end-date <ISO|ms>] [--offset <n>] [--limit <n>] [--corp <corpId>]
|
||||
seal-use data invoices [--search <text>] [--start-date <ISO|ms>] [--end-date <ISO|ms>] [--offset <n>] [--limit <n>] [--full] [--corp <corpId>]
|
||||
seal-use invoices [list] [--search <text>] [--start-date <ISO|ms>] [--end-date <ISO|ms>] [--offset <n>] [--limit <n>] [--full] [--corp <corpId>]
|
||||
seal-use invoices trace <invoiceNumber> [--corp <corpId>]
|
||||
seal-use invoices <invoiceNumber> [--corp <corpId>]
|
||||
seal-use expenses [list] [--search <text>] [--start-date <ISO|ms>] [--end-date <ISO|ms>] [--offset <n>] [--limit <n>] [--corp <corpId>]
|
||||
seal-use llm config [--corp <corpId>]
|
||||
seal-use llm providers [--corp <corpId>]
|
||||
seal-use permissions available [--corp <corpId>]
|
||||
|
||||
@@ -3,7 +3,9 @@ export const AREA_ALIASES: Readonly<Record<string, string>> = {
|
||||
corp: "corps",
|
||||
webhooks: "webhook",
|
||||
preferences: "preference",
|
||||
server: "mcp"
|
||||
server: "mcp",
|
||||
invoice: "invoices",
|
||||
expense: "expenses"
|
||||
}
|
||||
|
||||
export const UPDATE_ALIASES = new Set([
|
||||
|
||||
@@ -26,7 +26,10 @@ export async function handleDataCommand(
|
||||
}
|
||||
|
||||
if (action === "invoices" || action === "invoice") {
|
||||
await runCapability("sealInvoicesList", client, corp, params, outputOptions(args.options));
|
||||
const subAction = args.command[2];
|
||||
const maybeTarget = args.command[3];
|
||||
const { handleInvoicesCommand } = await import("./invoices.js");
|
||||
await handleInvoicesCommand(subAction, maybeTarget, client, corp, args);
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
import type { CorpConfig } from "../../core/config/types.js";
|
||||
import type { createSealClient } from "../../core/http/factory.js";
|
||||
import { traceInvoice } from "../../domains/seal/approval-runs/invoices.js";
|
||||
import { runCapability } from "../helpers.js";
|
||||
import { booleanOption, numberOption, stringOption } from "../parser.js";
|
||||
import { outputOptions, printJson } from "../printer.js";
|
||||
import type { ParsedArgs } from "../types.js";
|
||||
|
||||
export async function handleInvoicesCommand(
|
||||
action: string | undefined,
|
||||
maybeTarget: string | undefined,
|
||||
client: Awaited<ReturnType<typeof createSealClient>>,
|
||||
corp: CorpConfig,
|
||||
args: ParsedArgs
|
||||
) {
|
||||
// Check if subcommand is "trace" or a positional invoice number
|
||||
const isTrace = action === "trace";
|
||||
const invoiceNumberToTrace = isTrace
|
||||
? (maybeTarget ?? stringOption(args.options.number) ?? stringOption(args.options.invoice))
|
||||
: (action && /^\d{10,25}$/.test(action) ? action : undefined);
|
||||
|
||||
if (invoiceNumberToTrace) {
|
||||
const report = await traceInvoice(client, invoiceNumberToTrace, corp.id);
|
||||
if (!report) {
|
||||
printJson(
|
||||
{
|
||||
found: false,
|
||||
invoiceNumber: invoiceNumberToTrace,
|
||||
message: `未在进项发票库中找到发票号码为 ${invoiceNumberToTrace} 的记录。`
|
||||
},
|
||||
outputOptions(args.options)
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
if (report.conflictStatus === "MULTIPLE_DOCUMENTS_ATTACHED") {
|
||||
console.error(
|
||||
`\n💡 [CLI 辅助溯源指引](注:此指引由 seal-use CLI 基于进项发票库关联数据自动提炼,非后端大模型生成):\n` +
|
||||
`• 发票 ${report.invoice.invoiceNumber}(${report.invoice.sellerName},¥${report.invoice.totalAmount})在 ${report.associatedDocuments.length} 笔单据中均有挂载记录:\n` +
|
||||
report.associatedDocuments.map((d) => ` - 单号: ${d.sourceDocumentSN}(已占 ¥${d.usedAmount ?? 0})👉 诊断命令: ${d.nextDiagnose}`).join("\n") +
|
||||
`\n`
|
||||
);
|
||||
}
|
||||
|
||||
printJson(report, outputOptions(args.options));
|
||||
return;
|
||||
}
|
||||
|
||||
// Otherwise, default to list / search
|
||||
const searchQuery =
|
||||
stringOption(args.options.search) ??
|
||||
stringOption(args.options.query) ??
|
||||
(action && action !== "list" ? action : undefined);
|
||||
|
||||
const params = {
|
||||
offset: numberOption(args.options.offset),
|
||||
limit: numberOption(args.options.limit),
|
||||
startDate: stringOption(args.options.startDate) ?? stringOption(args.options["start-date"]),
|
||||
endDate: stringOption(args.options.endDate) ?? stringOption(args.options["end-date"]),
|
||||
search: searchQuery,
|
||||
full: booleanOption(args.options.full) === true
|
||||
};
|
||||
|
||||
await runCapability("sealInvoicesList", client, corp, params, outputOptions(args.options));
|
||||
}
|
||||
+39
-3
@@ -1169,13 +1169,49 @@ export const HELP_REGISTRY: AreaHelp[] = [
|
||||
commands: [
|
||||
{
|
||||
name: "expenses",
|
||||
summary: "Search raw expense items",
|
||||
summary: "Search raw expense items (also available as 'seal-use expenses')",
|
||||
usage: ["seal-use data expenses [--search <text>] [--start-date <ISO|ms>] [--end-date <ISO|ms>] [--offset <n>] [--limit <n>] [--corp <corpId>]"]
|
||||
},
|
||||
{
|
||||
name: "invoices",
|
||||
summary: "Search raw invoice records",
|
||||
usage: ["seal-use data invoices [--search <text>] [--start-date <ISO|ms>] [--end-date <ISO|ms>] [--offset <n>] [--limit <n>] [--corp <corpId>]"]
|
||||
summary: "Search raw invoice records (also available as 'seal-use invoices')",
|
||||
usage: ["seal-use data invoices [--search <text>] [--start-date <ISO|ms>] [--end-date <ISO|ms>] [--offset <n>] [--limit <n>] [--full] [--corp <corpId>]"]
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
area: "invoices",
|
||||
title: "进项发票查询与溯源",
|
||||
description: "查看已审批单据中出现的进项发票,支持单据关联穿透、跨单据重复占用排查与扁平化业务视图。",
|
||||
commands: [
|
||||
{
|
||||
name: "list",
|
||||
summary: "分页查询进项发票(默认输出扁平化业务字段,对齐控制台表格)",
|
||||
usage: [
|
||||
"seal-use invoices [list] [--search <text>] [--start-date <ISO|ms>] [--end-date <ISO|ms>] [--offset <n>] [--limit <n>] [--full] [--corp <corpId>]"
|
||||
]
|
||||
},
|
||||
{
|
||||
name: "trace",
|
||||
summary: "穿透溯源指定发票,排查在哪些报销单据中被使用及是否存在跨单重复占用",
|
||||
usage: [
|
||||
"seal-use invoices trace <invoiceNumber> [--corp <corpId>]",
|
||||
"seal-use invoices <invoiceNumber> [--corp <corpId>]"
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
area: "expenses",
|
||||
title: "费用明细查询",
|
||||
description: "查询历史费用明细记录。",
|
||||
commands: [
|
||||
{
|
||||
name: "list",
|
||||
summary: "分页查询费用明细",
|
||||
usage: [
|
||||
"seal-use expenses [list] [--search <text>] [--start-date <ISO|ms>] [--end-date <ISO|ms>] [--offset <n>] [--limit <n>] [--corp <corpId>]"
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
|
||||
@@ -65,6 +65,8 @@ const CLIENT_COMMANDS: Record<string, ClientCommand> = {
|
||||
"users": async (args, corp, client) => (await import("./commands/users.js")).handleUsersCommand(args.command[1], args.command[2], client, corp, args),
|
||||
"contacts": async (args, corp, client) => (await import("./commands/contacts.js")).handleContactsCommand(args.command[1], args.command[2], client, corp, args),
|
||||
"data": async (args, corp, client) => (await import("./commands/data.js")).handleDataCommand(args.command[1], client, corp, args),
|
||||
"invoices": async (args, corp, client) => (await import("./commands/invoices.js")).handleInvoicesCommand(args.command[1], args.command[2], client, corp, args),
|
||||
"expenses": async (args, corp, client) => (await import("./commands/data.js")).handleDataCommand("expenses", client, corp, args),
|
||||
"llm": async (args, corp, client) => (await import("./commands/llm.js")).handleLlmCommand(args.command[1], client, corp, args),
|
||||
"permissions": async (args, corp, client) => (await import("./commands/permissions.js")).handlePermissionsCommand(args.command[1], client, corp, args),
|
||||
"billing": async (args, corp, client) => (await import("./commands/billing.js")).handleBillingCommand(args.command[1], client, corp, args),
|
||||
|
||||
@@ -0,0 +1,168 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import {
|
||||
flattenInvoiceRecord,
|
||||
extractDocumentInvoices,
|
||||
detectInvoiceConflicts,
|
||||
normalizeInvoiceDate,
|
||||
normalizeInvoiceStatus
|
||||
} from "./invoices.js";
|
||||
import type { ApprovalRun } from "../types.js";
|
||||
|
||||
describe("invoices domain module", () => {
|
||||
test("normalizeInvoiceDate formats 8-digit and slash dates to YYYY-MM-DD", () => {
|
||||
expect(normalizeInvoiceDate("20260617")).toBe("2026-06-17");
|
||||
expect(normalizeInvoiceDate("2026/06/17")).toBe("2026-06-17");
|
||||
expect(normalizeInvoiceDate("2026-06-17")).toBe("2026-06-17");
|
||||
expect(normalizeInvoiceDate("")).toBe("");
|
||||
});
|
||||
|
||||
test("normalizeInvoiceStatus correctly normalizes verified status", () => {
|
||||
expect(normalizeInvoiceStatus(undefined, "NORMAL_BLUE")).toBe("已验真 (verified)");
|
||||
expect(normalizeInvoiceStatus("verified", undefined)).toBe("已验真 (verified)");
|
||||
expect(normalizeInvoiceStatus(undefined, undefined, "NORMAL_BLUE")).toBe("已验真 (verified)");
|
||||
});
|
||||
|
||||
test("flattenInvoiceRecord flattens nested verifyResult and fileInfo into 8 core business fields", () => {
|
||||
const raw = {
|
||||
id: "inv-1",
|
||||
invoiceNumber: "26957000000102316227",
|
||||
sourceDocumentSN: "B26002404",
|
||||
totalAmount: 500,
|
||||
usedAmount: 409.02,
|
||||
verifyStatus: "verified",
|
||||
verifyResult: {
|
||||
invoiceType: "电子发票(普通发票)",
|
||||
sellerName: "深圳石油公明加油站",
|
||||
buyerName: "钰泰半导体股份有限公司",
|
||||
invoiceDate: "2026-06-17"
|
||||
},
|
||||
fileInfo: {
|
||||
fileName: "test.pdf",
|
||||
ossSignedUrl: "https://oss.example.com/test.pdf"
|
||||
},
|
||||
relatedDocuments: [
|
||||
{
|
||||
sourceDocumentSN: "B26002404",
|
||||
sourceDocumentId: "ID01WfOdmKUHyT",
|
||||
approvalRecordId: "rec-1",
|
||||
relatedAt: 1790001624549
|
||||
}
|
||||
]
|
||||
};
|
||||
|
||||
const flattened = flattenInvoiceRecord(raw);
|
||||
|
||||
expect(flattened.sourceDocumentSN).toBe("B26002404");
|
||||
expect(flattened.invoiceNumber).toBe("26957000000102316227");
|
||||
expect(flattened.invoiceType).toBe("电子发票(普通发票)");
|
||||
expect(flattened.invoiceDate).toBe("2026-06-17");
|
||||
expect(flattened.sellerName).toBe("深圳石油公明加油站");
|
||||
expect(flattened.buyerName).toBe("钰泰半导体股份有限公司");
|
||||
expect(flattened.totalAmount).toBe(500);
|
||||
expect(flattened.usedAmount).toBe(409.02);
|
||||
expect(flattened.status).toBe("已验真 (verified)");
|
||||
expect(flattened.fileName).toBe("test.pdf");
|
||||
expect(flattened.attachmentUrl).toBe("https://oss.example.com/test.pdf");
|
||||
expect(flattened.relatedDocuments).toHaveLength(1);
|
||||
expect(flattened.relatedDocuments[0]?.sourceDocumentSN).toBe("B26002404");
|
||||
});
|
||||
|
||||
test("detectInvoiceConflicts identifies cross-document invoice reuse and attributes to CLI", () => {
|
||||
const mockRun = {
|
||||
id: "run-2570",
|
||||
sourceDocumentSN: "B26002570",
|
||||
sourceDocumentId: "doc-2570",
|
||||
document: {
|
||||
fields: [
|
||||
{
|
||||
label: "明细",
|
||||
value: [
|
||||
{
|
||||
invoice: {
|
||||
invoiceNumber: "26957000000102316227",
|
||||
totalAmount: 500,
|
||||
usedAmount: 409.02,
|
||||
sellerName: "深圳石油公明加油站",
|
||||
relatedDocuments: [
|
||||
{
|
||||
sourceDocumentSN: "B26002404",
|
||||
sourceDocumentId: "doc-2404",
|
||||
approvalRecordId: "run-2404"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
} as unknown as ApprovalRun;
|
||||
|
||||
const conflicts = detectInvoiceConflicts(mockRun, "testCorp");
|
||||
expect(conflicts).toHaveLength(1);
|
||||
const c = conflicts[0]!;
|
||||
expect(c.source).toBe("cli_analysis");
|
||||
expect(c.detectedBy).toContain("seal-use CLI");
|
||||
expect(c.invoiceNumber).toBe("26957000000102316227");
|
||||
expect(c.conflictingSN).toBe("B26002404");
|
||||
expect(c.usedAmount).toBe(409.02);
|
||||
expect(c.nextCommand).toBe("seal-use approval-runs diagnose --sn B26002404 --corp testCorp");
|
||||
});
|
||||
|
||||
test("detectInvoiceConflicts returns empty array when invoices only relate to current document", () => {
|
||||
const mockRun = {
|
||||
id: "run-2570",
|
||||
sourceDocumentSN: "B26002570",
|
||||
sourceDocumentId: "doc-2570",
|
||||
document: {
|
||||
fields: [
|
||||
{
|
||||
invoice: {
|
||||
invoiceNumber: "26952000000810724261",
|
||||
totalAmount: 400,
|
||||
relatedDocuments: [
|
||||
{
|
||||
sourceDocumentSN: "B26002570",
|
||||
sourceDocumentId: "doc-2570",
|
||||
approvalRecordId: "run-2570"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
} as unknown as ApprovalRun;
|
||||
|
||||
const conflicts = detectInvoiceConflicts(mockRun, "testCorp");
|
||||
expect(conflicts).toHaveLength(0);
|
||||
});
|
||||
|
||||
test("extractDocumentInvoices extracts and normalizes unique invoices from document fields", () => {
|
||||
const mockRun = {
|
||||
id: "run-2570",
|
||||
sourceDocumentSN: "B26002570",
|
||||
document: {
|
||||
fields: [
|
||||
{
|
||||
invoice: {
|
||||
invoiceNumber: "26957000000102316227",
|
||||
totalAmount: 500
|
||||
}
|
||||
},
|
||||
{
|
||||
// duplicate invoice reference in another field
|
||||
invoice: {
|
||||
invoiceNumber: "26957000000102316227",
|
||||
totalAmount: 500
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
} as unknown as ApprovalRun;
|
||||
|
||||
const invoices = extractDocumentInvoices(mockRun);
|
||||
expect(invoices).toHaveLength(1);
|
||||
expect(invoices[0]?.invoiceNumber).toBe("26957000000102316227");
|
||||
expect(invoices[0]?.totalAmount).toBe(500);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,290 @@
|
||||
import type { KyInstance } from "ky";
|
||||
import * as api from "../api.js";
|
||||
import type { ApprovalRun } from "../types.js";
|
||||
|
||||
export interface NormalizedInvoice {
|
||||
sourceDocumentSN: string;
|
||||
sourceDocumentId?: string;
|
||||
approvalRecordId?: string;
|
||||
invoiceNumber: string;
|
||||
invoiceType: string;
|
||||
invoiceDate: string;
|
||||
sellerName: string;
|
||||
buyerName: string;
|
||||
totalAmount: number;
|
||||
taxAmount: number;
|
||||
usedAmount: number;
|
||||
status: string;
|
||||
fileName: string;
|
||||
attachmentUrl?: string;
|
||||
relatedDocuments: Array<{
|
||||
sourceDocumentSN?: string;
|
||||
sourceDocumentId?: string;
|
||||
approvalRecordId?: string;
|
||||
relatedAt?: number;
|
||||
}>;
|
||||
}
|
||||
|
||||
export interface InvoiceConflict {
|
||||
source: "cli_analysis";
|
||||
detectedBy: "seal-use CLI (基于单据原始发票关联数据自动提炼,非后端大模型生成)";
|
||||
invoiceNumber: string;
|
||||
sellerName?: string;
|
||||
invoiceDate?: string;
|
||||
totalAmount?: number;
|
||||
usedAmount?: number;
|
||||
conflictingSN: string;
|
||||
conflictingDocumentId?: string;
|
||||
conflictingRecordId?: string;
|
||||
explanation: string;
|
||||
nextCommand: string;
|
||||
}
|
||||
|
||||
export interface InvoiceTraceReport {
|
||||
invoice: NormalizedInvoice;
|
||||
associatedDocuments: Array<{
|
||||
sourceDocumentSN: string;
|
||||
sourceDocumentId?: string;
|
||||
approvalRecordId?: string;
|
||||
usedAmount?: number;
|
||||
relatedAt?: number;
|
||||
nextDiagnose: string;
|
||||
}>;
|
||||
conflictStatus: "NONE" | "MULTIPLE_DOCUMENTS_ATTACHED";
|
||||
guidance: {
|
||||
source: "cli_analysis";
|
||||
detectedBy: "seal-use CLI (基于进项发票库关联数据提炼,非后端大模型生成)";
|
||||
summary: string;
|
||||
};
|
||||
}
|
||||
|
||||
export function normalizeInvoiceDate(rawDate?: unknown): string {
|
||||
if (!rawDate) return "";
|
||||
const str = String(rawDate).trim();
|
||||
if (/^\d{8}$/.test(str)) {
|
||||
return `${str.slice(0, 4)}-${str.slice(4, 6)}-${str.slice(6, 8)}`;
|
||||
}
|
||||
if (/^\d{4}[-/]\d{1,2}[-/]\d{1,2}/.test(str)) {
|
||||
return str.replace(/\//g, "-").slice(0, 10);
|
||||
}
|
||||
return str;
|
||||
}
|
||||
|
||||
export function normalizeInvoiceStatus(status?: unknown, verifyStatus?: unknown, verifyCode?: unknown): string {
|
||||
const combined = `${status ?? ""} ${verifyStatus ?? ""} ${verifyCode ?? ""}`.toLowerCase();
|
||||
if (combined.includes("verified") || combined.includes("normal_blue") || combined.includes("已验真")) {
|
||||
return "已验真 (verified)";
|
||||
}
|
||||
if (combined.includes("fail") || combined.includes("不合规")) {
|
||||
return "验真失败 (failed)";
|
||||
}
|
||||
return String(status ?? verifyStatus ?? "未知");
|
||||
}
|
||||
|
||||
export function flattenInvoiceRecord(raw: Record<string, unknown>): NormalizedInvoice {
|
||||
const verifyResult = (raw.verifyResult && typeof raw.verifyResult === "object" ? raw.verifyResult : {}) as Record<string, unknown>;
|
||||
const rawForm = (verifyResult.form && typeof verifyResult.form === "object" ? verifyResult.form : {}) as Record<string, unknown>;
|
||||
const fileInfo = (raw.fileInfo && typeof raw.fileInfo === "object" ? raw.fileInfo : {}) as Record<string, unknown>;
|
||||
const relatedDocs = Array.isArray(raw.relatedDocuments) ? raw.relatedDocuments : [];
|
||||
|
||||
const invoiceNumber = String(raw.invoiceNumber ?? verifyResult.invoiceNumber ?? rawForm["发票号码"] ?? "");
|
||||
const invoiceDate = normalizeInvoiceDate(verifyResult.invoiceDate ?? raw.invoiceDate ?? rawForm["发票日期"]);
|
||||
const invoiceType = String(verifyResult.invoiceType ?? raw.invoiceType ?? rawForm["发票类别"] ?? rawForm["发票类型"] ?? "");
|
||||
const sellerName = String(verifyResult.sellerName ?? raw.sellerName ?? rawForm["销售方名称"] ?? "");
|
||||
const buyerName = String(verifyResult.buyerName ?? raw.buyerName ?? rawForm["购买方名称"] ?? "");
|
||||
|
||||
const totalAmount = typeof raw.totalAmount === "number"
|
||||
? raw.totalAmount
|
||||
: Number(verifyResult.totalAmount ?? (rawForm["价税合计"] as string)?.replace(/[^0-9.]/g, "") ?? 0);
|
||||
|
||||
const taxAmount = typeof raw.taxAmount === "number"
|
||||
? raw.taxAmount
|
||||
: Number(verifyResult.taxAmount ?? (rawForm["税额"] as string)?.replace(/[^0-9.]/g, "") ?? 0);
|
||||
|
||||
const usedAmount = typeof raw.usedAmount === "number" ? raw.usedAmount : Number(raw.usedAmount ?? 0);
|
||||
|
||||
const status = normalizeInvoiceStatus(raw.status, raw.verifyStatus ?? verifyResult.verify, rawForm["发票状态"]);
|
||||
|
||||
const fileName = String(fileInfo.fileName ?? fileInfo.name ?? raw.fileName ?? "");
|
||||
const attachmentUrl = String(fileInfo.ossSignedUrl ?? fileInfo.fileUrl ?? raw.fileUrl ?? "");
|
||||
|
||||
const sourceDocumentSN = String(
|
||||
raw.sourceDocumentSN ??
|
||||
(relatedDocs[0] as Record<string, unknown>)?.sourceDocumentSN ??
|
||||
""
|
||||
);
|
||||
|
||||
return {
|
||||
sourceDocumentSN,
|
||||
sourceDocumentId: raw.sourceDocumentId ? String(raw.sourceDocumentId) : undefined,
|
||||
approvalRecordId: raw.approvalRecordId ? String(raw.approvalRecordId) : undefined,
|
||||
invoiceNumber,
|
||||
invoiceType,
|
||||
invoiceDate,
|
||||
sellerName,
|
||||
buyerName,
|
||||
totalAmount,
|
||||
taxAmount,
|
||||
usedAmount,
|
||||
status,
|
||||
fileName,
|
||||
attachmentUrl: attachmentUrl || undefined,
|
||||
relatedDocuments: relatedDocs.map((item) => {
|
||||
const doc = item as Record<string, unknown>;
|
||||
return {
|
||||
sourceDocumentSN: doc.sourceDocumentSN ? String(doc.sourceDocumentSN) : undefined,
|
||||
sourceDocumentId: doc.sourceDocumentId ? String(doc.sourceDocumentId) : undefined,
|
||||
approvalRecordId: doc.approvalRecordId ? String(doc.approvalRecordId) : undefined,
|
||||
relatedAt: typeof doc.relatedAt === "number" ? doc.relatedAt : undefined
|
||||
};
|
||||
})
|
||||
};
|
||||
}
|
||||
|
||||
export function extractDocumentInvoices(record: ApprovalRun): NormalizedInvoice[] {
|
||||
const rawInvoices: Array<Record<string, unknown>> = [];
|
||||
|
||||
function traverse(obj: unknown) {
|
||||
if (!obj) return;
|
||||
if (Array.isArray(obj)) {
|
||||
obj.forEach(traverse);
|
||||
return;
|
||||
}
|
||||
if (typeof obj === "object") {
|
||||
const r = obj as Record<string, unknown>;
|
||||
if (r.invoice && typeof r.invoice === "object") {
|
||||
rawInvoices.push(r.invoice as Record<string, unknown>);
|
||||
} else if (r.invoiceNumber) {
|
||||
rawInvoices.push(r);
|
||||
}
|
||||
for (const val of Object.values(r)) {
|
||||
traverse(val);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
traverse(record.document);
|
||||
|
||||
const seen = new Set<string>();
|
||||
const uniqueNormalized: NormalizedInvoice[] = [];
|
||||
|
||||
for (const raw of rawInvoices) {
|
||||
const normalized = flattenInvoiceRecord(raw);
|
||||
if (!normalized.invoiceNumber) continue;
|
||||
if (seen.has(normalized.invoiceNumber)) continue;
|
||||
seen.add(normalized.invoiceNumber);
|
||||
uniqueNormalized.push(normalized);
|
||||
}
|
||||
|
||||
return uniqueNormalized;
|
||||
}
|
||||
|
||||
export function detectInvoiceConflicts(detail: ApprovalRun, corpId?: string): InvoiceConflict[] {
|
||||
const invoices = extractDocumentInvoices(detail);
|
||||
const conflicts: InvoiceConflict[] = [];
|
||||
const currentSN = detail.sourceDocumentSN ?? "";
|
||||
const currentDocId = detail.sourceDocumentId ?? "";
|
||||
const currentRunId = detail.id ?? "";
|
||||
|
||||
for (const inv of invoices) {
|
||||
const conflictingDocs = inv.relatedDocuments.filter((doc) => {
|
||||
const sameSN = currentSN && doc.sourceDocumentSN === currentSN;
|
||||
const sameDocId = currentDocId && doc.sourceDocumentId === currentDocId;
|
||||
const sameRunId = currentRunId && doc.approvalRecordId === currentRunId;
|
||||
return !(sameSN || sameDocId || sameRunId);
|
||||
});
|
||||
|
||||
if (conflictingDocs.length > 0) {
|
||||
for (const cDoc of conflictingDocs) {
|
||||
const conflictingSN = cDoc.sourceDocumentSN ?? cDoc.sourceDocumentId ?? "未知单据";
|
||||
const corpArg = corpId ? ` --corp ${corpId}` : "";
|
||||
const nextCommand = cDoc.sourceDocumentSN
|
||||
? `seal-use approval-runs diagnose --sn ${cDoc.sourceDocumentSN}${corpArg}`
|
||||
: `seal-use approval-runs diagnose ${cDoc.approvalRecordId ?? ""}${corpArg}`;
|
||||
|
||||
const usedNote = inv.usedAmount > 0 ? `,历史占用/报销金额 ¥${inv.usedAmount}` : "";
|
||||
conflicts.push({
|
||||
source: "cli_analysis",
|
||||
detectedBy: "seal-use CLI (基于单据原始发票关联数据自动提炼,非后端大模型生成)",
|
||||
invoiceNumber: inv.invoiceNumber,
|
||||
sellerName: inv.sellerName,
|
||||
invoiceDate: inv.invoiceDate,
|
||||
totalAmount: inv.totalAmount,
|
||||
usedAmount: inv.usedAmount,
|
||||
conflictingSN,
|
||||
conflictingDocumentId: cDoc.sourceDocumentId,
|
||||
conflictingRecordId: cDoc.approvalRecordId,
|
||||
explanation: `发票 ${inv.invoiceNumber}(${inv.sellerName || "销售方"},¥${inv.totalAmount})曾被历史单据 ${conflictingSN} 挂载${usedNote}。请核实是否为重复报销。`,
|
||||
nextCommand
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return conflicts;
|
||||
}
|
||||
|
||||
export async function traceInvoice(
|
||||
client: KyInstance,
|
||||
invoiceNumber: string,
|
||||
corpId?: string
|
||||
): Promise<InvoiceTraceReport | null> {
|
||||
const cleanNumber = invoiceNumber.trim();
|
||||
if (!cleanNumber) return null;
|
||||
|
||||
const data = await api.listInvoices(client, { search: cleanNumber, limit: 10 });
|
||||
if (!data.invoices || data.invoices.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const matched = data.invoices.find((item) => {
|
||||
const num = String(item.invoiceNumber ?? (item.verifyResult as any)?.invoiceNumber ?? "");
|
||||
return num === cleanNumber;
|
||||
}) ?? data.invoices[0]!;
|
||||
|
||||
const invoice = flattenInvoiceRecord(matched as Record<string, unknown>);
|
||||
|
||||
const associatedDocuments: InvoiceTraceReport["associatedDocuments"] = [];
|
||||
const corpArg = corpId ? ` --corp ${corpId}` : "";
|
||||
|
||||
if (invoice.sourceDocumentSN) {
|
||||
associatedDocuments.push({
|
||||
sourceDocumentSN: invoice.sourceDocumentSN,
|
||||
sourceDocumentId: invoice.sourceDocumentId,
|
||||
approvalRecordId: invoice.approvalRecordId,
|
||||
usedAmount: invoice.usedAmount,
|
||||
nextDiagnose: `seal-use approval-runs diagnose --sn ${invoice.sourceDocumentSN}${corpArg}`
|
||||
});
|
||||
}
|
||||
|
||||
for (const doc of invoice.relatedDocuments) {
|
||||
if (doc.sourceDocumentSN && !associatedDocuments.some((d) => d.sourceDocumentSN === doc.sourceDocumentSN)) {
|
||||
associatedDocuments.push({
|
||||
sourceDocumentSN: doc.sourceDocumentSN,
|
||||
sourceDocumentId: doc.sourceDocumentId,
|
||||
approvalRecordId: doc.approvalRecordId,
|
||||
relatedAt: doc.relatedAt,
|
||||
nextDiagnose: `seal-use approval-runs diagnose --sn ${doc.sourceDocumentSN}${corpArg}`
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const hasMultiple = associatedDocuments.length > 1;
|
||||
const conflictStatus = hasMultiple ? "MULTIPLE_DOCUMENTS_ATTACHED" : "NONE";
|
||||
|
||||
const docListStr = associatedDocuments.map((d) => d.sourceDocumentSN).join("、");
|
||||
const summary = hasMultiple
|
||||
? `发票 ${invoice.invoiceNumber} 在 ${associatedDocuments.length} 笔单据(${docListStr})中均有挂载记录。若其中有单据已被驳回或删票,请确认合思发票池是否释放;若均在审批或已核销,则属于真实重复报销。`
|
||||
: `发票 ${invoice.invoiceNumber} 当前仅关联单据 ${invoice.sourceDocumentSN || "未知"},未检测到跨单据重复挂载冲突。`;
|
||||
|
||||
return {
|
||||
invoice,
|
||||
associatedDocuments,
|
||||
conflictStatus,
|
||||
guidance: {
|
||||
source: "cli_analysis",
|
||||
detectedBy: "seal-use CLI (基于进项发票库关联数据提炼,非后端大模型生成)",
|
||||
summary
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -14,6 +14,7 @@ import {
|
||||
import {
|
||||
type ApprovalRun
|
||||
} from "../types.js";
|
||||
import { detectInvoiceConflicts } from "../approval-runs/invoices.js";
|
||||
import type {
|
||||
CapabilityContext
|
||||
} from "./helpers.js";
|
||||
@@ -717,6 +718,16 @@ export const approvalRunsCapabilities = [
|
||||
}
|
||||
}
|
||||
|
||||
const invoiceConflicts = detectInvoiceConflicts(detail, context.corp.id);
|
||||
|
||||
if (invoiceConflicts.length > 0) {
|
||||
console.error(
|
||||
`\n💡 [CLI 辅助诊断指引](注:此冲突指引由 seal-use CLI 基于单据原始发票关联数据自动分析提炼,非后端大模型生成):\n` +
|
||||
invoiceConflicts.map((c) => `• 发票 ${c.invoiceNumber}(${c.sellerName || "销售方"},¥${c.totalAmount})曾被单据 ${c.conflictingSN} 挂载${c.usedAmount ? `(已占报销金额 ¥${c.usedAmount})` : ""}\n 👉 诊断冲突原单:${c.nextCommand}`).join("\n") +
|
||||
`\n`
|
||||
);
|
||||
}
|
||||
|
||||
return {
|
||||
recordId: detail.id,
|
||||
sourceDocumentSN: detail.sourceDocumentSN,
|
||||
@@ -727,10 +738,13 @@ export const approvalRunsCapabilities = [
|
||||
result: params.full === true ? detail.result : resultSummary,
|
||||
citedRules,
|
||||
ruleVersion,
|
||||
invoiceConflicts: invoiceConflicts.length > 0 ? invoiceConflicts : undefined,
|
||||
bridge: summarizeRunBridge([detail]),
|
||||
next: {
|
||||
url: `seal-use approval-runs url ${detail.id} --corp ${context.corp.id}`,
|
||||
hoseDocument: `seal-use approval-runs url ${detail.id} --type hose-document --corp ${context.corp.id}`,
|
||||
diagnoseConflict: invoiceConflicts[0]?.nextCommand,
|
||||
traceInvoice: invoiceConflicts[0] ? `seal-use invoices trace ${invoiceConflicts[0].invoiceNumber} --corp ${context.corp.id}` : undefined,
|
||||
replay: `seal-use approval-runs replay ${detail.id} --dry-run --corp ${context.corp.id}`
|
||||
}
|
||||
};
|
||||
|
||||
@@ -6,6 +6,8 @@ import type {
|
||||
CapabilityContext
|
||||
} from "./helpers.js";
|
||||
|
||||
import { flattenInvoiceRecord } from "../approval-runs/invoices.js";
|
||||
|
||||
export const insightCapabilities = [
|
||||
{
|
||||
name: "sealInsightStatsGet",
|
||||
@@ -87,14 +89,24 @@ export const insightCapabilities = [
|
||||
},
|
||||
{
|
||||
name: "sealInvoicesList",
|
||||
description: "分页查询进项发票",
|
||||
description: "分页查询进项发票(默认输出扁平化业务字段,对齐控制台表格)",
|
||||
parameters: z.object({
|
||||
offset: z.number().int().nonnegative().optional(),
|
||||
limit: z.number().int().positive().max(100).optional(),
|
||||
startDate: z.string().optional().describe("开始时间"),
|
||||
endDate: z.string().optional().describe("结束时间"),
|
||||
search: z.string().optional().describe("搜索发票号码或销售方")
|
||||
search: z.string().optional().describe("搜索发票号码或销售方"),
|
||||
full: z.boolean().optional().describe("是否返回未扁平化的后端原始数据,默认 false (扁平化)")
|
||||
}),
|
||||
handler: async (client: KyInstance, params: api.DataListParams) => api.listInvoices(client, params)
|
||||
handler: async (client: KyInstance, params: api.DataListParams & { full?: boolean }) => {
|
||||
const result = await api.listInvoices(client, params);
|
||||
if (params.full === true) {
|
||||
return result;
|
||||
}
|
||||
return {
|
||||
...result,
|
||||
invoices: (result.invoices ?? []).map((inv) => flattenInvoiceRecord(inv as Record<string, unknown>))
|
||||
};
|
||||
}
|
||||
}
|
||||
];
|
||||
Reference in new issue
Block a user