From 1a6fe311bc358c7ad9e6df775cdb082dd493aa2d Mon Sep 17 00:00:00 2001
From: stone16 <12712299+stone16@users.noreply.github.com>
Date: Sat, 28 Nov 2026 15:42:03 +0800
Subject: [PATCH 1/5] fix(core): preserve negative sign for red-ink invoice
amounts
---
.../invoice-core/src/invoice_core/extract.py | 18 +--
.../tests/test_extract_snapshot.py | 10 +-
.../tests/test_red_invoice_extract.py | 108 ++++++++++++++++++
3 files changed, 123 insertions(+), 13 deletions(-)
create mode 100644 packages/invoice-core/tests/test_red_invoice_extract.py
diff --git a/packages/invoice-core/src/invoice_core/extract.py b/packages/invoice-core/src/invoice_core/extract.py
index a6cb912..bc2e532 100644
--- a/packages/invoice-core/src/invoice_core/extract.py
+++ b/packages/invoice-core/src/invoice_core/extract.py
@@ -32,9 +32,9 @@ class FieldExtractor:
# Format is typically *类别*商品名称, we want to capture "类别*商品名称"
# Example: *家具*办公椅 → captures "家具*办公椅"
'item_name': r'\*([^*\n]+(?:\*[^*\n]+)*)',
- 'total_with_tax': r'(?:小写|价税合计)[))((]*\s*[¥¥]\s*([\d,.]+)',
- 'amount': r'(?:合\s*计|金\s*额)\s*[¥¥]?\s*([\d,.]+)',
- 'tax_amount': r'(?:税\s*额\s*[¥¥]?\s*([\d,.]+)|[¥¥]\s*[\d,.]+\s*[¥¥]\s*([\d,.]+))',
+ 'total_with_tax': r'(?:小写|价税合计)[))((]*\s*((?:[--−]\s*)?[¥¥]\s*(?:[--−]\s*)?\d[\d,.]*)',
+ 'amount': r'(?:合\s*计|金\s*额)\s*((?:[--−]\s*)?[¥¥]?\s*(?:[--−]\s*)?\d[\d,.]*)',
+ 'tax_amount': r'(?:税\s*额\s*((?:[--−]\s*)?[¥¥]?\s*(?:[--−]\s*)?\d[\d,.]*)|(?:[--−]\s*)?[¥¥]\s*(?:[--−]\s*)?\d[\d,.]*\s*((?:[--−]\s*)?[¥¥]\s*(?:[--−]\s*)?\d[\d,.]*))',
'tax_rate': r'(?:税率[//征收率]*[::]?\s*|金额\n)(\d+%?|免税)',
}
@@ -44,8 +44,8 @@ class FieldExtractor:
'issue_date': r'(?:Date|Invoice\s+Date)[:\s]+([A-Za-z]+\s+\d{1,2},?\s+\d{4}|\d{1,2}[/-]\d{1,2}[/-]\d{2,4}|\d{4}[/-]\d{1,2}[/-]\d{1,2})',
'buyer_name': r'Bill\s*To[:\s]*\n(?:.*\n)*?([A-Za-z][A-Za-z0-9\s]+?)(?:\n\d|\n[A-Z][a-z])',
'seller_name': r'INVOICE\n#[^\n]+\n([A-Za-z][A-Za-z\s]+)',
- 'total_with_tax': r'(?:Total|Balance\s+Due|Amount\s+Due)[:\s]*\$?\s*([\d,.]+)',
- 'amount': r'(?:Subtotal)[:\s]*\$?\s*([\d,.]+)',
+ 'total_with_tax': r'(?:Total|Balance\s+Due|Amount\s+Due)[:\s]*((?:[--−]\s*)?\$?\s*(?:[--−]\s*)?\d[\d,.]*)',
+ 'amount': r'(?:Subtotal)[:\s]*((?:[--−]\s*)?\$?\s*(?:[--−]\s*)?\d[\d,.]*)',
}
def _is_chinese_invoice(self, text: str) -> bool:
@@ -609,12 +609,14 @@ def _parse_date(self, date_str: str) -> Optional[str]:
return date_str
def _parse_currency(self, currency_str: str) -> Optional[str]:
- """Parse currency string, return as string to preserve precision."""
+ """Parse currency string, return as string to preserve precision and sign."""
if not currency_str:
return None
- # Remove currency symbols and formatting
- cleaned = re.sub(r'[$¥¥,\s]', '', currency_str)
+ # Normalize full-width/Unicode minus signs to ASCII '-'
+ normalized = currency_str.replace("-", "-").replace("−", "-")
+ # Remove currency symbols, thousand separators, and whitespace
+ cleaned = re.sub(r'[$¥¥,\s]', '', normalized)
try:
float(cleaned)
diff --git a/packages/invoice-core/tests/test_extract_snapshot.py b/packages/invoice-core/tests/test_extract_snapshot.py
index 5f9a011..a92cc81 100644
--- a/packages/invoice-core/tests/test_extract_snapshot.py
+++ b/packages/invoice-core/tests/test_extract_snapshot.py
@@ -168,8 +168,8 @@ def test_extract_cn_fallback_no_labels_snapshot():
}
-def test_extract_cn_red_invoice_preserves_c1ca829_behavior():
- """M2-0 is a pure move: negative amount handling remains untouched until M2-C."""
+def test_extract_cn_red_invoice_preserves_negative_amounts():
+ """M2-C: red-ink negative invoice amounts retain their leading minus sign."""
text = (
"电子发票(普通发票)\n"
f"发票号码:{SYNTH_INV_NUM_1}\n"
@@ -188,9 +188,9 @@ def test_extract_cn_red_invoice_preserves_c1ca829_behavior():
"seller_name": "示例卖方有限公司",
"seller_tax_id": None,
"item_name": None,
- "total_with_tax": None,
- "amount": None,
- "tax_amount": None,
+ "total_with_tax": "-106.00",
+ "amount": "-100.00",
+ "tax_amount": "-6.00",
"tax_rate": None,
}
diff --git a/packages/invoice-core/tests/test_red_invoice_extract.py b/packages/invoice-core/tests/test_red_invoice_extract.py
new file mode 100644
index 0000000..cad321d
--- /dev/null
+++ b/packages/invoice-core/tests/test_red_invoice_extract.py
@@ -0,0 +1,108 @@
+"""Tests for extracting negative amounts from red-ink (冲红/销项负数) invoices."""
+
+from invoice_core.extract import FieldExtractor
+
+SYNTH_RED_NUM_1 = "00000000000000000901"
+SYNTH_RED_NUM_2 = "00000000000000000902"
+
+
+def test_red_invoice_sign_after_currency_symbol():
+ text = (
+ "电子发票(普通发票)\n"
+ f"发票号码:{SYNTH_RED_NUM_1}\n"
+ "开票日期:2026年03月15日\n"
+ "购买方信息\n"
+ "名称:示例买方科技有限公司\n"
+ "统一社会信用代码/纳税人识别号:TESTBUYER000000001\n"
+ "销售方信息\n"
+ "名称:示例卖方服务有限公司\n"
+ "统一社会信用代码/纳税人识别号:TESTSELLER00000001\n"
+ "*信息技术服务*技术服务费\n"
+ "税率:6%\n"
+ "合计 ¥-1,000.00 ¥-60.00\n"
+ "价税合计(小写)¥-1,060.00\n"
+ )
+ fields = FieldExtractor().extract_fields(text)
+ assert fields["amount"] == "-1000.00"
+ assert fields["tax_amount"] == "-60.00"
+ assert fields["total_with_tax"] == "-1060.00"
+
+
+def test_red_invoice_sign_before_currency_symbol():
+ text = (
+ "电子发票(普通发票)\n"
+ f"发票号码:{SYNTH_RED_NUM_2}\n"
+ "开票日期:2026-04-02\n"
+ "购买方\n名称:示例买方科技有限公司\n"
+ "销售方\n名称:示例卖方服务有限公司\n"
+ "合计 -¥500.00 -¥30.00\n"
+ "价税合计(小写)-¥530.00\n"
+ )
+ fields = FieldExtractor().extract_fields(text)
+ assert fields["amount"] == "-500.00"
+ assert fields["tax_amount"] == "-30.00"
+ assert fields["total_with_tax"] == "-530.00"
+
+
+def test_red_invoice_fullwidth_minus_normalized():
+ text = (
+ "电子发票(普通发票)\n"
+ f"发票号码:{SYNTH_RED_NUM_1}\n"
+ "开票日期:2026年05月20日\n"
+ "购买方\n名称:示例买方科技有限公司\n"
+ "销售方\n名称:示例卖方服务有限公司\n"
+ "金额 ¥-1,234.56 税额 ¥-74.07\n"
+ "价税合计(小写)¥-1,308.63\n"
+ )
+ fields = FieldExtractor().extract_fields(text)
+ assert fields["amount"] == "-1234.56"
+ assert fields["tax_amount"] == "-74.07"
+ assert fields["total_with_tax"] == "-1308.63"
+
+
+def test_red_invoice_without_currency_symbol_on_amount_and_tax():
+ text = (
+ "电子发票(普通发票)\n"
+ f"发票号码:{SYNTH_RED_NUM_2}\n"
+ "开票日期:2026-06-01\n"
+ "购买方\n名称:示例买方科技有限公司\n"
+ "销售方\n名称:示例卖方服务有限公司\n"
+ "金额 -200.00 税额 -12.00\n"
+ "小写)¥ -212.00\n"
+ )
+ fields = FieldExtractor().extract_fields(text)
+ assert fields["amount"] == "-200.00"
+ assert fields["tax_amount"] == "-12.00"
+ assert fields["total_with_tax"] == "-212.00"
+
+
+def test_red_invoice_zero_tax_and_negative_amount():
+ text = (
+ "电子发票(普通发票)\n"
+ f"发票号码:{SYNTH_RED_NUM_1}\n"
+ "开票日期:2026-06-10\n"
+ "购买方\n名称:示例买方科技有限公司\n"
+ "销售方\n名称:示例卖方服务有限公司\n"
+ "金额 ¥-200.00 税额 ¥0.00\n"
+ "价税合计(小写)¥-200.00\n"
+ )
+ fields = FieldExtractor().extract_fields(text)
+ assert fields["amount"] == "-200.00"
+ assert fields["tax_amount"] == "0.00"
+ assert fields["total_with_tax"] == "-200.00"
+
+
+def test_english_credit_note_negative_amounts():
+ text = (
+ "INVOICE\n"
+ "#CN-2026-001\n"
+ "Demo Vendor LLC\n"
+ "Date: May 10, 2026\n"
+ "Bill To:\n"
+ "Demo Buyer Inc\n"
+ "Subtotal: -$120.00\n"
+ "Balance Due: $-132.00\n"
+ )
+ fields = FieldExtractor().extract_fields(text)
+ assert fields["amount"] == "-120.00"
+ assert fields["total_with_tax"] == "-120.00"
From c33e6f28e57be68a834ea3dbb20e9779541a0895 Mon Sep 17 00:00:00 2001
From: stone16 <12712299+stone16@users.noreply.github.com>
Date: Sat, 28 Nov 2026 15:46:27 +0800
Subject: [PATCH 2/5] feat(core): add KnownLedger, check rules, 3-sheet Excel,
and pypdfium2 merged PDF
---
packages/invoice-core/pyproject.toml | 1 +
.../invoice-core/src/invoice_core/__init__.py | 22 +
.../src/invoice_core/checks/__init__.py | 81 +++
.../src/invoice_core/checks/anomalies.py | 249 +++++++++
.../src/invoice_core/checks/buyer.py | 139 +++++
.../src/invoice_core/checks/completeness.py | 45 ++
.../src/invoice_core/checks/dedupe.py | 272 ++++++++++
.../src/invoice_core/export/__init__.py | 27 +
.../src/invoice_core/export/excel.py | 492 ++++++++++++++++++
.../src/invoice_core/export/pdf.py | 242 +++++++++
.../invoice-core/src/invoice_core/models.py | 69 +++
packages/invoice-core/tests/test_checks.py | 240 +++++++++
.../invoice-core/tests/test_export_excel.py | 148 ++++++
.../invoice-core/tests/test_export_pdf.py | 103 ++++
.../invoice-core/tests/test_import_guard.py | 13 +
15 files changed, 2143 insertions(+)
create mode 100644 packages/invoice-core/src/invoice_core/checks/__init__.py
create mode 100644 packages/invoice-core/src/invoice_core/checks/anomalies.py
create mode 100644 packages/invoice-core/src/invoice_core/checks/buyer.py
create mode 100644 packages/invoice-core/src/invoice_core/checks/completeness.py
create mode 100644 packages/invoice-core/src/invoice_core/checks/dedupe.py
create mode 100644 packages/invoice-core/src/invoice_core/export/__init__.py
create mode 100644 packages/invoice-core/src/invoice_core/export/excel.py
create mode 100644 packages/invoice-core/src/invoice_core/export/pdf.py
create mode 100644 packages/invoice-core/src/invoice_core/models.py
create mode 100644 packages/invoice-core/tests/test_checks.py
create mode 100644 packages/invoice-core/tests/test_export_excel.py
create mode 100644 packages/invoice-core/tests/test_export_pdf.py
diff --git a/packages/invoice-core/pyproject.toml b/packages/invoice-core/pyproject.toml
index 2211fc6..73799d4 100644
--- a/packages/invoice-core/pyproject.toml
+++ b/packages/invoice-core/pyproject.toml
@@ -11,6 +11,7 @@ dependencies = [
"pdfplumber==0.11.9",
"pypdfium2>=4.30,<6",
"Pillow>=10.0,<13",
+ "openpyxl>=3.1.0,<4.0",
]
[project.optional-dependencies]
diff --git a/packages/invoice-core/src/invoice_core/__init__.py b/packages/invoice-core/src/invoice_core/__init__.py
index 80f536f..293290c 100644
--- a/packages/invoice-core/src/invoice_core/__init__.py
+++ b/packages/invoice-core/src/invoice_core/__init__.py
@@ -1,5 +1,14 @@
"""Pure-Python core package for invoice parsing, field extraction, and reconciliation."""
+from invoice_core.checks import REGISTRY, run_checks
+from invoice_core.export import (
+ CorruptSourceFileError,
+ MergeSource,
+ amount_to_chinese_upper,
+ build_reimbursement_excel,
+ infer_category,
+ merge_sources_to_pdf,
+)
from invoice_core.extract import FieldExtractor, get_field_extractor
from invoice_core.llm_json import (
_normalize_field_value,
@@ -7,6 +16,7 @@
normalize_field_value,
parse_json_response,
)
+from invoice_core.models import CheckContext, CheckIssue, InvoiceRecord, KnownLedger
from invoice_core.parsers.pdf_text import extract_pdf_text_layer, render_pdf_pages
from invoice_core.parsers.vision import (
VisionAPIError,
@@ -59,4 +69,16 @@
"build_vision_messages",
"build_vision_payload",
"parse_invoice_with_vision",
+ "InvoiceRecord",
+ "CheckIssue",
+ "CheckContext",
+ "KnownLedger",
+ "REGISTRY",
+ "run_checks",
+ "amount_to_chinese_upper",
+ "infer_category",
+ "build_reimbursement_excel",
+ "CorruptSourceFileError",
+ "MergeSource",
+ "merge_sources_to_pdf",
]
diff --git a/packages/invoice-core/src/invoice_core/checks/__init__.py b/packages/invoice-core/src/invoice_core/checks/__init__.py
new file mode 100644
index 0000000..a262fd6
--- /dev/null
+++ b/packages/invoice-core/src/invoice_core/checks/__init__.py
@@ -0,0 +1,81 @@
+"""Check rule registry and unified execution entrypoint."""
+
+from __future__ import annotations
+
+from typing import Callable, Optional, Sequence
+
+from invoice_core.checks.anomalies import (
+ OFFICIAL_VERIFY_URL,
+ check_consecutive,
+ check_cross_year,
+ check_over_limit,
+ check_overdue,
+ check_red_invoice,
+ check_sum_mismatch,
+)
+from invoice_core.checks.buyer import check_buyer_mismatch, check_personal_buyer
+from invoice_core.checks.completeness import check_missing_data
+from invoice_core.checks.dedupe import (
+ check_dup_file,
+ check_dup_fuzzy,
+ check_dup_number,
+ check_dup_old,
+)
+from invoice_core.models import CheckContext, CheckIssue, InvoiceRecord, KnownLedger
+
+CheckRule = Callable[[Sequence[InvoiceRecord], CheckContext, KnownLedger], list[CheckIssue]]
+
+REGISTRY: list[CheckRule] = [
+ check_dup_file,
+ check_dup_number,
+ check_dup_old,
+ check_dup_fuzzy,
+ check_red_invoice,
+ check_buyer_mismatch,
+ check_personal_buyer,
+ check_cross_year,
+ check_overdue,
+ check_consecutive,
+ check_sum_mismatch,
+ check_over_limit,
+ check_missing_data,
+]
+
+
+def run_checks(
+ records: Sequence[InvoiceRecord],
+ ctx: Optional[CheckContext] = None,
+ known: Optional[KnownLedger] = None,
+ *,
+ rules: Optional[Sequence[CheckRule]] = None,
+) -> list[CheckIssue]:
+ """Execute all registered check rules against a batch of InvoiceRecord items."""
+ effective_ctx = ctx if ctx is not None else CheckContext()
+ effective_known = known if known is not None else KnownLedger()
+ active_rules = rules if rules is not None else REGISTRY
+
+ issues: list[CheckIssue] = []
+ for rule in active_rules:
+ issues.extend(rule(records, effective_ctx, effective_known))
+ return issues
+
+
+__all__ = [
+ "CheckRule",
+ "OFFICIAL_VERIFY_URL",
+ "REGISTRY",
+ "run_checks",
+ "check_dup_file",
+ "check_dup_number",
+ "check_dup_old",
+ "check_dup_fuzzy",
+ "check_red_invoice",
+ "check_buyer_mismatch",
+ "check_personal_buyer",
+ "check_cross_year",
+ "check_overdue",
+ "check_consecutive",
+ "check_sum_mismatch",
+ "check_over_limit",
+ "check_missing_data",
+]
diff --git a/packages/invoice-core/src/invoice_core/checks/anomalies.py b/packages/invoice-core/src/invoice_core/checks/anomalies.py
new file mode 100644
index 0000000..3792921
--- /dev/null
+++ b/packages/invoice-core/src/invoice_core/checks/anomalies.py
@@ -0,0 +1,249 @@
+"""Anomaly detection rules: RED_INVOICE, CROSS_YEAR, OVERDUE, CONSECUTIVE, SUM_MISMATCH, OVER_LIMIT."""
+
+from __future__ import annotations
+
+import re
+from collections import defaultdict
+from datetime import date
+from decimal import Decimal
+from typing import Sequence
+
+from invoice_core.models import CheckContext, CheckIssue, InvoiceRecord, KnownLedger
+
+OFFICIAL_VERIFY_URL = "https://inv-veri.chinatax.gov.cn"
+_RED_KEYWORDS = ("红字", "冲红", "作废", "销项负数")
+_DIGITS_ONLY_RE = re.compile(r"^\d{6,}$")
+
+
+def _norm_str(value: str | None) -> str:
+ if not value:
+ return ""
+ return re.sub(r"\s+", "", value).strip()
+
+
+def check_red_invoice(
+ records: Sequence[InvoiceRecord],
+ ctx: CheckContext,
+ known: KnownLedger,
+) -> list[CheckIssue]:
+ """Warn on negative amounts or red-ink/cancelled invoice keywords."""
+ del ctx, known
+ issues: list[CheckIssue] = []
+
+ for rec in records:
+ negative_fields: list[str] = []
+ if rec.total_with_tax is not None and rec.total_with_tax < Decimal("0"):
+ negative_fields.append(f"价税合计={rec.total_with_tax}")
+ if rec.amount is not None and rec.amount < Decimal("0"):
+ negative_fields.append(f"税前金额={rec.amount}")
+ if rec.tax_amount is not None and rec.tax_amount < Decimal("0"):
+ negative_fields.append(f"税额={rec.tax_amount}")
+
+ combined_text = " ".join(
+ part for part in (rec.raw_text, rec.invoice_type, rec.item_name, rec.remarks) if part
+ )
+ matched_keywords = [kw for kw in _RED_KEYWORDS if kw in combined_text]
+
+ if negative_fields or matched_keywords:
+ reasons: list[str] = []
+ if negative_fields:
+ reasons.append("存在负数金额(" + ",".join(negative_fields) + ")")
+ if matched_keywords:
+ reasons.append("文本包含关键字「" + "/".join(matched_keywords) + "」")
+ issues.append(
+ CheckIssue(
+ level="warning",
+ code="RED_INVOICE",
+ seqs=[rec.seq],
+ message=(
+ f"序号 {rec.seq} 疑似红字/冲红/作废发票:{';'.join(reasons)}。"
+ f"请前往全国增值税发票查验平台核验:{OFFICIAL_VERIFY_URL}"
+ ),
+ suggestion=f"请到国家税务总局全国增值税发票查验平台({OFFICIAL_VERIFY_URL})免费查验发票状态,确认未作废/红冲",
+ )
+ )
+
+ return issues
+
+
+def check_cross_year(
+ records: Sequence[InvoiceRecord],
+ ctx: CheckContext,
+ known: KnownLedger,
+) -> list[CheckIssue]:
+ """Warn when invoice issue year is earlier than the current calendar year."""
+ del known
+ ref_date = ctx.reference_date or date.today()
+ issues: list[CheckIssue] = []
+
+ for rec in records:
+ if rec.issue_date is not None and rec.issue_date.year < ref_date.year:
+ issues.append(
+ CheckIssue(
+ level="warning",
+ code="CROSS_YEAR",
+ seqs=[rec.seq],
+ message=(
+ f"序号 {rec.seq} 为跨年发票(开票日期 {rec.issue_date.isoformat()},"
+ f"早于当前年份 {ref_date.year})"
+ ),
+ suggestion="请确认财务是否允许跨年度发票报销",
+ )
+ )
+
+ return issues
+
+
+def check_overdue(
+ records: Sequence[InvoiceRecord],
+ ctx: CheckContext,
+ known: KnownLedger,
+) -> list[CheckIssue]:
+ """Warn when invoice age exceeds max_age_days (default 365 days)."""
+ del known
+ ref_date = ctx.reference_date or date.today()
+ max_age_days = ctx.max_age_days
+ issues: list[CheckIssue] = []
+
+ for rec in records:
+ if rec.issue_date is None:
+ continue
+ age_days = (ref_date - rec.issue_date).days
+ if age_days > max_age_days:
+ issues.append(
+ CheckIssue(
+ level="warning",
+ code="OVERDUE",
+ seqs=[rec.seq],
+ message=(
+ f"序号 {rec.seq} 发票已超期(开票日期 {rec.issue_date.isoformat()},"
+ f"距今 {age_days} 天,超过 {max_age_days} 天)"
+ ),
+ suggestion="请核实超期发票是否符合单位报销时效要求",
+ )
+ )
+
+ return issues
+
+
+def check_consecutive(
+ records: Sequence[InvoiceRecord],
+ ctx: CheckContext,
+ known: KnownLedger,
+) -> list[CheckIssue]:
+ """Warn when multiple invoices from the same seller have consecutive invoice numbers."""
+ del ctx, known
+ issues: list[CheckIssue] = []
+ by_seller: dict[str, list[tuple[int, InvoiceRecord]]] = defaultdict(list)
+
+ for rec in records:
+ seller_key = _norm_str(rec.seller_tax_id).upper() or _norm_str(rec.seller_name)
+ num = _norm_str(rec.invoice_number)
+ if not seller_key or not num or not _DIGITS_ONLY_RE.match(num):
+ continue
+ by_seller[seller_key].append((int(num), rec))
+
+ for _seller_key, entries in by_seller.items():
+ if len(entries) < 2:
+ continue
+ entries.sort(key=lambda item: (item[0], item[1].seq))
+
+ # Group entries by numeric value first to skip duplicate invoice numbers
+ unique_nums: list[tuple[int, list[InvoiceRecord]]] = []
+ for num_int, rec in entries:
+ if unique_nums and unique_nums[-1][0] == num_int:
+ unique_nums[-1][1].append(rec)
+ else:
+ unique_nums.append((num_int, [rec]))
+
+ run: list[tuple[int, list[InvoiceRecord]]] = []
+ for item in unique_nums:
+ if not run or item[0] == run[-1][0] + 1:
+ run.append(item)
+ else:
+ if len(run) >= 2:
+ _append_consecutive_issue(issues, run)
+ run = [item]
+ if len(run) >= 2:
+ _append_consecutive_issue(issues, run)
+
+ return issues
+
+
+def _append_consecutive_issue(
+ issues: list[CheckIssue],
+ run: list[tuple[int, list[InvoiceRecord]]],
+) -> None:
+ seqs = [rec.seq for _num, recs in run for rec in recs]
+ seller_display = run[0][1][0].seller_name or run[0][1][0].seller_tax_id or "同销方"
+ issues.append(
+ CheckIssue(
+ level="warning",
+ code="CONSECUTIVE",
+ seqs=seqs,
+ message=f"序号 {', '.join(map(str, seqs))} 同一销方({seller_display})发票连号,疑似拆单开票",
+ suggestion="请核实是否存在拆分消费/拆单开票情况并补充业务说明",
+ )
+ )
+
+
+def check_sum_mismatch(
+ records: Sequence[InvoiceRecord],
+ ctx: CheckContext,
+ known: KnownLedger,
+) -> list[CheckIssue]:
+ """Warn when |total_with_tax - (amount + tax_amount)| > 0.01."""
+ del ctx, known
+ issues: list[CheckIssue] = []
+ threshold = Decimal("0.01")
+
+ for rec in records:
+ if rec.amount is None or rec.tax_amount is None or rec.total_with_tax is None:
+ continue
+ expected = rec.amount + rec.tax_amount
+ diff = abs(rec.total_with_tax - expected)
+ if diff > threshold:
+ issues.append(
+ CheckIssue(
+ level="warning",
+ code="SUM_MISMATCH",
+ seqs=[rec.seq],
+ message=(
+ f"序号 {rec.seq} 价税合计校验不一致:税前金额 {rec.amount:.2f} + "
+ f"税额 {rec.tax_amount:.2f} = {expected:.2f},与价税合计 {rec.total_with_tax:.2f} "
+ f"相差 {diff:.2f}"
+ ),
+ suggestion="请核对发票原件上的金额、税额与价税合计,修正识别误差",
+ )
+ )
+
+ return issues
+
+
+def check_over_limit(
+ records: Sequence[InvoiceRecord],
+ ctx: CheckContext,
+ known: KnownLedger,
+) -> list[CheckIssue]:
+ """Warn when total_with_tax exceeds ctx.max_amount (only active when max_amount is provided)."""
+ del known
+ if ctx.max_amount is None:
+ return []
+
+ issues: list[CheckIssue] = []
+ for rec in records:
+ if rec.total_with_tax is not None and rec.total_with_tax > ctx.max_amount:
+ issues.append(
+ CheckIssue(
+ level="warning",
+ code="OVER_LIMIT",
+ seqs=[rec.seq],
+ message=(
+ f"序号 {rec.seq} 单张价税合计 ¥{rec.total_with_tax:.2f} "
+ f"超过设定限额 ¥{ctx.max_amount:.2f}"
+ ),
+ suggestion="请核对超额单据是否需要额外审批说明",
+ )
+ )
+
+ return issues
diff --git a/packages/invoice-core/src/invoice_core/checks/buyer.py b/packages/invoice-core/src/invoice_core/checks/buyer.py
new file mode 100644
index 0000000..6666b79
--- /dev/null
+++ b/packages/invoice-core/src/invoice_core/checks/buyer.py
@@ -0,0 +1,139 @@
+"""Buyer validation rules: BUYER_MISMATCH and PERSONAL_BUYER."""
+
+from __future__ import annotations
+
+import re
+from typing import Sequence
+
+from invoice_core.models import CheckContext, CheckIssue, InvoiceRecord, KnownLedger
+
+_ORG_KEYWORDS = (
+ "公司",
+ "集团",
+ "有限",
+ "股份",
+ "企业",
+ "中心",
+ "厂",
+ "协会",
+ "研究所",
+ "研究院",
+ "大学",
+ "学院",
+ "学校",
+ "医院",
+ "银行",
+ "事务所",
+ "工作室",
+ "合作社",
+ "委员会",
+ "政府",
+ "管理局",
+ "财政局",
+ "税务局",
+ "局",
+ "厅",
+ "部",
+ "院",
+ "所",
+ "店",
+ "行",
+ "馆",
+ "站",
+ "社",
+ "团",
+ "部",
+ "ltd",
+ "llc",
+ "inc",
+ "corp",
+ "co.",
+ "company",
+)
+
+_CJK_NAME_RE = re.compile(r"^[\u4e00-\u9fff·]{2,4}$")
+
+
+def _norm_name(value: str | None) -> str:
+ if not value:
+ return ""
+ text = value.replace("(", "(").replace(")", ")")
+ return re.sub(r"\s+", "", text).strip().lower()
+
+
+def _norm_tax_id(value: str | None) -> str:
+ if not value:
+ return ""
+ return re.sub(r"\s+", "", value).strip().upper()
+
+
+def check_buyer_mismatch(
+ records: Sequence[InvoiceRecord],
+ ctx: CheckContext,
+ known: KnownLedger,
+) -> list[CheckIssue]:
+ """Warn when an invoice's buyer name or tax ID differs from configured expectations."""
+ del known
+ expected_name = _norm_name(ctx.buyer_name)
+ expected_tax = _norm_tax_id(ctx.buyer_tax_id)
+ if not expected_name and not expected_tax:
+ return []
+
+ issues: list[CheckIssue] = []
+ for rec in records:
+ actual_name = _norm_name(rec.buyer_name)
+ actual_tax = _norm_tax_id(rec.buyer_tax_id)
+
+ reasons: list[str] = []
+ if expected_name and actual_name and actual_name != expected_name:
+ reasons.append(f"抬头不符(实际:{rec.buyer_name},期望:{ctx.buyer_name})")
+ if expected_tax and actual_tax and actual_tax != expected_tax:
+ reasons.append(f"税号不符(实际:{rec.buyer_tax_id},期望:{ctx.buyer_tax_id})")
+ if expected_tax and not actual_tax and actual_name and (not expected_name or actual_name != expected_name):
+ reasons.append(f"缺少购方税号(期望:{ctx.buyer_tax_id})")
+
+ if reasons:
+ issues.append(
+ CheckIssue(
+ level="warning",
+ code="BUYER_MISMATCH",
+ seqs=[rec.seq],
+ message=f"序号 {rec.seq} 购方信息与报销抬头不一致:{';'.join(reasons)}",
+ suggestion="请确认发票购方抬头与纳税人识别号是否与报销单位一致,必要时联系开票方重开",
+ )
+ )
+
+ return issues
+
+
+def check_personal_buyer(
+ records: Sequence[InvoiceRecord],
+ ctx: CheckContext,
+ known: KnownLedger,
+) -> list[CheckIssue]:
+ """Warn when an invoice appears to be issued to an individual rather than a company."""
+ del ctx, known
+ issues: list[CheckIssue] = []
+
+ for rec in records:
+ buyer_name = (rec.buyer_name or "").strip()
+ buyer_tax_id = _norm_tax_id(rec.buyer_tax_id)
+ if not buyer_name or buyer_tax_id:
+ continue
+
+ lowered = buyer_name.lower()
+ is_org = any(kw in lowered for kw in _ORG_KEYWORDS)
+ is_personal = "个人" in buyer_name or (not is_org and bool(_CJK_NAME_RE.match(buyer_name)))
+
+ if is_personal:
+ issues.append(
+ CheckIssue(
+ level="warning",
+ code="PERSONAL_BUYER",
+ seqs=[rec.seq],
+ message=f"序号 {rec.seq} 购方抬头为「{buyer_name}」且无纳税人识别号,疑似个人抬头发票",
+ suggestion="请确认公司报销制度是否允许个人抬头发票,如不允许请更换为公司抬头",
+ )
+ )
+
+ return issues
diff --git a/packages/invoice-core/src/invoice_core/checks/completeness.py b/packages/invoice-core/src/invoice_core/checks/completeness.py
new file mode 100644
index 0000000..aecd1cb
--- /dev/null
+++ b/packages/invoice-core/src/invoice_core/checks/completeness.py
@@ -0,0 +1,45 @@
+"""Completeness validation rule: MISSING_DATA."""
+
+from __future__ import annotations
+
+from typing import Sequence
+
+from invoice_core.models import CheckContext, CheckIssue, InvoiceRecord, KnownLedger
+
+
+def check_missing_data(
+ records: Sequence[InvoiceRecord],
+ ctx: CheckContext,
+ known: KnownLedger,
+) -> list[CheckIssue]:
+ """Warn when critical invoice fields are missing or an image has no OCR text."""
+ del ctx, known
+ issues: list[CheckIssue] = []
+
+ for rec in records:
+ missing: list[str] = []
+ if not (rec.invoice_number and rec.invoice_number.strip()):
+ missing.append("发票号码")
+ if rec.total_with_tax is None:
+ missing.append("价税合计")
+ if rec.issue_date is None:
+ missing.append("开票日期")
+ if not (rec.seller_name and rec.seller_name.strip()) and not (
+ rec.seller_tax_id and rec.seller_tax_id.strip()
+ ):
+ missing.append("销方信息")
+ if not rec.has_ocr_text:
+ missing.append("图片未完成OCR识别")
+
+ if missing:
+ issues.append(
+ CheckIssue(
+ level="warning",
+ code="MISSING_DATA",
+ seqs=[rec.seq],
+ message=f"序号 {rec.seq} 缺少关键信息:{'、'.join(missing)}",
+ suggestion="请核对原件并人工补全缺失字段后再提交报销",
+ )
+ )
+
+ return issues
diff --git a/packages/invoice-core/src/invoice_core/checks/dedupe.py b/packages/invoice-core/src/invoice_core/checks/dedupe.py
new file mode 100644
index 0000000..e8f2f09
--- /dev/null
+++ b/packages/invoice-core/src/invoice_core/checks/dedupe.py
@@ -0,0 +1,272 @@
+"""Duplicate detection rules: DUP_FILE, DUP_NUMBER, DUP_OLD, DUP_FUZZY."""
+
+from __future__ import annotations
+
+import re
+from collections import defaultdict
+from decimal import Decimal
+from typing import Sequence
+
+from invoice_core.models import CheckContext, CheckIssue, InvoiceRecord, KnownLedger
+
+_DIGITAL_20_RE = re.compile(r"^\d{20}$")
+
+
+def _norm_str(value: str | None) -> str:
+ if not value:
+ return ""
+ return re.sub(r"\s+", "", value).strip()
+
+
+def _norm_tax_id(value: str | None) -> str:
+ return _norm_str(value).upper()
+
+
+def _norm_format(value: str | None) -> str:
+ fmt = _norm_str(value).upper()
+ if fmt == "JPEG":
+ return "JPG"
+ return fmt
+
+
+def _is_digital_20(invoice_number: str) -> bool:
+ return bool(_DIGITAL_20_RE.match(invoice_number))
+
+
+def _quantize_amount(value: Decimal | None) -> Decimal | None:
+ if value is None:
+ return None
+ return value.quantize(Decimal("0.01"))
+
+
+def check_dup_file(
+ records: Sequence[InvoiceRecord],
+ ctx: CheckContext,
+ known: KnownLedger,
+) -> list[CheckIssue]:
+ """Detect identical source files by SHA-256 hash within batch or against KnownLedger."""
+ del ctx
+ issues: list[CheckIssue] = []
+ by_hash: dict[str, list[InvoiceRecord]] = defaultdict(list)
+ known_sha = {k.strip().lower(): v for k, v in known.sha256.items() if k and k.strip()}
+
+ for rec in records:
+ digest = _norm_str(rec.file_sha256).lower()
+ if not digest:
+ continue
+ by_hash[digest].append(rec)
+
+ for digest, group in by_hash.items():
+ if len(group) >= 2:
+ seqs = [r.seq for r in group]
+ issues.append(
+ CheckIssue(
+ level="error",
+ code="DUP_FILE",
+ seqs=seqs,
+ message=f"序号 {', '.join(map(str, seqs))} 的原件文件内容完全相同(SHA-256 重复)",
+ suggestion="请移除重复上传的发票原件,仅保留一份",
+ )
+ )
+ if digest in known_sha:
+ label = known_sha[digest]
+ for rec in group:
+ issues.append(
+ CheckIssue(
+ level="error",
+ code="DUP_FILE",
+ seqs=[rec.seq],
+ message=f"序号 {rec.seq} 的原件文件与历史台账重复({label})",
+ suggestion="该文件已入库或已报销,请核实后移除重复单据",
+ )
+ )
+
+ return issues
+
+
+def check_dup_number(
+ records: Sequence[InvoiceRecord],
+ ctx: CheckContext,
+ known: KnownLedger,
+) -> list[CheckIssue]:
+ """Detect duplicate 20-digit digital e-invoice numbers (same format or in KnownLedger)."""
+ del ctx
+ issues: list[CheckIssue] = []
+ by_num_fmt: dict[tuple[str, str], list[InvoiceRecord]] = defaultdict(list)
+ known_nums = {_norm_str(k): v for k, v in known.numbers.items() if _norm_str(k)}
+
+ for rec in records:
+ num = _norm_str(rec.invoice_number)
+ if not num or not _is_digital_20(num):
+ continue
+ fmt = _norm_format(rec.file_format)
+ by_num_fmt[(num, fmt)].append(rec)
+
+ if num in known_nums:
+ label = known_nums[num]
+ issues.append(
+ CheckIssue(
+ level="error",
+ code="DUP_NUMBER",
+ seqs=[rec.seq],
+ message=f"序号 {rec.seq} 的20位数电发票号码 {num} 与历史台账重复({label})",
+ suggestion="请核实该发票是否已提交报销,切勿重复报销",
+ )
+ )
+
+ for (num, fmt), group in by_num_fmt.items():
+ if len(group) >= 2:
+ seqs = [r.seq for r in group]
+ fmt_hint = f"(格式:{fmt})" if fmt else ""
+ issues.append(
+ CheckIssue(
+ level="error",
+ code="DUP_NUMBER",
+ seqs=seqs,
+ message=f"序号 {', '.join(map(str, seqs))} 存在重复的20位数电发票号码 {num}{fmt_hint}",
+ suggestion="请核实并移除重复发票,同票号仅允许提交一次",
+ )
+ )
+
+ return issues
+
+
+def check_dup_old(
+ records: Sequence[InvoiceRecord],
+ ctx: CheckContext,
+ known: KnownLedger,
+) -> list[CheckIssue]:
+ """Detect suspected duplicates for legacy (non-20-digit) invoices via (number+code) or (number+seller_tax_id)."""
+ del ctx
+ issues: list[CheckIssue] = []
+ by_num_code: dict[tuple[str, str], list[InvoiceRecord]] = defaultdict(list)
+ by_num_seller: dict[tuple[str, str], list[InvoiceRecord]] = defaultdict(list)
+
+ known_num_seller = {
+ (_norm_str(k[0]), _norm_tax_id(k[1])): v
+ for k, v in known.number_seller.items()
+ if _norm_str(k[0]) and _norm_tax_id(k[1])
+ }
+ known_num_code = {
+ (_norm_str(k[0]), _norm_str(k[1])): v
+ for k, v in known.number_code.items()
+ if _norm_str(k[0]) and _norm_str(k[1])
+ }
+
+ flagged_known_seqs: set[int] = set()
+
+ for rec in records:
+ num = _norm_str(rec.invoice_number)
+ if not num or _is_digital_20(num):
+ continue
+ code = _norm_str(rec.invoice_code)
+ seller_tax = _norm_tax_id(rec.seller_tax_id)
+
+ if code:
+ by_num_code[(num, code)].append(rec)
+ if (num, code) in known_num_code and rec.seq not in flagged_known_seqs:
+ flagged_known_seqs.add(rec.seq)
+ label = known_num_code[(num, code)]
+ issues.append(
+ CheckIssue(
+ level="warning",
+ code="DUP_OLD",
+ seqs=[rec.seq],
+ message=f"序号 {rec.seq} 旧版发票(号码 {num} / 代码 {code})疑似与历史台账重复({label})",
+ suggestion="请人工核对发票代码、开票日期及原件,确认非重复报销",
+ )
+ )
+
+ if seller_tax:
+ by_num_seller[(num, seller_tax)].append(rec)
+ if (num, seller_tax) in known_num_seller and rec.seq not in flagged_known_seqs:
+ flagged_known_seqs.add(rec.seq)
+ label = known_num_seller[(num, seller_tax)]
+ issues.append(
+ CheckIssue(
+ level="warning",
+ code="DUP_OLD",
+ seqs=[rec.seq],
+ message=f"序号 {rec.seq} 旧版发票(号码 {num} / 销方税号 {seller_tax})疑似与历史台账重复({label})",
+ suggestion="请人工核对销方、日期及发票代码,确认非重复报销",
+ )
+ )
+
+ seen_seq_groups: set[tuple[int, ...]] = set()
+ for (num, code), group in by_num_code.items():
+ if len(group) >= 2:
+ seqs = tuple(r.seq for r in group)
+ seen_seq_groups.add(seqs)
+ issues.append(
+ CheckIssue(
+ level="warning",
+ code="DUP_OLD",
+ seqs=list(seqs),
+ message=f"序号 {', '.join(map(str, seqs))} 旧版发票号码 {num} 与代码 {code} 相同,疑似重复",
+ suggestion="请人工核对原件,确认是否为同一张发票重复提交",
+ )
+ )
+
+ for (num, seller_tax), group in by_num_seller.items():
+ if len(group) >= 2:
+ seqs = tuple(r.seq for r in group)
+ if seqs in seen_seq_groups:
+ continue
+ seen_seq_groups.add(seqs)
+ issues.append(
+ CheckIssue(
+ level="warning",
+ code="DUP_OLD",
+ seqs=list(seqs),
+ message=f"序号 {', '.join(map(str, seqs))} 旧版发票号码 {num} 与销方税号 {seller_tax} 相同,疑似重复",
+ suggestion="请人工核对原件,确认是否为同一张发票重复提交",
+ )
+ )
+
+ return issues
+
+
+def check_dup_fuzzy(
+ records: Sequence[InvoiceRecord],
+ ctx: CheckContext,
+ known: KnownLedger,
+) -> list[CheckIssue]:
+ """Detect fuzzy duplicates: same seller (tax_id or name) + same issue_date + same total_with_tax."""
+ del ctx, known
+ issues: list[CheckIssue] = []
+ buckets: dict[tuple[str, str, Decimal], list[InvoiceRecord]] = defaultdict(list)
+
+ for rec in records:
+ seller_key = _norm_tax_id(rec.seller_tax_id) or _norm_str(rec.seller_name)
+ total = _quantize_amount(rec.total_with_tax)
+ if not seller_key or rec.issue_date is None or total is None:
+ continue
+ buckets[(seller_key, rec.issue_date.isoformat(), total)].append(rec)
+
+ for (_seller_key, issue_date_str, total), group in buckets.items():
+ if len(group) < 2:
+ continue
+ # Skip if all items in the bucket are multi-format copies of the exact same 20-digit invoice
+ nums = {_norm_str(r.invoice_number) for r in group}
+ fmts = [_norm_format(r.file_format) for r in group]
+ if len(nums) == 1:
+ only_num = next(iter(nums))
+ if only_num and _is_digital_20(only_num) and len(set(fmts)) == len(fmts) and "" not in fmts:
+ continue
+
+ seqs = [r.seq for r in group]
+ seller_display = group[0].seller_name or group[0].seller_tax_id or _seller_key
+ issues.append(
+ CheckIssue(
+ level="warning",
+ code="DUP_FUZZY",
+ seqs=seqs,
+ message=(
+ f"序号 {', '.join(map(str, seqs))} 同销方({seller_display})、"
+ f"同开票日期({issue_date_str})、同价税合计(¥{total:.2f}),疑似重复提交"
+ ),
+ suggestion="请核实是否为电子票与截图/行程单重复提交,或确实为同日同额多笔消费",
+ )
+ )
+
+ return issues
diff --git a/packages/invoice-core/src/invoice_core/export/__init__.py b/packages/invoice-core/src/invoice_core/export/__init__.py
new file mode 100644
index 0000000..a73094a
--- /dev/null
+++ b/packages/invoice-core/src/invoice_core/export/__init__.py
@@ -0,0 +1,27 @@
+"""Export helpers: 3-sheet reimbursement Excel workbook and pypdfium2 merged PDF."""
+
+from invoice_core.export.excel import (
+ CATEGORIES,
+ DETAIL_HEADERS,
+ ISSUE_HEADERS,
+ amount_to_chinese_upper,
+ build_reimbursement_excel,
+ infer_category,
+)
+from invoice_core.export.pdf import (
+ CorruptSourceFileError,
+ MergeSource,
+ merge_sources_to_pdf,
+)
+
+__all__ = [
+ "CATEGORIES",
+ "DETAIL_HEADERS",
+ "ISSUE_HEADERS",
+ "amount_to_chinese_upper",
+ "build_reimbursement_excel",
+ "infer_category",
+ "CorruptSourceFileError",
+ "MergeSource",
+ "merge_sources_to_pdf",
+]
diff --git a/packages/invoice-core/src/invoice_core/export/excel.py b/packages/invoice-core/src/invoice_core/export/excel.py
new file mode 100644
index 0000000..528d9e9
--- /dev/null
+++ b/packages/invoice-core/src/invoice_core/export/excel.py
@@ -0,0 +1,492 @@
+"""3-sheet reimbursement Excel generator and pure-Python RMB Chinese uppercase converter."""
+
+from __future__ import annotations
+
+from collections import defaultdict
+from datetime import date
+from decimal import Decimal, ROUND_HALF_UP
+from io import BytesIO
+from typing import Optional, Sequence
+
+import openpyxl
+from openpyxl.styles import Alignment, Border, Font, PatternFill, Side
+from openpyxl.utils import get_column_letter
+
+from invoice_core.models import CheckIssue, InvoiceRecord
+
+_CN_DIGITS = "零壹贰叁肆伍陆柒捌玖"
+_CN_SUB_UNITS = ("", "拾", "佰", "仟")
+_CN_SEC_UNITS = ("", "万", "亿", "兆")
+
+CATEGORIES: tuple[str, ...] = (
+ "交通出行",
+ "餐饮美食",
+ "酒店住宿",
+ "办公用品",
+ "电子设备与耗材",
+ "通讯与网络",
+ "云服务与软件订阅",
+ "快递物流",
+ "会议与培训",
+ "其他",
+)
+
+_CATEGORY_KEYWORDS: tuple[tuple[str, tuple[str, ...]], ...] = (
+ (
+ "交通出行",
+ (
+ "打车",
+ "网约车",
+ "出租车",
+ "客运",
+ "铁路",
+ "高铁",
+ "动车",
+ "火车",
+ "航空",
+ "机票",
+ "运输服务",
+ "高速",
+ "通行费",
+ "加油",
+ "汽油",
+ "柴油",
+ "充电",
+ "停车",
+ "出行",
+ "滴滴",
+ ),
+ ),
+ ("餐饮美食", ("餐饮", "餐费", "饮食", "美食", "饭店", "酒楼", "咖啡", "茶饮", "食品", "工作餐", "外卖")),
+ ("酒店住宿", ("住宿", "酒店", "宾馆", "旅馆", "民宿", "房费")),
+ ("办公用品", ("办公用品", "文具", "纸品", "打印纸", "档案", "印章", "日用百货")),
+ ("电子设备与耗材", ("电子设备", "电脑", "手机", "显示器", "键盘", "鼠标", "硒鼓", "墨盒", "耗材", "硬件", "数码")),
+ ("通讯与网络", ("通讯", "通信", "电信", "移动", "联通", "宽带", "话费", "流量")),
+ ("云服务与软件订阅", ("云服务", "云计算", "云主机", "服务器", "软件", "信息技术", "技术服务", "域名", "订阅", "SaaS")),
+ ("快递物流", ("快递", "物流", "收派", "速运", "顺丰", "邮政", "货运", "配送")),
+ ("会议与培训", ("会议", "会务", "培训", "教育", "课程", "咨询服务", "展览")),
+)
+
+DETAIL_HEADERS: tuple[str, ...] = (
+ "序号",
+ "发票类型",
+ "异常预警",
+ "开票日期",
+ "分类",
+ "货品/项目名称",
+ "发票号码",
+ "发票代码",
+ "税前金额",
+ "税额",
+ "价税合计",
+ "实报金额",
+ "购方抬头",
+ "购方税号",
+ "销方抬头",
+ "销方税号",
+ "原件格式",
+ "备注",
+)
+
+ISSUE_HEADERS: tuple[str, ...] = (
+ "级别",
+ "规则代码",
+ "涉及序号",
+ "说明",
+ "建议处理",
+)
+
+
+def _four_digit_section_to_cn(section: int) -> str:
+ """Convert an integer in 1..9999 into Chinese uppercase digits with sub-units."""
+ parts: list[str] = []
+ zero_pending = False
+ for pos in range(3, -1, -1):
+ digit = (section // (10**pos)) % 10
+ if digit == 0:
+ if parts:
+ zero_pending = True
+ else:
+ if zero_pending:
+ parts.append("零")
+ zero_pending = False
+ parts.append(_CN_DIGITS[digit] + _CN_SUB_UNITS[pos])
+ return "".join(parts)
+
+
+def amount_to_chinese_upper(amount: Decimal | int | str) -> str:
+ """Convert a monetary amount to Chinese financial uppercase RMB string.
+
+ Supports zero, exact yuan (整), jiao/fen decimals, 万/亿/兆 section carries,
+ and negative amounts prefixed with 「负」.
+ """
+ value = amount if isinstance(amount, Decimal) else Decimal(str(amount))
+ quantized = value.quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)
+
+ if quantized == Decimal("0.00"):
+ return "零元整"
+
+ prefix = "负" if quantized < Decimal("0") else ""
+ abs_val = abs(quantized)
+ total_cents = int((abs_val * 100).to_integral_value(rounding=ROUND_HALF_UP))
+ yuan = total_cents // 100
+ cents = total_cents % 100
+ jiao = cents // 10
+ fen = cents % 10
+
+ int_str = ""
+ if yuan > 0:
+ sections: list[int] = []
+ rem = yuan
+ while rem > 0:
+ sections.append(rem % 10000)
+ rem //= 10000
+ if len(sections) > len(_CN_SEC_UNITS):
+ raise ValueError(f"Amount too large for Chinese uppercase conversion: {amount}")
+
+ parts: list[str] = []
+ need_zero = False
+ for idx in range(len(sections) - 1, -1, -1):
+ sec = sections[idx]
+ if sec == 0:
+ if parts:
+ need_zero = True
+ else:
+ if parts and (need_zero or sec < 1000):
+ parts.append("零")
+ parts.append(_four_digit_section_to_cn(sec) + _CN_SEC_UNITS[idx])
+ need_zero = False
+ int_str = "".join(parts) + "元"
+
+ if jiao == 0 and fen == 0:
+ frac_str = "整"
+ elif jiao > 0 and fen == 0:
+ frac_str = f"{_CN_DIGITS[jiao]}角整"
+ elif jiao == 0 and fen > 0:
+ frac_str = (f"零{_CN_DIGITS[fen]}分") if yuan > 0 else f"{_CN_DIGITS[fen]}分"
+ else:
+ frac_str = f"{_CN_DIGITS[jiao]}角{_CN_DIGITS[fen]}分"
+
+ return prefix + int_str + frac_str
+
+
+def infer_category(record: InvoiceRecord) -> str:
+ """Return record.category if set, otherwise infer one of the 10 standard categories."""
+ if record.category and record.category.strip():
+ return record.category.strip()
+ haystack = f"{record.item_name or ''} {record.seller_name or ''}"
+ for category, keywords in _CATEGORY_KEYWORDS:
+ if any(kw in haystack for kw in keywords):
+ return category
+ return "其他"
+
+
+def _safe_excel_text(value: Optional[str]) -> str:
+ """Prevent spreadsheet formula injection on untrusted text cells."""
+ if not value:
+ return ""
+ if value[0] in ("=", "+", "@", "\t", "\r"):
+ return "'" + value
+ return value
+
+
+def _to_float_or_blank(value: Optional[Decimal]) -> float | str:
+ if value is None:
+ return ""
+ return float(value.quantize(Decimal("0.01"), rounding=ROUND_HALF_UP))
+
+
+def _auto_fit_columns(ws, max_width: int = 48) -> None:
+ for col_cells in ws.columns:
+ col_letter = get_column_letter(col_cells[0].column)
+ max_len = 0
+ for cell in col_cells:
+ val = cell.value
+ if val is None:
+ continue
+ text = str(val)
+ if text.startswith("="):
+ continue
+ # Approximate CJK wide character width as 2 columns
+ width = sum(2 if ord(ch) > 127 else 1 for ch in text)
+ if width > max_len:
+ max_len = width
+ ws.column_dimensions[col_letter].width = min(max(max_len + 4, 10), max_width)
+
+
+def build_reimbursement_excel(
+ records: Sequence[InvoiceRecord],
+ issues: Sequence[CheckIssue] = (),
+ *,
+ title: str = "报销单",
+ report_date: Optional[date] = None,
+ set_name: Optional[str] = None,
+) -> bytes:
+ """Build a 3-sheet reimbursement Excel workbook (汇总 / 明细 / 问题清单)."""
+ effective_date = report_date or date.today()
+
+ wb = openpyxl.Workbook()
+ ws_summary = wb.active
+ ws_summary.title = "汇总"
+ ws_detail = wb.create_sheet(title="明细")
+ ws_issues = wb.create_sheet(title="问题清单")
+
+ # Shared styles
+ title_font = Font(size=16, bold=True)
+ section_font = Font(size=11, bold=True)
+ header_font = Font(bold=True)
+ bold_font = Font(bold=True)
+ note_font = Font(size=9, italic=True, color="666666")
+ header_fill = PatternFill(start_color="F2F4F7", end_color="F2F4F7", fill_type="solid")
+ total_fill = PatternFill(start_color="FFFBE6", end_color="FFFBE6", fill_type="solid")
+ error_fill = PatternFill(start_color="FFF1F0", end_color="FFF1F0", fill_type="solid")
+ warn_fill = PatternFill(start_color="FFF7E6", end_color="FFF7E6", fill_type="solid")
+ thin = Side(style="thin", color="D9D9D9")
+ border = Border(left=thin, right=thin, top=thin, bottom=thin)
+ center = Alignment(horizontal="center", vertical="center")
+ left_align = Alignment(horizontal="left", vertical="center")
+ right_align = Alignment(horizontal="right", vertical="center")
+
+ # Index issues by sequence number for Detail sheet alert column
+ issues_by_seq: dict[int, list[str]] = defaultdict(list)
+ for issue in issues:
+ label = f"[{issue.level}] {issue.code}"
+ for seq in issue.seqs:
+ if label not in issues_by_seq[seq]:
+ issues_by_seq[seq].append(label)
+
+ # ---- Sheet 2: 明细 ----
+ for col_idx, header in enumerate(DETAIL_HEADERS, start=1):
+ cell = ws_detail.cell(row=1, column=col_idx, value=header)
+ cell.font = header_font
+ cell.fill = header_fill
+ cell.border = border
+ cell.alignment = center
+
+ category_stats: dict[str, list[Decimal | int]] = {}
+ total_reimbursable = Decimal("0.00")
+
+ for row_offset, rec in enumerate(records, start=2):
+ category = infer_category(rec)
+ reimb = rec.reimbursable_amount if rec.reimbursable_amount is not None else rec.total_with_tax
+ total_wt = rec.total_with_tax if rec.total_with_tax is not None else Decimal("0.00")
+ reimb_dec = reimb if reimb is not None else Decimal("0.00")
+ total_reimbursable += reimb_dec
+
+ if category not in category_stats:
+ category_stats[category] = [0, Decimal("0.00"), Decimal("0.00")]
+ category_stats[category][0] = int(category_stats[category][0]) + 1
+ category_stats[category][1] = Decimal(category_stats[category][1]) + total_wt
+ category_stats[category][2] = Decimal(category_stats[category][2]) + reimb_dec
+
+ alert_str = "; ".join(issues_by_seq.get(rec.seq, []))
+ row_values = [
+ rec.seq,
+ _safe_excel_text(rec.invoice_type or "电子发票"),
+ alert_str,
+ rec.issue_date.isoformat() if rec.issue_date else "",
+ _safe_excel_text(category),
+ _safe_excel_text(rec.item_name),
+ _safe_excel_text(rec.invoice_number),
+ _safe_excel_text(rec.invoice_code),
+ _to_float_or_blank(rec.amount),
+ _to_float_or_blank(rec.tax_amount),
+ _to_float_or_blank(rec.total_with_tax),
+ _to_float_or_blank(reimb),
+ _safe_excel_text(rec.buyer_name),
+ _safe_excel_text(rec.buyer_tax_id),
+ _safe_excel_text(rec.seller_name),
+ _safe_excel_text(rec.seller_tax_id),
+ _safe_excel_text((rec.file_format or "").upper()),
+ _safe_excel_text(rec.remarks),
+ ]
+
+ for col_idx, val in enumerate(row_values, start=1):
+ cell = ws_detail.cell(row=row_offset, column=col_idx, value=val)
+ cell.border = border
+ if col_idx == 1:
+ cell.alignment = center
+ elif col_idx in (7, 8, 14, 16):
+ cell.number_format = "@"
+ cell.alignment = left_align
+ elif col_idx in (9, 10, 11, 12):
+ cell.number_format = "#,##0.00"
+ cell.alignment = right_align
+ else:
+ cell.alignment = left_align
+
+ last_data_row = len(records) + 1
+ total_row = last_data_row + 1
+ ws_detail.cell(row=total_row, column=1, value="合计").font = bold_font
+ ws_detail.cell(row=total_row, column=1).alignment = center
+ for col_idx in range(1, len(DETAIL_HEADERS) + 1):
+ c = ws_detail.cell(row=total_row, column=col_idx)
+ c.border = border
+ c.fill = total_fill
+ if col_idx in (9, 10, 11, 12):
+ col_letter = get_column_letter(col_idx)
+ c.value = f"=SUM({col_letter}2:{col_letter}{last_data_row})" if records else 0
+ c.font = bold_font
+ c.number_format = "#,##0.00"
+ c.alignment = right_align
+
+ # ---- Sheet 1: 汇总 ----
+ ws_summary.merge_cells("A1:F1")
+ title_cell = ws_summary["A1"]
+ title_cell.value = title
+ title_cell.font = title_font
+ title_cell.alignment = center
+ ws_summary.row_dimensions[1].height = 28
+
+ meta_rows = [
+ ("填报日期", effective_date.isoformat(), "共附单据", f"共附单据 {len(records)} 张", "报销集", _safe_excel_text(set_name or "")),
+ ("报销人", "", "部门", "", "事由", ""),
+ ]
+ for r_idx, row_data in enumerate(meta_rows, start=3):
+ for c_idx, val in enumerate(row_data, start=1):
+ cell = ws_summary.cell(row=r_idx, column=c_idx, value=val)
+ cell.border = border
+ if c_idx in (1, 3, 5):
+ cell.font = header_font
+ cell.fill = header_fill
+ cell.alignment = center
+ else:
+ cell.alignment = left_align
+
+ # Category summary table
+ cat_title_row = 6
+ ws_summary.cell(row=cat_title_row, column=1, value="按科目/类型汇总").font = section_font
+
+ cat_header_row = 7
+ for c_idx, h in enumerate(("科目/类型", "单据张数", "价税合计(元)", "实报金额(元)"), start=1):
+ cell = ws_summary.cell(row=cat_header_row, column=c_idx, value=h)
+ cell.font = header_font
+ cell.fill = header_fill
+ cell.border = border
+ cell.alignment = center
+
+ ordered_categories = [c for c in CATEGORIES if c in category_stats] + [
+ c for c in sorted(category_stats.keys()) if c not in CATEGORIES
+ ]
+
+ cur_row = cat_header_row + 1
+ if ordered_categories:
+ for cat in ordered_categories:
+ cnt, sum_total, sum_reimb = category_stats[cat]
+ row_vals = [
+ cat,
+ int(cnt),
+ float(Decimal(sum_total).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)),
+ float(Decimal(sum_reimb).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)),
+ ]
+ for c_idx, val in enumerate(row_vals, start=1):
+ cell = ws_summary.cell(row=cur_row, column=c_idx, value=val)
+ cell.border = border
+ if c_idx == 2:
+ cell.alignment = center
+ elif c_idx in (3, 4):
+ cell.number_format = "#,##0.00"
+ cell.alignment = right_align
+ else:
+ cell.alignment = left_align
+ cur_row += 1
+ else:
+ for c_idx, val in enumerate(("无", 0, 0.0, 0.0), start=1):
+ cell = ws_summary.cell(row=cur_row, column=c_idx, value=val)
+ cell.border = border
+ cur_row += 1
+
+ # Totals block (with SUM formula referencing 明细!L2:L{last_data_row})
+ total_lower_row = cur_row + 1
+ ws_summary.cell(row=total_lower_row, column=1, value="实报合计(小写)").font = bold_font
+ ws_summary.cell(row=total_lower_row, column=1).fill = total_fill
+ ws_summary.cell(row=total_lower_row, column=1).border = border
+ sum_formula_cell = ws_summary.cell(
+ row=total_lower_row,
+ column=2,
+ value=f"=SUM(明细!L2:L{last_data_row})" if records else "=0",
+ )
+ sum_formula_cell.font = bold_font
+ sum_formula_cell.fill = total_fill
+ sum_formula_cell.border = border
+ sum_formula_cell.number_format = "#,##0.00"
+ sum_formula_cell.alignment = right_align
+ for extra_col in (3, 4):
+ c = ws_summary.cell(row=total_lower_row, column=extra_col, value="")
+ c.fill = total_fill
+ c.border = border
+
+ total_upper_row = total_lower_row + 1
+ ws_summary.cell(row=total_upper_row, column=1, value="实报合计(人民币大写)").font = bold_font
+ ws_summary.cell(row=total_upper_row, column=1).fill = total_fill
+ ws_summary.cell(row=total_upper_row, column=1).border = border
+ ws_summary.merge_cells(start_row=total_upper_row, start_column=2, end_row=total_upper_row, end_column=4)
+ upper_cell = ws_summary.cell(
+ row=total_upper_row,
+ column=2,
+ value=amount_to_chinese_upper(total_reimbursable),
+ )
+ upper_cell.font = bold_font
+ upper_cell.fill = total_fill
+ upper_cell.alignment = left_align
+ for extra_col in (2, 3, 4):
+ ws_summary.cell(row=total_upper_row, column=extra_col).border = border
+
+ note_row = total_upper_row + 1
+ ws_summary.merge_cells(start_row=note_row, start_column=1, end_row=note_row, end_column=6)
+ note_cell = ws_summary.cell(
+ row=note_row,
+ column=1,
+ value="注:人民币大写于生成时计算;若手动修改「明细」中的实报金额,请人工复核大写金额。",
+ )
+ note_cell.font = note_font
+
+ # Bottom 3-column signature block
+ sig_row = note_row + 2
+ sig_labels = [("填报人", 1, 2), ("财会审核", 3, 4), ("终审", 5, 6)]
+ for label, label_col, val_col in sig_labels:
+ lc = ws_summary.cell(row=sig_row, column=label_col, value=label)
+ lc.font = header_font
+ lc.fill = header_fill
+ lc.border = border
+ lc.alignment = center
+ vc = ws_summary.cell(row=sig_row, column=val_col, value="")
+ vc.border = border
+ ws_summary.row_dimensions[sig_row].height = 26
+
+ # ---- Sheet 3: 问题清单 ----
+ for col_idx, header in enumerate(ISSUE_HEADERS, start=1):
+ cell = ws_issues.cell(row=1, column=col_idx, value=header)
+ cell.font = header_font
+ cell.fill = header_fill
+ cell.border = border
+ cell.alignment = center
+
+ sorted_issues = sorted(
+ issues,
+ key=lambda item: (0 if item.level == "error" else 1, item.code, item.seqs),
+ )
+ for row_idx, issue in enumerate(sorted_issues, start=2):
+ level_label = "错误 (error)" if issue.level == "error" else "警告 (warning)"
+ seqs_str = ", ".join(str(s) for s in issue.seqs)
+ row_vals = [
+ level_label,
+ issue.code,
+ seqs_str,
+ _safe_excel_text(issue.message),
+ _safe_excel_text(issue.suggestion),
+ ]
+ fill = error_fill if issue.level == "error" else warn_fill
+ for col_idx, val in enumerate(row_vals, start=1):
+ cell = ws_issues.cell(row=row_idx, column=col_idx, value=val)
+ cell.border = border
+ cell.fill = fill
+ cell.alignment = center if col_idx in (1, 2, 3) else left_align
+
+ _auto_fit_columns(ws_summary)
+ _auto_fit_columns(ws_detail)
+ _auto_fit_columns(ws_issues)
+
+ out = BytesIO()
+ wb.save(out)
+ return out.getvalue()
diff --git a/packages/invoice-core/src/invoice_core/export/pdf.py b/packages/invoice-core/src/invoice_core/export/pdf.py
new file mode 100644
index 0000000..5ceae49
--- /dev/null
+++ b/packages/invoice-core/src/invoice_core/export/pdf.py
@@ -0,0 +1,242 @@
+"""Streaming merged PDF builder using pypdfium2 and Pillow (no PyMuPDF/reportlab/img2pdf)."""
+
+from __future__ import annotations
+
+from dataclasses import dataclass
+from io import BytesIO
+from typing import Sequence
+
+from PIL import Image, ImageOps, UnidentifiedImageError
+
+from invoice_core.parsers.pdf_text import _PDFIUM_LOCK
+
+_SUPPORTED_IMAGE_TYPES = frozenset({"jpg", "jpeg", "png"})
+_A4_WIDTH_PT = 595.0
+_A4_HEIGHT_PT = 842.0
+
+
+class CorruptSourceFileError(ValueError):
+ """Raised when a source file is missing, empty, unsupported, or unreadable."""
+
+ def __init__(self, message: str, *, index: int | None = None, file_name: str = "") -> None:
+ super().__init__(message)
+ self.index = index
+ self.file_name = file_name
+
+
+@dataclass(frozen=True)
+class MergeSource:
+ """Single source document (PDF or raster image) to merge into a multi-page PDF."""
+
+ data: bytes
+ file_type: str
+ file_name: str = ""
+
+
+def _image_to_rgb(img: Image.Image) -> Image.Image:
+ """Apply EXIF orientation and flatten transparency onto white RGB background."""
+ transposed = ImageOps.exif_transpose(img)
+ if transposed.mode == "RGB":
+ return transposed
+ if transposed.mode in ("RGBA", "LA") or (transposed.mode == "P" and "transparency" in transposed.info):
+ rgba = transposed.convert("RGBA")
+ bg = Image.new("RGB", rgba.size, (255, 255, 255))
+ bg.paste(rgba, mask=rgba.split()[3])
+ rgba.close()
+ if transposed is not img:
+ transposed.close()
+ return bg
+ rgb = transposed.convert("RGB")
+ if transposed is not img:
+ transposed.close()
+ return rgb
+
+
+def _append_jpeg_page(
+ out_doc,
+ pdfium_mod,
+ pil_image: Image.Image,
+ width_pt: float,
+ height_pt: float,
+ jpeg_quality: int,
+) -> None:
+ """Encode a single RGB PIL Image to JPEG and append it as one page, releasing buffers immediately."""
+ jpeg_buf = BytesIO()
+ try:
+ pil_image.save(jpeg_buf, format="JPEG", quality=jpeg_quality, optimize=True)
+ jpeg_buf.seek(0)
+ page = out_doc.new_page(width_pt, height_pt)
+ try:
+ image_obj = pdfium_mod.PdfImage.new(out_doc)
+ image_obj.load_jpeg(jpeg_buf, inline=True, autoclose=False)
+ image_obj.set_matrix(pdfium_mod.PdfMatrix(width_pt, 0, 0, height_pt, 0, 0))
+ page.insert_obj(image_obj)
+ page.gen_content()
+ finally:
+ page.close()
+ finally:
+ jpeg_buf.close()
+
+
+def _image_page_size_pt(width_px: int, height_px: int, dpi: int) -> tuple[float, float]:
+ """Compute PDF page dimensions in points for an image, fitting comfortably within A4 bounds."""
+ if width_px <= 0 or height_px <= 0:
+ raise CorruptSourceFileError("图像尺寸无效")
+ w_pt = width_px * 72.0 / dpi
+ h_pt = height_px * 72.0 / dpi
+ max_w, max_h = (_A4_HEIGHT_PT, _A4_WIDTH_PT) if width_px > height_px else (_A4_WIDTH_PT, _A4_HEIGHT_PT)
+ scale = min(max_w / w_pt, max_h / h_pt, 1.0)
+ return w_pt * scale, h_pt * scale
+
+
+def merge_sources_to_pdf(
+ sources: Sequence[MergeSource],
+ *,
+ dpi: int = 200,
+ jpeg_quality: int = 85,
+) -> bytes:
+ """Merge PDF and image sources in order into a single multi-page PDF.
+
+ Each source page is rendered and streamed as a JPEG image object before releasing
+ its bitmap and PIL image to keep peak memory bounded.
+ """
+ if not sources:
+ raise CorruptSourceFileError("没有可合并的原件文件")
+ if dpi <= 0:
+ raise ValueError("dpi must be positive")
+ if not (1 <= jpeg_quality <= 100):
+ raise ValueError("jpeg_quality must be between 1 and 100")
+
+ import pypdfium2 as pdfium
+
+ scale = dpi / 72.0
+
+ with _PDFIUM_LOCK:
+ out_doc = pdfium.PdfDocument.new()
+ try:
+ for idx, src in enumerate(sources):
+ label = src.file_name or f"source#{idx + 1}"
+ if not src.data:
+ raise CorruptSourceFileError(
+ f"原件缺失或为空:{label}",
+ index=idx,
+ file_name=src.file_name,
+ )
+
+ ext = (src.file_type or "").strip().lower().lstrip(".")
+ if ext == "pdf":
+ try:
+ src_pdf = pdfium.PdfDocument(src.data)
+ except Exception as exc:
+ raise CorruptSourceFileError(
+ f"PDF 原件损坏或无法解析:{label}",
+ index=idx,
+ file_name=src.file_name,
+ ) from exc
+
+ try:
+ page_count = len(src_pdf)
+ if page_count == 0:
+ raise CorruptSourceFileError(
+ f"PDF 原件不包含任何页面:{label}",
+ index=idx,
+ file_name=src.file_name,
+ )
+
+ for page_idx in range(page_count):
+ src_page = src_pdf[page_idx]
+ bitmap = None
+ pil_img = None
+ try:
+ mediabox = src_page.get_mediabox(fallback_ok=False)
+ cropbox = src_page.get_cropbox(fallback_ok=False)
+ if (
+ mediabox is not None
+ and len(mediabox) == 4
+ and mediabox[2] > mediabox[0]
+ and mediabox[3] > mediabox[1]
+ and cropbox is not None
+ and cropbox != mediabox
+ ):
+ src_page.set_cropbox(*mediabox)
+
+ width_pt, height_pt = src_page.get_size()
+ bitmap = src_page.render(scale=scale)
+ pil_img = bitmap.to_pil()
+ if pil_img.mode != "RGB":
+ rgb_img = pil_img.convert("RGB")
+ pil_img.close()
+ pil_img = rgb_img
+ else:
+ copied = pil_img.copy()
+ pil_img.close()
+ pil_img = copied
+ except CorruptSourceFileError:
+ raise
+ except Exception as exc:
+ raise CorruptSourceFileError(
+ f"PDF 第 {page_idx + 1} 页渲染失败:{label}",
+ index=idx,
+ file_name=src.file_name,
+ ) from exc
+ finally:
+ if bitmap is not None:
+ bitmap.close()
+ src_page.close()
+
+ try:
+ _append_jpeg_page(
+ out_doc,
+ pdfium,
+ pil_img,
+ float(width_pt),
+ float(height_pt),
+ jpeg_quality,
+ )
+ finally:
+ if pil_img is not None:
+ pil_img.close()
+ finally:
+ src_pdf.close()
+
+ elif ext in _SUPPORTED_IMAGE_TYPES:
+ raw_img = None
+ rgb_img = None
+ try:
+ raw_img = Image.open(BytesIO(src.data))
+ raw_img.load()
+ rgb_img = _image_to_rgb(raw_img)
+ width_pt, height_pt = _image_page_size_pt(rgb_img.width, rgb_img.height, dpi)
+ _append_jpeg_page(
+ out_doc,
+ pdfium,
+ rgb_img,
+ width_pt,
+ height_pt,
+ jpeg_quality,
+ )
+ except CorruptSourceFileError:
+ raise
+ except (UnidentifiedImageError, OSError, ValueError) as exc:
+ raise CorruptSourceFileError(
+ f"图片原件损坏或无法读取:{label}",
+ index=idx,
+ file_name=src.file_name,
+ ) from exc
+ finally:
+ if rgb_img is not None and rgb_img is not raw_img:
+ rgb_img.close()
+ if raw_img is not None:
+ raw_img.close()
+ else:
+ raise CorruptSourceFileError(
+ f"不支持的原件格式 ({ext or 'unknown'}):{label}",
+ index=idx,
+ file_name=src.file_name,
+ )
+
+ out_buf = BytesIO()
+ out_doc.save(out_buf)
+ return out_buf.getvalue()
+ finally:
+ out_doc.close()
diff --git a/packages/invoice-core/src/invoice_core/models.py b/packages/invoice-core/src/invoice_core/models.py
new file mode 100644
index 0000000..c5f5b64
--- /dev/null
+++ b/packages/invoice-core/src/invoice_core/models.py
@@ -0,0 +1,69 @@
+"""Pure-Python domain data models for invoice checking, ledgers, and exports."""
+
+from __future__ import annotations
+
+from dataclasses import dataclass, field
+from datetime import date
+from decimal import Decimal
+from typing import Mapping, Optional
+
+
+@dataclass
+class InvoiceRecord:
+ """Normalized invoice representation consumed by check rules and exporters."""
+
+ seq: int = 1
+ invoice_number: Optional[str] = None
+ invoice_code: Optional[str] = None
+ invoice_type: Optional[str] = None
+ issue_date: Optional[date] = None
+ buyer_name: Optional[str] = None
+ buyer_tax_id: Optional[str] = None
+ seller_name: Optional[str] = None
+ seller_tax_id: Optional[str] = None
+ item_name: Optional[str] = None
+ category: Optional[str] = None
+ amount: Optional[Decimal] = None
+ tax_amount: Optional[Decimal] = None
+ tax_rate: Optional[str] = None
+ total_with_tax: Optional[Decimal] = None
+ reimbursable_amount: Optional[Decimal] = None
+ file_name: Optional[str] = None
+ file_format: Optional[str] = None
+ file_sha256: Optional[str] = None
+ raw_text: Optional[str] = None
+ remarks: Optional[str] = None
+ invoice_id: Optional[int] = None
+ has_ocr_text: bool = True
+
+
+@dataclass
+class CheckIssue:
+ """A single validation or duplicate-detection finding."""
+
+ level: str # "error" | "warning"
+ code: str
+ seqs: list[int]
+ message: str
+ suggestion: str = ""
+
+
+@dataclass(frozen=True)
+class CheckContext:
+ """Optional contextual parameters controlling check rules."""
+
+ buyer_name: Optional[str] = None
+ buyer_tax_id: Optional[str] = None
+ reference_date: Optional[date] = None
+ max_age_days: int = 365
+ max_amount: Optional[Decimal] = None
+
+
+@dataclass(frozen=True)
+class KnownLedger:
+ """Read-only cross-batch ledger used for historical duplicate checks."""
+
+ numbers: Mapping[str, str] = field(default_factory=dict)
+ number_seller: Mapping[tuple[str, str], str] = field(default_factory=dict)
+ sha256: Mapping[str, str] = field(default_factory=dict)
+ number_code: Mapping[tuple[str, str], str] = field(default_factory=dict)
diff --git a/packages/invoice-core/tests/test_checks.py b/packages/invoice-core/tests/test_checks.py
new file mode 100644
index 0000000..474dfe5
--- /dev/null
+++ b/packages/invoice-core/tests/test_checks.py
@@ -0,0 +1,240 @@
+"""Unit tests for invoice_core check rules and KnownLedger cross-batch dedupe."""
+
+from datetime import date
+from decimal import Decimal
+
+from invoice_core.checks import OFFICIAL_VERIFY_URL, REGISTRY, run_checks
+from invoice_core.models import CheckContext, InvoiceRecord, KnownLedger
+
+NUM_1 = "00000000000000000001"
+NUM_2 = "00000000000000000002"
+NUM_3 = "00000000000000000003"
+BUYER_NAME = "示例买方科技有限公司"
+BUYER_TAX = "TESTBUYER000000001"
+SELLER_NAME = "示例卖方服务有限公司"
+SELLER_TAX = "TESTSELLER00000001"
+
+
+def _make_record(**overrides) -> InvoiceRecord:
+ base = dict(
+ seq=1,
+ invoice_number=NUM_1,
+ invoice_code=None,
+ invoice_type="电子发票(普通发票)",
+ issue_date=date(2026, 5, 10),
+ buyer_name=BUYER_NAME,
+ buyer_tax_id=BUYER_TAX,
+ seller_name=SELLER_NAME,
+ seller_tax_id=SELLER_TAX,
+ item_name="信息技术服务*云主机租用费",
+ amount=Decimal("100.00"),
+ tax_amount=Decimal("6.00"),
+ total_with_tax=Decimal("106.00"),
+ file_name="demo_01.pdf",
+ file_format="PDF",
+ file_sha256="a" * 64,
+ has_ocr_text=True,
+ )
+ base.update(overrides)
+ return InvoiceRecord(**base)
+
+
+def test_registry_contains_all_rules_and_clean_batch_passes():
+ assert len(REGISTRY) == 13
+ rec = _make_record()
+ ctx = CheckContext(
+ buyer_name=BUYER_NAME,
+ buyer_tax_id=BUYER_TAX,
+ reference_date=date(2026, 6, 1),
+ max_age_days=365,
+ max_amount=Decimal("500.00"),
+ )
+ issues = run_checks([rec], ctx=ctx)
+ assert issues == []
+
+
+def test_dup_file_in_batch_and_against_known_ledger():
+ r1 = _make_record(seq=1, invoice_number=NUM_1, file_sha256="1" * 64)
+ r2 = _make_record(seq=2, invoice_number=NUM_2, file_sha256="1" * 64)
+ r3 = _make_record(seq=3, invoice_number=NUM_3, file_sha256="2" * 64)
+ known = KnownLedger(sha256={"2" * 64: "历史报销集 #2026-04"})
+
+ issues = run_checks([r1, r2, r3], ctx=CheckContext(reference_date=date(2026, 6, 1)), known=known)
+ dup_file_issues = [i for i in issues if i.code == "DUP_FILE"]
+ assert len(dup_file_issues) == 2
+ assert all(i.level == "error" for i in dup_file_issues)
+ assert {tuple(i.seqs) for i in dup_file_issues} == {(1, 2), (3,)}
+ assert any("历史报销集 #2026-04" in i.message for i in dup_file_issues)
+
+
+def test_dup_number_same_format_blocks_but_multi_format_allowed():
+ r_pdf1 = _make_record(seq=1, invoice_number=NUM_1, file_format="PDF", file_sha256="a" * 64)
+ r_pdf2 = _make_record(seq=2, invoice_number=NUM_1, file_format="PDF", file_sha256="b" * 64)
+ r_ofd = _make_record(seq=3, invoice_number=NUM_2, file_format="OFD", file_sha256="c" * 64)
+ r_xml = _make_record(seq=4, invoice_number=NUM_2, file_format="XML", file_sha256="d" * 64)
+
+ issues = run_checks(
+ [r_pdf1, r_pdf2, r_ofd, r_xml],
+ ctx=CheckContext(reference_date=date(2026, 6, 1)),
+ )
+ dup_nums = [i for i in issues if i.code == "DUP_NUMBER"]
+ assert len(dup_nums) == 1
+ assert dup_nums[0].level == "error"
+ assert dup_nums[0].seqs == [1, 2]
+ # Different formats for NUM_2 should not falsely raise DUP_FUZZY either
+ fuzzy = [i for i in issues if i.code == "DUP_FUZZY" and set(i.seqs) == {3, 4}]
+ assert fuzzy == []
+
+
+def test_dup_number_against_known_ledger():
+ rec = _make_record(seq=1, invoice_number=NUM_1, file_sha256="a" * 64)
+ known = KnownLedger(numbers={NUM_1: "历史台账 #99"})
+ issues = run_checks([rec], ctx=CheckContext(reference_date=date(2026, 6, 1)), known=known)
+ dup_nums = [i for i in issues if i.code == "DUP_NUMBER"]
+ assert len(dup_nums) == 1
+ assert dup_nums[0].level == "error"
+ assert dup_nums[0].seqs == [1]
+ assert "历史台账 #99" in dup_nums[0].message
+
+
+def test_dup_old_by_code_and_by_seller_and_known_ledger():
+ r1 = _make_record(seq=1, invoice_number="12345678", invoice_code="011001900111", file_sha256="a" * 64)
+ r2 = _make_record(
+ seq=2,
+ invoice_number="12345678",
+ invoice_code="011001900111",
+ seller_tax_id="TESTSELLER00000002",
+ file_sha256="b" * 64,
+ )
+ r3 = _make_record(
+ seq=3,
+ invoice_number="87654321",
+ invoice_code=None,
+ seller_tax_id=SELLER_TAX,
+ file_sha256="c" * 64,
+ )
+ known = KnownLedger(number_seller={("87654321", SELLER_TAX): "历史旧票 #10"})
+
+ issues = run_checks([r1, r2, r3], ctx=CheckContext(reference_date=date(2026, 6, 1)), known=known)
+ dup_old = [i for i in issues if i.code == "DUP_OLD"]
+ assert len(dup_old) == 2
+ assert all(i.level == "warning" for i in dup_old)
+ assert {tuple(i.seqs) for i in dup_old} == {(1, 2), (3,)}
+
+
+def test_dup_fuzzy_catches_same_seller_date_and_total_with_different_numbers():
+ r1 = _make_record(seq=1, invoice_number=NUM_1, file_sha256="a" * 64)
+ r2 = _make_record(seq=2, invoice_number=NUM_3, file_format="JPG", file_sha256="b" * 64)
+
+ issues = run_checks([r1, r2], ctx=CheckContext(reference_date=date(2026, 6, 1)))
+ fuzzy = [i for i in issues if i.code == "DUP_FUZZY"]
+ assert len(fuzzy) == 1
+ assert fuzzy[0].level == "warning"
+ assert fuzzy[0].seqs == [1, 2]
+
+
+def test_red_invoice_negative_and_keyword_and_official_url():
+ r_neg = _make_record(
+ seq=1,
+ invoice_number=NUM_1,
+ amount=Decimal("-100.00"),
+ tax_amount=Decimal("-6.00"),
+ total_with_tax=Decimal("-106.00"),
+ file_sha256="a" * 64,
+ )
+ r_kw = _make_record(
+ seq=2,
+ invoice_number=NUM_2,
+ raw_text="本发票已作废,请勿报销",
+ file_sha256="b" * 64,
+ )
+ issues = run_checks([r_neg, r_kw], ctx=CheckContext(reference_date=date(2026, 6, 1)))
+ red_issues = [i for i in issues if i.code == "RED_INVOICE"]
+ assert len(red_issues) == 2
+ assert all(i.level == "warning" for i in red_issues)
+ assert all(OFFICIAL_VERIFY_URL in i.message for i in red_issues)
+
+
+def test_buyer_mismatch_and_personal_buyer():
+ r_wrong = _make_record(
+ seq=1,
+ invoice_number=NUM_1,
+ buyer_name="其他演示公司",
+ buyer_tax_id="TESTBUYER000000999",
+ file_sha256="a" * 64,
+ )
+ r_person = _make_record(
+ seq=2,
+ invoice_number=NUM_2,
+ buyer_name="个人",
+ buyer_tax_id=None,
+ file_sha256="b" * 64,
+ )
+ r_person_name = _make_record(
+ seq=3,
+ invoice_number=NUM_3,
+ buyer_name="张三",
+ buyer_tax_id=None,
+ file_sha256="c" * 64,
+ )
+ ctx = CheckContext(
+ buyer_name=BUYER_NAME,
+ buyer_tax_id=BUYER_TAX,
+ reference_date=date(2026, 6, 1),
+ )
+ issues = run_checks([r_wrong, r_person, r_person_name], ctx=ctx)
+ mismatch = [i for i in issues if i.code == "BUYER_MISMATCH"]
+ personal = [i for i in issues if i.code == "PERSONAL_BUYER"]
+ assert {s for i in mismatch for s in i.seqs} == {1, 2, 3}
+ assert {s for i in personal for s in i.seqs} == {2, 3}
+
+
+def test_cross_year_overdue_consecutive_sum_mismatch_over_limit_and_missing_data():
+ r_old = _make_record(
+ seq=1,
+ invoice_number="00000000000000001001",
+ issue_date=date(2024, 12, 31),
+ amount=Decimal("100.00"),
+ tax_amount=Decimal("6.00"),
+ total_with_tax=Decimal("106.05"), # diff 0.05 > 0.01
+ file_sha256="a" * 64,
+ )
+ r_consec = _make_record(
+ seq=2,
+ invoice_number="00000000000000001002",
+ issue_date=date(2026, 5, 1),
+ amount=Decimal("600.00"),
+ tax_amount=Decimal("36.00"),
+ total_with_tax=Decimal("636.00"), # > max_amount 500
+ file_sha256="b" * 64,
+ )
+ r_missing = _make_record(
+ seq=3,
+ invoice_number=None,
+ issue_date=None,
+ seller_name=None,
+ seller_tax_id=None,
+ total_with_tax=None,
+ has_ocr_text=False,
+ file_sha256="c" * 64,
+ )
+
+ ctx_no_limit = CheckContext(reference_date=date(2026, 6, 1), max_age_days=365, max_amount=None)
+ issues_no_limit = run_checks([r_old, r_consec, r_missing], ctx=ctx_no_limit)
+ codes_no_limit = {i.code for i in issues_no_limit}
+ assert "CROSS_YEAR" in codes_no_limit
+ assert "OVERDUE" in codes_no_limit
+ assert "CONSECUTIVE" in codes_no_limit
+ assert "SUM_MISMATCH" in codes_no_limit
+ assert "MISSING_DATA" in codes_no_limit
+ assert "OVER_LIMIT" not in codes_no_limit
+
+ ctx_with_limit = CheckContext(
+ reference_date=date(2026, 6, 1),
+ max_age_days=365,
+ max_amount=Decimal("500.00"),
+ )
+ issues_with_limit = run_checks([r_old, r_consec, r_missing], ctx=ctx_with_limit)
+ over_limit = [i for i in issues_with_limit if i.code == "OVER_LIMIT"]
+ assert len(over_limit) == 1
+ assert over_limit[0].seqs == [2]
diff --git a/packages/invoice-core/tests/test_export_excel.py b/packages/invoice-core/tests/test_export_excel.py
new file mode 100644
index 0000000..da5547f
--- /dev/null
+++ b/packages/invoice-core/tests/test_export_excel.py
@@ -0,0 +1,148 @@
+"""Unit tests for RMB Chinese uppercase conversion and 3-sheet reimbursement Excel generation."""
+
+from datetime import date
+from decimal import Decimal
+from io import BytesIO
+
+import openpyxl
+import pytest
+
+from invoice_core.export.excel import (
+ DETAIL_HEADERS,
+ ISSUE_HEADERS,
+ amount_to_chinese_upper,
+ build_reimbursement_excel,
+)
+from invoice_core.models import CheckIssue, InvoiceRecord
+
+
+@pytest.mark.parametrize(
+ ("amount", "expected"),
+ [
+ (Decimal("0"), "零元整"),
+ (Decimal("0.00"), "零元整"),
+ (Decimal("0.05"), "伍分"),
+ (Decimal("0.50"), "伍角整"),
+ (Decimal("0.56"), "伍角陆分"),
+ (Decimal("1.00"), "壹元整"),
+ (Decimal("1.05"), "壹元零伍分"),
+ (Decimal("1.50"), "壹元伍角整"),
+ (Decimal("1.56"), "壹元伍角陆分"),
+ (Decimal("10.00"), "壹拾元整"),
+ (Decimal("100.00"), "壹佰元整"),
+ (Decimal("101.00"), "壹佰零壹元整"),
+ (Decimal("1001.00"), "壹仟零壹元整"),
+ (Decimal("1010.00"), "壹仟零壹拾元整"),
+ (Decimal("10000.00"), "壹万元整"),
+ (Decimal("10001.00"), "壹万零壹元整"),
+ (Decimal("10100.00"), "壹万零壹佰元整"),
+ (Decimal("11000.00"), "壹万壹仟元整"),
+ (Decimal("100000.00"), "壹拾万元整"),
+ (Decimal("100000000.00"), "壹亿元整"),
+ (Decimal("100000001.00"), "壹亿零壹元整"),
+ (Decimal("100010000.00"), "壹亿零壹万元整"),
+ (Decimal("101000000.00"), "壹亿零壹佰万元整"),
+ (Decimal("100001000.00"), "壹亿零壹仟元整"),
+ (Decimal("123456789.05"), "壹亿贰仟叁佰肆拾伍万陆仟柒佰捌拾玖元零伍分"),
+ (Decimal("-106.00"), "负壹佰零陆元整"),
+ (Decimal("-0.05"), "负伍分"),
+ (Decimal("-10001.50"), "负壹万零壹元伍角整"),
+ ],
+)
+def test_amount_to_chinese_upper_edge_cases(amount: Decimal, expected: str):
+ assert amount_to_chinese_upper(amount) == expected
+
+
+def test_build_reimbursement_excel_three_sheets_content():
+ records = [
+ InvoiceRecord(
+ seq=1,
+ invoice_number="00000000000000000001",
+ invoice_code="012345678901",
+ invoice_type="电子发票(普通发票)",
+ issue_date=date(2026, 5, 1),
+ buyer_name="示例买方科技有限公司",
+ buyer_tax_id="TESTBUYER000000001",
+ seller_name="示例餐饮服务有限公司",
+ seller_tax_id="TESTSELLER00000001",
+ item_name="餐饮服务*工作餐",
+ amount=Decimal("200.00"),
+ tax_amount=Decimal("12.00"),
+ total_with_tax=Decimal("212.00"),
+ file_format="PDF",
+ ),
+ InvoiceRecord(
+ seq=2,
+ invoice_number="00000000000000000002",
+ invoice_type="电子发票(普通发票)",
+ issue_date=date(2026, 5, 2),
+ buyer_name="示例买方科技有限公司",
+ buyer_tax_id="TESTBUYER000000001",
+ seller_name="示例云服务科技有限公司",
+ seller_tax_id="TESTSELLER00000002",
+ item_name="信息技术服务*云主机租用费",
+ amount=Decimal("1000.00"),
+ tax_amount=Decimal("60.00"),
+ total_with_tax=Decimal("1060.00"),
+ file_format="PDF",
+ ),
+ ]
+ issues = [
+ CheckIssue(
+ level="warning",
+ code="CROSS_YEAR",
+ seqs=[1],
+ message="序号 1 为跨年发票",
+ suggestion="请确认是否允许跨年报销",
+ )
+ ]
+
+ xlsx_bytes = build_reimbursement_excel(
+ records,
+ issues,
+ report_date=date(2026, 5, 20),
+ set_name="2026-05 差旅报销",
+ )
+
+ wb = openpyxl.load_workbook(BytesIO(xlsx_bytes), data_only=False)
+ assert wb.sheetnames == ["汇总", "明细", "问题清单"]
+
+ ws_sum = wb["汇总"]
+ assert ws_sum["A1"].value == "报销单"
+ summary_values = [
+ cell.value
+ for row in ws_sum.iter_rows(values_only=False)
+ for cell in row
+ if cell.value is not None
+ ]
+ assert "2026-05-20" in summary_values
+ assert "共附单据 2 张" in summary_values
+ assert "报销人" in summary_values
+ assert "部门" in summary_values
+ assert "事由" in summary_values
+ assert "=SUM(明细!L2:L3)" in summary_values
+ assert amount_to_chinese_upper(Decimal("1272.00")) in summary_values
+ assert "填报人" in summary_values
+ assert "财会审核" in summary_values
+ assert "终审" in summary_values
+
+ ws_detail = wb["明细"]
+ detail_headers = tuple(ws_detail.cell(row=1, column=i).value for i in range(1, len(DETAIL_HEADERS) + 1))
+ assert detail_headers == DETAIL_HEADERS
+ assert ws_detail.cell(row=2, column=1).value == 1
+ assert ws_detail.cell(row=2, column=3).value == "[warning] CROSS_YEAR"
+ assert ws_detail.cell(row=2, column=5).value == "餐饮美食"
+ assert ws_detail.cell(row=2, column=7).value == "00000000000000000001"
+ assert ws_detail.cell(row=2, column=11).value == pytest.approx(212.00)
+ assert ws_detail.cell(row=2, column=12).value == pytest.approx(212.00)
+ assert ws_detail.cell(row=3, column=5).value == "云服务与软件订阅"
+ assert ws_detail.cell(row=4, column=1).value == "合计"
+ assert ws_detail.cell(row=4, column=11).value == "=SUM(K2:K3)"
+ assert ws_detail.cell(row=4, column=12).value == "=SUM(L2:L3)"
+
+ ws_issues = wb["问题清单"]
+ issue_headers = tuple(ws_issues.cell(row=1, column=i).value for i in range(1, len(ISSUE_HEADERS) + 1))
+ assert issue_headers == ISSUE_HEADERS
+ assert ws_issues.cell(row=2, column=2).value == "CROSS_YEAR"
+ assert ws_issues.cell(row=2, column=3).value == "1"
+ assert ws_issues.cell(row=2, column=4).value == "序号 1 为跨年发票"
diff --git a/packages/invoice-core/tests/test_export_pdf.py b/packages/invoice-core/tests/test_export_pdf.py
new file mode 100644
index 0000000..c2c2f2b
--- /dev/null
+++ b/packages/invoice-core/tests/test_export_pdf.py
@@ -0,0 +1,103 @@
+"""Unit tests for pypdfium2 + Pillow streaming merged PDF export."""
+
+from io import BytesIO
+
+import pypdfium2 as pdfium
+import pytest
+from PIL import Image
+
+from invoice_core.export.pdf import CorruptSourceFileError, MergeSource, merge_sources_to_pdf
+from invoice_core.parsers.pdf_text import render_pdf_pages
+
+
+def _make_solid_image_bytes(color: tuple[int, int, int], fmt: str, size: tuple[int, int] = (400, 300)) -> bytes:
+ buf = BytesIO()
+ img = Image.new("RGB", size, color)
+ img.save(buf, format=fmt)
+ return buf.getvalue()
+
+
+def _make_colored_pdf_bytes(colors: list[tuple[int, int, int]]) -> bytes:
+ """Create a multi-page PDF with distinct solid-color pages using pypdfium2."""
+ doc = pdfium.PdfDocument.new()
+ try:
+ for color in colors:
+ jbuf = BytesIO()
+ Image.new("RGB", (300, 400), color).save(jbuf, format="JPEG", quality=90)
+ jbuf.seek(0)
+ page = doc.new_page(300, 400)
+ try:
+ pimg = pdfium.PdfImage.new(doc)
+ pimg.load_jpeg(jbuf, inline=True, autoclose=False)
+ pimg.set_matrix(pdfium.PdfMatrix(300, 0, 0, 400, 0, 0))
+ page.insert_obj(pimg)
+ page.gen_content()
+ finally:
+ page.close()
+ out = BytesIO()
+ doc.save(out)
+ return out.getvalue()
+ finally:
+ doc.close()
+
+
+def test_merge_pdf_and_images_preserves_order_and_page_count():
+ pdf_2pages = _make_colored_pdf_bytes([(220, 40, 40), (40, 200, 60)]) # red, green
+ png_blue = _make_solid_image_bytes((40, 80, 220), "PNG", size=(500, 350))
+ jpg_yellow = _make_solid_image_bytes((230, 210, 40), "JPEG", size=(350, 500))
+
+ merged = merge_sources_to_pdf(
+ [
+ MergeSource(data=pdf_2pages, file_type="pdf", file_name="01_two_pages.pdf"),
+ MergeSource(data=png_blue, file_type="png", file_name="02_blue.png"),
+ MergeSource(data=jpg_yellow, file_type="jpg", file_name="03_yellow.jpg"),
+ ],
+ dpi=150,
+ jpeg_quality=85,
+ )
+
+ assert merged.startswith(b"%PDF")
+ rendered = render_pdf_pages(merged, dpi=72)
+ assert len(rendered) == 4
+
+ # Check center pixel dominant channel on each page to verify exact order
+ p1 = rendered[0].getpixel((rendered[0].width // 2, rendered[0].height // 2))
+ p2 = rendered[1].getpixel((rendered[1].width // 2, rendered[1].height // 2))
+ p3 = rendered[2].getpixel((rendered[2].width // 2, rendered[2].height // 2))
+ p4 = rendered[3].getpixel((rendered[3].width // 2, rendered[3].height // 2))
+
+ assert p1[0] > 180 and p1[1] < 90 # red
+ assert p2[1] > 160 and p2[0] < 90 # green
+ assert p3[2] > 180 and p3[0] < 90 # blue
+ assert p4[0] > 180 and p4[1] > 170 and p4[2] < 90 # yellow
+
+
+def test_merge_rgba_png_handles_alpha_cleanly():
+ buf = BytesIO()
+ img = Image.new("RGBA", (300, 200), (20, 120, 220, 128))
+ img.save(buf, format="PNG")
+ merged = merge_sources_to_pdf([MergeSource(data=buf.getvalue(), file_type="png", file_name="alpha.png")])
+ rendered = render_pdf_pages(merged, dpi=72)
+ assert len(rendered) == 1
+ assert rendered[0].mode == "RGB"
+
+
+def test_merge_corrupt_or_missing_sources_raise_corrupt_source_file_error():
+ with pytest.raises(CorruptSourceFileError):
+ merge_sources_to_pdf([])
+
+ with pytest.raises(CorruptSourceFileError) as exc_empty:
+ merge_sources_to_pdf([MergeSource(data=b"", file_type="pdf", file_name="empty.pdf")])
+ assert exc_empty.value.index == 0
+ assert exc_empty.value.file_name == "empty.pdf"
+
+ with pytest.raises(CorruptSourceFileError) as exc_pdf:
+ merge_sources_to_pdf([MergeSource(data=b"not a valid pdf", file_type="pdf", file_name="bad.pdf")])
+ assert exc_pdf.value.index == 0
+
+ with pytest.raises(CorruptSourceFileError) as exc_img:
+ merge_sources_to_pdf([MergeSource(data=b"not an image", file_type="jpg", file_name="bad.jpg")])
+ assert exc_img.value.index == 0
+
+ with pytest.raises(CorruptSourceFileError):
+ merge_sources_to_pdf([MergeSource(data=b"hello", file_type="exe", file_name="bad.exe")])
diff --git a/packages/invoice-core/tests/test_import_guard.py b/packages/invoice-core/tests/test_import_guard.py
index e819850..8faa1c3 100644
--- a/packages/invoice-core/tests/test_import_guard.py
+++ b/packages/invoice-core/tests/test_import_guard.py
@@ -15,6 +15,10 @@
"pdf2image",
"uvicorn",
"alembic",
+ "fitz",
+ "pymupdf",
+ "reportlab",
+ "img2pdf",
}
)
@@ -76,4 +80,13 @@ def test_runtime_sys_modules_forbids_backend_and_heavy_imports():
assert "invoice_core.prompts" in result["loaded"]
assert "invoice_core.parsers.pdf_text" in result["loaded"]
assert "invoice_core.parsers.vision" in result["loaded"]
+ assert "invoice_core.models" in result["loaded"]
+ assert "invoice_core.checks" in result["loaded"]
+ assert "invoice_core.checks.dedupe" in result["loaded"]
+ assert "invoice_core.checks.buyer" in result["loaded"]
+ assert "invoice_core.checks.anomalies" in result["loaded"]
+ assert "invoice_core.checks.completeness" in result["loaded"]
+ assert "invoice_core.export" in result["loaded"]
+ assert "invoice_core.export.excel" in result["loaded"]
+ assert "invoice_core.export.pdf" in result["loaded"]
assert result["hits"] == [], f"Forbidden modules loaded at runtime: {result['hits']}"
From ead58f464e42f4fac3f2721ed439bcd960dc8ba8 Mon Sep 17 00:00:00 2001
From: stone16 <12712299+stone16@users.noreply.github.com>
Date: Sat, 28 Nov 2026 15:53:33 +0800
Subject: [PATCH 3/5] feat(backend): add reimbursement sets CRUD, duplicate
upload hint, and validated exports
---
backend/app/config.py | 4 +
backend/app/main.py | 8 +-
backend/app/models/__init__.py | 14 +
backend/app/models/reimbursement_set.py | 50 ++
backend/app/routers/invoices.py | 31 +-
backend/app/routers/reimbursement_sets.py | 537 +++++++++++++++
backend/app/schemas/invoice.py | 2 +
backend/app/schemas/reimbursement_set.py | 73 +++
backend/app/services/reimbursement_service.py | 440 +++++++++++++
backend/tests/test_reimbursement_sets.py | 616 ++++++++++++++++++
10 files changed, 1772 insertions(+), 3 deletions(-)
create mode 100644 backend/app/models/reimbursement_set.py
create mode 100644 backend/app/routers/reimbursement_sets.py
create mode 100644 backend/app/schemas/reimbursement_set.py
create mode 100644 backend/app/services/reimbursement_service.py
create mode 100644 backend/tests/test_reimbursement_sets.py
diff --git a/backend/app/config.py b/backend/app/config.py
index b33dec0..1c00b9a 100644
--- a/backend/app/config.py
+++ b/backend/app/config.py
@@ -95,6 +95,10 @@ class Settings(BaseSettings):
max_file_size: int = 10 * 1024 * 1024 # 10MB
allowed_extensions: list[str] = ["pdf", "jpg", "jpeg", "png"]
+ # Reimbursement bundle export safety limits
+ reimbursement_export_max_items: int = 200
+ reimbursement_export_max_bytes: int = 200 * 1024 * 1024 # 200MB
+
# Parallel processing settings
# Separate pools for OCR and LLM to maximize throughput
# OCR is CPU-bound (image processing), limit based on available cores
diff --git a/backend/app/main.py b/backend/app/main.py
index 0e14461..cb0706c 100644
--- a/backend/app/main.py
+++ b/backend/app/main.py
@@ -6,7 +6,7 @@
from slowapi.errors import RateLimitExceeded
from app.config import get_settings
-from app.routers import health, invoices, settings as settings_router
+from app.routers import health, invoices, reimbursement_sets, settings as settings_router
from app.rate_limit import limiter
settings = get_settings()
@@ -40,12 +40,18 @@ async def rate_limit_handler(request: Request, exc: RateLimitExceeded):
# Include routers
app.include_router(health.router, prefix="/api", tags=["Health"])
app.include_router(invoices.router, prefix="/api/invoices", tags=["Invoices"])
+app.include_router(
+ reimbursement_sets.router,
+ prefix="/api/reimbursement-sets",
+ tags=["Reimbursement Sets"],
+)
app.include_router(settings_router.router, prefix="/api/settings", tags=["Settings"])
@app.on_event("startup")
async def startup():
from app.database import engine, Base
+ from app.models import reimbursement_set as _reimbursement_set # noqa: F401
async with engine.begin() as conn:
await conn.run_sync(Base.metadata.create_all)
diff --git a/backend/app/models/__init__.py b/backend/app/models/__init__.py
index e69de29..1d8428e 100644
--- a/backend/app/models/__init__.py
+++ b/backend/app/models/__init__.py
@@ -0,0 +1,14 @@
+from app.models.audit_log import AuditLog
+from app.models.invoice import Invoice, InvoiceStatus, LlmResult, OcrResult, ParsingDiff
+from app.models.reimbursement_set import ReimbursementSet, ReimbursementSetItem
+
+__all__ = [
+ "AuditLog",
+ "Invoice",
+ "InvoiceStatus",
+ "LlmResult",
+ "OcrResult",
+ "ParsingDiff",
+ "ReimbursementSet",
+ "ReimbursementSetItem",
+]
diff --git a/backend/app/models/reimbursement_set.py b/backend/app/models/reimbursement_set.py
new file mode 100644
index 0000000..f4bf760
--- /dev/null
+++ b/backend/app/models/reimbursement_set.py
@@ -0,0 +1,50 @@
+"""SQLAlchemy models for reimbursement sets and ordered invoice membership."""
+
+from datetime import datetime
+from sqlalchemy import Column, DateTime, ForeignKey, Integer, String, Text, UniqueConstraint
+from sqlalchemy.orm import relationship
+
+from app.database import Base
+
+
+class ReimbursementSet(Base):
+ __tablename__ = "reimbursement_sets"
+
+ id = Column(Integer, primary_key=True, index=True)
+ name = Column(String(200), nullable=False)
+ description = Column(Text, nullable=True)
+ created_at = Column(DateTime, default=datetime.utcnow, nullable=False)
+ updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)
+
+ items = relationship(
+ "ReimbursementSetItem",
+ back_populates="reimbursement_set",
+ cascade="all, delete-orphan",
+ order_by="ReimbursementSetItem.position",
+ )
+
+
+class ReimbursementSetItem(Base):
+ __tablename__ = "reimbursement_set_items"
+ __table_args__ = (
+ UniqueConstraint("set_id", "position", name="uq_reimbursement_set_items_set_position"),
+ )
+
+ id = Column(Integer, primary_key=True, index=True)
+ set_id = Column(
+ Integer,
+ ForeignKey("reimbursement_sets.id", ondelete="CASCADE"),
+ nullable=False,
+ index=True,
+ )
+ invoice_id = Column(
+ Integer,
+ ForeignKey("invoices.id", ondelete="CASCADE"),
+ nullable=False,
+ unique=True,
+ )
+ position = Column(Integer, nullable=False)
+ created_at = Column(DateTime, default=datetime.utcnow, nullable=False)
+
+ reimbursement_set = relationship("ReimbursementSet", back_populates="items")
+ invoice = relationship("Invoice")
diff --git a/backend/app/routers/invoices.py b/backend/app/routers/invoices.py
index cba8180..2d6983d 100644
--- a/backend/app/routers/invoices.py
+++ b/backend/app/routers/invoices.py
@@ -16,6 +16,10 @@
)
from app.config import get_settings
from app.services.audit_service import log_audit_no_commit, get_client_info
+from app.services.reimbursement_service import (
+ compute_duplicate_warnings_for_invoices,
+ detect_upload_duplicate_warning,
+)
from app.rate_limit import limiter
settings = get_settings()
@@ -60,6 +64,8 @@ async def upload_invoices(
results = []
invoice_ids_to_process = []
client_info = get_client_info(request)
+ batch_seen_hashes: dict[str, str] = {}
+ batch_seen_numbers: dict[str, str] = {}
for file in files:
# Validate file type
@@ -86,6 +92,16 @@ async def upload_invoices(
))
continue
+ # Non-blocking duplicate detection (20-digit invoice number or identical SHA-256)
+ duplicate_warning = await detect_upload_duplicate_warning(
+ db=db,
+ content=content,
+ file_type=ext,
+ batch_seen_hashes=batch_seen_hashes,
+ batch_seen_numbers=batch_seen_numbers,
+ current_file_name=file.filename or "unknown",
+ )
+
# Create invoice record with UPLOADED status (not yet processed)
invoice = Invoice(
file_name=file.filename or "unknown",
@@ -113,7 +129,8 @@ async def upload_invoices(
id=invoice.id,
file_name=invoice.file_name,
status="success",
- message="上传成功,等待解析"
+ message="上传成功,等待解析",
+ duplicate_warning=duplicate_warning,
))
await db.commit()
@@ -260,9 +277,16 @@ async def list_invoices(
result = await db.execute(query)
invoices = result.scalars().all()
+ dup_warnings = await compute_duplicate_warnings_for_invoices(db, invoices)
+
+ items = []
+ for inv in invoices:
+ resp = InvoiceResponse.model_validate(inv)
+ resp.duplicate_warning = dup_warnings.get(inv.id)
+ items.append(resp)
return InvoiceListResponse(
- items=[InvoiceResponse.model_validate(inv) for inv in invoices],
+ items=items,
total=total,
page=page,
page_size=page_size
@@ -329,6 +353,8 @@ async def get_invoice(
diff_result = await db.execute(diff_query)
diffs = diff_result.scalars().all()
+ dup_warnings = await compute_duplicate_warnings_for_invoices(db, [invoice])
+
# Build response dict from invoice to avoid lazy loading issues
invoice_dict = {
"id": invoice.id,
@@ -336,6 +362,7 @@ async def get_invoice(
"file_type": invoice.file_type,
"status": invoice.status,
"owner": invoice.owner,
+ "duplicate_warning": dup_warnings.get(invoice.id),
"invoice_number": invoice.invoice_number,
"issue_date": invoice.issue_date,
"buyer_name": invoice.buyer_name,
diff --git a/backend/app/routers/reimbursement_sets.py b/backend/app/routers/reimbursement_sets.py
new file mode 100644
index 0000000..74557f8
--- /dev/null
+++ b/backend/app/routers/reimbursement_sets.py
@@ -0,0 +1,537 @@
+"""API routes for reimbursement sets CRUD, ordered membership, and validated bundle exports."""
+
+from __future__ import annotations
+
+import asyncio
+from datetime import datetime
+from decimal import Decimal
+from io import BytesIO
+from typing import Dict, List, Sequence
+from urllib.parse import quote
+
+from fastapi import APIRouter, Depends, HTTPException, Request, status
+from fastapi.responses import StreamingResponse
+from sqlalchemy import func, select
+from sqlalchemy.exc import IntegrityError
+from sqlalchemy.ext.asyncio import AsyncSession
+
+from app.config import get_settings
+from app.database import get_db
+from app.models.invoice import Invoice
+from app.models.reimbursement_set import ReimbursementSet, ReimbursementSetItem
+from app.schemas.reimbursement_set import (
+ CheckIssueResponse,
+ ReimbursementSetAddItemsRequest,
+ ReimbursementSetCreate,
+ ReimbursementSetDetailResponse,
+ ReimbursementSetItemResponse,
+ ReimbursementSetReorderRequest,
+ ReimbursementSetSummaryResponse,
+ ReimbursementSetUpdate,
+)
+from app.services.audit_service import get_client_info, log_audit_no_commit
+from app.services.reimbursement_service import (
+ SetSnapshot,
+ begin_repeatable_read,
+ build_set_excel_bytes,
+ build_set_pdf_bytes,
+ build_set_zip_bytes,
+ load_set_snapshot,
+ validate_snapshot_for_export,
+)
+
+router = APIRouter()
+
+
+def _dedupe_preserve_order(values: Sequence[int]) -> List[int]:
+ seen: set[int] = set()
+ ordered: List[int] = []
+ for val in values:
+ if val not in seen:
+ seen.add(val)
+ ordered.append(val)
+ return ordered
+
+
+def _snapshot_to_detail_response(snapshot: SetSnapshot) -> ReimbursementSetDetailResponse:
+ rset = snapshot.reimbursement_set
+ items = [
+ ReimbursementSetItemResponse(
+ position=member.position,
+ invoice_id=member.invoice.id,
+ file_name=member.invoice.file_name,
+ file_type=member.invoice.file_type,
+ invoice_number=member.invoice.invoice_number,
+ issue_date=member.invoice.issue_date,
+ buyer_name=member.invoice.buyer_name,
+ buyer_tax_id=member.invoice.buyer_tax_id,
+ seller_name=member.invoice.seller_name,
+ seller_tax_id=member.invoice.seller_tax_id,
+ item_name=member.invoice.item_name,
+ amount=member.invoice.amount,
+ tax_amount=member.invoice.tax_amount,
+ total_with_tax=member.invoice.total_with_tax,
+ status=member.invoice.status,
+ )
+ for member in snapshot.members
+ ]
+ issues = [
+ CheckIssueResponse(
+ level=issue.level,
+ code=issue.code,
+ seqs=list(issue.seqs),
+ message=issue.message,
+ suggestion=issue.suggestion,
+ )
+ for issue in snapshot.issues
+ ]
+ error_count = sum(1 for i in issues if i.level == "error")
+ warning_count = sum(1 for i in issues if i.level == "warning")
+
+ return ReimbursementSetDetailResponse(
+ id=rset.id,
+ name=rset.name,
+ description=rset.description,
+ item_count=len(items),
+ total_amount=snapshot.total_amount,
+ total_tax=snapshot.total_tax,
+ total_with_tax=snapshot.total_with_tax,
+ created_at=rset.created_at,
+ updated_at=rset.updated_at,
+ items=items,
+ issues=issues,
+ error_count=error_count,
+ warning_count=warning_count,
+ )
+
+
+async def _attach_invoices_to_set(
+ db: AsyncSession,
+ reimbursement_set: ReimbursementSet,
+ invoice_ids: Sequence[int],
+) -> None:
+ """Validate and append invoices to a reimbursement set enforcing UNIQUE(invoice_id)."""
+ unique_ids = _dedupe_preserve_order(invoice_ids)
+ if not unique_ids:
+ return
+
+ # 1. Verify every requested invoice exists
+ existing_ids = set(
+ (await db.execute(select(Invoice.id).where(Invoice.id.in_(unique_ids)))).scalars().all()
+ )
+ missing_ids = [inv_id for inv_id in unique_ids if inv_id not in existing_ids]
+ if missing_ids:
+ raise HTTPException(
+ status_code=404,
+ detail={"code": "INVOICE_NOT_FOUND", "message": f"发票不存在:{missing_ids}"},
+ )
+
+ # 2. Check existing memberships (one invoice -> at most one reimbursement set)
+ existing_links = (
+ await db.execute(
+ select(
+ ReimbursementSetItem.invoice_id,
+ ReimbursementSetItem.set_id,
+ ReimbursementSet.name,
+ )
+ .join(ReimbursementSet, ReimbursementSet.id == ReimbursementSetItem.set_id)
+ .where(ReimbursementSetItem.invoice_id.in_(unique_ids))
+ )
+ ).all()
+
+ conflicts = [
+ {"invoice_id": row.invoice_id, "set_id": row.set_id, "set_name": row.name}
+ for row in existing_links
+ if row.set_id != reimbursement_set.id
+ ]
+ if conflicts:
+ conflict_desc = "、".join(
+ f"发票 #{c['invoice_id']}(已归属「{c['set_name']}」)" for c in conflicts
+ )
+ raise HTTPException(
+ status_code=409,
+ detail={
+ "code": "INVOICE_ALREADY_ASSIGNED",
+ "message": f"以下发票已归属其他报销集,每张发票只能加入一个报销集:{conflict_desc}",
+ "conflicts": conflicts,
+ },
+ )
+
+ already_in_this_set = {row.invoice_id for row in existing_links if row.set_id == reimbursement_set.id}
+ to_add = [inv_id for inv_id in unique_ids if inv_id not in already_in_this_set]
+ if not to_add:
+ return
+
+ max_pos = (
+ await db.scalar(
+ select(func.coalesce(func.max(ReimbursementSetItem.position), 0)).where(
+ ReimbursementSetItem.set_id == reimbursement_set.id
+ )
+ )
+ ) or 0
+
+ for offset, inv_id in enumerate(to_add, start=1):
+ db.add(
+ ReimbursementSetItem(
+ set_id=reimbursement_set.id,
+ invoice_id=inv_id,
+ position=max_pos + offset,
+ )
+ )
+ reimbursement_set.updated_at = datetime.utcnow()
+
+
+async def _compact_positions(db: AsyncSession, set_id: int) -> None:
+ """Re-number remaining positions 1..N without transient UNIQUE(set_id, position) collisions."""
+ items = (
+ await db.execute(
+ select(ReimbursementSetItem)
+ .where(ReimbursementSetItem.set_id == set_id)
+ .order_by(ReimbursementSetItem.position.asc(), ReimbursementSetItem.id.asc())
+ )
+ ).scalars().all()
+ if not items:
+ return
+ # Two-phase update avoids unique constraint collisions on PostgreSQL
+ for idx, item in enumerate(items, start=1):
+ item.position = -idx
+ await db.flush()
+ for idx, item in enumerate(items, start=1):
+ item.position = idx
+ await db.flush()
+
+
+@router.get("", response_model=List[ReimbursementSetSummaryResponse])
+async def list_reimbursement_sets(db: AsyncSession = Depends(get_db)):
+ """获取所有报销集列表(含张数与金额汇总)"""
+ sets = (
+ await db.execute(select(ReimbursementSet).order_by(ReimbursementSet.created_at.desc()))
+ ).scalars().all()
+ if not sets:
+ return []
+
+ agg_rows = (
+ await db.execute(
+ select(
+ ReimbursementSetItem.set_id,
+ func.count(ReimbursementSetItem.id).label("item_count"),
+ func.coalesce(func.sum(Invoice.amount), 0).label("total_amount"),
+ func.coalesce(func.sum(Invoice.tax_amount), 0).label("total_tax"),
+ func.coalesce(func.sum(Invoice.total_with_tax), 0).label("total_with_tax"),
+ )
+ .join(Invoice, Invoice.id == ReimbursementSetItem.invoice_id)
+ .group_by(ReimbursementSetItem.set_id)
+ )
+ ).all()
+ stats_map: Dict[int, tuple[int, Decimal, Decimal, Decimal]] = {
+ row.set_id: (
+ int(row.item_count or 0),
+ Decimal(str(row.total_amount or 0)),
+ Decimal(str(row.total_tax or 0)),
+ Decimal(str(row.total_with_tax or 0)),
+ )
+ for row in agg_rows
+ }
+
+ results: List[ReimbursementSetSummaryResponse] = []
+ for rset in sets:
+ cnt, total_amt, total_tax, total_wt = stats_map.get(
+ rset.id, (0, Decimal("0.00"), Decimal("0.00"), Decimal("0.00"))
+ )
+ results.append(
+ ReimbursementSetSummaryResponse(
+ id=rset.id,
+ name=rset.name,
+ description=rset.description,
+ item_count=cnt,
+ total_amount=total_amt,
+ total_tax=total_tax,
+ total_with_tax=total_wt,
+ created_at=rset.created_at,
+ updated_at=rset.updated_at,
+ )
+ )
+ return results
+
+
+@router.post("", response_model=ReimbursementSetDetailResponse, status_code=status.HTTP_201_CREATED)
+async def create_reimbursement_set(
+ payload: ReimbursementSetCreate,
+ request: Request,
+ db: AsyncSession = Depends(get_db),
+):
+ """创建报销集(支持空集或直接带 invoice_ids 创建)"""
+ name = payload.name.strip()
+ if not name:
+ raise HTTPException(status_code=400, detail="报销集名称不能为空")
+
+ rset = ReimbursementSet(name=name, description=payload.description)
+ db.add(rset)
+ await db.flush()
+
+ try:
+ if payload.invoice_ids:
+ await _attach_invoices_to_set(db, rset, payload.invoice_ids)
+
+ client_info = get_client_info(request)
+ await log_audit_no_commit(
+ db=db,
+ entity_type="reimbursement_set",
+ entity_id=rset.id,
+ action="create",
+ new_value={"name": rset.name, "invoice_ids": payload.invoice_ids},
+ ip_address=client_info.get("ip_address"),
+ user_agent=client_info.get("user_agent"),
+ )
+ await db.commit()
+ except IntegrityError as exc:
+ await db.rollback()
+ raise HTTPException(
+ status_code=409,
+ detail={"code": "INVOICE_ALREADY_ASSIGNED", "message": "所选发票已归属其他报销集"},
+ ) from exc
+ except HTTPException:
+ await db.rollback()
+ raise
+
+ snapshot = await load_set_snapshot(db, rset.id)
+ return _snapshot_to_detail_response(snapshot)
+
+
+@router.get("/{set_id}", response_model=ReimbursementSetDetailResponse)
+async def get_reimbursement_set(set_id: int, db: AsyncSession = Depends(get_db)):
+ """获取报销集详情、有序成员列表、金额汇总及实时校验结果"""
+ snapshot = await load_set_snapshot(db, set_id)
+ return _snapshot_to_detail_response(snapshot)
+
+
+@router.patch("/{set_id}", response_model=ReimbursementSetSummaryResponse)
+async def update_reimbursement_set(
+ set_id: int,
+ payload: ReimbursementSetUpdate,
+ request: Request,
+ db: AsyncSession = Depends(get_db),
+):
+ """更新报销集名称或说明"""
+ rset = (
+ await db.execute(select(ReimbursementSet).where(ReimbursementSet.id == set_id))
+ ).scalar_one_or_none()
+ if not rset:
+ raise HTTPException(status_code=404, detail="报销集不存在")
+
+ old_value = {"name": rset.name, "description": rset.description}
+ data = payload.model_dump(exclude_unset=True)
+ if "name" in data:
+ cleaned_name = (data["name"] or "").strip()
+ if not cleaned_name:
+ raise HTTPException(status_code=400, detail="报销集名称不能为空")
+ rset.name = cleaned_name
+ if "description" in data:
+ rset.description = data["description"]
+ rset.updated_at = datetime.utcnow()
+
+ client_info = get_client_info(request)
+ await log_audit_no_commit(
+ db=db,
+ entity_type="reimbursement_set",
+ entity_id=set_id,
+ action="update",
+ old_value=old_value,
+ new_value={"name": rset.name, "description": rset.description},
+ ip_address=client_info.get("ip_address"),
+ user_agent=client_info.get("user_agent"),
+ )
+ await db.commit()
+
+ snapshot = await load_set_snapshot(db, set_id)
+ return ReimbursementSetSummaryResponse(
+ id=rset.id,
+ name=rset.name,
+ description=rset.description,
+ item_count=len(snapshot.members),
+ total_amount=snapshot.total_amount,
+ total_tax=snapshot.total_tax,
+ total_with_tax=snapshot.total_with_tax,
+ created_at=rset.created_at,
+ updated_at=rset.updated_at,
+ )
+
+
+@router.delete("/{set_id}")
+async def delete_reimbursement_set(
+ set_id: int,
+ request: Request,
+ db: AsyncSession = Depends(get_db),
+):
+ """删除报销集(仅解除关联,不删除发票本身)"""
+ rset = (
+ await db.execute(select(ReimbursementSet).where(ReimbursementSet.id == set_id))
+ ).scalar_one_or_none()
+ if not rset:
+ raise HTTPException(status_code=404, detail="报销集不存在")
+
+ client_info = get_client_info(request)
+ await log_audit_no_commit(
+ db=db,
+ entity_type="reimbursement_set",
+ entity_id=set_id,
+ action="delete",
+ old_value={"name": rset.name},
+ ip_address=client_info.get("ip_address"),
+ user_agent=client_info.get("user_agent"),
+ )
+ await db.delete(rset)
+ await db.commit()
+ return {"message": "报销集已删除"}
+
+
+@router.post("/{set_id}/items", response_model=ReimbursementSetDetailResponse)
+async def add_items_to_reimbursement_set(
+ set_id: int,
+ payload: ReimbursementSetAddItemsRequest,
+ db: AsyncSession = Depends(get_db),
+):
+ """批量向报销集加入发票(一票一集,冲突返回 409)"""
+ rset = (
+ await db.execute(select(ReimbursementSet).where(ReimbursementSet.id == set_id))
+ ).scalar_one_or_none()
+ if not rset:
+ raise HTTPException(status_code=404, detail="报销集不存在")
+
+ try:
+ await _attach_invoices_to_set(db, rset, payload.invoice_ids)
+ await db.commit()
+ except IntegrityError as exc:
+ await db.rollback()
+ raise HTTPException(
+ status_code=409,
+ detail={"code": "INVOICE_ALREADY_ASSIGNED", "message": "所选发票已归属其他报销集"},
+ ) from exc
+ except HTTPException:
+ await db.rollback()
+ raise
+
+ snapshot = await load_set_snapshot(db, set_id)
+ return _snapshot_to_detail_response(snapshot)
+
+
+@router.delete("/{set_id}/items/{invoice_id}", response_model=ReimbursementSetDetailResponse)
+async def remove_item_from_reimbursement_set(
+ set_id: int,
+ invoice_id: int,
+ db: AsyncSession = Depends(get_db),
+):
+ """从报销集中移出单张发票"""
+ rset = (
+ await db.execute(select(ReimbursementSet).where(ReimbursementSet.id == set_id))
+ ).scalar_one_or_none()
+ if not rset:
+ raise HTTPException(status_code=404, detail="报销集不存在")
+
+ item = (
+ await db.execute(
+ select(ReimbursementSetItem).where(
+ ReimbursementSetItem.set_id == set_id,
+ ReimbursementSetItem.invoice_id == invoice_id,
+ )
+ )
+ ).scalar_one_or_none()
+ if not item:
+ raise HTTPException(status_code=404, detail="该发票不在此报销集中")
+
+ await db.delete(item)
+ await db.flush()
+ await _compact_positions(db, set_id)
+ rset.updated_at = datetime.utcnow()
+ await db.commit()
+
+ snapshot = await load_set_snapshot(db, set_id)
+ return _snapshot_to_detail_response(snapshot)
+
+
+@router.put("/{set_id}/items/order", response_model=ReimbursementSetDetailResponse)
+async def reorder_reimbursement_set_items(
+ set_id: int,
+ payload: ReimbursementSetReorderRequest,
+ db: AsyncSession = Depends(get_db),
+):
+ """调整报销集内发票顺序"""
+ rset = (
+ await db.execute(select(ReimbursementSet).where(ReimbursementSet.id == set_id))
+ ).scalar_one_or_none()
+ if not rset:
+ raise HTTPException(status_code=404, detail="报销集不存在")
+
+ items = (
+ await db.execute(
+ select(ReimbursementSetItem).where(ReimbursementSetItem.set_id == set_id)
+ )
+ ).scalars().all()
+ by_invoice_id = {item.invoice_id: item for item in items}
+
+ requested = payload.invoice_ids
+ if len(requested) != len(set(requested)) or set(requested) != set(by_invoice_id.keys()):
+ raise HTTPException(
+ status_code=400,
+ detail="排序列表必须与当前报销集的全部发票ID完全一致且不可重复",
+ )
+
+ # Two-phase position update prevents transient UNIQUE(set_id, position) conflicts
+ for idx, inv_id in enumerate(requested, start=1):
+ by_invoice_id[inv_id].position = -idx
+ await db.flush()
+ for idx, inv_id in enumerate(requested, start=1):
+ by_invoice_id[inv_id].position = idx
+ rset.updated_at = datetime.utcnow()
+ await db.commit()
+
+ snapshot = await load_set_snapshot(db, set_id)
+ return _snapshot_to_detail_response(snapshot)
+
+
+@router.get("/{set_id}/export/excel")
+async def export_reimbursement_set_excel(set_id: int, db: AsyncSession = Depends(get_db)):
+ """导出报销集 3-Sheet 报销单 Excel(导出前在 REPEATABLE READ 快照内校验)"""
+ await begin_repeatable_read(db)
+ snapshot = await load_set_snapshot(db, set_id)
+ validate_snapshot_for_export(snapshot, get_settings())
+
+ xlsx_bytes = await asyncio.to_thread(build_set_excel_bytes, snapshot)
+ filename = quote(f"{snapshot.reimbursement_set.name}_报销单.xlsx")
+ return StreamingResponse(
+ BytesIO(xlsx_bytes),
+ media_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
+ headers={"Content-Disposition": f"attachment; filename*=UTF-8''{filename}"},
+ )
+
+
+@router.get("/{set_id}/export/pdf")
+async def export_reimbursement_set_pdf(set_id: int, db: AsyncSession = Depends(get_db)):
+ """导出报销集合并 PDF(导出前在 REPEATABLE READ 快照内校验)"""
+ await begin_repeatable_read(db)
+ snapshot = await load_set_snapshot(db, set_id)
+ validate_snapshot_for_export(snapshot, get_settings())
+
+ pdf_bytes = await asyncio.to_thread(build_set_pdf_bytes, snapshot)
+ filename = quote(f"{snapshot.reimbursement_set.name}_合并原件.pdf")
+ return StreamingResponse(
+ BytesIO(pdf_bytes),
+ media_type="application/pdf",
+ headers={"Content-Disposition": f"attachment; filename*=UTF-8''{filename}"},
+ )
+
+
+@router.get("/{set_id}/export/zip")
+async def export_reimbursement_set_zip(set_id: int, db: AsyncSession = Depends(get_db)):
+ """导出报销集 ZIP 打包(含按序命名原件 + 3-Sheet Excel + 合并 PDF)"""
+ await begin_repeatable_read(db)
+ snapshot = await load_set_snapshot(db, set_id)
+ validate_snapshot_for_export(snapshot, get_settings())
+
+ zip_bytes = await asyncio.to_thread(build_set_zip_bytes, snapshot)
+ filename = quote(f"{snapshot.reimbursement_set.name}_报销资料包.zip")
+ return StreamingResponse(
+ BytesIO(zip_bytes),
+ media_type="application/zip",
+ headers={"Content-Disposition": f"attachment; filename*=UTF-8''{filename}"},
+ )
diff --git a/backend/app/schemas/invoice.py b/backend/app/schemas/invoice.py
index c000362..73d72b7 100644
--- a/backend/app/schemas/invoice.py
+++ b/backend/app/schemas/invoice.py
@@ -48,6 +48,7 @@ class InvoiceResponse(InvoiceBase):
file_type: str
status: InvoiceStatus
owner: Optional[str] = None
+ duplicate_warning: Optional[str] = None
created_at: datetime
updated_at: datetime
@@ -153,6 +154,7 @@ class UploadResponse(BaseModel):
file_name: str
status: str
message: str
+ duplicate_warning: Optional[str] = None
class ResolveDiffRequest(BaseModel):
diff --git a/backend/app/schemas/reimbursement_set.py b/backend/app/schemas/reimbursement_set.py
new file mode 100644
index 0000000..c6ff805
--- /dev/null
+++ b/backend/app/schemas/reimbursement_set.py
@@ -0,0 +1,73 @@
+"""Pydantic schemas for reimbursement sets, validation issues, and member operations."""
+
+from datetime import date, datetime
+from decimal import Decimal
+from typing import List, Optional
+
+from pydantic import BaseModel, Field
+
+from app.schemas.invoice import InvoiceStatus
+
+
+class CheckIssueResponse(BaseModel):
+ level: str
+ code: str
+ seqs: List[int]
+ message: str
+ suggestion: str = ""
+
+
+class ReimbursementSetCreate(BaseModel):
+ name: str = Field(..., min_length=1, max_length=200, description="报销集名称")
+ description: Optional[str] = Field(None, max_length=2000, description="备注说明")
+ invoice_ids: List[int] = Field(default_factory=list, description="初始加入的发票ID列表")
+
+
+class ReimbursementSetUpdate(BaseModel):
+ name: Optional[str] = Field(None, min_length=1, max_length=200, description="报销集名称")
+ description: Optional[str] = Field(None, max_length=2000, description="备注说明")
+
+
+class ReimbursementSetAddItemsRequest(BaseModel):
+ invoice_ids: List[int] = Field(..., min_length=1, description="要加入报销集的发票ID列表")
+
+
+class ReimbursementSetReorderRequest(BaseModel):
+ invoice_ids: List[int] = Field(..., description="按新顺序排列的完整发票ID列表")
+
+
+class ReimbursementSetSummaryResponse(BaseModel):
+ id: int
+ name: str
+ description: Optional[str] = None
+ item_count: int = 0
+ total_amount: Decimal = Decimal("0.00")
+ total_tax: Decimal = Decimal("0.00")
+ total_with_tax: Decimal = Decimal("0.00")
+ created_at: datetime
+ updated_at: datetime
+
+
+class ReimbursementSetItemResponse(BaseModel):
+ position: int
+ invoice_id: int
+ file_name: str
+ file_type: str
+ invoice_number: Optional[str] = None
+ issue_date: Optional[date] = None
+ buyer_name: Optional[str] = None
+ buyer_tax_id: Optional[str] = None
+ seller_name: Optional[str] = None
+ seller_tax_id: Optional[str] = None
+ item_name: Optional[str] = None
+ amount: Optional[Decimal] = None
+ tax_amount: Optional[Decimal] = None
+ total_with_tax: Optional[Decimal] = None
+ status: InvoiceStatus
+
+
+class ReimbursementSetDetailResponse(ReimbursementSetSummaryResponse):
+ items: List[ReimbursementSetItemResponse] = Field(default_factory=list)
+ issues: List[CheckIssueResponse] = Field(default_factory=list)
+ error_count: int = 0
+ warning_count: int = 0
diff --git a/backend/app/services/reimbursement_service.py b/backend/app/services/reimbursement_service.py
new file mode 100644
index 0000000..9448cb5
--- /dev/null
+++ b/backend/app/services/reimbursement_service.py
@@ -0,0 +1,440 @@
+"""Reimbursement set business logic, KnownLedger assembly, and validated exports."""
+
+from __future__ import annotations
+
+import hashlib
+import re
+import zipfile
+from dataclasses import asdict, dataclass
+from decimal import Decimal
+from io import BytesIO
+from pathlib import PurePosixPath
+from typing import Dict, List, Optional, Sequence, Tuple
+
+from fastapi import HTTPException
+from sqlalchemy import and_, func, or_, select, text
+from sqlalchemy.ext.asyncio import AsyncSession
+
+from app.config import Settings
+from app.models.invoice import Invoice, InvoiceStatus, OcrResult
+from app.models.reimbursement_set import ReimbursementSet, ReimbursementSetItem
+from invoice_core.checks import run_checks
+from invoice_core.export.excel import build_reimbursement_excel
+from invoice_core.export.pdf import CorruptSourceFileError, MergeSource, merge_sources_to_pdf
+from invoice_core.extract import get_field_extractor
+from invoice_core.models import CheckContext, CheckIssue, InvoiceRecord, KnownLedger
+from invoice_core.parsers.pdf_text import extract_pdf_text_layer
+
+_DIGITAL_20_RE = re.compile(r"^\d{20}$")
+_UNSAFE_FILENAME_RE = re.compile(r'[<>:"/\\|?*\x00-\x1f]+')
+
+
+@dataclass
+class SetMemberRow:
+ position: int
+ seq: int
+ invoice: Invoice
+ raw_text: Optional[str]
+ file_sha256: Optional[str]
+
+
+@dataclass
+class SetSnapshot:
+ reimbursement_set: ReimbursementSet
+ members: List[SetMemberRow]
+ records: List[InvoiceRecord]
+ issues: List[CheckIssue]
+ total_amount: Decimal
+ total_tax: Decimal
+ total_with_tax: Decimal
+ total_bytes: int
+
+
+def compute_sha256(data: Optional[bytes]) -> Optional[str]:
+ if not data:
+ return None
+ return hashlib.sha256(data).hexdigest()
+
+
+def sanitize_zip_filename(file_name: Optional[str], fallback_ext: str = "") -> str:
+ """Return a zip-slip-safe flat filename containing no path separators or '..'."""
+ raw = (file_name or "invoice").replace("\\", "/")
+ base = PurePosixPath(raw).name
+ base = base.replace("..", "_")
+ base = _UNSAFE_FILENAME_RE.sub("_", base).strip(" ._")
+ if not base:
+ base = "invoice"
+
+ ext = (fallback_ext or "").strip().lower().lstrip(".")
+ if ext and not base.lower().endswith(f".{ext}"):
+ stem = base[:72]
+ return f"{stem}.{ext}"
+
+ if len(base) > 80:
+ if "." in base:
+ stem, suffix = base.rsplit(".", 1)
+ base = f"{stem[:72]}.{suffix[:7]}"
+ else:
+ base = base[:80]
+ return base
+
+
+def extract_candidate_digital_number(content: bytes, file_type: str) -> Optional[str]:
+ """Best-effort fast text-layer extraction of a 20-digit e-invoice number on upload."""
+ if file_type.lower() != "pdf" or not content:
+ return None
+ try:
+ text_layer, has_useful = extract_pdf_text_layer(content)
+ if not has_useful or not text_layer:
+ return None
+ fields = get_field_extractor().extract_fields(text_layer)
+ candidate = (fields.get("invoice_number") or "").strip()
+ if _DIGITAL_20_RE.match(candidate):
+ return candidate
+ except Exception:
+ return None
+ return None
+
+
+async def detect_upload_duplicate_warning(
+ db: AsyncSession,
+ content: bytes,
+ file_type: str,
+ batch_seen_hashes: Dict[str, str],
+ batch_seen_numbers: Dict[str, str],
+ current_file_name: str,
+) -> Optional[str]:
+ """Check whether an uploaded file duplicates an existing invoice (non-blocking warning)."""
+ file_hash = compute_sha256(content)
+ candidate_number = extract_candidate_digital_number(content, file_type)
+
+ # 1. Check same-batch upload duplicates first
+ if file_hash and file_hash in batch_seen_hashes:
+ prev_name = batch_seen_hashes[file_hash]
+ return f"疑似重复:文件内容与本批次已上传文件「{prev_name}」完全相同"
+
+ if candidate_number and candidate_number in batch_seen_numbers:
+ prev_name = batch_seen_numbers[candidate_number]
+ return f"疑似重复:20位发票号码 {candidate_number} 与本批次已上传文件「{prev_name}」相同"
+
+ # 2. Check existing invoices in DB by 20-digit invoice_number
+ if candidate_number:
+ existing_num_row = (
+ await db.execute(
+ select(Invoice.id, Invoice.file_name)
+ .where(Invoice.invoice_number == candidate_number)
+ .order_by(Invoice.id.asc())
+ .limit(1)
+ )
+ ).first()
+ if existing_num_row:
+ return (
+ f"疑似重复:检测到已有发票 #{existing_num_row.id}({existing_num_row.file_name})"
+ f"具有相同的20位发票号码 {candidate_number}"
+ )
+
+ # 3. Check existing invoices in DB by file SHA-256 (pre-filter by byte length)
+ if file_hash:
+ content_len = len(content)
+ same_size_rows = (
+ await db.execute(
+ select(Invoice.id, Invoice.file_name, Invoice.file_data).where(
+ func.length(Invoice.file_data) == content_len
+ )
+ )
+ ).all()
+ for row in same_size_rows:
+ if row.file_data and compute_sha256(row.file_data) == file_hash:
+ return f"疑似重复:文件内容与已有发票 #{row.id}({row.file_name})完全相同"
+
+ if file_hash:
+ batch_seen_hashes[file_hash] = current_file_name
+ if candidate_number:
+ batch_seen_numbers[candidate_number] = current_file_name
+ return None
+
+
+async def compute_duplicate_warnings_for_invoices(
+ db: AsyncSession,
+ invoices: Sequence[Invoice],
+) -> Dict[int, str]:
+ """Return a map of invoice_id -> duplicate_warning for 20-digit numbers appearing multiple times."""
+ numbers = {
+ inv.invoice_number.strip()
+ for inv in invoices
+ if inv.invoice_number and _DIGITAL_20_RE.match(inv.invoice_number.strip())
+ }
+ if not numbers:
+ return {}
+
+ rows = (
+ await db.execute(
+ select(Invoice.id, Invoice.invoice_number, Invoice.file_name)
+ .where(Invoice.invoice_number.in_(numbers))
+ .order_by(Invoice.id.asc())
+ )
+ ).all()
+
+ by_number: Dict[str, List[Tuple[int, str]]] = {}
+ for inv_id, inv_num, fname in rows:
+ if inv_num:
+ by_number.setdefault(inv_num.strip(), []).append((inv_id, fname))
+
+ warnings: Dict[int, str] = {}
+ for inv in invoices:
+ if not inv.invoice_number:
+ continue
+ num = inv.invoice_number.strip()
+ peers = by_number.get(num, [])
+ others = [(pid, pfile) for pid, pfile in peers if pid != inv.id]
+ if others:
+ other_labels = "、".join(f"#{pid}({pfile})" for pid, pfile in others[:3])
+ warnings[inv.id] = f"疑似重复:20位发票号码 {num} 与已有发票 {other_labels} 重复"
+ return warnings
+
+
+async def begin_repeatable_read(db: AsyncSession) -> None:
+ """Use REPEATABLE READ isolation on PostgreSQL so export reads a single consistent snapshot."""
+ bind = db.get_bind()
+ dialect_name = getattr(getattr(bind, "dialect", None), "name", "")
+ if dialect_name == "postgresql":
+ await db.execute(text("SET TRANSACTION ISOLATION LEVEL REPEATABLE READ"))
+
+
+def _invoice_to_record(member: SetMemberRow) -> InvoiceRecord:
+ inv = member.invoice
+ return InvoiceRecord(
+ seq=member.seq,
+ invoice_number=inv.invoice_number,
+ invoice_code=None,
+ invoice_type="电子发票",
+ issue_date=inv.issue_date,
+ buyer_name=inv.buyer_name,
+ buyer_tax_id=inv.buyer_tax_id,
+ seller_name=inv.seller_name,
+ seller_tax_id=inv.seller_tax_id,
+ item_name=inv.item_name,
+ amount=Decimal(inv.amount) if inv.amount is not None else None,
+ tax_amount=Decimal(inv.tax_amount) if inv.tax_amount is not None else None,
+ tax_rate=inv.tax_rate,
+ total_with_tax=Decimal(inv.total_with_tax) if inv.total_with_tax is not None else None,
+ reimbursable_amount=Decimal(inv.total_with_tax) if inv.total_with_tax is not None else None,
+ file_name=inv.file_name,
+ file_format=(inv.file_type or "").upper(),
+ file_sha256=member.file_sha256,
+ raw_text=member.raw_text,
+ invoice_id=inv.id,
+ has_ocr_text=True,
+ )
+
+
+async def _build_known_ledger(db: AsyncSession, set_id: int, member_invoice_ids: Sequence[int]) -> KnownLedger:
+ """Build KnownLedger from invoices outside this set that are in other sets or already reimbursed."""
+ stmt = (
+ select(
+ Invoice.id,
+ Invoice.invoice_number,
+ Invoice.seller_tax_id,
+ Invoice.file_name,
+ Invoice.file_data,
+ Invoice.status,
+ ReimbursementSet.id.label("other_set_id"),
+ ReimbursementSet.name.label("other_set_name"),
+ )
+ .outerjoin(ReimbursementSetItem, ReimbursementSetItem.invoice_id == Invoice.id)
+ .outerjoin(ReimbursementSet, ReimbursementSet.id == ReimbursementSetItem.set_id)
+ .where(
+ or_(
+ and_(
+ ReimbursementSetItem.set_id.is_not(None),
+ ReimbursementSetItem.set_id != set_id,
+ ),
+ Invoice.status == InvoiceStatus.REIMBURSED,
+ )
+ )
+ )
+ if member_invoice_ids:
+ stmt = stmt.where(Invoice.id.notin_(member_invoice_ids))
+
+ rows = (await db.execute(stmt)).all()
+
+ numbers: Dict[str, str] = {}
+ number_seller: Dict[Tuple[str, str], str] = {}
+ sha256_map: Dict[str, str] = {}
+
+ for row in rows:
+ if row.other_set_id is not None and row.other_set_id != set_id:
+ label = f"报销集「{row.other_set_name}」/ 发票 #{row.id}"
+ else:
+ label = f"已报销发票 #{row.id}({row.file_name})"
+
+ num = (row.invoice_number or "").strip()
+ if num:
+ if _DIGITAL_20_RE.match(num):
+ numbers.setdefault(num, label)
+ elif row.seller_tax_id:
+ number_seller.setdefault((num, row.seller_tax_id.strip().upper()), label)
+
+ digest = compute_sha256(row.file_data)
+ if digest:
+ sha256_map.setdefault(digest, label)
+
+ return KnownLedger(
+ numbers=numbers,
+ number_seller=number_seller,
+ sha256=sha256_map,
+ )
+
+
+async def load_set_snapshot(db: AsyncSession, set_id: int) -> SetSnapshot:
+ """Unified ordered loader ensuring totals, checks, Excel, PDF, and ZIP stay 100% consistent."""
+ reimbursement_set = (
+ await db.execute(select(ReimbursementSet).where(ReimbursementSet.id == set_id))
+ ).scalar_one_or_none()
+ if not reimbursement_set:
+ raise HTTPException(status_code=404, detail="报销集不存在")
+
+ rows = (
+ await db.execute(
+ select(ReimbursementSetItem, Invoice, OcrResult.raw_text)
+ .join(Invoice, Invoice.id == ReimbursementSetItem.invoice_id)
+ .outerjoin(OcrResult, OcrResult.invoice_id == Invoice.id)
+ .where(ReimbursementSetItem.set_id == set_id)
+ .order_by(ReimbursementSetItem.position.asc(), ReimbursementSetItem.id.asc())
+ )
+ ).all()
+
+ members: List[SetMemberRow] = []
+ records: List[InvoiceRecord] = []
+ total_amount = Decimal("0.00")
+ total_tax = Decimal("0.00")
+ total_with_tax = Decimal("0.00")
+ total_bytes = 0
+
+ for seq_idx, (item, invoice, raw_text) in enumerate(rows, start=1):
+ digest = compute_sha256(invoice.file_data)
+ member = SetMemberRow(
+ position=item.position,
+ seq=seq_idx,
+ invoice=invoice,
+ raw_text=raw_text,
+ file_sha256=digest,
+ )
+ members.append(member)
+ records.append(_invoice_to_record(member))
+ total_amount += Decimal(invoice.amount) if invoice.amount is not None else Decimal("0.00")
+ total_tax += Decimal(invoice.tax_amount) if invoice.tax_amount is not None else Decimal("0.00")
+ total_with_tax += (
+ Decimal(invoice.total_with_tax) if invoice.total_with_tax is not None else Decimal("0.00")
+ )
+ total_bytes += len(invoice.file_data) if invoice.file_data else 0
+
+ member_invoice_ids = [m.invoice.id for m in members]
+ known = await _build_known_ledger(db, set_id, member_invoice_ids)
+ issues = run_checks(records, ctx=CheckContext(), known=known)
+
+ return SetSnapshot(
+ reimbursement_set=reimbursement_set,
+ members=members,
+ records=records,
+ issues=issues,
+ total_amount=total_amount,
+ total_tax=total_tax,
+ total_with_tax=total_with_tax,
+ total_bytes=total_bytes,
+ )
+
+
+def validate_snapshot_for_export(snapshot: SetSnapshot, settings: Settings) -> None:
+ """Enforce empty-set, safety limits (413), and blocking error checks (409)."""
+ if not snapshot.members:
+ raise HTTPException(
+ status_code=400,
+ detail={"code": "EMPTY_SET", "message": "报销集为空,请先加入发票后再导出"},
+ )
+
+ if len(snapshot.members) > settings.reimbursement_export_max_items:
+ raise HTTPException(
+ status_code=413,
+ detail={
+ "code": "EXPORT_LIMIT_EXCEEDED",
+ "message": (
+ f"单次导出发票数量({len(snapshot.members)} 张)超过安全上限"
+ f"(最多 {settings.reimbursement_export_max_items} 张),请分批导出"
+ ),
+ },
+ )
+
+ if snapshot.total_bytes > settings.reimbursement_export_max_bytes:
+ max_mb = max(1, settings.reimbursement_export_max_bytes // (1024 * 1024))
+ raise HTTPException(
+ status_code=413,
+ detail={
+ "code": "EXPORT_SIZE_EXCEEDED",
+ "message": f"报销集原件总大小超过安全上限({max_mb}MB),请拆分报销集后导出",
+ },
+ )
+
+ blocking_errors = [issue for issue in snapshot.issues if issue.level == "error"]
+ if blocking_errors:
+ raise HTTPException(
+ status_code=409,
+ detail={
+ "code": "VALIDATION_BLOCKED",
+ "message": f"存在 {len(blocking_errors)} 项阻断性校验错误,请先处理冲突发票后再导出",
+ "issues": [asdict(issue) for issue in snapshot.issues],
+ },
+ )
+
+
+def build_set_excel_bytes(snapshot: SetSnapshot) -> bytes:
+ return build_reimbursement_excel(
+ snapshot.records,
+ snapshot.issues,
+ title="报销单",
+ set_name=snapshot.reimbursement_set.name,
+ )
+
+
+def build_set_pdf_bytes(snapshot: SetSnapshot) -> bytes:
+ sources = [
+ MergeSource(
+ data=member.invoice.file_data or b"",
+ file_type=member.invoice.file_type or "",
+ file_name=member.invoice.file_name or f"invoice_{member.seq}",
+ )
+ for member in snapshot.members
+ ]
+ try:
+ return merge_sources_to_pdf(sources, dpi=200, jpeg_quality=85)
+ except CorruptSourceFileError as exc:
+ raise HTTPException(
+ status_code=422,
+ detail={
+ "code": "CORRUPT_SOURCE_FILE",
+ "message": f"原件缺失或损坏,无法生成合并 PDF:{exc}",
+ },
+ ) from exc
+
+
+def build_set_zip_bytes(snapshot: SetSnapshot) -> bytes:
+ excel_bytes = build_set_excel_bytes(snapshot)
+ pdf_bytes = build_set_pdf_bytes(snapshot)
+
+ buf = BytesIO()
+ with zipfile.ZipFile(buf, mode="w", compression=zipfile.ZIP_DEFLATED) as zf:
+ zf.writestr("报销单.xlsx", excel_bytes)
+ zf.writestr("合并原件.pdf", pdf_bytes)
+ for member in snapshot.members:
+ if not member.invoice.file_data:
+ raise HTTPException(
+ status_code=422,
+ detail={
+ "code": "CORRUPT_SOURCE_FILE",
+ "message": f"序号 {member.seq} 发票原件缺失:{member.invoice.file_name}",
+ },
+ )
+ safe_name = sanitize_zip_filename(member.invoice.file_name, member.invoice.file_type)
+ zf.writestr(f"originals/{member.seq:02d}_{safe_name}", member.invoice.file_data)
+
+ return buf.getvalue()
diff --git a/backend/tests/test_reimbursement_sets.py b/backend/tests/test_reimbursement_sets.py
new file mode 100644
index 0000000..f673974
--- /dev/null
+++ b/backend/tests/test_reimbursement_sets.py
@@ -0,0 +1,616 @@
+"""Integration tests for reimbursement sets CRUD, upload duplicate hints, and validated exports."""
+
+from __future__ import annotations
+
+import zipfile
+from datetime import date
+from decimal import Decimal
+from io import BytesIO
+from typing import Any, Optional
+
+import openpyxl
+import pypdfium2 as pdfium
+import pytest
+from fastapi import FastAPI
+from fastapi.testclient import TestClient
+from PIL import Image
+from sqlalchemy import create_engine, event
+from sqlalchemy.orm import Session, sessionmaker
+from sqlalchemy.pool import StaticPool
+
+import app.config as config_module
+from app.database import Base, get_db
+from app.models.invoice import Invoice, InvoiceStatus
+from app.models.reimbursement_set import ReimbursementSet, ReimbursementSetItem # noqa: F401
+from app.rate_limit import limiter
+from app.routers import invoices as invoices_router
+from app.routers import reimbursement_sets as sets_router
+from invoice_core.export.excel import amount_to_chinese_upper
+from invoice_core.parsers.pdf_text import render_pdf_pages
+
+NUM_1 = "00000000000000000001"
+NUM_2 = "00000000000000000002"
+NUM_3 = "00000000000000000003"
+
+
+class _SyncToAsyncSession:
+ """Minimal AsyncSession adapter over in-memory SQLite Session for dependency-free tests."""
+
+ def __init__(self, sync_session: Session) -> None:
+ self._sync = sync_session
+
+ def add(self, instance: Any) -> None:
+ self._sync.add(instance)
+
+ def get_bind(self):
+ return self._sync.get_bind()
+
+ async def execute(self, statement: Any, *args: Any, **kwargs: Any):
+ return self._sync.execute(statement, *args, **kwargs)
+
+ async def scalar(self, statement: Any, *args: Any, **kwargs: Any):
+ return self._sync.scalar(statement, *args, **kwargs)
+
+ async def flush(self) -> None:
+ self._sync.flush()
+
+ async def commit(self) -> None:
+ self._sync.commit()
+
+ async def rollback(self) -> None:
+ self._sync.rollback()
+
+ async def refresh(self, instance: Any) -> None:
+ self._sync.refresh(instance)
+
+ async def delete(self, instance: Any) -> None:
+ self._sync.delete(instance)
+
+ async def close(self) -> None:
+ self._sync.close()
+
+
+def _make_colored_pdf(color: tuple[int, int, int]) -> bytes:
+ doc = pdfium.PdfDocument.new()
+ try:
+ jbuf = BytesIO()
+ Image.new("RGB", (300, 400), color).save(jbuf, format="JPEG", quality=90)
+ jbuf.seek(0)
+ page = doc.new_page(300, 400)
+ try:
+ pimg = pdfium.PdfImage.new(doc)
+ pimg.load_jpeg(jbuf, inline=True, autoclose=False)
+ pimg.set_matrix(pdfium.PdfMatrix(300, 0, 0, 400, 0, 0))
+ page.insert_obj(pimg)
+ page.gen_content()
+ finally:
+ page.close()
+ out = BytesIO()
+ doc.save(out)
+ return out.getvalue()
+ finally:
+ doc.close()
+
+
+def _make_synthetic_text_pdf(lines: list[str]) -> bytes:
+ """Build a valid single-page PDF with an embedded ToUnicode text layer."""
+ unique_chars: list[str] = []
+ char_to_byte: dict[str, int] = {}
+ for line in lines:
+ for ch in line:
+ if ch not in char_to_byte:
+ char_to_byte[ch] = len(unique_chars) + 1
+ unique_chars.append(ch)
+
+ bfchar_lines = [f"<{char_to_byte[ch]:02X}> <{ord(ch):04X}>" for ch in unique_chars]
+ cmap = (
+ "/CIDInit /ProcSet findresource begin\n"
+ "12 dict begin\n"
+ "begincmap\n"
+ "/CIDSystemInfo << /Registry (Demo) /Ordering (UCS) /Supplement 0 >> def\n"
+ "/CMapName /Demo-UCS def\n"
+ "/CMapType 2 def\n"
+ "1 begincodespacerange\n"
+ "<01>
+ 暂无已有报销集,请先点击「新建报销集」。
+
+ 组合多张发票进行统一查重校验,一键导出 3-Sheet 报销单 Excel、合并 PDF 与完整 ZIP 资料包
+ {detail.description}报销集
+ {detail.name}
+ {detail.description && (
+
+
+ {exportError.issues.map((issue, idx) => (
+
+ ) : undefined
+ }
+ />
+