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..febbb7d --- /dev/null +++ b/backend/app/routers/reimbursement_sets.py @@ -0,0 +1,579 @@ +"""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, + is_postgresql, + load_set_snapshot, + precheck_export_limits, + validate_snapshot_for_export, +) + +router = APIRouter() + + +def _content_disposition(ascii_fallback: str, utf8_filename: str) -> str: + return f'attachment; filename="{ascii_fallback}"; filename*=UTF-8\'\'{quote(utf8_filename)}' + + +def _integrity_error_to_http_409(exc: IntegrityError) -> HTTPException: + raw = f"{exc} {getattr(exc, 'orig', '')}".lower() + if "uq_reimbursement_set_items_set_position" in raw or ( + "position" in raw and "invoice_id" not in raw + ): + return HTTPException( + status_code=409, + detail={ + "code": "CONCURRENT_POSITION_CONFLICT", + "message": "报销集成员顺序正在被并发修改,请刷新后重试", + }, + ) + return HTTPException( + status_code=409, + detail={ + "code": "INVOICE_ALREADY_ASSIGNED", + "message": "所选发票已归属其他报销集,每张发票只能加入一个报销集", + }, + ) + + +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 _integrity_error_to_http_409(exc) from exc + except HTTPException: + await db.rollback() + raise + + snapshot = await load_set_snapshot(db, rset.id, include_blobs=False) + 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, include_blobs=False) + 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)""" + stmt = select(ReimbursementSet).where(ReimbursementSet.id == set_id) + if is_postgresql(db): + stmt = stmt.with_for_update() + rset = (await db.execute(stmt)).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 _integrity_error_to_http_409(exc) from exc + except HTTPException: + await db.rollback() + raise + + snapshot = await load_set_snapshot(db, set_id, include_blobs=False) + 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), +): + """从报销集中移出单张发票""" + stmt = select(ReimbursementSet).where(ReimbursementSet.id == set_id) + if is_postgresql(db): + stmt = stmt.with_for_update() + rset = (await db.execute(stmt)).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, include_blobs=False) + 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), +): + """调整报销集内发票顺序""" + stmt = select(ReimbursementSet).where(ReimbursementSet.id == set_id) + if is_postgresql(db): + stmt = stmt.with_for_update() + rset = (await db.execute(stmt)).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, include_blobs=False) + 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 快照内校验)""" + settings = get_settings() + await begin_repeatable_read(db) + await precheck_export_limits(db, set_id, settings) + snapshot = await load_set_snapshot(db, set_id, include_blobs=False) + validate_snapshot_for_export(snapshot, settings) + + xlsx_bytes = await asyncio.to_thread(build_set_excel_bytes, snapshot) + utf8_name = f"{snapshot.reimbursement_set.name}_报销单.xlsx" + return StreamingResponse( + BytesIO(xlsx_bytes), + media_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", + headers={ + "Content-Disposition": _content_disposition( + f"reimbursement_set_{set_id}.xlsx", utf8_name + ) + }, + ) + + +@router.get("/{set_id}/export/pdf") +async def export_reimbursement_set_pdf(set_id: int, db: AsyncSession = Depends(get_db)): + """导出报销集合并 PDF(导出前在 REPEATABLE READ 快照内 SQL 预检并校验)""" + settings = get_settings() + await begin_repeatable_read(db) + await precheck_export_limits(db, set_id, settings) + snapshot = await load_set_snapshot(db, set_id, include_blobs=True) + validate_snapshot_for_export(snapshot, settings) + + pdf_bytes = await asyncio.to_thread(build_set_pdf_bytes, snapshot) + utf8_name = f"{snapshot.reimbursement_set.name}_合并原件.pdf" + return StreamingResponse( + BytesIO(pdf_bytes), + media_type="application/pdf", + headers={ + "Content-Disposition": _content_disposition( + f"reimbursement_set_{set_id}.pdf", utf8_name + ) + }, + ) + + +@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)""" + settings = get_settings() + await begin_repeatable_read(db) + await precheck_export_limits(db, set_id, settings) + snapshot = await load_set_snapshot(db, set_id, include_blobs=True) + validate_snapshot_for_export(snapshot, settings) + + zip_bytes = await asyncio.to_thread(build_set_zip_bytes, snapshot) + utf8_name = f"{snapshot.reimbursement_set.name}_报销资料包.zip" + return StreamingResponse( + BytesIO(zip_bytes), + media_type="application/zip", + headers={ + "Content-Disposition": _content_disposition( + f"reimbursement_set_{set_id}.zip", utf8_name + ) + }, + ) 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..6d601d5 --- /dev/null +++ b/backend/app/services/reimbursement_service.py @@ -0,0 +1,724 @@ +"""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 sqlalchemy.orm import defer +from starlette.concurrency import run_in_threadpool + +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]+') +_SQLITE_HASH_BATCH_SIZE = 50 + + +@dataclass +class SetMemberRow: + position: int + seq: int + invoice: Invoice + raw_text: Optional[str] + file_sha256: Optional[str] + file_size: int = 0 + file_data: Optional[bytes] = None + + +@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 is_postgresql(db: AsyncSession) -> bool: + bind = db.get_bind() + return getattr(getattr(bind, "dialect", None), "name", "") == "postgresql" + + +def _pg_sha256_hex(column): + return func.encode(func.sha256(column), "hex") + + +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 _compute_sqlite_sha256_for_ids( + db: AsyncSession, + invoice_ids: Sequence[int], +) -> Dict[int, str]: + """Compute SHA-256 in bounded keyset batches on SQLite without materializing all blobs at once.""" + if not invoice_ids: + return {} + sorted_ids = sorted(set(invoice_ids)) + hashes: Dict[int, str] = {} + for start in range(0, len(sorted_ids), _SQLITE_HASH_BATCH_SIZE): + chunk_ids = sorted_ids[start : start + _SQLITE_HASH_BATCH_SIZE] + rows = ( + await db.execute( + select(Invoice.id, Invoice.file_data).where(Invoice.id.in_(chunk_ids)) + ) + ).all() + for inv_id, blob in rows: + digest = compute_sha256(blob) + if digest: + hashes[inv_id] = digest + return hashes + + +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 = await run_in_threadpool(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 trimmed 20-digit invoice_number + if candidate_number: + existing_num_row = ( + await db.execute( + select(Invoice.id, Invoice.file_name) + .where(func.trim(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 + if file_hash: + content_len = len(content) + if is_postgresql(db): + match_row = ( + await db.execute( + select(Invoice.id, Invoice.file_name) + .where( + func.length(Invoice.file_data) == content_len, + _pg_sha256_hex(Invoice.file_data) == file_hash, + ) + .order_by(Invoice.id.asc()) + .limit(1) + ) + ).first() + if match_row: + return f"疑似重复:文件内容与已有发票 #{match_row.id}({match_row.file_name})完全相同" + else: + # Bounded keyset pagination fallback for SQLite unit tests + last_id = 0 + while True: + batch_rows = ( + await db.execute( + select(Invoice.id, Invoice.file_name, Invoice.file_data) + .where( + Invoice.id > last_id, + func.length(Invoice.file_data) == content_len, + ) + .order_by(Invoice.id.asc()) + .limit(_SQLITE_HASH_BATCH_SIZE) + ) + ).all() + if not batch_rows: + break + for row in batch_rows: + last_id = row.id + if row.file_data and compute_sha256(row.file_data) == file_hash: + return f"疑似重复:文件内容与已有发票 #{row.id}({row.file_name})完全相同" + if len(batch_rows) < _SQLITE_HASH_BATCH_SIZE: + break + + 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 both 20-digit numbers and identical SHA-256 content.""" + if not invoices: + return {} + + warnings: Dict[int, str] = {} + + # Part A: 20-digit invoice number duplicates (using trimmed DB column) + numbers = { + inv.invoice_number.strip() + for inv in invoices + if inv.invoice_number and _DIGITAL_20_RE.match(inv.invoice_number.strip()) + } + if numbers: + rows = ( + await db.execute( + select(Invoice.id, func.trim(Invoice.invoice_number).label("trimmed_num"), Invoice.file_name) + .where(func.trim(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)) + + 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} 重复" + + # Part B: Content-only SHA-256 duplicates for invoices not already flagged by 20-digit number + remaining = [inv for inv in invoices if inv.id not in warnings] + if not remaining: + return warnings + + remaining_ids = [inv.id for inv in remaining] + if is_postgresql(db): + target_rows = ( + await db.execute( + select( + Invoice.id, + func.length(Invoice.file_data).label("file_len"), + _pg_sha256_hex(Invoice.file_data).label("file_sha256"), + ).where(Invoice.id.in_(remaining_ids)) + ) + ).all() + target_hash_by_id = { + row.id: row.file_sha256 for row in target_rows if row.file_len and row.file_sha256 + } + target_lengths = {row.file_len for row in target_rows if row.file_len} + target_hashes = set(target_hash_by_id.values()) + if target_hashes: + peer_rows = ( + await db.execute( + select( + Invoice.id, + Invoice.file_name, + _pg_sha256_hex(Invoice.file_data).label("file_sha256"), + ) + .where( + func.length(Invoice.file_data).in_(target_lengths), + _pg_sha256_hex(Invoice.file_data).in_(target_hashes), + ) + .order_by(Invoice.id.asc()) + ) + ).all() + by_hash: Dict[str, List[Tuple[int, str]]] = {} + for pid, pname, digest in peer_rows: + if digest: + by_hash.setdefault(digest, []).append((pid, pname)) + for inv_id, digest in target_hash_by_id.items(): + others = [(pid, pname) for pid, pname in by_hash.get(digest, []) if pid != inv_id] + if others: + other_labels = "、".join(f"#{pid}({pname})" for pid, pname in others[:3]) + warnings[inv_id] = f"疑似重复:文件内容与已有发票 {other_labels} 完全相同" + else: + # Bounded keyset pagination fallback for SQLite unit tests + target_hash_by_id = {} + target_lengths: set[int] = set() + for inv in remaining: + if inv.file_data: + digest = compute_sha256(inv.file_data) + if digest: + target_hash_by_id[inv.id] = digest + target_lengths.add(len(inv.file_data)) + target_hashes = set(target_hash_by_id.values()) + if target_hashes and target_lengths: + by_hash_sqlite: Dict[str, List[Tuple[int, str]]] = {} + last_id = 0 + while True: + batch_rows = ( + await db.execute( + select(Invoice.id, Invoice.file_name, Invoice.file_data) + .where( + Invoice.id > last_id, + func.length(Invoice.file_data).in_(target_lengths), + ) + .order_by(Invoice.id.asc()) + .limit(_SQLITE_HASH_BATCH_SIZE) + ) + ).all() + if not batch_rows: + break + for row in batch_rows: + last_id = row.id + digest = compute_sha256(row.file_data) + if digest and digest in target_hashes: + by_hash_sqlite.setdefault(digest, []).append((row.id, row.file_name)) + if len(batch_rows) < _SQLITE_HASH_BATCH_SIZE: + break + + for inv_id, digest in target_hash_by_id.items(): + others = [ + (pid, pname) for pid, pname in by_hash_sqlite.get(digest, []) if pid != inv_id + ] + if others: + other_labels = "、".join(f"#{pid}({pname})" for pid, pname in others[:3]) + warnings[inv_id] = f"疑似重复:文件内容与已有发票 {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.""" + if is_postgresql(db): + await db.execute(text("SET TRANSACTION ISOLATION LEVEL REPEATABLE READ")) + + +async def precheck_export_limits( + db: AsyncSession, + set_id: int, + settings: Settings, +) -> Tuple[int, int]: + """SQL pre-check of item count and total blob bytes BEFORE loading any Invoice.file_data.""" + exists = ( + await db.execute(select(ReimbursementSet.id).where(ReimbursementSet.id == set_id)) + ).scalar_one_or_none() + if exists is None: + raise HTTPException(status_code=404, detail="报销集不存在") + + row = ( + await db.execute( + select( + func.count(ReimbursementSetItem.id).label("item_count"), + func.coalesce(func.sum(func.length(Invoice.file_data)), 0).label("total_bytes"), + ) + .join(Invoice, Invoice.id == ReimbursementSetItem.invoice_id) + .where(ReimbursementSetItem.set_id == set_id) + ) + ).one() + + item_count = int(row.item_count or 0) + total_bytes = int(row.total_bytes or 0) + + if item_count == 0: + raise HTTPException( + status_code=400, + detail={"code": "EMPTY_SET", "message": "报销集为空,请先加入发票后再导出"}, + ) + if item_count > settings.reimbursement_export_max_items: + raise HTTPException( + status_code=413, + detail={ + "code": "EXPORT_LIMIT_EXCEEDED", + "message": ( + f"单次导出发票数量({item_count} 张)超过安全上限" + f"(最多 {settings.reimbursement_export_max_items} 张),请分批导出" + ), + }, + ) + if 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),请拆分报销集后导出", + }, + ) + return item_count, total_bytes + + +def _invoice_to_record(member: SetMemberRow) -> InvoiceRecord: + inv = member.invoice + has_structured_fields = any( + ( + inv.invoice_number, + inv.issue_date is not None, + inv.total_with_tax is not None, + inv.seller_name, + inv.seller_tax_id, + ) + ) + has_ocr_text = bool((member.raw_text and member.raw_text.strip()) or has_structured_fields) + 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=has_ocr_text, + ) + + +async def _build_known_ledger( + db: AsyncSession, + set_id: int, + member_invoice_ids: Sequence[int], +) -> KnownLedger: + """Build KnownLedger without pulling historical file_data into Python on PostgreSQL.""" + use_pg = is_postgresql(db) + columns = [ + Invoice.id, + Invoice.invoice_number, + Invoice.seller_tax_id, + Invoice.file_name, + Invoice.status, + ReimbursementSet.id.label("other_set_id"), + ReimbursementSet.name.label("other_set_name"), + ] + if use_pg: + columns.append(_pg_sha256_hex(Invoice.file_data).label("file_sha256")) + + stmt = ( + select(*columns) + .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() + + sqlite_hashes: Dict[int, str] = {} + if not use_pg and rows: + sqlite_hashes = await _compute_sqlite_sha256_for_ids(db, [row.id for row in rows]) + + 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 = row.file_sha256 if use_pg else sqlite_hashes.get(row.id) + 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, + *, + include_blobs: bool = False, +) -> SetSnapshot: + """Unified ordered loader ensuring totals, checks, Excel, PDF, and ZIP stay 100% consistent. + + When `include_blobs=False` (default for detail/CRUD/Excel paths), `Invoice.file_data` is + deferred and never pulled into memory; SHA-256 and byte length are computed in SQL on PG. + """ + 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="报销集不存在") + + use_pg = is_postgresql(db) + + if include_blobs: + stmt = ( + select( + ReimbursementSetItem, + Invoice, + OcrResult.raw_text, + func.coalesce(func.length(Invoice.file_data), 0).label("file_size"), + ) + .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()) + ) + rows = (await db.execute(stmt)).all() + else: + select_cols = [ + ReimbursementSetItem, + Invoice, + OcrResult.raw_text, + func.coalesce(func.length(Invoice.file_data), 0).label("file_size"), + ] + if use_pg: + select_cols.append(_pg_sha256_hex(Invoice.file_data).label("file_sha256")) + stmt = ( + select(*select_cols) + .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()) + .options(defer(Invoice.file_data)) + ) + rows = (await db.execute(stmt)).all() + + sqlite_member_hashes: Dict[int, str] = {} + if not include_blobs and not use_pg and rows: + sqlite_member_hashes = await _compute_sqlite_sha256_for_ids( + db, [row[1].id for row in rows] + ) + + 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, row in enumerate(rows, start=1): + item = row[0] + invoice = row[1] + raw_text = row[2] + file_size = int(row[3] or 0) + + if include_blobs: + blob_data = invoice.file_data + digest = compute_sha256(blob_data) + else: + blob_data = None + digest = row[4] if use_pg else sqlite_member_hashes.get(invoice.id) + + member = SetMemberRow( + position=item.position, + seq=seq_idx, + invoice=invoice, + raw_text=raw_text, + file_sha256=digest, + file_size=file_size, + file_data=blob_data, + ) + 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 += file_size + + 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.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.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.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..4abacda --- /dev/null +++ b/backend/tests/test_reimbursement_sets.py @@ -0,0 +1,726 @@ +"""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> \n" + "endcodespacerange\n" + f"{len(bfchar_lines)} beginbfchar\n" + + "\n".join(bfchar_lines) + + "\nendbfchar\n" + "endcmap\n" + "CMapName currentdict /CMap defineresource pop\n" + "end\n" + "end\n" + ).encode("ascii") + + content_ops = ["BT", "/F1 12 Tf"] + y = 760 + for line in lines: + hex_str = "".join(f"{char_to_byte[ch]:02X}" for ch in line) + content_ops.append(f"1 0 0 1 40 {y} Tm <{hex_str}> Tj") + y -= 18 + content_ops.append("ET") + content_stream = ("\n".join(content_ops) + "\n").encode("ascii") + + objects = [ + b"<< /Type /Catalog /Pages 2 0 R >>", + b"<< /Type /Pages /Kids [5 0 R] /Count 1 >>", + b"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /ToUnicode 4 0 R >>", + b"<< /Length " + str(len(cmap)).encode("ascii") + b" >>\nstream\n" + cmap + b"endstream", + b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 595 842] /Resources << /Font << /F1 3 0 R >> >> /Contents 6 0 R >>", + b"<< /Length " + + str(len(content_stream)).encode("ascii") + + b" >>\nstream\n" + + content_stream + + b"endstream", + ] + + buf = BytesIO() + buf.write(b"%PDF-1.4\n") + offsets = [0] + for idx, obj in enumerate(objects, start=1): + offsets.append(buf.tell()) + buf.write(f"{idx} 0 obj\n".encode("ascii")) + buf.write(obj) + buf.write(b"\nendobj\n") + xref_pos = buf.tell() + buf.write(f"xref\n0 {len(objects) + 1}\n".encode("ascii")) + buf.write(b"0000000000 65535 f \n") + for off in offsets[1:]: + buf.write(f"{off:010d} 00000 n \n".encode("ascii")) + buf.write( + f"trailer\n<< /Size {len(objects) + 1} /Root 1 0 R >>\nstartxref\n{xref_pos}\n%%EOF\n".encode("ascii") + ) + return buf.getvalue() + + +def _make_png(color: tuple[int, int, int]) -> bytes: + buf = BytesIO() + Image.new("RGB", (320, 240), color).save(buf, format="PNG") + return buf.getvalue() + + +@pytest.fixture() +def test_env(monkeypatch): + engine = create_engine( + "sqlite:///:memory:", + connect_args={"check_same_thread": False}, + poolclass=StaticPool, + ) + + @event.listens_for(engine, "connect") + def _enable_sqlite_fks(dbapi_connection, _connection_record): + cursor = dbapi_connection.cursor() + cursor.execute("PRAGMA foreign_keys=ON") + cursor.close() + + Base.metadata.create_all(engine) + SessionLocal = sessionmaker(bind=engine, expire_on_commit=False) + + async def _override_get_db(): + sync_db = SessionLocal() + adapter = _SyncToAsyncSession(sync_db) + try: + yield adapter + finally: + await adapter.close() + + async def _noop_bg(_invoice_id: int, max_retries: int = 3): + del max_retries + return None + + monkeypatch.setattr(invoices_router, "process_invoice_background", _noop_bg) + monkeypatch.setattr(limiter, "enabled", False) + + app = FastAPI() + app.state.limiter = limiter + app.include_router(invoices_router.router, prefix="/api/invoices") + app.include_router(sets_router.router, prefix="/api/reimbursement-sets") + app.dependency_overrides[get_db] = _override_get_db + + client = TestClient(app) + yield client, SessionLocal + Base.metadata.drop_all(engine) + engine.dispose() + + +def _seed_invoice( + session: Session, + *, + invoice_number: Optional[str], + file_name: str, + file_type: str, + file_data: bytes, + issue_date: Optional[date] = date(2026, 5, 10), + amount: Decimal = Decimal("100.00"), + tax_amount: Decimal = Decimal("6.00"), + total_with_tax: Decimal = Decimal("106.00"), + seller_name: str = "示例卖方服务有限公司", + seller_tax_id: str = "TESTSELLER00000001", + item_name: str = "信息技术服务*云主机租用费", + status: InvoiceStatus = InvoiceStatus.CONFIRMED, +) -> Invoice: + inv = Invoice( + file_name=file_name, + file_type=file_type, + file_data=file_data, + invoice_number=invoice_number, + issue_date=issue_date, + buyer_name="示例买方科技有限公司", + buyer_tax_id="TESTBUYER000000001", + seller_name=seller_name, + seller_tax_id=seller_tax_id, + item_name=item_name, + amount=amount, + tax_amount=tax_amount, + total_with_tax=total_with_tax, + status=status, + ) + session.add(inv) + session.commit() + session.refresh(inv) + return inv + + +def test_reimbursement_set_crud_one_set_per_invoice_and_reorder(test_env): + client, SessionLocal = test_env + with SessionLocal() as db: + inv1 = _seed_invoice( + db, + invoice_number=NUM_1, + file_name="inv_01.pdf", + file_type="pdf", + file_data=_make_colored_pdf((220, 40, 40)), + total_with_tax=Decimal("106.00"), + ) + inv2 = _seed_invoice( + db, + invoice_number=NUM_2, + file_name="inv_02.png", + file_type="png", + file_data=_make_png((40, 80, 220)), + amount=Decimal("200.00"), + tax_amount=Decimal("12.00"), + total_with_tax=Decimal("212.00"), + ) + + # Create set A with inv1 + resp_a = client.post( + "/api/reimbursement-sets", + json={"name": "2026-05 差旅报销", "description": "初版", "invoice_ids": [inv1.id]}, + ) + assert resp_a.status_code == 201 + set_a = resp_a.json() + assert set_a["item_count"] == 1 + assert Decimal(str(set_a["total_with_tax"])) == Decimal("106.00") + + # Create empty set B, then attempt to add inv1 -> must return 409 + resp_b = client.post("/api/reimbursement-sets", json={"name": "2026-06 办公报销"}) + assert resp_b.status_code == 201 + set_b_id = resp_b.json()["id"] + + conflict_resp = client.post( + f"/api/reimbursement-sets/{set_b_id}/items", + json={"invoice_ids": [inv1.id]}, + ) + assert conflict_resp.status_code == 409 + assert conflict_resp.json()["detail"]["code"] == "INVOICE_ALREADY_ASSIGNED" + + # Add inv2 to set A + add_resp = client.post( + f"/api/reimbursement-sets/{set_a['id']}/items", + json={"invoice_ids": [inv2.id]}, + ) + assert add_resp.status_code == 200 + detail = add_resp.json() + assert [item["invoice_id"] for item in detail["items"]] == [inv1.id, inv2.id] + assert [item["position"] for item in detail["items"]] == [1, 2] + assert Decimal(str(detail["total_with_tax"])) == Decimal("318.00") + + # Reorder [inv2, inv1] without triggering UNIQUE(set_id, position) + reorder_resp = client.put( + f"/api/reimbursement-sets/{set_a['id']}/items/order", + json={"invoice_ids": [inv2.id, inv1.id]}, + ) + assert reorder_resp.status_code == 200 + assert [item["invoice_id"] for item in reorder_resp.json()["items"]] == [inv2.id, inv1.id] + assert [item["position"] for item in reorder_resp.json()["items"]] == [1, 2] + + # Patch metadata + patch_resp = client.patch( + f"/api/reimbursement-sets/{set_a['id']}", + json={"name": "2026-05 差旅报销(已核对)"}, + ) + assert patch_resp.status_code == 200 + assert patch_resp.json()["name"] == "2026-05 差旅报销(已核对)" + + # Remove inv2 and verify compaction + remove_resp = client.delete(f"/api/reimbursement-sets/{set_a['id']}/items/{inv2.id}") + assert remove_resp.status_code == 200 + assert [item["invoice_id"] for item in remove_resp.json()["items"]] == [inv1.id] + assert remove_resp.json()["items"][0]["position"] == 1 + + # Delete set A -> invoices still exist + del_resp = client.delete(f"/api/reimbursement-sets/{set_a['id']}") + assert del_resp.status_code == 200 + assert client.get(f"/api/invoices/{inv1.id}").status_code == 200 + + +def test_upload_duplicate_warning_is_non_blocking(test_env): + client, SessionLocal = test_env + pdf_a = _make_synthetic_text_pdf( + [ + "电子发票(普通发票)", + f"发票号码:{NUM_1}", + "开票日期:2026年05月10日", + "购买方名称:示例买方科技有限公司", + "统一社会信用代码:TESTBUYER000000001", + "销售方名称:示例卖方服务有限公司", + "统一社会信用代码:TESTSELLER00000001", + "价税合计(小写)¥106.00", + "备注:这是一份用于上传查重验证的合成数电票样本数据一。", + ] + ) + # Different bytes (different remark), SAME 20-digit invoice number + pdf_same_num = _make_synthetic_text_pdf( + [ + "电子发票(普通发票)", + f"发票号码:{NUM_1}", + "开票日期:2026年05月10日", + "购买方名称:示例买方科技有限公司", + "统一社会信用代码:TESTBUYER000000001", + "销售方名称:示例卖方服务有限公司", + "统一社会信用代码:TESTSELLER00000001", + "价税合计(小写)¥106.00", + "备注:这是另一份字节不同但票号相同的合成数电票样本数据二。", + ] + ) + # Pure PNG image with NO invoice number to exercise SHA-256 duplicate path directly + png_no_num = _make_png((80, 140, 200)) + + with SessionLocal() as db: + # Store with surrounding spaces to verify trimmed DB matching + _seed_invoice( + db, + invoice_number=f" {NUM_1} ", + file_name="existing.pdf", + file_type="pdf", + file_data=pdf_a, + ) + existing_img = _seed_invoice( + db, + invoice_number=None, + file_name="existing_scan.png", + file_type="png", + file_data=png_no_num, + status=InvoiceStatus.REVIEWING, + ) + + # 1. Upload different file with same 20-digit number -> succeeds with duplicate_warning + up_num = client.post( + "/api/invoices/upload", + files=[("files", ("dup_num.pdf", pdf_same_num, "application/pdf"))], + ) + assert up_num.status_code == 200 + body_num = up_num.json() + assert len(body_num) == 1 + assert body_num[0]["status"] == "success" + assert body_num[0]["id"] > 0 + assert body_num[0]["duplicate_warning"] is not None + assert NUM_1 in body_num[0]["duplicate_warning"] + + # 2. Upload identical PNG image (no invoice number) -> genuinely hits SHA-256 branch + up_sha = client.post( + "/api/invoices/upload", + files=[("files", ("dup_scan.png", png_no_num, "image/png"))], + ) + assert up_sha.status_code == 200 + body_sha = up_sha.json() + assert body_sha[0]["status"] == "success" + assert body_sha[0]["duplicate_warning"] is not None + assert "文件内容" in body_sha[0]["duplicate_warning"] + new_img_id = body_sha[0]["id"] + + # 3. List and detail endpoints must retain content-only SHA-256 duplicate warnings + list_items = {item["id"]: item for item in client.get("/api/invoices").json()["items"]} + assert list_items[existing_img.id]["duplicate_warning"] is not None + assert list_items[new_img_id]["duplicate_warning"] is not None + + detail_img = client.get(f"/api/invoices/{new_img_id}").json() + assert detail_img["duplicate_warning"] is not None + assert "文件内容" in detail_img["duplicate_warning"] + + +def test_export_excel_pdf_zip_consistency_and_zip_slip_protection(test_env): + client, SessionLocal = test_env + red_pdf = _make_colored_pdf((220, 40, 40)) + blue_png = _make_png((40, 80, 220)) + + with SessionLocal() as db: + inv1 = _seed_invoice( + db, + invoice_number=NUM_1, + file_name="../../unsafe/path/red_first.pdf", + file_type="pdf", + file_data=red_pdf, + issue_date=date(2026, 5, 1), + amount=Decimal("100.00"), + tax_amount=Decimal("6.00"), + total_with_tax=Decimal("106.00"), + item_name="餐饮服务*工作餐", + ) + inv2 = _seed_invoice( + db, + invoice_number=NUM_2, + file_name="blue_second.png", + file_type="png", + file_data=blue_png, + issue_date=date(2026, 5, 2), + amount=Decimal("200.00"), + tax_amount=Decimal("12.00"), + total_with_tax=Decimal("212.00"), + item_name="信息技术服务*云主机租用费", + ) + # Stray unbundled duplicate in DB must NOT block exporting valid set [inv1, inv2] + _seed_invoice( + db, + invoice_number=NUM_1, + file_name="stray_dup.pdf", + file_type="pdf", + file_data=_make_colored_pdf((120, 120, 120)), + status=InvoiceStatus.REVIEWING, + ) + + rset = client.post( + "/api/reimbursement-sets", + json={"name": "五月报销集", "invoice_ids": [inv1.id, inv2.id]}, + ).json() + set_id = rset["id"] + + # 1. Excel export (verify ASCII fallback + UTF-8 Content-Disposition) + excel_resp = client.get(f"/api/reimbursement-sets/{set_id}/export/excel") + assert excel_resp.status_code == 200 + cd_excel = excel_resp.headers["content-disposition"] + assert f'filename="reimbursement_set_{set_id}.xlsx"' in cd_excel + assert "filename*=UTF-8''" in cd_excel + wb = openpyxl.load_workbook(BytesIO(excel_resp.content), data_only=False) + assert wb.sheetnames == ["汇总", "明细", "问题清单"] + ws_detail = wb["明细"] + assert ws_detail.cell(row=2, column=7).value == NUM_1 + assert ws_detail.cell(row=3, column=7).value == NUM_2 + assert ws_detail.cell(row=4, column=12).value == "=SUM(L2:L3)" + summary_vals = [ + c.value for row in wb["汇总"].iter_rows() for c in row if c.value is not None + ] + assert amount_to_chinese_upper(Decimal("318.00")) in summary_vals + + # 2. PDF export matches exact order (page 1 red, page 2 blue) + pdf_resp = client.get(f"/api/reimbursement-sets/{set_id}/export/pdf") + assert pdf_resp.status_code == 200 + assert pdf_resp.content.startswith(b"%PDF") + pages = render_pdf_pages(pdf_resp.content, dpi=72) + assert len(pages) == 2 + p1 = pages[0].getpixel((pages[0].width // 2, pages[0].height // 2)) + p2 = pages[1].getpixel((pages[1].width // 2, pages[1].height // 2)) + assert p1[0] > 180 and p1[2] < 90 + assert p2[2] > 180 and p2[0] < 90 + + # 3. ZIP export contains Excel + PDF + ordered sanitized originals without zip-slip + zip_resp = client.get(f"/api/reimbursement-sets/{set_id}/export/zip") + assert zip_resp.status_code == 200 + with zipfile.ZipFile(BytesIO(zip_resp.content), "r") as zf: + names = zf.namelist() + assert "报销单.xlsx" in names + assert "合并原件.pdf" in names + assert all(".." not in n and not n.startswith("/") for n in names) + originals = sorted(n for n in names if n.startswith("originals/")) + assert len(originals) == 2 + assert originals[0] == "originals/01_red_first.pdf" + assert originals[1] == "originals/02_blue_second.png" + assert zf.read(originals[0]) == red_pdf + assert zf.read(originals[1]) == blue_png + zip_pdf_pages = render_pdf_pages(zf.read("合并原件.pdf"), dpi=72) + assert len(zip_pdf_pages) == 2 + + # 4. Existing legacy invoice exports remain backward compatible + assert client.get("/api/invoices/export/csv").status_code == 200 + assert client.get("/api/invoices/export/excel").status_code == 200 + + +def test_export_blocks_with_409_on_in_set_and_cross_set_duplicates(test_env): + client, SessionLocal = test_env + with SessionLocal() as db: + inv1 = _seed_invoice( + db, + invoice_number=NUM_1, + file_name="a.pdf", + file_type="pdf", + file_data=_make_colored_pdf((200, 50, 50)), + ) + inv2 = _seed_invoice( + db, + invoice_number=NUM_1, # duplicate 20-digit number + file_name="b.pdf", + file_type="pdf", + file_data=_make_colored_pdf((50, 200, 50)), + ) + inv3 = _seed_invoice( + db, + invoice_number=NUM_2, + file_name="c.pdf", + file_type="pdf", + file_data=_make_colored_pdf((50, 50, 200)), + ) + inv4 = _seed_invoice( + db, + invoice_number=NUM_2, # duplicates inv3 across sets + file_name="d.pdf", + file_type="pdf", + file_data=_make_colored_pdf((200, 200, 50)), + ) + + # Case 1: Same-set duplicate -> 409 across excel, pdf, zip + dup_set = client.post( + "/api/reimbursement-sets", + json={"name": "含重复票报销集", "invoice_ids": [inv1.id, inv2.id]}, + ).json() + for fmt in ("excel", "pdf", "zip"): + resp = client.get(f"/api/reimbursement-sets/{dup_set['id']}/export/{fmt}") + assert resp.status_code == 409 + detail = resp.json()["detail"] + assert detail["code"] == "VALIDATION_BLOCKED" + assert any(i["code"] == "DUP_NUMBER" and i["level"] == "error" for i in detail["issues"]) + + # Case 2: Cross-set duplicate via KnownLedger -> 409 + set_first = client.post( + "/api/reimbursement-sets", + json={"name": "第一期报销", "invoice_ids": [inv3.id]}, + ).json() + set_second = client.post( + "/api/reimbursement-sets", + json={"name": "第二期报销", "invoice_ids": [inv4.id]}, + ).json() + cross_resp = client.get(f"/api/reimbursement-sets/{set_second['id']}/export/excel") + assert cross_resp.status_code == 409 + cross_detail = cross_resp.json()["detail"] + assert any( + i["code"] == "DUP_NUMBER" and set_first["name"] in i["message"] + for i in cross_detail["issues"] + ) + + +def test_export_returns_413_on_limit_exceeded_and_422_on_corrupt_source(test_env, monkeypatch): + client, SessionLocal = test_env + with SessionLocal() as db: + inv1 = _seed_invoice( + db, + invoice_number=NUM_1, + file_name="ok1.pdf", + file_type="pdf", + file_data=_make_colored_pdf((200, 60, 60)), + ) + inv2 = _seed_invoice( + db, + invoice_number=NUM_2, + file_name="ok2.pdf", + file_type="pdf", + file_data=_make_colored_pdf((60, 200, 60)), + ) + inv_corrupt = _seed_invoice( + db, + invoice_number=NUM_3, + file_name="broken.pdf", + file_type="pdf", + file_data=b"corrupted pdf payload", + ) + + set_ok = client.post( + "/api/reimbursement-sets", + json={"name": "超限测试集", "invoice_ids": [inv1.id, inv2.id]}, + ).json() + + # Limit exceeded by item count -> 413 + monkeypatch.setenv("REIMBURSEMENT_EXPORT_MAX_ITEMS", "1") + config_module.clear_settings_cache() + try: + resp_count = client.get(f"/api/reimbursement-sets/{set_ok['id']}/export/excel") + assert resp_count.status_code == 413 + assert resp_count.json()["detail"]["code"] == "EXPORT_LIMIT_EXCEEDED" + finally: + monkeypatch.delenv("REIMBURSEMENT_EXPORT_MAX_ITEMS", raising=False) + config_module.clear_settings_cache() + + # Limit exceeded by total byte size -> 413 + monkeypatch.setenv("REIMBURSEMENT_EXPORT_MAX_BYTES", "10") + config_module.clear_settings_cache() + try: + resp_bytes = client.get(f"/api/reimbursement-sets/{set_ok['id']}/export/pdf") + assert resp_bytes.status_code == 413 + assert resp_bytes.json()["detail"]["code"] == "EXPORT_SIZE_EXCEEDED" + finally: + monkeypatch.delenv("REIMBURSEMENT_EXPORT_MAX_BYTES", raising=False) + config_module.clear_settings_cache() + + # Corrupt source file -> 422 for pdf and zip + set_bad = client.post( + "/api/reimbursement-sets", + json={"name": "坏原件测试集", "invoice_ids": [inv_corrupt.id]}, + ).json() + for fmt in ("pdf", "zip"): + resp_bad = client.get(f"/api/reimbursement-sets/{set_bad['id']}/export/{fmt}") + assert resp_bad.status_code == 422 + assert resp_bad.json()["detail"]["code"] == "CORRUPT_SOURCE_FILE" + + +def test_same_number_different_format_pdf_and_png_blocks_export_with_409(test_env): + """P1-1: PDF + PNG sharing a 20-digit invoice number must block with DUP_NUMBER / HTTP 409.""" + client, SessionLocal = test_env + with SessionLocal() as db: + inv_pdf = _seed_invoice( + db, + invoice_number=NUM_1, + file_name="ticket.pdf", + file_type="pdf", + file_data=_make_colored_pdf((200, 80, 80)), + total_with_tax=Decimal("106.00"), + ) + inv_png = _seed_invoice( + db, + invoice_number=NUM_1, + file_name="ticket_screenshot.png", + file_type="png", + file_data=_make_png((80, 120, 200)), + total_with_tax=Decimal("106.00"), + ) + + rset = client.post( + "/api/reimbursement-sets", + json={"name": "同票号不同格式测试集", "invoice_ids": [inv_pdf.id, inv_png.id]}, + ).json() + assert rset["error_count"] >= 1 + assert any(i["code"] == "DUP_NUMBER" and i["level"] == "error" for i in rset["issues"]) + + for fmt in ("excel", "pdf", "zip"): + resp = client.get(f"/api/reimbursement-sets/{rset['id']}/export/{fmt}") + assert resp.status_code == 409 + detail = resp.json()["detail"] + assert detail["code"] == "VALIDATION_BLOCKED" + assert any(i["code"] == "DUP_NUMBER" and i["level"] == "error" for i in detail["issues"]) + + +def test_export_precheck_blocks_413_before_loading_blobs_and_missing_ocr_flagged( + test_env, monkeypatch +): + """P1-2: 413 pre-check rejects before load_set_snapshot is invoked; unparsed images flag MISSING_DATA.""" + client, SessionLocal = test_env + with SessionLocal() as db: + inv_unparsed = _seed_invoice( + db, + invoice_number=None, + file_name="scan_unparsed.png", + file_type="png", + file_data=_make_png((100, 100, 100)), + issue_date=None, + amount=None, + tax_amount=None, + total_with_tax=None, + seller_name=None, + seller_tax_id=None, + status=InvoiceStatus.REVIEWING, + ) + + rset = client.post( + "/api/reimbursement-sets", + json={"name": "未识别图片集", "invoice_ids": [inv_unparsed.id]}, + ).json() + missing = [i for i in rset["issues"] if i["code"] == "MISSING_DATA"] + assert len(missing) == 1 + assert "图片未完成OCR识别" in missing[0]["message"] + + # Ensure load_set_snapshot is NEVER called when SQL precheck rejects with 413 + called = {"snapshot": False} + orig_loader = sets_router.load_set_snapshot + + async def _spy_loader(*args, **kwargs): + called["snapshot"] = True + return await orig_loader(*args, **kwargs) + + monkeypatch.setattr(sets_router, "load_set_snapshot", _spy_loader) + monkeypatch.setenv("REIMBURSEMENT_EXPORT_MAX_BYTES", "10") + config_module.clear_settings_cache() + try: + resp = client.get(f"/api/reimbursement-sets/{rset['id']}/export/pdf") + assert resp.status_code == 413 + assert called["snapshot"] is False + finally: + monkeypatch.delenv("REIMBURSEMENT_EXPORT_MAX_BYTES", raising=False) + config_module.clear_settings_cache() diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index cd8f851..42d5ed5 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -4,6 +4,7 @@ import { message } from 'antd'; import UploadPage from './pages/UploadPage'; import InvoiceListPage from './pages/InvoiceListPage'; import InvoiceDetailPage from './pages/InvoiceDetailPage'; +import ReimbursementSetsPage from './pages/ReimbursementSetsPage'; import LLMConfigModal from './components/LLMConfigModal'; import OnboardingGuide from './components/OnboardingGuide'; import { MainLayout } from './components/layout'; @@ -119,6 +120,7 @@ function AppContent() { } /> } /> + } /> } /> diff --git a/frontend/src/components/layout/Sidebar/Sidebar.tsx b/frontend/src/components/layout/Sidebar/Sidebar.tsx index 5d77e9c..ee1b50c 100644 --- a/frontend/src/components/layout/Sidebar/Sidebar.tsx +++ b/frontend/src/components/layout/Sidebar/Sidebar.tsx @@ -19,6 +19,7 @@ interface SidebarProps { const navItems: NavItem[] = [ { path: '/', label: '发票列表' }, { path: '/upload', label: '上传发票' }, + { path: '/reimbursement-sets', label: '报销集' }, ]; export default function Sidebar({ llmConfigured, onOpenLLMConfig }: SidebarProps) { diff --git a/frontend/src/hooks/useColumnSettings.ts b/frontend/src/hooks/useColumnSettings.ts index 410c823..68c253e 100644 --- a/frontend/src/hooks/useColumnSettings.ts +++ b/frontend/src/hooks/useColumnSettings.ts @@ -33,7 +33,7 @@ const defaultColumnConfigs: ColumnConfig[] = [ ]; const defaultColumnWidths: Record = { - invoice_number: 150, + invoice_number: 280, issue_date: 120, buyer_name: 180, buyer_tax_id: 180, @@ -48,12 +48,12 @@ const defaultColumnWidths: Record = { tax_rate: 80, tax_amount: 120, total_with_tax: 120, - status: 100, + status: 110, owner: 100, file_name: 150, created_at: 160, updated_at: 160, - action: 120, + action: 136, }; function loadSettings(): ColumnSettings | null { @@ -90,7 +90,14 @@ export function useColumnSettings() { const [columnWidths, setColumnWidths] = useState>(() => { const stored = loadSettings(); - return { ...defaultColumnWidths, ...(stored?.widths || {}) }; + const merged = { ...defaultColumnWidths, ...(stored?.widths || {}) }; + if (merged.invoice_number < 240) { + merged.invoice_number = defaultColumnWidths.invoice_number; + } + if (merged.action < 130) { + merged.action = defaultColumnWidths.action; + } + return merged; }); // Save settings when they change diff --git a/frontend/src/pages/InvoiceListPage.tsx b/frontend/src/pages/InvoiceListPage.tsx index dd20efe..30716bf 100644 --- a/frontend/src/pages/InvoiceListPage.tsx +++ b/frontend/src/pages/InvoiceListPage.tsx @@ -14,6 +14,8 @@ import { Statistic, Row, Col, + Tooltip, + Form, } from 'antd'; import { EyeOutlined, @@ -22,11 +24,24 @@ import { ReloadOutlined, DownloadOutlined, SyncOutlined, + FolderAddOutlined, + PlusOutlined, } from '@ant-design/icons'; import type { ColumnsType } from 'antd/es/table'; import dayjs from 'dayjs'; -import { listInvoices, deleteInvoice, batchUpdateInvoices, batchDeleteInvoices, batchReprocessInvoices, getStatistics } from '../services/api'; -import type { Invoice, Statistics } from '../types/invoice'; +import { + listInvoices, + deleteInvoice, + batchUpdateInvoices, + batchDeleteInvoices, + batchReprocessInvoices, + getStatistics, + listReimbursementSets, + createReimbursementSet, + addItemsToReimbursementSet, + extractApiErrorMessage, +} from '../services/api'; +import type { Invoice, ReimbursementSetSummary, Statistics } from '../types/invoice'; import { InvoiceStatus } from '../types/invoice'; import ResizableTitle from '../components/ResizableTitle'; import ColumnSelector from '../components/ColumnSelector'; @@ -57,6 +72,14 @@ function InvoiceListPage() { const [selectedRowKeys, setSelectedRowKeys] = useState([]); const [statistics, setStatistics] = useState(null); + // Batch reimbursement set modals + const [createSetModalOpen, setCreateSetModalOpen] = useState(false); + const [addToSetModalOpen, setAddToSetModalOpen] = useState(false); + const [existingSets, setExistingSets] = useState([]); + const [targetSetId, setTargetSetId] = useState(); + const [submittingSet, setSubmittingSet] = useState(false); + const [createSetForm] = Form.useForm(); + // Filters const [statusFilter, setStatusFilter] = useState(); const [ownerFilter, setOwnerFilter] = useState(''); @@ -233,6 +256,72 @@ function InvoiceListPage() { window.open(url, '_blank'); }; + const handleOpenCreateSetModal = () => { + if (selectedRowKeys.length === 0) { + message.warning('请先选择发票'); + return; + } + createSetForm.resetFields(); + setCreateSetModalOpen(true); + }; + + const handleConfirmCreateSet = async () => { + try { + const values = await createSetForm.validateFields(); + setSubmittingSet(true); + const created = await createReimbursementSet({ + name: values.name, + description: values.description || undefined, + invoice_ids: selectedRowKeys, + }); + message.success(`已创建报销集「${created.name}」(共 ${created.item_count} 张发票)`); + setCreateSetModalOpen(false); + setSelectedRowKeys([]); + navigate(`/reimbursement-sets?setId=${created.id}`); + } catch (error) { + if (error && typeof error === 'object' && 'errorFields' in error) { + return; + } + message.error(extractApiErrorMessage(error, '新建报销集失败')); + } finally { + setSubmittingSet(false); + } + }; + + const handleOpenAddToSetModal = async () => { + if (selectedRowKeys.length === 0) { + message.warning('请先选择发票'); + return; + } + try { + const sets = await listReimbursementSets(); + setExistingSets(sets); + setTargetSetId(sets[0]?.id); + setAddToSetModalOpen(true); + } catch (error) { + message.error(extractApiErrorMessage(error, '获取报销集列表失败')); + } + }; + + const handleConfirmAddToSet = async () => { + if (!targetSetId) { + message.warning('请选择目标报销集'); + return; + } + setSubmittingSet(true); + try { + const updated = await addItemsToReimbursementSet(targetSetId, selectedRowKeys); + message.success(`已加入报销集「${updated.name}」(当前共 ${updated.item_count} 张)`); + setAddToSetModalOpen(false); + setSelectedRowKeys([]); + navigate(`/reimbursement-sets?setId=${updated.id}`); + } catch (error) { + message.error(extractApiErrorMessage(error, '加入报销集失败')); + } finally { + setSubmittingSet(false); + } + }; + // All column definitions const allColumnDefinitions: Record[number]> = useMemo( () => ({ @@ -241,8 +330,20 @@ function InvoiceListPage() { dataIndex: 'invoice_number', key: 'invoice_number', width: columnWidths.invoice_number, - ellipsis: true, - render: (val) => val || '-', + render: (val, record) => ( +
+ + {val || '-'} + + {record.duplicate_warning && ( + + + 疑似重复 + + + )} +
+ ), onHeaderCell: () => ({ width: columnWidths.invoice_number, onResize: handleColumnResize('invoice_number'), @@ -507,12 +608,13 @@ function InvoiceListPage() { .filter(Boolean); }, [visibleColumns, allColumnDefinitions]); - // Calculate total scroll width + // Calculate total scroll width (include checkbox selection column width) const scrollX = useMemo(() => { - return visibleColumns.reduce( + const columnsSum = visibleColumns.reduce( (sum, col) => sum + (columnWidths[col.key] || 100), 0 ); + return columnsSum + 60; }, [visibleColumns, columnWidths]); // Calculate statistics from current page invoices @@ -660,6 +762,20 @@ function InvoiceListPage() { {selectedRowKeys.length > 0 && ( <> + + + + + + + + + + {/* Add to Existing Reimbursement Set Modal */} + setAddToSetModalOpen(false)} + confirmLoading={submittingSet} + okButtonProps={{ disabled: existingSets.length === 0 }} + okText="确认加入" + cancelText="取消" + > + {existingSets.length === 0 ? ( +

+ 暂无已有报销集,请先点击「新建报销集」。 +

+ ) : ( +
+ + + + + + + + + {/* Export Error Modal (409 / 413 / 422 parsed from Blob JSON) */} + setExportError(null)} + onCancel={() => setExportError(null)} + cancelButtonProps={{ style: { display: 'none' } }} + okText="我知道了" + width={620} + > + {exportError && ( +
+ 0 ? ( +
    + {exportError.issues.map((issue, idx) => ( +
  • + + {issue.code} + + {issue.message} +
  • + ))} +
+ ) : undefined + } + /> +
+ )} +
+
+ ); +} + +export default ReimbursementSetsPage; diff --git a/frontend/src/pages/UploadPage.tsx b/frontend/src/pages/UploadPage.tsx index 306ee50..8cc9392 100644 --- a/frontend/src/pages/UploadPage.tsx +++ b/frontend/src/pages/UploadPage.tsx @@ -1,7 +1,7 @@ import { useState } from 'react'; import { useNavigate } from 'react-router-dom'; -import { Upload, message, List, Tag } from 'antd'; -import { UploadOutlined, CheckCircleOutlined, CloseCircleOutlined } from '@ant-design/icons'; +import { Upload, message, List, Tag, Alert, Space } from 'antd'; +import { UploadOutlined, CheckCircleOutlined, CloseCircleOutlined, WarningOutlined } from '@ant-design/icons'; import type { UploadFile } from 'antd/es/upload/interface'; import { uploadInvoices } from '../services/api'; import type { UploadResponse } from '../types/invoice'; @@ -33,6 +33,11 @@ function UploadPage() { setFileList([]); } + const dupCount = response.filter((r) => r.duplicate_warning).length; + if (dupCount > 0) { + message.warning(`其中 ${dupCount} 个文件检测到疑似重复,请核对下方提示`); + } + const failCount = response.filter((r) => r.status === 'error').length; if (failCount > 0) { message.error(`${failCount} 个文件上传失败`); @@ -127,8 +132,29 @@ function UploadPage() { ) } - title={item.file_name} - description={item.message} + title={ + + {item.file_name} + {item.duplicate_warning && ( + }> + 疑似重复 + + )} + + } + description={ +
+
{item.message}
+ {item.duplicate_warning && ( + + )} +
+ } /> {item.status === 'success' && ( ID: {item.id} diff --git a/frontend/src/services/api.ts b/frontend/src/services/api.ts index b91e0b2..9c70467 100644 --- a/frontend/src/services/api.ts +++ b/frontend/src/services/api.ts @@ -11,6 +11,9 @@ import type { LLMConfigResponse, LLMTestResponse, ModelsResponse, + CheckIssue, + ReimbursementSetSummary, + ReimbursementSetDetail, } from '../types/invoice'; const api = axios.create({ @@ -218,4 +221,181 @@ export const getAvailableModels = async ( return response.data; }; +// Reimbursement Sets APIs + +export class ReimbursementExportError extends Error { + status: number; + code?: string; + issues: CheckIssue[]; + + constructor(message: string, status: number, code?: string, issues: CheckIssue[] = []) { + super(message); + this.name = 'ReimbursementExportError'; + this.status = status; + this.code = code; + this.issues = issues; + } +} + +export const extractApiErrorMessage = (error: unknown, fallback: string): string => { + if (axios.isAxiosError(error)) { + const detail = error.response?.data?.detail; + if (typeof detail === 'string' && detail.trim()) { + return detail; + } + if (detail && typeof detail === 'object' && typeof detail.message === 'string') { + return detail.message; + } + } + if (error instanceof Error && error.message) { + return error.message; + } + return fallback; +}; + +export const listReimbursementSets = async (): Promise => { + const response = await api.get('/reimbursement-sets'); + return response.data; +}; + +export const createReimbursementSet = async (payload: { + name: string; + description?: string; + invoice_ids?: number[]; +}): Promise => { + const response = await api.post('/reimbursement-sets', payload); + return response.data; +}; + +export const getReimbursementSet = async (id: number): Promise => { + const response = await api.get(`/reimbursement-sets/${id}`); + return response.data; +}; + +export const updateReimbursementSet = async ( + id: number, + payload: { name?: string; description?: string } +): Promise => { + const response = await api.patch(`/reimbursement-sets/${id}`, payload); + return response.data; +}; + +export const deleteReimbursementSet = async (id: number): Promise => { + await api.delete(`/reimbursement-sets/${id}`); +}; + +export const addItemsToReimbursementSet = async ( + id: number, + invoiceIds: number[] +): Promise => { + const response = await api.post(`/reimbursement-sets/${id}/items`, { + invoice_ids: invoiceIds, + }); + return response.data; +}; + +export const removeItemFromReimbursementSet = async ( + id: number, + invoiceId: number +): Promise => { + const response = await api.delete(`/reimbursement-sets/${id}/items/${invoiceId}`); + return response.data; +}; + +export const reorderReimbursementSetItems = async ( + id: number, + invoiceIds: number[] +): Promise => { + const response = await api.put(`/reimbursement-sets/${id}/items/order`, { + invoice_ids: invoiceIds, + }); + return response.data; +}; + +const _parseDownloadFilename = (disposition: string | undefined, fallback: string): string => { + if (!disposition) return fallback; + const utf8Match = disposition.match(/filename\*=UTF-8''([^;\n]+)/i); + if (utf8Match?.[1]) { + try { + return decodeURIComponent(utf8Match[1].trim()); + } catch { + return utf8Match[1].trim(); + } + } + const plainMatch = disposition.match(/filename="?([^";\n]+)"?/i); + if (plainMatch?.[1]) { + return plainMatch[1].trim(); + } + return fallback; +}; + +export const exportReimbursementSet = async ( + id: number, + format: 'excel' | 'pdf' | 'zip', + setName?: string +): Promise => { + const extMap: Record<'excel' | 'pdf' | 'zip', string> = { + excel: 'xlsx', + pdf: 'pdf', + zip: 'zip', + }; + const fallbackName = `${setName || `reimbursement_set_${id}`}.${extMap[format]}`; + + try { + const response = await api.get(`/reimbursement-sets/${id}/export/${format}`, { + responseType: 'blob', + }); + const filename = _parseDownloadFilename(response.headers['content-disposition'], fallbackName); + const blob = response.data instanceof Blob ? response.data : new Blob([response.data]); + const url = window.URL.createObjectURL(blob); + const link = document.createElement('a'); + link.href = url; + link.download = filename; + document.body.appendChild(link); + link.click(); + link.remove(); + window.setTimeout(() => { + window.URL.revokeObjectURL(url); + }, 1000); + return filename; + } catch (error) { + if (axios.isAxiosError(error) && error.response) { + const status = error.response.status; + const data = error.response.data; + let messageText = `导出失败(HTTP ${status})`; + let code: string | undefined; + let issues: CheckIssue[] = []; + + if (data instanceof Blob) { + try { + const text = await data.text(); + const parsed = JSON.parse(text); + const detail = parsed?.detail; + if (typeof detail === 'string') { + messageText = detail; + } else if (detail && typeof detail === 'object') { + if (typeof detail.message === 'string') messageText = detail.message; + if (typeof detail.code === 'string') code = detail.code; + if (Array.isArray(detail.issues)) issues = detail.issues; + } + } catch { + // Non-JSON error body; keep fallback status message + } + } else if (data?.detail) { + const detail = data.detail; + if (typeof detail === 'string') { + messageText = detail; + } else if (typeof detail === 'object') { + if (typeof detail.message === 'string') messageText = detail.message; + if (typeof detail.code === 'string') code = detail.code; + if (Array.isArray(detail.issues)) issues = detail.issues; + } + } + + throw new ReimbursementExportError(messageText, status, code, issues); + } + throw new ReimbursementExportError('导出失败,请检查网络连接后重试', 0); + } +}; + export default api; diff --git a/frontend/src/styles/antd-overrides.css b/frontend/src/styles/antd-overrides.css index c6b781e..63fbb36 100644 --- a/frontend/src/styles/antd-overrides.css +++ b/frontend/src/styles/antd-overrides.css @@ -63,9 +63,32 @@ border-bottom: none; } -/* Table Row Selection */ -.ant-table-tbody > tr.ant-table-row-selected > td { - background-color: rgba(228, 35, 19, 0.05) !important; +/* Table Row Selection & Opaque Fixed Columns */ +.ant-table-tbody > tr > td.ant-table-cell-fix-right, +.ant-table-tbody > tr > td.ant-table-cell-fix-left { + background-color: var(--background) !important; +} + +.ant-table-tbody > tr:hover > td.ant-table-cell-fix-right, +.ant-table-tbody > tr:hover > td.ant-table-cell-fix-left { + background-color: var(--surface) !important; +} + +.ant-table-tbody > tr.ant-table-row-selected > td, +.ant-table-tbody > tr.ant-table-row-selected > td.ant-table-cell-fix-right, +.ant-table-tbody > tr.ant-table-row-selected > td.ant-table-cell-fix-left { + background-color: #FEF4F3 !important; +} + +.ant-table-tbody > tr.ant-table-row-selected:hover > td, +.ant-table-tbody > tr.ant-table-row-selected:hover > td.ant-table-cell-fix-right, +.ant-table-tbody > tr.ant-table-row-selected:hover > td.ant-table-cell-fix-left { + background-color: #FDECEB !important; +} + +.ant-table-cell-fix-right-first { + box-shadow: -6px 0 10px -6px rgba(0, 0, 0, 0.12); + border-left: 1px solid var(--border); } /* ================ INPUT ================ */ diff --git a/frontend/src/types/invoice.ts b/frontend/src/types/invoice.ts index af2d8f1..5f0fdcd 100644 --- a/frontend/src/types/invoice.ts +++ b/frontend/src/types/invoice.ts @@ -29,6 +29,7 @@ export interface Invoice { tax_amount: number | null; status: InvoiceStatus; owner: string | null; + duplicate_warning?: string | null; created_at: string; updated_at: string; } @@ -112,6 +113,52 @@ export interface UploadResponse { file_name: string; status: string; message: string; + duplicate_warning?: string | null; +} + +export interface CheckIssue { + level: 'error' | 'warning' | string; + code: string; + seqs: number[]; + message: string; + suggestion?: string; +} + +export interface ReimbursementSetSummary { + id: number; + name: string; + description: string | null; + item_count: number; + total_amount: number | string; + total_tax: number | string; + total_with_tax: number | string; + created_at: string; + updated_at: string; +} + +export interface ReimbursementSetItem { + position: number; + invoice_id: number; + file_name: string; + file_type: string; + invoice_number: string | null; + issue_date: string | null; + buyer_name: string | null; + buyer_tax_id: string | null; + seller_name: string | null; + seller_tax_id: string | null; + item_name: string | null; + amount: number | string | null; + tax_amount: number | string | null; + total_with_tax: number | string | null; + status: InvoiceStatus; +} + +export interface ReimbursementSetDetail extends ReimbursementSetSummary { + items: ReimbursementSetItem[]; + issues: CheckIssue[]; + error_count: number; + warning_count: number; } // LLM Configuration Types 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..deb5e15 --- /dev/null +++ b/packages/invoice-core/src/invoice_core/checks/anomalies.py @@ -0,0 +1,251 @@ +"""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.checks.dedupe import build_seller_key_map +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] = [] + seller_keys = build_seller_key_map(records) + by_seller: dict[str, list[tuple[int, InvoiceRecord]]] = defaultdict(list) + + for idx, rec in enumerate(records): + seller_key = seller_keys.get(idx) + 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..035ef1f --- /dev/null +++ b/packages/invoice-core/src/invoice_core/checks/dedupe.py @@ -0,0 +1,306 @@ +"""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 build_seller_key_map(records: Sequence[InvoiceRecord]) -> dict[int, str]: + """Resolve canonical seller keys so name-only records merge with same-name tax-ID records.""" + name_to_taxes: dict[str, set[str]] = defaultdict(set) + for rec in records: + name = _norm_str(rec.seller_name) + tax = _norm_tax_id(rec.seller_tax_id) + if name and tax: + name_to_taxes[name].add(tax) + + canonical_tax_by_name = { + name: next(iter(taxes)) + for name, taxes in name_to_taxes.items() + if len(taxes) == 1 + } + + result: dict[int, str] = {} + for idx, rec in enumerate(records): + tax = _norm_tax_id(rec.seller_tax_id) + name = _norm_str(rec.seller_name) + if tax: + result[idx] = f"tax:{tax}" + elif name and name in canonical_tax_by_name: + result[idx] = f"tax:{canonical_tax_by_name[name]}" + elif name: + result[idx] = f"name:{name}" + return result + + +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. + + By default (`ctx.allow_multi_format_same_number=False`), each InvoiceRecord is treated + as a separate reimbursable entry so any repeated 20-digit invoice number is an error + regardless of file format (prevents PDF + PNG double reimbursement). + """ + issues: list[CheckIssue] = [] + by_key: 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_key = _norm_format(rec.file_format) if ctx.allow_multi_format_same_number else "" + by_key[(num, fmt_key)].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_key), group in by_key.items(): + if len(group) >= 2: + seqs = [r.seq for r in group] + fmt_hint = f"(格式:{fmt_key})" if fmt_key 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 matched name) + same issue_date + same total_with_tax.""" + del known + issues: list[CheckIssue] = [] + seller_keys = build_seller_key_map(records) + buckets: dict[tuple[str, str, Decimal], list[InvoiceRecord]] = defaultdict(list) + + for idx, rec in enumerate(records): + seller_key = seller_keys.get(idx) + 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 + # Only exempt multi-format copies of the exact same 20-digit invoice when explicitly enabled + if ctx.allow_multi_format_same_number: + 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..a50016a --- /dev/null +++ b/packages/invoice-core/src/invoice_core/export/excel.py @@ -0,0 +1,501 @@ +"""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 _round_cents(value: Optional[Decimal]) -> Optional[Decimal]: + if value is None: + return None + return value.quantize(Decimal("0.01"), rounding=ROUND_HALF_UP) + + +def _to_float_or_blank(value: Optional[Decimal]) -> float | str: + rounded = _round_cents(value) + if rounded is None: + return "" + return float(rounded) + + +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_raw = rec.reimbursable_amount if rec.reimbursable_amount is not None else rec.total_with_tax + total_wt_rounded = _round_cents(rec.total_with_tax) + reimb_rounded = _round_cents(reimb_raw) + total_wt_dec = total_wt_rounded if total_wt_rounded is not None else Decimal("0.00") + reimb_dec = reimb_rounded if reimb_rounded 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_dec + 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(total_wt_rounded), + _to_float_or_blank(reimb_rounded), + _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 = _safe_excel_text(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 = [ + _safe_excel_text(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..8d92c9f --- /dev/null +++ b/packages/invoice-core/src/invoice_core/export/pdf.py @@ -0,0 +1,300 @@ +"""Streaming merged PDF builder using pypdfium2 and Pillow (no PyMuPDF/reportlab/img2pdf).""" + +from __future__ import annotations + +import math +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 +# Cap per-page rasterized pixel count (~25 MP => ~75 MB uncompressed RGB max) to prevent OOM +MAX_RENDER_PIXELS = 25_000_000 + + +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 _encode_jpeg(pil_image: Image.Image, jpeg_quality: int) -> bytes: + """Encode an RGB PIL image to JPEG bytes outside the PDFium lock.""" + jpeg_buf = BytesIO() + try: + pil_image.save(jpeg_buf, format="JPEG", quality=jpeg_quality, optimize=True) + return jpeg_buf.getvalue() + finally: + jpeg_buf.close() + + +def _append_jpeg_bytes_page( + out_doc, + pdfium_mod, + jpeg_bytes: bytes, + width_pt: float, + height_pt: float, +) -> None: + """Append a pre-encoded JPEG buffer as a single PDF page (caller holds _PDFIUM_LOCK).""" + jpeg_buf = BytesIO(jpeg_bytes) + try: + 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 _bounded_render_scale(width_pt: float, height_pt: float, requested_scale: float) -> float: + """Clamp render scale so a huge MediaBox cannot trigger an OOM bitmap allocation.""" + if width_pt <= 0 or height_pt <= 0: + raise CorruptSourceFileError("PDF 页面尺寸无效") + est_pixels = (width_pt * requested_scale) * (height_pt * requested_scale) + if est_pixels <= MAX_RENDER_PIXELS: + return requested_scale + return math.sqrt(MAX_RENDER_PIXELS / (width_pt * height_pt)) + + +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. `_PDFIUM_LOCK` is held only + during individual PDFium calls (not during Pillow decoding or JPEG compression). + """ + 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 + + requested_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": + with _PDFIUM_LOCK: + 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: + with _PDFIUM_LOCK: + try: + page_count = len(src_pdf) + except Exception as exc: + raise CorruptSourceFileError( + f"PDF 页数读取失败:{label}", + index=idx, + file_name=src.file_name, + ) from exc + + if page_count == 0: + raise CorruptSourceFileError( + f"PDF 原件不包含任何页面:{label}", + index=idx, + file_name=src.file_name, + ) + + for page_idx in range(page_count): + pil_img = None + width_pt = 0.0 + height_pt = 0.0 + + # Step A: Render a single PDF page under the lock and close bitmap/page immediately + with _PDFIUM_LOCK: + src_page = None + bitmap = None + try: + src_page = src_pdf[page_idx] + 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) + + raw_w, raw_h = src_page.get_size() + width_pt = float(raw_w) + height_pt = float(raw_h) + effective_scale = _bounded_render_scale( + width_pt, height_pt, requested_scale + ) + bitmap = src_page.render(scale=effective_scale) + pil_img = bitmap.to_pil().copy() + 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() + if src_page is not None: + src_page.close() + + # Step B: Convert RGB & encode JPEG outside the PDFium lock + try: + if pil_img.mode != "RGB": + rgb_img = pil_img.convert("RGB") + pil_img.close() + pil_img = rgb_img + jpeg_bytes = _encode_jpeg(pil_img, jpeg_quality) + finally: + if pil_img is not None: + pil_img.close() + + # Step C: Append JPEG page to output PDF under the lock + with _PDFIUM_LOCK: + _append_jpeg_bytes_page( + out_doc, pdfium, jpeg_bytes, width_pt, height_pt + ) + finally: + with _PDFIUM_LOCK: + 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) + # Cap extreme raster image dimensions to prevent excessive memory use + if rgb_img.width * rgb_img.height > MAX_RENDER_PIXELS: + shrink = math.sqrt(MAX_RENDER_PIXELS / (rgb_img.width * rgb_img.height)) + resized = rgb_img.resize( + (max(1, int(rgb_img.width * shrink)), max(1, int(rgb_img.height * shrink))), + Image.Resampling.LANCZOS, + ) + if rgb_img is not raw_img: + rgb_img.close() + rgb_img = resized + width_pt, height_pt = _image_page_size_pt(rgb_img.width, rgb_img.height, dpi) + jpeg_bytes = _encode_jpeg(rgb_img, jpeg_quality) + except CorruptSourceFileError: + raise + except ( + UnidentifiedImageError, + Image.DecompressionBombError, + 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() + + with _PDFIUM_LOCK: + _append_jpeg_bytes_page(out_doc, pdfium, jpeg_bytes, width_pt, height_pt) + else: + raise CorruptSourceFileError( + f"不支持的原件格式 ({ext or 'unknown'}):{label}", + index=idx, + file_name=src.file_name, + ) + + with _PDFIUM_LOCK: + out_buf = BytesIO() + out_doc.save(out_buf) + return out_buf.getvalue() + finally: + with _PDFIUM_LOCK: + out_doc.close() diff --git a/packages/invoice-core/src/invoice_core/extract.py b/packages/invoice-core/src/invoice_core/extract.py index a6cb912..3cff133 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'(?:\bTotal|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/src/invoice_core/models.py b/packages/invoice-core/src/invoice_core/models.py new file mode 100644 index 0000000..43e88cd --- /dev/null +++ b/packages/invoice-core/src/invoice_core/models.py @@ -0,0 +1,70 @@ +"""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 + allow_multi_format_same_number: bool = False + + +@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..1eefa69 --- /dev/null +++ b/packages/invoice-core/tests/test_checks.py @@ -0,0 +1,281 @@ +"""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_blocks_across_formats_by_default(): + """By default, PDF + PNG (or OFD + XML) with the same 20-digit number must block with DUP_NUMBER.""" + r_pdf = _make_record(seq=1, invoice_number=NUM_1, file_format="PDF", file_sha256="a" * 64) + r_png = _make_record(seq=2, invoice_number=NUM_1, file_format="PNG", file_sha256="b" * 64) + + issues = run_checks( + [r_pdf, r_png], + 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] + fuzzy = [i for i in issues if i.code == "DUP_FUZZY"] + assert len(fuzzy) == 1 + assert fuzzy[0].seqs == [1, 2] + + +def test_dup_number_allows_multi_format_only_when_explicitly_enabled(): + 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), + allow_multi_format_same_number=True, + ), + ) + 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] + fuzzy = [i for i in issues if i.code == "DUP_FUZZY" and set(i.seqs) == {3, 4}] + assert fuzzy == [] + + +def test_same_seller_name_with_one_missing_tax_id_merges_for_fuzzy_and_consecutive(): + r_with_tax = _make_record( + seq=1, + invoice_number="00000000000000002001", + seller_name=SELLER_NAME, + seller_tax_id=SELLER_TAX, + file_sha256="a" * 64, + ) + r_name_only = _make_record( + seq=2, + invoice_number="00000000000000002002", + seller_name=SELLER_NAME, + seller_tax_id=None, + file_sha256="b" * 64, + ) + issues = run_checks([r_with_tax, r_name_only], ctx=CheckContext(reference_date=date(2026, 6, 1))) + codes = {i.code for i in issues} + assert "DUP_FUZZY" in codes + assert "CONSECUTIVE" in codes + + +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..d9853e2 --- /dev/null +++ b/packages/invoice-core/tests/test_export_excel.py @@ -0,0 +1,186 @@ +"""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 为跨年发票" + + +def test_excel_rounds_sub_cent_reimbursable_before_summing_and_escapes_summary_formulas(): + records = [ + InvoiceRecord( + seq=1, + invoice_number="00000000000000000001", + issue_date=date(2026, 5, 1), + category="=SUM(A1:A2)", + total_with_tax=Decimal("10.004"), + reimbursable_amount=Decimal("10.004"), + file_format="PDF", + ), + InvoiceRecord( + seq=2, + invoice_number="00000000000000000002", + issue_date=date(2026, 5, 2), + category="=SUM(A1:A2)", + total_with_tax=Decimal("10.004"), + reimbursable_amount=Decimal("10.004"), + file_format="PDF", + ), + ] + + xlsx_bytes = build_reimbursement_excel(records, title="=1+1", report_date=date(2026, 5, 20)) + wb = openpyxl.load_workbook(BytesIO(xlsx_bytes), data_only=False) + ws_sum = wb["汇总"] + + # Title and category must be escaped text, never formulas + assert ws_sum["A1"].data_type == "s" + assert ws_sum["A1"].value == "'=1+1" + assert ws_sum.cell(row=8, column=1).data_type == "s" + assert ws_sum.cell(row=8, column=1).value == "'=SUM(A1:A2)" + + # Each line rounds to 10.00 -> total is 20.00 (贰拾元整), NOT 20.01 + assert ws_sum.cell(row=8, column=4).value == pytest.approx(20.00) + summary_vals = [c.value for row in ws_sum.iter_rows() for c in row if c.value is not None] + assert "贰拾元整" in summary_vals 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..347a104 --- /dev/null +++ b/packages/invoice-core/tests/test_export_pdf.py @@ -0,0 +1,151 @@ +"""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 ( + MAX_RENDER_PIXELS, + CorruptSourceFileError, + MergeSource, + _bounded_render_scale, + 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")]) + + +def test_merge_decompression_bomb_and_page_load_failure_raise_corrupt_source(monkeypatch): + valid_png = _make_solid_image_bytes((100, 120, 140), "PNG") + + def _raise_bomb(*_args, **_kwargs): + raise Image.DecompressionBombError("image exceeds pixel limit") + + monkeypatch.setattr(Image, "open", _raise_bomb) + with pytest.raises(CorruptSourceFileError) as exc_bomb: + merge_sources_to_pdf([MergeSource(data=valid_png, file_type="png", file_name="bomb.png")]) + assert exc_bomb.value.index == 0 + assert exc_bomb.value.file_name == "bomb.png" + + # Huge MediaBox scale clamping protects against bitmap OOM + clamped = _bounded_render_scale(20000.0, 20000.0, 200.0 / 72.0) + assert (20000.0 * clamped) * (20000.0 * clamped) <= MAX_RENDER_PIXELS + 1 + + # Corrupt page-tree access on src_pdf[page_idx] converts to CorruptSourceFileError + class _BrokenPdfDoc: + def __init__(self, _data): + pass + + def __len__(self): + return 1 + + def __getitem__(self, _idx): + raise RuntimeError("broken page tree") + + def close(self): + pass + + real_new = pdfium.PdfDocument.new + + def _fake_pdf_doc(data): + return _BrokenPdfDoc(data) + + _fake_pdf_doc.new = real_new # type: ignore[attr-defined] + monkeypatch.setattr(pdfium, "PdfDocument", _fake_pdf_doc) + with pytest.raises(CorruptSourceFileError) as exc_page: + merge_sources_to_pdf([MergeSource(data=b"%PDF-1.4 broken", file_type="pdf", file_name="tree.pdf")]) + assert exc_page.value.index == 0 diff --git a/packages/invoice-core/tests/test_extract_snapshot.py b/packages/invoice-core/tests/test_extract_snapshot.py index 5f9a011..3238de1 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, } @@ -212,6 +212,6 @@ def test_extract_en_invoice_text_snapshot(): "issue_date": "2025-08-13", "buyer_name": "Demo Buyer Inc", "seller_name": "Acme Services LLC\nDate", - "total_with_tax": "1200.00", + "total_with_tax": "1320.00", "amount": "1200.00", } 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']}" 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..020c60b --- /dev/null +++ b/packages/invoice-core/tests/test_red_invoice_extract.py @@ -0,0 +1,124 @@ +"""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"] == "-132.00" + + +def test_english_positive_total_does_not_match_subtotal(): + text = ( + "INVOICE\n" + "#INV-2026-100\n" + "Demo Vendor LLC\n" + "Date: May 12, 2026\n" + "Bill To:\n" + "Demo Buyer Inc\n" + "Subtotal: $100.00\n" + "Total: $106.00\n" + ) + fields = FieldExtractor().extract_fields(text) + assert fields["amount"] == "100.00" + assert fields["total_with_tax"] == "106.00"