feat: add reviewed OCR and AI document workflow

This commit is contained in:
leefer
2026-08-01 15:59:28 +08:00
parent 3ef13b5674
commit a3203f95da
12 changed files with 1808 additions and 6 deletions
+216 -2
View File
@@ -108,6 +108,66 @@ interface ExportInfo {
checksum: string;
}
interface ProviderStatus {
ocrConfigured: boolean;
ocrEnabled: boolean;
ocrProvider: string;
llmConfigured: boolean;
llmEnabled: boolean;
llmProvider: string;
llmModel: string;
localDevelopmentOnly: boolean;
}
interface InvoiceLineItem {
name: string;
amountInCents: number | null;
taxRate: string;
taxInCents: number | null;
}
interface InvoiceExtraction {
invoiceType: string;
invoiceNumber: string;
invoiceDate: string;
purchaserName: string;
purchaserTaxId: string;
sellerName: string;
sellerTaxId: string;
totalAmountInCents: number | null;
totalTaxInCents: number | null;
totalWithTaxInCents: number | null;
amountInWords: string;
drawer: string;
remarks: string;
confidence: number;
lineItems: InvoiceLineItem[];
}
interface BookkeepingSuggestion {
direction: "income" | "expense";
category: string;
counterparty: string;
occurredOn: string;
amountInCents: number;
businessPurpose: string;
confidence: number;
reason: string;
}
interface StoredDocument {
id: string;
fileName: string;
mimeType: string;
sizeBytes: number;
status: "stored" | "processing" | "needs_review" | "confirmed" | "failed";
lastError: string | null;
createdAt: string;
updatedAt: string;
extraction: InvoiceExtraction | null;
suggestion: BookkeepingSuggestion | null;
}
function entityTypeLabel(entityType: BusinessProfile["entityType"]) {
return entityType === "sole_proprietor" ? "个体工商户" : "小微企业";
}
@@ -485,9 +545,163 @@ function ConfirmPage({ pending, isLocal, reviewingId, onConfirm, onNotify }: {
</div>;
}
function amountInput(cents: number | null) {
return cents === null ? "" : (cents / 100).toFixed(2);
}
function inputCents(value: string) {
const trimmed = value.trim();
if (!/^\d+(\.\d{1,2})?$/.test(trimmed)) return null;
const [whole, decimal = ""] = trimmed.split(".");
return Number(whole) * 100 + Number(decimal.padEnd(2, "0"));
}
function documentStatus(document: StoredDocument) {
if (document.status === "confirmed") return { label: "已核对", className: "done" };
if (document.status === "needs_review") return { label: "待核对", className: "waiting" };
if (document.status === "processing") return { label: "识别中", className: "waiting" };
if (document.status === "failed") return { label: "需重试", className: "error" };
return { label: "已归档", className: "personal" };
}
function DocumentReview({ document, llmReady, busy, onConfirm, onSuggest }: {
document: StoredDocument;
llmReady: boolean;
busy: "ocr" | "llm" | "confirm" | null;
onConfirm: (input: Record<string, unknown>) => Promise<void>;
onSuggest: () => Promise<void>;
}) {
const extraction = document.extraction;
const [invoiceNumber, setInvoiceNumber] = useState(extraction?.invoiceNumber ?? "");
const [invoiceDate, setInvoiceDate] = useState(extraction?.invoiceDate ?? "");
const [purchaserName, setPurchaserName] = useState(extraction?.purchaserName ?? "");
const [purchaserTaxId, setPurchaserTaxId] = useState(extraction?.purchaserTaxId ?? "");
const [sellerName, setSellerName] = useState(extraction?.sellerName ?? "");
const [sellerTaxId, setSellerTaxId] = useState(extraction?.sellerTaxId ?? "");
const [totalAmount, setTotalAmount] = useState(amountInput(extraction?.totalAmountInCents ?? null));
const [totalTax, setTotalTax] = useState(amountInput(extraction?.totalTaxInCents ?? null));
const [totalWithTax, setTotalWithTax] = useState(amountInput(extraction?.totalWithTaxInCents ?? null));
if (!extraction) {
return <div className="document-detail-empty"><Icon name={document.status === "failed" ? "bell" : "file"} size={28}/><h2>{document.status === "failed" ? "这张票据暂未识别成功" : "正在准备识别结果"}</h2><p>{document.lastError ?? "完成后会在这里显示可核对字段。"}</p></div>;
}
const confirm = async (event: FormEvent<HTMLFormElement>) => {
event.preventDefault();
const amounts = [totalAmount, totalTax, totalWithTax].map((value) => value.trim() ? inputCents(value) : null);
if (amounts.some((value, index) => [totalAmount, totalTax, totalWithTax][index].trim() && value === null)) return;
await onConfirm({
documentId: document.id,
invoiceNumber,
invoiceDate,
purchaserName,
purchaserTaxId,
sellerName,
sellerTaxId,
totalAmountInCents: amounts[0],
totalTaxInCents: amounts[1],
totalWithTaxInCents: amounts[2],
});
};
return <div className="document-detail-content">
<div className="document-detail-heading"><div><span>{extraction.invoiceType || "增值税发票"}</span><h2>{document.fileName}</h2><p>OCR 分类置信度 {(extraction.confidence * 100).toFixed(1)}%,请以票面原件为准。</p></div><span className={`status ${documentStatus(document).className}`}>{documentStatus(document).label}</span></div>
<form className="invoice-review-form" onSubmit={confirm}>
<div className="invoice-fields">
<label><span>发票号码</span><input value={invoiceNumber} onChange={(event) => setInvoiceNumber(event.target.value)} required/></label>
<label><span>开票日期</span><input type="date" value={invoiceDate} onChange={(event) => setInvoiceDate(event.target.value)} required/></label>
<label className="field-wide"><span>销售方名称</span><input value={sellerName} onChange={(event) => setSellerName(event.target.value)} required/></label>
<label className="field-wide"><span>销售方税号</span><input value={sellerTaxId} onChange={(event) => setSellerTaxId(event.target.value)}/></label>
<label className="field-wide"><span>购买方名称</span><input value={purchaserName} onChange={(event) => setPurchaserName(event.target.value)}/></label>
<label className="field-wide"><span>购买方税号</span><input value={purchaserTaxId} onChange={(event) => setPurchaserTaxId(event.target.value)}/></label>
<label><span>不含税金额</span><input inputMode="decimal" value={totalAmount} onChange={(event) => setTotalAmount(event.target.value)} placeholder="0.00"/></label>
<label><span>税额</span><input inputMode="decimal" value={totalTax} onChange={(event) => setTotalTax(event.target.value)} placeholder="0.00"/></label>
<label><span>价税合计</span><input inputMode="decimal" value={totalWithTax} onChange={(event) => setTotalWithTax(event.target.value)} placeholder="0.00" required/></label>
</div>
{extraction.lineItems.length ? <div className="invoice-items"><div className="invoice-items-heading"><strong>商品与服务明细</strong><span>{extraction.lineItems.length} 行</span></div>{extraction.lineItems.map((item, index) => <div className="invoice-item" key={`${item.name}-${index}`}><span title={item.name}>{item.name || "未识别名称"}</span><small>{item.taxRate || "税率未知"}</small><b>{item.amountInCents === null ? "金额未知" : formatCurrency(item.amountInCents)}</b></div>)}</div> : null}
{document.suggestion ? <section className="suggestion-box"><div><span>AI 记账建议</span><strong>{document.suggestion.direction === "income" ? "经营收入" : "经营支出"},{document.suggestion.category}</strong><p>{document.suggestion.businessPurpose}。{document.suggestion.reason}</p></div><b>{Math.round(document.suggestion.confidence * 100)}% 把握</b></section> : null}
<div className="document-review-actions"><button className="primary-button" disabled={busy !== null || document.status === "confirmed"} type="submit">{busy === "confirm" ? "正在保存" : document.status === "confirmed" ? "已完成人工核对" : "确认字段无误"}</button><button className="secondary-button" disabled={busy !== null || !llmReady} type="button" onClick={onSuggest}>{busy === "llm" ? "正在生成" : document.suggestion ? "重新生成记账建议" : "生成记账建议"}</button><span>AI 建议不会直接入账</span></div>
</form>
</div>;
}
function DocumentsPage({ onNotify }: { onNotify: (message: string) => void }) {
return <div className="page"><PageIntro eyebrow="票据中心" title="票据归档正在准备中" description="0.9 内测版尚未启用票据上传和识别,避免把预览数据误当成真实票据。" />
<section className="empty-state feature-preview"><Icon name="file" size={32}/><span className="safe-pill">后续功能</span><h2>这里将保存原始票据与识别结果</h2><p>票据文件、识别字段和人工修订会分开保存;在功能通过完整验收前不会开放入口。</p><button className="secondary-button" onClick={() => onNotify("票据模块会在原始文件存储与恢复测试通过后开放")}>了解开放条件</button></section>
const fileInput = useRef<HTMLInputElement>(null);
const [providerStatus, setProviderStatus] = useState<ProviderStatus | null>(null);
const [documents, setDocuments] = useState<StoredDocument[]>([]);
const [selectedId, setSelectedId] = useState<string | null>(null);
const [busy, setBusy] = useState<"ocr" | "llm" | "confirm" | null>(null);
const [loading, setLoading] = useState(true);
const selected = documents.find((item) => item.id === selectedId) ?? documents[0] ?? null;
const ocrReady = Boolean(providerStatus?.ocrConfigured && providerStatus.ocrEnabled);
const llmReady = Boolean(providerStatus?.llmConfigured && providerStatus.llmEnabled);
const loadDocuments = async () => {
const stored = await invoke<StoredDocument[]>("list_documents");
setDocuments(stored);
setSelectedId((current) => current && stored.some((item) => item.id === current) ? current : stored[0]?.id ?? null);
return stored;
};
useEffect(() => {
if (!isTauriRuntime()) { setLoading(false); return; }
Promise.all([invoke<ProviderStatus>("get_provider_status"), loadDocuments()])
.then(([status]) => setProviderStatus(status))
.catch((error) => onNotify(`票据中心初始化失败:${String(error)}`))
.finally(() => setLoading(false));
}, []);
const chooseFile = () => {
if (!isTauriRuntime()) { onNotify("票据识别请在 Windows 客户端中使用"); return; }
if (!ocrReady) { onNotify("请先在本地配置中启用百度 OCR"); return; }
fileInput.current?.click();
};
const recognize = async (event: ChangeEvent<HTMLInputElement>) => {
const file = event.target.files?.[0];
event.target.value = "";
if (!file) return;
if (file.size > 2_500_000) { onNotify("图片不能超过 2.5 MB"); return; }
const mimeType = file.type || (file.name.toLowerCase().endsWith(".png") ? "image/png" : "image/jpeg");
setBusy("ocr");
try {
const stored = await invoke<StoredDocument>("recognize_document", { input: { fileName: file.name, mimeType, bytes: Array.from(new Uint8Array(await file.arrayBuffer())) } });
await loadDocuments();
setSelectedId(stored.id);
onNotify(stored.status === "confirmed" ? "这张票据已经归档并核对" : "票据识别完成,请核对字段");
} catch (error) {
await loadDocuments().catch(() => undefined);
onNotify(`票据识别失败:${String(error)}`);
} finally { setBusy(null); }
};
const generateSuggestion = async () => {
if (!selected) return;
setBusy("llm");
try {
await invoke<StoredDocument>("generate_document_suggestion", { documentId: selected.id });
await loadDocuments();
onNotify("记账建议已生成,仍需人工确认");
} catch (error) { onNotify(`生成建议失败:${String(error)}`); }
finally { setBusy(null); }
};
const confirm = async (input: Record<string, unknown>) => {
setBusy("confirm");
try {
await invoke<StoredDocument>("confirm_document", { input });
await loadDocuments();
onNotify("人工核对结果已保存,原始 OCR 结果仍保留");
} catch (error) { onNotify(`保存核对结果失败:${String(error)}`); throw error; }
finally { setBusy(null); }
};
const pendingCount = documents.filter((item) => item.status === "needs_review").length;
const confirmedCount = documents.filter((item) => item.status === "confirmed").length;
return <div className="page documents-page"><PageIntro eyebrow="票据中心" title="票据先识别,再由你确认" description="原图和识别记录保存在本地加密账本;上传时只有当前图片会发送给百度 OCR。" action={<div className="page-actions"><input ref={fileInput} className="visually-hidden" type="file" accept="image/png,image/jpeg,image/bmp,image/webp" onChange={recognize}/><button className="primary-button" disabled={busy !== null || !ocrReady} onClick={chooseFile}><Icon name="plus" size={17}/>{busy === "ocr" ? "正在识别" : "上传并识别"}</button></div>} />
<section className={`provider-strip ${ocrReady ? "ready" : "blocked"}`}><Icon name={ocrReady ? "shield" : "bell"} size={20}/><div><strong>{ocrReady ? `${providerStatus?.ocrProvider}已就绪` : "OCR 当前未启用"}</strong><p>{ocrReady ? "本次上传会调用云端识别;原图同时写入本地 SQLCipher 加密账本。" : loading ? "正在检查本地开发配置。" : "请把 local.providers.toml 中的百度 OCR enabled 改为 true。"}</p></div><span>{providerStatus?.localDevelopmentOnly ? "仅本地开发" : "服务端模式"}</span></section>
<section className="document-stats"><article><span>加密归档</span><strong>{documents.length}</strong><small>按内容哈希自动去重</small></article><article><span>等待核对</span><strong>{pendingCount}</strong><small>不会自动写入账簿</small></article><article><span>已人工确认</span><strong>{confirmedCount}</strong><small>修改记录单独保存</small></article></section>
{loading ? <section className="empty-state document-loading"><Icon name="file" size={28}/><h2>正在读取加密票据</h2><p>请稍候,系统不会把票据内容写入日志。</p></section> : documents.length === 0 ? <section className="empty-state feature-preview"><Icon name="file" size={32}/><span className="safe-pill">本地加密归档</span><h2>上传第一张经营票据</h2><p>支持 PNG、JPG、BMP 和 WebP,单张不超过 2.5 MB。点击上传即表示同意将当前图片发送给百度 OCR。</p><button className="secondary-button" disabled={!ocrReady} onClick={chooseFile}>选择测试票据</button></section> : <section className="documents-workspace"><div className="document-list-panel"><div className="document-list-heading"><div><h2>票据记录</h2><p>最近上传优先</p></div><span>{documents.length} 张</span></div><div className="document-list">{documents.map((document) => { const status = documentStatus(document); return <button key={document.id} className={selected?.id === document.id ? "active" : ""} onClick={() => setSelectedId(document.id)}><span className="document-list-icon"><Icon name="file" size={18}/></span><span><strong title={document.fileName}>{document.fileName}</strong><small>{document.extraction?.sellerName || document.lastError || "等待识别结果"}</small></span><span className={`status ${status.className}`}>{status.label}</span></button>; })}</div></div><div className="document-detail">{selected ? <DocumentReview key={`${selected.id}-${selected.updatedAt}`} document={selected} llmReady={llmReady} busy={busy} onConfirm={confirm} onSuggest={generateSuggestion}/> : null}</div></section>}
</div>;
}
+70
View File
@@ -246,6 +246,7 @@ th:nth-child(1) { width: 21%; } th:nth-child(2) { width: 25%; } th:nth-child(3)
.status.done { color: var(--accent-700); background: var(--accent-050); }
.status.waiting { color: var(--warning); background: var(--warning-bg); }
.status.personal { color: #5b6472; background: #eef0f3; }
.status.error { color: #9a3f32; background: #fff0ed; }
.right-rail { display: grid; gap: 16px; }
.action-panel-title { padding: 17px 17px 11px; display: flex; align-items: center; gap: 11px; }
@@ -291,6 +292,74 @@ th:nth-child(1) { width: 21%; } th:nth-child(2) { width: 25%; } th:nth-child(3)
.feature-preview .safe-pill { margin-top: 5px; }
.feature-preview p { max-width: 520px; line-height: 1.7; }
.feature-preview .secondary-button { margin-top: 10px; }
.document-loading { min-height: 330px; }
.provider-strip {
min-height: 66px;
margin-bottom: 14px;
padding: 13px 17px;
display: grid;
grid-template-columns: auto minmax(0, 1fr) auto;
align-items: center;
gap: 12px;
border: 1px solid;
border-radius: var(--radius-surface);
}
.provider-strip.ready { color: #315e56; background: var(--accent-050); border-color: #cce2dc; }
.provider-strip.blocked { color: #755600; background: var(--warning-bg); border-color: #ead99e; }
.provider-strip strong, .provider-strip p { display: block; margin: 0; }
.provider-strip strong { color: #283b38; font-size: 11.5px; }
.provider-strip p { margin-top: 4px; color: #5e706c; font-size: 10px; line-height: 1.45; }
.provider-strip > span { padding: 4px 8px; color: inherit; background: rgba(255, 255, 255, .68); border-radius: 6px; font-size: 9px; font-weight: 650; white-space: nowrap; }
.documents-workspace { min-height: 520px; display: grid; grid-template-columns: 278px minmax(0, 1fr); gap: 14px; align-items: stretch; }
.document-list-panel, .document-detail { overflow: hidden; background: #fff; border: 1px solid var(--border); border-radius: var(--radius-surface); }
.document-list-heading { min-height: 64px; padding: 14px 16px; display: flex; align-items: center; justify-content: space-between; border-bottom: 1px solid #e8ecee; }
.document-list-heading h2, .document-list-heading p { margin: 0; }
.document-list-heading h2 { font-size: 13px; }
.document-list-heading p { margin-top: 4px; color: var(--muted); font-size: 9.5px; }
.document-list-heading > span { color: var(--muted); font-size: 9.5px; }
.document-list { padding: 5px; display: grid; gap: 2px; }
.document-list > button { width: 100%; min-height: 60px; padding: 8px 9px; display: grid; grid-template-columns: 34px minmax(0, 1fr) auto; align-items: center; gap: 9px; text-align: left; color: var(--text); background: transparent; border: 1px solid transparent; border-radius: 8px; cursor: pointer; }
.document-list > button:hover { background: #f6f8f9; }
.document-list > button.active { background: var(--accent-050); border-color: #d2e6e0; }
.document-list-icon { width: 32px; height: 34px; display: grid; place-items: center; color: var(--accent-700); background: #e7f2ef; border-radius: 7px; }
.document-list button > span:nth-child(2) { min-width: 0; }
.document-list strong, .document-list small { display: block; overflow: hidden; white-space: nowrap; text-overflow: ellipsis; }
.document-list strong { font-size: 10.5px; }
.document-list small { margin-top: 5px; color: var(--muted); font-size: 9px; }
.document-list .status { white-space: nowrap; }
.document-detail { min-width: 0; }
.document-detail-empty { min-height: 100%; padding: 40px; display: grid; place-content: center; justify-items: center; text-align: center; color: var(--accent-700); }
.document-detail-empty h2 { margin: 13px 0 6px; color: var(--text); font-size: 15px; }
.document-detail-empty p { max-width: 420px; margin: 0; color: var(--muted); font-size: 10.5px; line-height: 1.6; }
.document-detail-content { min-width: 0; }
.document-detail-heading { min-height: 84px; padding: 16px 19px; display: flex; align-items: flex-start; justify-content: space-between; gap: 20px; border-bottom: 1px solid #e8ecee; }
.document-detail-heading > div { min-width: 0; }
.document-detail-heading span:first-child { color: var(--accent-700); font-size: 9.5px; font-weight: 650; }
.document-detail-heading h2 { margin: 5px 0 0; overflow: hidden; color: var(--text); font-size: 14px; white-space: nowrap; text-overflow: ellipsis; }
.document-detail-heading p { margin: 5px 0 0; color: var(--muted); font-size: 9.5px; }
.invoice-review-form { padding-bottom: 18px; }
.invoice-fields { padding: 17px 19px 4px; display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 13px; }
.invoice-fields label > span { display: block; margin-bottom: 6px; color: #344149; font-size: 9.5px; font-weight: 650; }
.invoice-fields input { width: 100%; height: 35px; padding: 0 9px; color: var(--text); background: #fff; border: 1px solid #cbd3d8; border-radius: var(--radius-control); outline: none; font-size: 10.5px; }
.invoice-fields input:focus { border-color: var(--accent-600); box-shadow: 0 0 0 2px rgba(38, 124, 112, .13); }
.invoice-fields .field-wide { grid-column: span 2; }
.invoice-items { margin: 14px 19px 0; overflow: hidden; border: 1px solid #e2e6e9; border-radius: 9px; }
.invoice-items-heading { min-height: 39px; padding: 0 12px; display: flex; align-items: center; justify-content: space-between; background: #f7f9fa; }
.invoice-items-heading strong { font-size: 10px; }
.invoice-items-heading span { color: var(--muted); font-size: 9px; }
.invoice-item { min-height: 39px; padding: 0 12px; display: grid; grid-template-columns: minmax(0, 1fr) 58px 82px; align-items: center; gap: 10px; border-top: 1px solid #edf0f2; }
.invoice-item > span { overflow: hidden; font-size: 9.5px; white-space: nowrap; text-overflow: ellipsis; }
.invoice-item small { color: var(--muted); font-size: 9px; }
.invoice-item b { text-align: right; font-size: 9.5px; font-variant-numeric: tabular-nums; }
.suggestion-box { margin: 14px 19px 0; padding: 13px 14px; display: grid; grid-template-columns: minmax(0, 1fr) auto; align-items: center; gap: 16px; color: #355a54; background: var(--accent-050); border: 1px solid #cce2dc; border-radius: 9px; }
.suggestion-box span, .suggestion-box strong { display: block; }
.suggestion-box span { font-size: 9px; }
.suggestion-box strong { margin-top: 4px; color: #24413c; font-size: 11px; }
.suggestion-box p { margin: 5px 0 0; color: #58716b; font-size: 9.5px; line-height: 1.5; }
.suggestion-box > b { font-size: 10px; white-space: nowrap; }
.document-review-actions { margin: 16px 19px 0; padding-top: 15px; display: flex; align-items: center; gap: 8px; border-top: 1px solid #e6eaec; }
.document-review-actions > span { margin-left: auto; color: var(--muted); font-size: 9px; }
.document-review-actions button:disabled, .page-actions button:disabled, .feature-preview button:disabled { cursor: not-allowed; opacity: .58; }
.confirm-card { padding: 21px; display: grid; grid-template-columns: 38px 1fr; gap: 15px; background: #fff; border: 1px solid var(--border); border-radius: var(--radius-surface); }
.confirm-index { width: 34px; height: 34px; display: grid; place-items: center; border-radius: 8px; color: var(--accent-700); background: var(--accent-050); font-size: 11px; font-weight: 700; }
.source-line { color: var(--muted); font-size: 10px; }
@@ -438,4 +507,5 @@ th:nth-child(1) { width: 21%; } th:nth-child(2) { width: 25%; } th:nth-child(3)
.profile-safety .icon { grid-row: 1 / span 2; }
.transaction-form-grid { grid-template-columns: repeat(2, minmax(0, 1fr)); }
.document-grid { grid-template-columns: repeat(2, 1fr); }
.documents-workspace { grid-template-columns: 250px minmax(0, 1fr); }
}