From 1e972cb1d41f7fc293add671f2e17362c6aef481 Mon Sep 17 00:00:00 2001 From: stone16 <12712299+stone16@users.noreply.github.com> Date: Sat, 28 Nov 2026 17:56:30 +0800 Subject: [PATCH 1/4] feat(backend): add keyword search, filtered statistics, inline PDF preview, reimbursable amount, and field bboxes --- backend/app/config.py | 5 +- backend/app/database.py | 37 + backend/app/main.py | 6 +- backend/app/models/invoice.py | 7 +- backend/app/routers/invoices.py | 805 ++++++++++++++++-- backend/app/routers/reimbursement_sets.py | 16 +- backend/app/routers/settings.py | 24 + backend/app/schemas/invoice.py | 35 +- backend/app/schemas/reimbursement_set.py | 3 + backend/app/services/invoice_service.py | 16 +- backend/app/services/reimbursement_service.py | 19 +- backend/tests/test_m2b_apis.py | 431 ++++++++++ .../src/invoice_core/parsers/pdf_text.py | 135 +++ 13 files changed, 1461 insertions(+), 78 deletions(-) create mode 100644 backend/tests/test_m2b_apis.py diff --git a/backend/app/config.py b/backend/app/config.py index 1c00b9a..f0e0a5d 100644 --- a/backend/app/config.py +++ b/backend/app/config.py @@ -178,7 +178,10 @@ def is_provider_configured(self, provider_id: str) -> bool: def get_active_llm_provider(self) -> Optional[str]: """Get the canonical active LLM provider based on configuration.""" if self.llm_provider: - return resolve_provider_id(self.llm_provider) + resolved = resolve_provider_id(self.llm_provider) + if resolved in ("ocr_only", "none", "off", "disabled"): + return None + return resolved # Auto-detect based on available API keys (preserve historical priority order first) priority_order = ( diff --git a/backend/app/database.py b/backend/app/database.py index a4e248a..94527dd 100644 --- a/backend/app/database.py +++ b/backend/app/database.py @@ -1,3 +1,4 @@ +from sqlalchemy import text from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine, async_sessionmaker from sqlalchemy.orm import DeclarativeBase @@ -16,6 +17,42 @@ class Base(DeclarativeBase): pass +_INVOICE_MIGRATION_COLUMNS: tuple[tuple[str, str, str], ...] = ( + ("reimbursable_amount", "NUMERIC(12, 2)", "NUMERIC(12, 2)"), + ("reimbursement_note", "TEXT", "TEXT"), + ("field_bboxes", "JSON", "JSON"), +) + + +def _ensure_invoice_columns_sync(sync_conn) -> None: + """Idempotently add backward-compatible nullable columns to existing invoices tables.""" + dialect = getattr(getattr(sync_conn, "dialect", None), "name", "") + if dialect == "postgresql": + for col_name, pg_type, _sqlite_type in _INVOICE_MIGRATION_COLUMNS: + sync_conn.execute( + text(f"ALTER TABLE invoices ADD COLUMN IF NOT EXISTS {col_name} {pg_type}") + ) + elif dialect == "sqlite": + rows = sync_conn.execute(text("PRAGMA table_info(invoices)")).fetchall() + existing = {row[1] for row in rows} + for col_name, _pg_type, sqlite_type in _INVOICE_MIGRATION_COLUMNS: + if col_name not in existing: + sync_conn.execute( + text(f"ALTER TABLE invoices ADD COLUMN {col_name} {sqlite_type}") + ) + + +async def init_db(target_engine=None) -> None: + """Create missing tables and idempotently migrate new nullable columns.""" + from app.models import invoice as _invoice # noqa: F401 + from app.models import reimbursement_set as _reimbursement_set # noqa: F401 + + eng = target_engine or engine + async with eng.begin() as conn: + await conn.run_sync(Base.metadata.create_all) + await conn.run_sync(_ensure_invoice_columns_sync) + + async def get_db(): async with async_session_maker() as session: try: diff --git a/backend/app/main.py b/backend/app/main.py index cb0706c..bae0472 100644 --- a/backend/app/main.py +++ b/backend/app/main.py @@ -50,10 +50,8 @@ async def rate_limit_handler(request: Request, exc: RateLimitExceeded): @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) + from app.database import init_db + await init_db() def mount_spa(target_app: FastAPI, static_dir: Path) -> None: diff --git a/backend/app/models/invoice.py b/backend/app/models/invoice.py index dccfac9..7a1001c 100644 --- a/backend/app/models/invoice.py +++ b/backend/app/models/invoice.py @@ -3,7 +3,7 @@ from enum import Enum from sqlalchemy import ( Column, Integer, String, DateTime, Date, Numeric, - Text, LargeBinary, ForeignKey, Enum as SQLEnum + Text, LargeBinary, ForeignKey, Enum as SQLEnum, JSON ) from sqlalchemy.orm import relationship @@ -52,6 +52,11 @@ class Invoice(Base): tax_rate = Column(String(20), nullable=True) # 税率 tax_amount = Column(Numeric(12, 2), nullable=True) # 税额 + # Reimbursement adjustment & spatial proofreading bounding boxes (backward-compatible nullable) + reimbursable_amount = Column(Numeric(12, 2), nullable=True) # 核定实报金额 + reimbursement_note = Column(Text, nullable=True) # 实报核减说明 + field_bboxes = Column(JSON, nullable=True) # 字段归一化坐标框 {field: [x0, y0, x1, y1]} + # Status management status = Column(SQLEnum(InvoiceStatus), default=InvoiceStatus.PENDING, nullable=False) owner = Column(String(100), nullable=True) # 归属人 diff --git a/backend/app/routers/invoices.py b/backend/app/routers/invoices.py index 2d6983d..dee33f3 100644 --- a/backend/app/routers/invoices.py +++ b/backend/app/routers/invoices.py @@ -1,18 +1,20 @@ -from typing import Optional, List +from typing import Dict, Optional, List, Sequence from io import BytesIO from datetime import date +import re from fastapi import APIRouter, Depends, UploadFile, File, HTTPException, Query, BackgroundTasks, Request from fastapi.responses import StreamingResponse from sqlalchemy.ext.asyncio import AsyncSession -from sqlalchemy import select, func +from sqlalchemy import select, func, or_ from decimal import Decimal from app.database import get_db from app.models.invoice import Invoice, OcrResult, LlmResult, ParsingDiff, InvoiceStatus +from app.models.reimbursement_set import ReimbursementSet, ReimbursementSetItem from app.schemas.invoice import ( InvoiceResponse, InvoiceListResponse, InvoiceDetailResponse, InvoiceUpdate, BatchUpdateRequest, BatchDeleteRequest, StatisticsResponse, UploadResponse, - ResolveDiffRequest + ResolveDiffRequest, CategoryBreakdownItem, TaxRateBreakdownItem, ) from app.config import get_settings from app.services.audit_service import log_audit_no_commit, get_client_info @@ -236,53 +238,549 @@ async def process_invoice_background(invoice_id: int, max_retries: int = 3): logger.error(f"Failed to update invoice {invoice_id} status after retry exhaustion: {e}") -@router.get("", response_model=InvoiceListResponse) -async def list_invoices( - page: int = Query(1, ge=1, description="页码"), - page_size: int = Query(20, ge=1, le=100, description="每页数量"), - status: Optional[InvoiceStatus] = Query(None, description="状态筛选"), - owner: Optional[str] = Query(None, description="归属人筛选"), - start_date: Optional[str] = Query(None, description="开始日期"), - end_date: Optional[str] = Query(None, description="结束日期"), - db: AsyncSession = Depends(get_db) -): - """获取发票列表""" - query = select(Invoice) +_PENDING_STATUSES = ( + InvoiceStatus.UPLOADED, + InvoiceStatus.PROCESSING, + InvoiceStatus.PENDING, + InvoiceStatus.REVIEWING, +) +_CONFIRMED_STATUSES = ( + InvoiceStatus.CONFIRMED, + InvoiceStatus.NOT_REIMBURSED, +) +_REIMBURSED_STATUSES = (InvoiceStatus.REIMBURSED,) + +_CATEGORY_RULES: tuple[tuple[str, re.Pattern[str]], ...] = ( + ("云服务", re.compile(r"信息技术|云|软件|算力|存储|服务器|数据库|网络|SaaS|技术服务", re.I)), + ("住宿", re.compile(r"住宿|酒店|宾馆|旅馆|民宿|客栈", re.I)), + ("交通", re.compile(r"旅客运输|铁路|客票|火车|高铁|航空|机票|出行|网约车|出租车|打车|通行费|高速|交通", re.I)), + ("餐饮", re.compile(r"餐饮|餐费|工作餐|咖啡|饮品|餐厅|饭店|酒楼", re.I)), + ("办公", re.compile(r"办公|文具|耗材|外设|纸品|电子产品|电脑|器材", re.I)), +) + +_DEMO_SEED_NUMBERS = ( + "26310000008800000101", + "26310000008800000102", + "26310000008800000103", + "26310000008800000105", +) - # Apply filters + +def classify_invoice_category(item_name: Optional[str], seller_name: Optional[str] = None) -> str: + """Classify an invoice into a concise financial expense category.""" + haystack = f"{item_name or ''} {seller_name or ''}".strip() + if not haystack: + return "其他" + for cat, pattern in _CATEGORY_RULES: + if pattern.search(haystack): + return cat + return "其他" + + +def _apply_invoice_filters( + query, + *, + q: Optional[str] = None, + status: Optional[InvoiceStatus] = None, + status_group: Optional[str] = None, + owner: Optional[str] = None, + buyer_name: Optional[str] = None, + start_date: Optional[str] = None, + end_date: Optional[str] = None, +): if status: query = query.where(Invoice.status == status) + elif status_group: + grp = status_group.strip().lower() + if grp in ("pending", "review", "reviewing"): + query = query.where(Invoice.status.in_(_PENDING_STATUSES)) + elif grp in ("confirmed", "unreimbursed", "to_reimburse"): + query = query.where(Invoice.status.in_(_CONFIRMED_STATUSES)) + elif grp == "reimbursed": + query = query.where(Invoice.status.in_(_REIMBURSED_STATUSES)) if owner: query = query.where(Invoice.owner == owner) + if buyer_name: + query = query.where(Invoice.buyer_name == buyer_name) + if q and q.strip(): + kw = f"%{q.strip()}%" + query = query.where( + or_( + Invoice.invoice_number.ilike(kw), + Invoice.seller_name.ilike(kw), + Invoice.buyer_name.ilike(kw), + Invoice.item_name.ilike(kw), + ) + ) if start_date: try: start_date_obj = date.fromisoformat(start_date) query = query.where(Invoice.issue_date >= start_date_obj) except ValueError: - pass # Invalid date format, skip filter + pass if end_date: try: end_date_obj = date.fromisoformat(end_date) query = query.where(Invoice.issue_date <= end_date_obj) except ValueError: - pass # Invalid date format, skip filter + pass + return query - # Count total - count_query = select(func.count()).select_from(query.subquery()) - total = await db.scalar(count_query) or 0 - # Apply pagination - query = query.order_by(Invoice.created_at.desc()) - query = query.offset((page - 1) * page_size).limit(page_size) +async def _load_invoice_enrichments( + db: AsyncSession, + invoices: Sequence[Invoice], +) -> tuple[Dict[int, tuple[int, str]], Dict[int, int]]: + """Fetch reimbursement set membership and unresolved diff counts in two batched queries.""" + if not invoices: + return {}, {} + inv_ids = [inv.id for inv in invoices] + set_rows = ( + await db.execute( + select( + ReimbursementSetItem.invoice_id, + ReimbursementSet.id, + ReimbursementSet.name, + ) + .join(ReimbursementSet, ReimbursementSet.id == ReimbursementSetItem.set_id) + .where(ReimbursementSetItem.invoice_id.in_(inv_ids)) + ) + ).all() + set_map: Dict[int, tuple[int, str]] = { + row.invoice_id: (row.id, row.name) for row in set_rows + } - result = await db.execute(query) - invoices = result.scalars().all() - dup_warnings = await compute_duplicate_warnings_for_invoices(db, invoices) + diff_rows = ( + await db.execute( + select(ParsingDiff.invoice_id, func.count(ParsingDiff.id)) + .where( + ParsingDiff.invoice_id.in_(inv_ids), + ParsingDiff.resolved == 0, + ) + .group_by(ParsingDiff.invoice_id) + ) + ).all() + diff_map: Dict[int, int] = {row[0]: int(row[1]) for row in diff_rows} + return set_map, diff_map + + +def _build_demo_pdf( + invoice_number: str, + issue_date: str, + seller_name: str, + buyer_name: str, + total_with_tax: str, + amount: str, + tax_amount: str, + tax_rate: str, +) -> bytes: + """Create a crisp, valid single-page synthetic PDF preview with zero external dependencies.""" + import pypdfium2 as pdfium + from PIL import Image, ImageDraw + + w, h = 1120, 740 + img = Image.new("RGB", (w, h), (255, 254, 250)) + draw = ImageDraw.Draw(img) + + seal_red = (168, 40, 29) + ink = (56, 44, 38) + muted = (122, 108, 98) + + # Outer voucher border & double header divider + draw.rectangle([36, 36, w - 36, h - 36], outline=seal_red, width=3) + draw.line([(320, 104), (800, 104)], fill=seal_red, width=2) + draw.line([(320, 110), (800, 110)], fill=seal_red, width=1) + + # Supervision oval stamp (geometric placeholder) + draw.ellipse([480, 48, 640, 112], outline=seal_red, width=2) + draw.ellipse([490, 56, 630, 104], outline=seal_red, width=1) + + # QR code geometric placeholder top-left + draw.rectangle([58, 54, 134, 130], outline=ink, width=2) + for bx, by in ((66, 62), (108, 62), (66, 104)): + draw.rectangle([bx, by, bx + 18, by + 18], outline=ink, width=3) + draw.rectangle([bx + 6, by + 6, bx + 12, by + 12], fill=ink) + draw.rectangle([94, 88, 126, 120], fill=ink) + + # Header ASCII metadata (always crisp in Pillow default font) + draw.text((390, 68), "CHINA E-INVOICE (DEMO)", fill=seal_red) + draw.text((770, 60), f"NO: {invoice_number}", fill=ink) + draw.text((770, 84), f"DATE: {issue_date}", fill=ink) + + # Grid lines matching standard Chinese e-invoice proportions + draw.rectangle([58, 152, w - 58, 668], outline=seal_red, width=2) + draw.line([(58, 286), (w - 58, 286)], fill=seal_red, width=2) + draw.line([(560, 152), (560, 286)], fill=seal_red, width=2) + draw.line([(58, 326), (w - 58, 326)], fill=seal_red, width=1) + draw.line([(58, 514), (w - 58, 514)], fill=seal_red, width=2) + draw.line([(58, 578), (w - 58, 578)], fill=seal_red, width=2) + + # Buyer / Seller sections + draw.text((78, 174), "BUYER / ENTITY", fill=seal_red) + draw.text((78, 202), f"NAME: Demo Entity ({len(buyer_name)} chars)", fill=ink) + draw.text((78, 232), "TAX ID: 91310115MA1K4B238X", fill=muted) + + draw.text((580, 174), "SELLER / VENDOR", fill=seal_red) + draw.text((580, 202), f"VENDOR: Synthetic Vendor ({len(seller_name)} chars)", fill=ink) + draw.text((580, 232), f"REF: {invoice_number[-8:]}", fill=muted) + + # Items table header & row + draw.text((78, 298), "ITEM / SERVICE", fill=seal_red) + draw.text((620, 298), "AMOUNT", fill=seal_red) + draw.text((790, 298), "RATE", fill=seal_red) + draw.text((900, 298), "TAX", fill=seal_red) + + draw.text((78, 356), "Synthetic Cloud / Travel / Office Demo Line Item", fill=ink) + draw.text((620, 356), f"CNY {amount}", fill=ink) + draw.text((790, 356), f"{tax_rate}", fill=ink) + draw.text((900, 356), f"CNY {tax_amount}", fill=ink) + + # Total row + draw.text((78, 536), "TOTAL WITH TAX", fill=seal_red) + draw.text((620, 536), f"CNY {total_with_tax}", fill=seal_red) + draw.text((820, 536), f"(EX-TAX {amount} + TAX {tax_amount})", fill=muted) + + # Footer note + draw.text((78, 608), "SYNTHETIC DEMO VOUCHER - FOR TESTING & SHOWCASE ONLY", fill=muted) + + doc = pdfium.PdfDocument.new() + try: + jbuf = BytesIO() + img.save(jbuf, format="JPEG", quality=92) + jbuf.seek(0) + page = doc.new_page(w, h) + try: + pimg = pdfium.PdfImage.new(doc) + pimg.load_jpeg(jbuf, inline=True, autoclose=False) + pimg.set_matrix(pdfium.PdfMatrix(w, 0, 0, h, 0, 0)) + page.insert_obj(pimg) + page.gen_content() + finally: + page.close() + out = BytesIO() + doc.save(out) + return out.getvalue() + finally: + doc.close() + + +_DEMO_FIELD_BBOXES = { + "invoice_number": [0.68, 0.07, 0.94, 0.11], + "issue_date": [0.68, 0.11, 0.90, 0.15], + "buyer_name": [0.06, 0.25, 0.48, 0.31], + "buyer_tax_id": [0.06, 0.31, 0.48, 0.36], + "seller_name": [0.52, 0.25, 0.94, 0.31], + "seller_tax_id": [0.52, 0.31, 0.94, 0.36], + "item_name": [0.06, 0.46, 0.54, 0.56], + "amount": [0.55, 0.46, 0.70, 0.54], + "tax_amount": [0.80, 0.46, 0.93, 0.54], + "total_with_tax": [0.54, 0.71, 0.78, 0.77], +} + + +@router.post("/demo-seed") +async def seed_demo_invoices( + request: Request, + db: AsyncSession = Depends(get_db), +): + """Idempotently seed 5 clearly synthetic demo invoices for instant empty-state onboarding.""" + existing = ( + await db.execute( + select(Invoice).where(Invoice.invoice_number.in_(_DEMO_SEED_NUMBERS)) + ) + ).scalars().all() + if existing: + return { + "seeded": False, + "count": len(existing), + "invoice_ids": [inv.id for inv in existing], + "message": f"演示发票已存在(共 {len(existing)} 张)", + } + + specs = [ + { + "file_name": "demo_20261124_yunsan_cloud.pdf", + "invoice_number": "26310000008800000101", + "issue_date": date(2026, 11, 24), + "buyer_name": "星云数科(上海)有限公司", + "buyer_tax_id": "91310115MA1K4B238X", + "seller_name": "云杉网络技术(杭州)有限公司", + "seller_tax_id": "91330106MA2H9C512K", + "item_name": "*信息技术服务*企业级对象存储与算力资源年包", + "specification": "标准企业版", + "unit": "套", + "quantity": Decimal("1"), + "unit_price": Decimal("3207.55"), + "amount": Decimal("3207.55"), + "tax_rate": "6%", + "tax_amount": Decimal("192.45"), + "total_with_tax": Decimal("3400.00"), + "reimbursable_amount": None, + "reimbursement_note": None, + "status": InvoiceStatus.REVIEWING, + "owner": "周明远", + "diffs": [ + ("buyer_tax_id", "91310115MA1K4B23SX", "91310115MA1K4B238X"), + ("tax_amount", "192.40", "192.45"), + ], + }, + { + "file_name": "demo_20261122_jincheng_hotel.pdf", + "invoice_number": "26310000008800000102", + "issue_date": date(2026, 11, 22), + "buyer_name": "星云数科(上海)有限公司", + "buyer_tax_id": "91310115MA1K4B238X", + "seller_name": "锦城悦居酒店管理有限公司", + "seller_tax_id": "91320508MA1N6P884T", + "item_name": "*住宿服务*商务大床房(2晚)", + "specification": "11/20-11/22", + "unit": "间夜", + "quantity": Decimal("2"), + "unit_price": Decimal("650.94"), + "amount": Decimal("1301.89"), + "tax_rate": "6%", + "tax_amount": Decimal("78.11"), + "total_with_tax": Decimal("1380.00"), + "reimbursable_amount": Decimal("1200.00"), + "reimbursement_note": "超出二线城市差旅标准,核定实报 ¥1,200.00", + "status": InvoiceStatus.CONFIRMED, + "owner": "林澈", + "diffs": [], + }, + { + "file_name": "demo_20261120_qingsong_db.pdf", + "invoice_number": "26310000008800000103", + "issue_date": date(2026, 11, 20), + "buyer_name": "星云数科(上海)有限公司", + "buyer_tax_id": "91310115MA1K4B238X", + "seller_name": "青松云计算服务有限公司", + "seller_tax_id": "91440300MA5D2W771E", + "item_name": "*信息技术服务*高可用数据库实例月租", + "specification": "4C16G-HA", + "unit": "月", + "quantity": Decimal("1"), + "unit_price": Decimal("886.79"), + "amount": Decimal("886.79"), + "tax_rate": "6%", + "tax_amount": Decimal("53.21"), + "total_with_tax": Decimal("940.00"), + "reimbursable_amount": None, + "reimbursement_note": None, + "status": InvoiceStatus.CONFIRMED, + "owner": "周明远", + "diffs": [], + }, + { + "file_name": "demo_20261122_jincheng_hotel_dup.pdf", + "invoice_number": "26310000008800000102", + "issue_date": date(2026, 11, 22), + "buyer_name": "星云数科(上海)有限公司", + "buyer_tax_id": "91310115MA1K4B238X", + "seller_name": "锦城悦居酒店管理有限公司", + "seller_tax_id": "91320508MA1N6P884T", + "item_name": "*住宿服务*商务大床房(2晚)", + "specification": "11/20-11/22", + "unit": "间夜", + "quantity": Decimal("2"), + "unit_price": Decimal("650.94"), + "amount": Decimal("1301.89"), + "tax_rate": "6%", + "tax_amount": Decimal("78.11"), + "total_with_tax": Decimal("1380.00"), + "reimbursable_amount": None, + "reimbursement_note": None, + "status": InvoiceStatus.REVIEWING, + "owner": "林澈", + "diffs": [], + }, + { + "file_name": "demo_20261028_chenguang_office.pdf", + "invoice_number": "26310000008800000105", + "issue_date": date(2026, 10, 28), + "buyer_name": "星云数科(上海)有限公司", + "buyer_tax_id": "91310115MA1K4B238X", + "seller_name": "晨光文仪商贸(上海)有限公司", + "seller_tax_id": "91310112MA1G8K114M", + "item_name": "*办公用品*人体工学键鼠套装与耗材", + "specification": "M-Pro", + "unit": "批", + "quantity": Decimal("1"), + "unit_price": Decimal("608.85"), + "amount": Decimal("608.85"), + "tax_rate": "13%", + "tax_amount": Decimal("79.15"), + "total_with_tax": Decimal("688.00"), + "reimbursable_amount": None, + "reimbursement_note": None, + "status": InvoiceStatus.REIMBURSED, + "owner": "许嘉宁", + "diffs": [], + }, + ] + + created_ids: List[int] = [] + for spec in specs: + pdf_bytes = _build_demo_pdf( + invoice_number=spec["invoice_number"], + issue_date=spec["issue_date"].isoformat(), + seller_name=spec["seller_name"], + buyer_name=spec["buyer_name"], + total_with_tax=f"{spec['total_with_tax']:.2f}", + amount=f"{spec['amount']:.2f}", + tax_amount=f"{spec['tax_amount']:.2f}", + tax_rate=spec["tax_rate"], + ) + inv = Invoice( + file_name=spec["file_name"], + file_type="pdf", + file_data=pdf_bytes, + invoice_number=spec["invoice_number"], + issue_date=spec["issue_date"], + buyer_name=spec["buyer_name"], + buyer_tax_id=spec["buyer_tax_id"], + seller_name=spec["seller_name"], + seller_tax_id=spec["seller_tax_id"], + item_name=spec["item_name"], + specification=spec["specification"], + unit=spec["unit"], + quantity=spec["quantity"], + unit_price=spec["unit_price"], + amount=spec["amount"], + tax_rate=spec["tax_rate"], + tax_amount=spec["tax_amount"], + total_with_tax=spec["total_with_tax"], + reimbursable_amount=spec["reimbursable_amount"], + reimbursement_note=spec["reimbursement_note"], + field_bboxes=dict(_DEMO_FIELD_BBOXES), + status=spec["status"], + owner=spec["owner"], + ) + db.add(inv) + await db.flush() + created_ids.append(inv.id) + + if spec["diffs"]: + db.add( + OcrResult( + invoice_id=inv.id, + invoice_number=spec["invoice_number"], + buyer_tax_id="91310115MA1K4B23SX", + tax_amount="192.40", + total_with_tax=f"{spec['total_with_tax']:.2f}", + ) + ) + db.add( + LlmResult( + invoice_id=inv.id, + invoice_number=spec["invoice_number"], + buyer_tax_id=spec["buyer_tax_id"], + tax_amount=f"{spec['tax_amount']:.2f}", + total_with_tax=f"{spec['total_with_tax']:.2f}", + ) + ) + for fname, ocr_val, llm_val in spec["diffs"]: + db.add( + ParsingDiff( + invoice_id=inv.id, + field_name=fname, + ocr_value=ocr_val, + llm_value=llm_val, + final_value=llm_val, + source="llm", + resolved=0, + ) + ) + + await db.commit() + return { + "seeded": True, + "count": len(created_ids), + "invoice_ids": created_ids, + "message": f"已载入 {len(created_ids)} 张合成演示发票", + } + + +@router.delete("/demo-seed") +async def clear_demo_invoices(db: AsyncSession = Depends(get_db)): + """Remove previously seeded synthetic demo invoices.""" + existing = ( + await db.execute( + select(Invoice).where(Invoice.invoice_number.in_(_DEMO_SEED_NUMBERS)) + ) + ).scalars().all() + count = len(existing) + for inv in existing: + await db.delete(inv) + await db.commit() + return {"deleted_count": count, "message": f"已清理 {count} 张演示发票"} + + +@router.get("", response_model=InvoiceListResponse) +async def list_invoices( + page: int = Query(1, ge=1, description="页码"), + page_size: int = Query(20, ge=1, le=100, description="每页数量"), + q: Optional[str] = Query(None, description="关键词模糊搜索(票号/销方/购方/项目名)"), + status: Optional[InvoiceStatus] = Query(None, description="状态筛选"), + status_group: Optional[str] = Query(None, description="快捷状态分组: pending/confirmed/reimbursed"), + owner: Optional[str] = Query(None, description="归属人筛选"), + buyer_name: Optional[str] = Query(None, description="购买方抬头筛选"), + category: Optional[str] = Query(None, description="费用科目筛选"), + duplicate_only: bool = Query(False, description="仅显示疑似重复发票"), + start_date: Optional[str] = Query(None, description="开始日期"), + end_date: Optional[str] = Query(None, description="结束日期"), + date_from: Optional[str] = Query(None, description="开始日期别名"), + date_to: Optional[str] = Query(None, description="结束日期别名"), + db: AsyncSession = Depends(get_db) +): + """获取发票列表""" + eff_start = start_date or date_from + eff_end = end_date or date_to + + query = _apply_invoice_filters( + select(Invoice), + q=q, + status=status, + status_group=status_group, + owner=owner, + buyer_name=buyer_name, + start_date=eff_start, + end_date=eff_end, + ) + + if category or duplicate_only: + all_rows = (await db.execute(query.order_by(Invoice.created_at.desc()))).scalars().all() + dup_warnings = await compute_duplicate_warnings_for_invoices(db, all_rows) + filtered = [] + for inv in all_rows: + if duplicate_only and inv.id not in dup_warnings: + continue + if category and classify_invoice_category(inv.item_name, inv.seller_name) != category: + continue + filtered.append(inv) + total = len(filtered) + start_idx = (page - 1) * page_size + invoices = filtered[start_idx : start_idx + page_size] + else: + count_query = select(func.count()).select_from(query.subquery()) + total = await db.scalar(count_query) or 0 + result = await db.execute( + query.order_by(Invoice.created_at.desc()) + .offset((page - 1) * page_size) + .limit(page_size) + ) + invoices = result.scalars().all() + dup_warnings = await compute_duplicate_warnings_for_invoices(db, invoices) + + set_map, diff_map = await _load_invoice_enrichments(db, invoices) items = [] for inv in invoices: resp = InvoiceResponse.model_validate(inv) resp.duplicate_warning = dup_warnings.get(inv.id) + resp.category = classify_invoice_category(inv.item_name, inv.seller_name) + if inv.id in set_map: + resp.reimbursement_set_id, resp.reimbursement_set_name = set_map[inv.id] + resp.unresolved_diff_count = diff_map.get(inv.id, 0) items.append(resp) return InvoiceListResponse( @@ -296,34 +794,163 @@ async def list_invoices( @router.get("/statistics", response_model=StatisticsResponse) async def get_statistics( invoice_ids: Optional[str] = Query(None, description="发票ID列表,逗号分隔"), + q: Optional[str] = Query(None, description="关键词模糊搜索"), status: Optional[InvoiceStatus] = Query(None, description="状态筛选"), + status_group: Optional[str] = Query(None, description="快捷状态分组"), owner: Optional[str] = Query(None, description="归属人筛选"), + buyer_name: Optional[str] = Query(None, description="购买方抬头筛选"), + category: Optional[str] = Query(None, description="费用科目筛选"), + duplicate_only: bool = Query(False, description="仅统计疑似重复发票"), + start_date: Optional[str] = Query(None, description="开始日期"), + end_date: Optional[str] = Query(None, description="结束日期"), + date_from: Optional[str] = Query(None, description="开始日期别名"), + date_to: Optional[str] = Query(None, description="结束日期别名"), db: AsyncSession = Depends(get_db) ): - """获取发票统计数据""" - query = select(Invoice) + """获取筛选条件下的全量发票统计数据""" + eff_start = start_date or date_from + eff_end = end_date or date_to + + query = _apply_invoice_filters( + select(Invoice), + q=q, + status=status, + status_group=status_group, + owner=owner, + buyer_name=buyer_name, + start_date=eff_start, + end_date=eff_end, + ) ids = _parse_invoice_ids(invoice_ids) if ids: query = query.where(Invoice.id.in_(ids)) - if status: - query = query.where(Invoice.status == status) - if owner: - query = query.where(Invoice.owner == owner) result = await db.execute(query) invoices = result.scalars().all() + dup_warnings = await compute_duplicate_warnings_for_invoices(db, invoices) + + if category or duplicate_only: + invoices = [ + inv for inv in invoices + if (not duplicate_only or inv.id in dup_warnings) + and (not category or classify_invoice_category(inv.item_name, inv.seller_name) == category) + ] + + # Global lightweight metadata (buyers, owners, global status tab counts) + all_meta_rows = ( + await db.execute(select(Invoice.id, Invoice.status, Invoice.buyer_name, Invoice.owner)) + ).all() + buyer_freq: Dict[str, int] = {} + owner_set: set[str] = set() + g_pending = 0 + g_confirmed = 0 + g_reimbursed = 0 + for row in all_meta_rows: + if row.buyer_name and row.buyer_name.strip(): + b = row.buyer_name.strip() + buyer_freq[b] = buyer_freq.get(b, 0) + 1 + if row.owner and row.owner.strip(): + owner_set.add(row.owner.strip()) + if row.status in _PENDING_STATUSES: + g_pending += 1 + elif row.status in _CONFIRMED_STATUSES: + g_confirmed += 1 + elif row.status in _REIMBURSED_STATUSES: + g_reimbursed += 1 + + buyers_sorted = [b for b, _ in sorted(buyer_freq.items(), key=lambda x: (-x[1], x[0]))] + owners_sorted = sorted(owner_set) + + # Global duplicate count (fast when unfiltered, reuse dup_warnings if same size) + if len(invoices) == len(all_meta_rows): + global_dup_count = sum(1 for inv in invoices if inv.id in dup_warnings) + else: + all_invs = (await db.execute(select(Invoice))).scalars().all() + all_dups = await compute_duplicate_warnings_for_invoices(db, all_invs) + global_dup_count = len(all_dups) count = len(invoices) - total_amount = sum((inv.amount or Decimal(0)) for inv in invoices) - total_tax = sum((inv.tax_amount or Decimal(0)) for inv in invoices) - total_with_tax = sum((inv.total_with_tax or Decimal(0)) for inv in invoices) + total_amount = Decimal("0.00") + total_tax = Decimal("0.00") + total_with_tax = Decimal("0.00") + total_reimbursable = Decimal("0.00") + pending_count = 0 + confirmed_count = 0 + reimbursed_count = 0 + duplicate_count = 0 + status_breakdown: Dict[str, int] = {} + cat_agg: Dict[str, list] = {} + tax_agg: Dict[str, list] = {} + + for inv in invoices: + amt = inv.amount or Decimal("0.00") + tax = inv.tax_amount or Decimal("0.00") + wt = inv.total_with_tax or Decimal("0.00") + reimb = inv.reimbursable_amount if inv.reimbursable_amount is not None else wt + + total_amount += amt + total_tax += tax + total_with_tax += wt + total_reimbursable += reimb + + st_val = inv.status.value if inv.status else "未知" + status_breakdown[st_val] = status_breakdown.get(st_val, 0) + 1 + if inv.status in _PENDING_STATUSES: + pending_count += 1 + elif inv.status in _CONFIRMED_STATUSES: + confirmed_count += 1 + elif inv.status in _REIMBURSED_STATUSES: + reimbursed_count += 1 + + if inv.id in dup_warnings: + duplicate_count += 1 + + cat = classify_invoice_category(inv.item_name, inv.seller_name) + if cat not in cat_agg: + cat_agg[cat] = [0, Decimal("0.00"), Decimal("0.00")] + cat_agg[cat][0] += 1 + cat_agg[cat][1] += amt + cat_agg[cat][2] += wt + + rate_key = (inv.tax_rate or "免税/未知").strip() or "免税/未知" + if rate_key not in tax_agg: + tax_agg[rate_key] = [0, Decimal("0.00")] + tax_agg[rate_key][0] += 1 + tax_agg[rate_key][1] += tax + + category_breakdown = [ + CategoryBreakdownItem(category=k, count=v[0], amount=v[1], total_with_tax=v[2]) + for k, v in sorted(cat_agg.items(), key=lambda x: (-x[1][1], x[0])) + ] + tax_rate_breakdown = [ + TaxRateBreakdownItem(tax_rate=k, count=v[0], tax_amount=v[1]) + for k, v in sorted(tax_agg.items(), key=lambda x: (-x[1][1], x[0])) + ] return StatisticsResponse( count=count, + total_count=count, + pending_count=pending_count, + confirmed_count=confirmed_count, + reimbursed_count=reimbursed_count, + duplicate_count=duplicate_count, total_amount=total_amount, total_tax=total_tax, - total_with_tax=total_with_tax + total_with_tax=total_with_tax, + total_reimbursable=total_reimbursable, + status_breakdown=status_breakdown, + category_breakdown=category_breakdown, + tax_rate_breakdown=tax_rate_breakdown, + buyers=buyers_sorted, + owners=owners_sorted, + global_counts={ + "all": len(all_meta_rows), + "pending": g_pending, + "duplicate": global_dup_count, + "confirmed": g_confirmed, + "reimbursed": g_reimbursed, + }, ) @@ -354,6 +981,8 @@ async def get_invoice( diffs = diff_result.scalars().all() dup_warnings = await compute_duplicate_warnings_for_invoices(db, [invoice]) + set_map, diff_map = await _load_invoice_enrichments(db, [invoice]) + set_id, set_name = set_map.get(invoice.id, (None, None)) # Build response dict from invoice to avoid lazy loading issues invoice_dict = { @@ -378,6 +1007,13 @@ async def get_invoice( "amount": invoice.amount, "tax_rate": invoice.tax_rate, "tax_amount": invoice.tax_amount, + "reimbursable_amount": invoice.reimbursable_amount, + "reimbursement_note": invoice.reimbursement_note, + "field_bboxes": invoice.field_bboxes, + "category": classify_invoice_category(invoice.item_name, invoice.seller_name), + "reimbursement_set_id": set_id, + "reimbursement_set_name": set_name, + "unresolved_diff_count": diff_map.get(invoice.id, 0), "created_at": invoice.created_at, "updated_at": invoice.updated_at, "ocr_result": ocr, @@ -391,9 +1027,11 @@ async def get_invoice( @router.get("/{invoice_id}/file") async def get_invoice_file( invoice_id: int, + inline: bool = Query(False, description="内联预览模式(Content-Disposition: inline)"), + download: bool = Query(False, description="附件下载模式(Content-Disposition: attachment)"), db: AsyncSession = Depends(get_db) ): - """获取发票原始文件""" + """获取发票原始文件(支持 ?inline=1 内联预览与 ?download=1 附件下载)""" from fastapi.responses import Response from urllib.parse import quote @@ -411,24 +1049,27 @@ async def get_invoice_file( "png": "image/png" } - # URL-encode filename for Content-Disposition header (RFC 5987) - encoded_filename = quote(invoice.file_name) + ext = (invoice.file_type or "bin").lower().lstrip(".") + ascii_fallback = f"invoice_{invoice_id}.{ext}" + encoded_filename = quote(invoice.file_name or ascii_fallback) + disposition = "attachment" if download else "inline" return Response( content=invoice.file_data, - media_type=content_type_map.get(invoice.file_type, "application/octet-stream"), - headers={"Content-Disposition": f"attachment; filename*=UTF-8''{encoded_filename}"} + media_type=content_type_map.get(ext, "application/octet-stream"), + headers={ + "Content-Disposition": f'{disposition}; filename="{ascii_fallback}"; filename*=UTF-8\'\'{encoded_filename}', + "X-Content-Type-Options": "nosniff", + } ) -@router.put("/{invoice_id}", response_model=InvoiceResponse) -async def update_invoice( +async def _do_update_invoice( invoice_id: int, update_data: InvoiceUpdate, request: Request, - db: AsyncSession = Depends(get_db) -): - """更新发票信息""" + db: AsyncSession, +) -> InvoiceResponse: query = select(Invoice).where(Invoice.id == invoice_id) result = await db.execute(query) invoice = result.scalar_one_or_none() @@ -439,11 +1080,10 @@ async def update_invoice( # Capture old values for audit update_dict = update_data.model_dump(exclude_unset=True) old_values = {key: getattr(invoice, key) for key in update_dict.keys()} - # Convert non-serializable types for key, value in old_values.items(): - if hasattr(value, 'value'): # Enum + if hasattr(value, 'value'): old_values[key] = value.value - elif hasattr(value, 'isoformat'): # Date/DateTime + elif hasattr(value, 'isoformat'): old_values[key] = value.isoformat() elif isinstance(value, Decimal): old_values[key] = str(value) @@ -451,13 +1091,12 @@ async def update_invoice( for key, value in update_dict.items(): setattr(invoice, key, value) - # Audit log client_info = get_client_info(request) new_values = update_dict.copy() for key, value in new_values.items(): - if hasattr(value, 'value'): # Enum + if hasattr(value, 'value'): new_values[key] = value.value - elif hasattr(value, 'isoformat'): # Date/DateTime + elif hasattr(value, 'isoformat'): new_values[key] = value.isoformat() elif isinstance(value, Decimal): new_values[key] = str(value) @@ -476,7 +1115,37 @@ async def update_invoice( await db.commit() await db.refresh(invoice) - return InvoiceResponse.model_validate(invoice) + dup_warnings = await compute_duplicate_warnings_for_invoices(db, [invoice]) + set_map, diff_map = await _load_invoice_enrichments(db, [invoice]) + resp = InvoiceResponse.model_validate(invoice) + resp.duplicate_warning = dup_warnings.get(invoice.id) + resp.category = classify_invoice_category(invoice.item_name, invoice.seller_name) + if invoice.id in set_map: + resp.reimbursement_set_id, resp.reimbursement_set_name = set_map[invoice.id] + resp.unresolved_diff_count = diff_map.get(invoice.id, 0) + return resp + + +@router.put("/{invoice_id}", response_model=InvoiceResponse) +async def update_invoice( + invoice_id: int, + update_data: InvoiceUpdate, + request: Request, + db: AsyncSession = Depends(get_db) +): + """更新发票信息(PUT)""" + return await _do_update_invoice(invoice_id, update_data, request, db) + + +@router.patch("/{invoice_id}", response_model=InvoiceResponse) +async def patch_invoice( + invoice_id: int, + update_data: InvoiceUpdate, + request: Request, + db: AsyncSession = Depends(get_db) +): + """局部更新发票信息(PATCH)""" + return await _do_update_invoice(invoice_id, update_data, request, db) @router.post("/batch-update") @@ -890,8 +1559,10 @@ async def confirm_invoice( async def export_invoices_csv( request: Request, invoice_ids: Optional[str] = Query(None, description="发票ID列表,逗号分隔"), + q: Optional[str] = Query(None, description="关键词筛选"), status: Optional[InvoiceStatus] = Query(None, description="状态筛选"), owner: Optional[str] = Query(None, description="归属人筛选"), + buyer_name: Optional[str] = Query(None, description="购买方筛选"), start_date: Optional[str] = Query(None, description="开始日期"), end_date: Optional[str] = Query(None, description="结束日期"), db: AsyncSession = Depends(get_db) @@ -900,15 +1571,17 @@ async def export_invoices_csv( import csv from urllib.parse import quote - query = select(Invoice) + query = _apply_invoice_filters( + select(Invoice), + q=q, + status=status, + owner=owner, + buyer_name=buyer_name, + ) ids = _parse_invoice_ids(invoice_ids) if ids: query = query.where(Invoice.id.in_(ids)) - if status: - query = query.where(Invoice.status == status) - if owner: - query = query.where(Invoice.owner == owner) start_date_obj = _parse_date_param(start_date, "start_date") if start_date_obj: query = query.where(Invoice.issue_date >= start_date_obj) @@ -973,8 +1646,10 @@ async def export_invoices_csv( async def export_invoices_excel( request: Request, invoice_ids: Optional[str] = Query(None, description="发票ID列表,逗号分隔"), + q: Optional[str] = Query(None, description="关键词筛选"), status: Optional[InvoiceStatus] = Query(None, description="状态筛选"), owner: Optional[str] = Query(None, description="归属人筛选"), + buyer_name: Optional[str] = Query(None, description="购买方筛选"), start_date: Optional[str] = Query(None, description="开始日期"), end_date: Optional[str] = Query(None, description="结束日期"), db: AsyncSession = Depends(get_db) @@ -988,15 +1663,17 @@ async def export_invoices_excel( except ImportError: raise HTTPException(status_code=500, detail="Excel导出需要安装openpyxl库") - query = select(Invoice) + query = _apply_invoice_filters( + select(Invoice), + q=q, + status=status, + owner=owner, + buyer_name=buyer_name, + ) ids = _parse_invoice_ids(invoice_ids) if ids: query = query.where(Invoice.id.in_(ids)) - if status: - query = query.where(Invoice.status == status) - if owner: - query = query.where(Invoice.owner == owner) start_date_obj = _parse_date_param(start_date, "start_date") if start_date_obj: query = query.where(Invoice.issue_date >= start_date_obj) diff --git a/backend/app/routers/reimbursement_sets.py b/backend/app/routers/reimbursement_sets.py index febbb7d..dc0a010 100644 --- a/backend/app/routers/reimbursement_sets.py +++ b/backend/app/routers/reimbursement_sets.py @@ -98,6 +98,8 @@ def _snapshot_to_detail_response(snapshot: SetSnapshot) -> ReimbursementSetDetai amount=member.invoice.amount, tax_amount=member.invoice.tax_amount, total_with_tax=member.invoice.total_with_tax, + reimbursable_amount=member.invoice.reimbursable_amount, + reimbursement_note=member.invoice.reimbursement_note, status=member.invoice.status, ) for member in snapshot.members @@ -123,6 +125,7 @@ def _snapshot_to_detail_response(snapshot: SetSnapshot) -> ReimbursementSetDetai total_amount=snapshot.total_amount, total_tax=snapshot.total_tax, total_with_tax=snapshot.total_with_tax, + total_reimbursable=snapshot.total_reimbursable, created_at=rset.created_at, updated_at=rset.updated_at, items=items, @@ -245,25 +248,30 @@ async def list_reimbursement_sets(db: AsyncSession = Depends(get_db)): 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"), + func.coalesce( + func.sum(func.coalesce(Invoice.reimbursable_amount, Invoice.total_with_tax)), + 0, + ).label("total_reimbursable"), ) .join(Invoice, Invoice.id == ReimbursementSetItem.invoice_id) .group_by(ReimbursementSetItem.set_id) ) ).all() - stats_map: Dict[int, tuple[int, Decimal, Decimal, Decimal]] = { + stats_map: Dict[int, tuple[int, Decimal, 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)), + Decimal(str(row.total_reimbursable 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")) + cnt, total_amt, total_tax, total_wt, total_reimb = stats_map.get( + rset.id, (0, Decimal("0.00"), Decimal("0.00"), Decimal("0.00"), Decimal("0.00")) ) results.append( ReimbursementSetSummaryResponse( @@ -274,6 +282,7 @@ async def list_reimbursement_sets(db: AsyncSession = Depends(get_db)): total_amount=total_amt, total_tax=total_tax, total_with_tax=total_wt, + total_reimbursable=total_reimb, created_at=rset.created_at, updated_at=rset.updated_at, ) @@ -376,6 +385,7 @@ async def update_reimbursement_set( total_amount=snapshot.total_amount, total_tax=snapshot.total_tax, total_with_tax=snapshot.total_with_tax, + total_reimbursable=snapshot.total_reimbursable, created_at=rset.created_at, updated_at=rset.updated_at, ) diff --git a/backend/app/routers/settings.py b/backend/app/routers/settings.py index fc8ebc9..b0e2f27 100644 --- a/backend/app/routers/settings.py +++ b/backend/app/routers/settings.py @@ -346,6 +346,30 @@ async def configure_llm( raise HTTPException(status_code=500, detail="配置失败,请检查配置参数是否正确") from e +@router.post("/llm/disable", response_model=LLMConfigResponse) +async def disable_llm( + x_llm_config_token: Optional[str] = Header(default=None, alias="X-LLM-Config-Token"), + authorization: Optional[str] = Header(default=None), +): + """Switch active recognition engine to pure local OCR offline mode and persist.""" + _require_llm_config_token( + app_config.get_settings().llm_config_token, + x_llm_config_token, + authorization, + ) + env_updates = {"LLM_PROVIDER": "ocr_only"} + for key, value in env_updates.items(): + os.environ[key] = value + _update_env_file(env_updates) + app_config.clear_settings_cache() + reset_llm_service() + return LLMConfigResponse( + success=True, + message="已切换为纯本地 OCR 离线模式", + provider="ocr_only", + ) + + @router.post("/llm/test") async def test_llm_connection(): """Test the current saved LLM configuration with a simple request.""" diff --git a/backend/app/schemas/invoice.py b/backend/app/schemas/invoice.py index 73d72b7..77ef672 100644 --- a/backend/app/schemas/invoice.py +++ b/backend/app/schemas/invoice.py @@ -1,6 +1,6 @@ from datetime import date, datetime from decimal import Decimal -from typing import Optional, List +from typing import Dict, Optional, List from pydantic import BaseModel, Field from enum import Enum @@ -31,6 +31,8 @@ class InvoiceBase(BaseModel): amount: Optional[Decimal] = Field(None, description="金额") tax_rate: Optional[str] = Field(None, description="税率") tax_amount: Optional[Decimal] = Field(None, description="税额") + reimbursable_amount: Optional[Decimal] = Field(None, description="核定实报金额") + reimbursement_note: Optional[str] = Field(None, description="实报核减说明") class InvoiceCreate(InvoiceBase): @@ -40,6 +42,7 @@ class InvoiceCreate(InvoiceBase): class InvoiceUpdate(InvoiceBase): status: Optional[InvoiceStatus] = None owner: Optional[str] = None + field_bboxes: Optional[Dict[str, List[float]]] = None class InvoiceResponse(InvoiceBase): @@ -48,6 +51,11 @@ class InvoiceResponse(InvoiceBase): file_type: str status: InvoiceStatus owner: Optional[str] = None + field_bboxes: Optional[Dict[str, List[float]]] = None + category: Optional[str] = None + reimbursement_set_id: Optional[int] = None + reimbursement_set_name: Optional[str] = None + unresolved_diff_count: int = 0 duplicate_warning: Optional[str] = None created_at: datetime updated_at: datetime @@ -142,11 +150,36 @@ class BatchDeleteRequest(BaseModel): invoice_ids: List[int] = Field(..., description="要删除的发票ID列表") +class CategoryBreakdownItem(BaseModel): + category: str + count: int + amount: Decimal + total_with_tax: Decimal + + +class TaxRateBreakdownItem(BaseModel): + tax_rate: str + count: int + tax_amount: Decimal + + class StatisticsResponse(BaseModel): count: int = Field(description="发票数量") + total_count: int = Field(0, description="筛选后总张数") + pending_count: int = Field(0, description="待校对/处理中张数") + confirmed_count: int = Field(0, description="已确认/待报销张数") + reimbursed_count: int = Field(0, description="已报销张数") + duplicate_count: int = Field(0, description="疑似重复张数") total_amount: Decimal = Field(description="金额合计") total_tax: Decimal = Field(description="税额合计") total_with_tax: Decimal = Field(description="价税合计") + total_reimbursable: Decimal = Field(Decimal("0.00"), description="核定实报合计") + status_breakdown: Dict[str, int] = Field(default_factory=dict, description="状态分布") + category_breakdown: List[CategoryBreakdownItem] = Field(default_factory=list, description="费用科目分布") + tax_rate_breakdown: List[TaxRateBreakdownItem] = Field(default_factory=list, description="税率结构分布") + buyers: List[str] = Field(default_factory=list, description="购买方抬头列表") + owners: List[str] = Field(default_factory=list, description="归属人列表") + global_counts: Dict[str, int] = Field(default_factory=dict, description="全局快捷状态计数") class UploadResponse(BaseModel): diff --git a/backend/app/schemas/reimbursement_set.py b/backend/app/schemas/reimbursement_set.py index c6ff805..59126e4 100644 --- a/backend/app/schemas/reimbursement_set.py +++ b/backend/app/schemas/reimbursement_set.py @@ -44,6 +44,7 @@ class ReimbursementSetSummaryResponse(BaseModel): total_amount: Decimal = Decimal("0.00") total_tax: Decimal = Decimal("0.00") total_with_tax: Decimal = Decimal("0.00") + total_reimbursable: Decimal = Decimal("0.00") created_at: datetime updated_at: datetime @@ -63,6 +64,8 @@ class ReimbursementSetItemResponse(BaseModel): amount: Optional[Decimal] = None tax_amount: Optional[Decimal] = None total_with_tax: Optional[Decimal] = None + reimbursable_amount: Optional[Decimal] = None + reimbursement_note: Optional[str] = None status: InvoiceStatus diff --git a/backend/app/services/invoice_service.py b/backend/app/services/invoice_service.py index efb2329..1cb503b 100644 --- a/backend/app/services/invoice_service.py +++ b/backend/app/services/invoice_service.py @@ -11,7 +11,7 @@ from app.services.ocr_service import get_ocr_service, get_field_extractor from app.services.llm_service import get_llm_service from app.config import get_settings -from invoice_core.parsers.pdf_text import render_pdf_pages +from invoice_core.parsers.pdf_text import extract_pdf_field_bboxes, render_pdf_pages from invoice_core.reconcile import ( COMPARABLE_FIELDS, NUMERIC_FIELDS, @@ -234,6 +234,20 @@ async def process_invoice(invoice_id: int, db: AsyncSession) -> bool: # Update invoice with final data _update_invoice_from_fields(invoice, final_fields) + # Extract normalized field bounding boxes for spatial proofreading on PDF invoices + if invoice.file_type == 'pdf' and invoice.file_data: + try: + bboxes = await loop.run_in_executor( + _ocr_executor, + extract_pdf_field_bboxes, + invoice.file_data, + final_fields, + ) + if bboxes: + invoice.field_bboxes = bboxes + except Exception as bbox_err: + logger.debug(f"Skipping bbox extraction for invoice {invoice_id}: {bbox_err}") + # Set status based on whether review is needed # Check for conflicts in diffs has_conflicts = any(d['needs_review'] for d in diffs) diff --git a/backend/app/services/reimbursement_service.py b/backend/app/services/reimbursement_service.py index 6d601d5..5fe3b3a 100644 --- a/backend/app/services/reimbursement_service.py +++ b/backend/app/services/reimbursement_service.py @@ -52,6 +52,7 @@ class SetSnapshot: total_amount: Decimal total_tax: Decimal total_with_tax: Decimal + total_reimbursable: Decimal total_bytes: int @@ -437,11 +438,16 @@ def _invoice_to_record(member: SetMemberRow) -> InvoiceRecord: 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, + reimbursable_amount=( + Decimal(inv.reimbursable_amount) + if inv.reimbursable_amount is not None + else (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, + remarks=inv.reimbursement_note, invoice_id=inv.id, has_ocr_text=has_ocr_text, ) @@ -580,6 +586,7 @@ async def load_set_snapshot( total_amount = Decimal("0.00") total_tax = Decimal("0.00") total_with_tax = Decimal("0.00") + total_reimbursable = Decimal("0.00") total_bytes = 0 for seq_idx, row in enumerate(rows, start=1): @@ -608,9 +615,14 @@ async def load_set_snapshot( 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") + inv_total = Decimal(invoice.total_with_tax) if invoice.total_with_tax is not None else Decimal("0.00") + total_with_tax += inv_total + inv_reimb = ( + Decimal(invoice.reimbursable_amount) + if invoice.reimbursable_amount is not None + else inv_total ) + total_reimbursable += inv_reimb total_bytes += file_size member_invoice_ids = [m.invoice.id for m in members] @@ -625,6 +637,7 @@ async def load_set_snapshot( total_amount=total_amount, total_tax=total_tax, total_with_tax=total_with_tax, + total_reimbursable=total_reimbursable, total_bytes=total_bytes, ) diff --git a/backend/tests/test_m2b_apis.py b/backend/tests/test_m2b_apis.py new file mode 100644 index 0000000..5480b66 --- /dev/null +++ b/backend/tests/test_m2b_apis.py @@ -0,0 +1,431 @@ +"""Unit & integration tests for M2-B backend APIs: +- Keyword search `q`, buyer/category/duplicate/status_group filtering +- Full filtered statistics (`GET /api/invoices/statistics`) +- Inline vs attachment file preview (`GET /api/invoices/{id}/file?inline=1` / `?download=1`) +- Reimbursable amount & note persistence (`PATCH /api/invoices/{id}`) + reimbursement set Excel linkage +- Normalized PDF field bounding boxes (`extract_pdf_field_bboxes`) +- Idempotent schema migration for legacy DBs +- Synthetic demo-seed endpoint & OCR-only disable endpoint +""" + +from __future__ import annotations + +from datetime import date +from decimal import Decimal +from io import BytesIO +from typing import Any + +import openpyxl +import pytest +from fastapi import FastAPI +from fastapi.testclient import TestClient +from sqlalchemy import create_engine, event, text +from sqlalchemy.orm import Session, sessionmaker +from sqlalchemy.pool import StaticPool + +from app.database import Base, _ensure_invoice_columns_sync, 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.parsers.pdf_text import extract_pdf_field_bboxes + + +class _SyncToAsyncSession: + 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_text_pdf_for_bbox() -> bytes: + """Build a minimal valid single-page PDF with ASCII embedded text positions for pdfplumber.""" + stream = ( + b"BT\n" + b"/F1 12 Tf\n" + b"400 720 Td (26310000009999111111) Tj\n" + b"0 -20 Td (2026-11-24) Tj\n" + b"-340 -80 Td (91310115MA1K4B238X) Tj\n" + b"280 0 Td (91330106MA2H9C512K) Tj\n" + b"-280 -120 Td (3207.55) Tj\n" + b"200 0 Td (192.45) Tj\n" + b"-200 -80 Td (3400.00) Tj\n" + b"ET\n" + ) + objects = [ + b"1 0 obj << /Type /Catalog /Pages 2 0 R >> endobj\n", + b"2 0 obj << /Type /Pages /Kids [3 0 R] /Count 1 >> endobj\n", + ( + b"3 0 obj << /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] " + b"/Resources << /Font << /F1 4 0 R >> >> /Contents 5 0 R >> endobj\n" + ), + b"4 0 obj << /Type /Font /Subtype /Type1 /BaseFont /Helvetica >> endobj\n", + ( + f"5 0 obj << /Length {len(stream)} >> stream\n".encode("ascii") + + stream + + b"endstream endobj\n" + ), + ] + out = BytesIO() + out.write(b"%PDF-1.4\n") + offsets = [] + for obj in objects: + offsets.append(out.tell()) + out.write(obj) + xref_pos = out.tell() + out.write(f"xref\n0 {len(objects) + 1}\n0000000000 65535 f \n".encode("ascii")) + for off in offsets: + out.write(f"{off:010d} 00000 n \n".encode("ascii")) + out.write( + f"trailer << /Size {len(objects) + 1} /Root 1 0 R >>\nstartxref\n{xref_pos}\n%%EOF\n".encode("ascii") + ) + return out.getvalue() + + +@pytest.fixture() +def test_env(): + engine = create_engine( + "sqlite://", + connect_args={"check_same_thread": False}, + poolclass=StaticPool, + ) + + @event.listens_for(engine, "connect") + def _set_sqlite_pragma(dbapi_conn, _conn_record): + cursor = dbapi_conn.cursor() + cursor.execute("PRAGMA foreign_keys=ON") + cursor.close() + + Base.metadata.create_all(engine) + SessionLocal = sessionmaker(bind=engine, autocommit=False, autoflush=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") + + async def _override_get_db(): + sync_db = SessionLocal() + adapter = _SyncToAsyncSession(sync_db) + try: + yield adapter + finally: + await adapter.close() + + app.dependency_overrides[get_db] = _override_get_db + client = TestClient(app) + yield client, SessionLocal + engine.dispose() + + +def _seed_sample_invoices(SessionLocal) -> list[int]: + pdf_bytes = _make_text_pdf_for_bbox() + with SessionLocal() as db: + invs = [ + Invoice( + file_name="中文票据_云杉.pdf", + file_type="pdf", + file_data=pdf_bytes, + invoice_number="26310000009999111111", + issue_date=date(2026, 11, 24), + buyer_name="星云数科(上海)有限公司", + buyer_tax_id="91310115MA1K4B238X", + seller_name="云杉网络技术(杭州)有限公司", + seller_tax_id="91330106MA2H9C512K", + item_name="*信息技术服务*对象存储服务费", + amount=Decimal("3207.55"), + tax_rate="6%", + tax_amount=Decimal("192.45"), + total_with_tax=Decimal("3400.00"), + status=InvoiceStatus.REVIEWING, + owner="周明远", + ), + Invoice( + file_name="hotel_stay.pdf", + file_type="pdf", + file_data=pdf_bytes + b"%unique1", + invoice_number="26310000009999222222", + issue_date=date(2026, 11, 22), + buyer_name="星云数科(上海)有限公司", + buyer_tax_id="91310115MA1K4B238X", + seller_name="锦城悦居酒店管理有限公司", + seller_tax_id="91320508MA1N6P884T", + item_name="*住宿服务*商务大床房", + amount=Decimal("1301.89"), + tax_rate="6%", + tax_amount=Decimal("78.11"), + total_with_tax=Decimal("1380.00"), + reimbursable_amount=Decimal("1200.00"), + reimbursement_note="超标核减 180 元", + status=InvoiceStatus.CONFIRMED, + owner="林澈", + ), + Invoice( + file_name="hotel_stay_dup.pdf", + file_type="pdf", + file_data=pdf_bytes + b"%unique2", + invoice_number="26310000009999222222", + issue_date=date(2026, 11, 22), + buyer_name="远航科技(北京)有限公司", + buyer_tax_id="91110108MA01ABCD12", + seller_name="锦城悦居酒店管理有限公司", + seller_tax_id="91320508MA1N6P884T", + item_name="*住宿服务*商务大床房", + amount=Decimal("1301.89"), + tax_rate="6%", + tax_amount=Decimal("78.11"), + total_with_tax=Decimal("1380.00"), + status=InvoiceStatus.REIMBURSED, + owner="许嘉宁", + ), + ] + db.add_all(invs) + db.commit() + return [inv.id for inv in invs] + + +def test_keyword_search_and_filters(test_env): + client, SessionLocal = test_env + _seed_sample_invoices(SessionLocal) + + # Search by invoice number substring + r = client.get("/api/invoices", params={"q": "9999111111"}) + assert r.status_code == 200 + assert r.json()["total"] == 1 + assert r.json()["items"][0]["seller_name"] == "云杉网络技术(杭州)有限公司" + assert r.json()["items"][0]["category"] == "云服务" + + # Search by seller name + r = client.get("/api/invoices", params={"q": "锦城悦居"}) + assert r.status_code == 200 + assert r.json()["total"] == 2 + + # Filter by buyer_name + r = client.get("/api/invoices", params={"buyer_name": "远航科技(北京)有限公司"}) + assert r.status_code == 200 + assert r.json()["total"] == 1 + + # Filter by category + r = client.get("/api/invoices", params={"category": "住宿"}) + assert r.status_code == 200 + assert r.json()["total"] == 2 + + # Filter by duplicate_only + r = client.get("/api/invoices", params={"duplicate_only": "true"}) + assert r.status_code == 200 + assert r.json()["total"] == 2 + assert all(item["duplicate_warning"] for item in r.json()["items"]) + + +def test_filtered_statistics_and_breakdowns(test_env): + client, SessionLocal = test_env + _seed_sample_invoices(SessionLocal) + + r = client.get("/api/invoices/statistics") + assert r.status_code == 200 + stats = r.json() + assert stats["count"] == 3 + assert stats["total_count"] == 3 + assert stats["pending_count"] == 1 + assert stats["confirmed_count"] == 1 + assert stats["reimbursed_count"] == 1 + assert stats["duplicate_count"] == 2 + assert Decimal(str(stats["total_with_tax"])) == Decimal("6160.00") + assert Decimal(str(stats["total_reimbursable"])) == Decimal("5980.00") + assert stats["buyers"][0] == "星云数科(上海)有限公司" + assert "远航科技(北京)有限公司" in stats["buyers"] + assert len(stats["category_breakdown"]) == 2 + assert len(stats["tax_rate_breakdown"]) == 1 + + # Filtered statistics via q + r_q = client.get("/api/invoices/statistics", params={"q": "云杉"}) + assert r_q.status_code == 200 + s_q = r_q.json() + assert s_q["total_count"] == 1 + assert Decimal(str(s_q["total_with_tax"])) == Decimal("3400.00") + assert s_q["global_counts"]["all"] == 3 + + +def test_file_inline_vs_download_headers(test_env): + client, SessionLocal = test_env + ids = _seed_sample_invoices(SessionLocal) + + r_inline = client.get(f"/api/invoices/{ids[0]}/file?inline=1") + assert r_inline.status_code == 200 + assert r_inline.headers["content-type"] == "application/pdf" + cd_inline = r_inline.headers["content-disposition"] + assert cd_inline.startswith("inline;") + assert f'filename="invoice_{ids[0]}.pdf"' in cd_inline + assert "filename*=UTF-8''" in cd_inline + + r_download = client.get(f"/api/invoices/{ids[0]}/file?download=1") + assert r_download.status_code == 200 + cd_dl = r_download.headers["content-disposition"] + assert cd_dl.startswith("attachment;") + assert f'filename="invoice_{ids[0]}.pdf"' in cd_dl + assert "filename*=UTF-8''" in cd_dl + + +def test_reimbursable_amount_patch_and_excel_linkage(test_env): + client, SessionLocal = test_env + ids = _seed_sample_invoices(SessionLocal) + + # PATCH reimbursable_amount & reimbursement_note + r_patch = client.patch( + f"/api/invoices/{ids[0]}", + json={ + "reimbursable_amount": "3000.00", + "reimbursement_note": "研发预算封顶 3000 元", + }, + ) + assert r_patch.status_code == 200 + body = r_patch.json() + assert Decimal(str(body["reimbursable_amount"])) == Decimal("3000.00") + assert body["reimbursement_note"] == "研发预算封顶 3000 元" + + # Remove the already-reimbursed duplicate inv[2] so the set passes KnownLedger dedupe checks + r_del_dup = client.delete(f"/api/invoices/{ids[2]}") + assert r_del_dup.status_code == 200 + + # Create reimbursement set containing invoice 0 & invoice 1 (non-duplicate pair) + r_set = client.post( + "/api/reimbursement-sets", + json={"name": "测试实报核减集", "invoice_ids": [ids[0], ids[1]]}, + ) + assert r_set.status_code == 201 + set_data = r_set.json() + # total_with_tax = 3400 + 1380 = 4780, total_reimbursable = 3000 + 1200 = 4200 + assert Decimal(str(set_data["total_with_tax"])) == Decimal("4780.00") + assert Decimal(str(set_data["total_reimbursable"])) == Decimal("4200.00") + + # Export 3-Sheet Excel and verify reimbursable_amount column reflects 3000 & 1200 + r_xlsx = client.get(f"/api/reimbursement-sets/{set_data['id']}/export/excel") + assert r_xlsx.status_code == 200 + wb = openpyxl.load_workbook(BytesIO(r_xlsx.content), data_only=False) + detail_ws = wb["明细"] + headers = [detail_ws.cell(row=1, column=c).value for c in range(1, detail_ws.max_column + 1)] + reimb_col = next(i + 1 for i, h in enumerate(headers) if h and "实报" in str(h)) + vals = [ + detail_ws.cell(row=r_idx, column=reimb_col).value + for r_idx in range(2, detail_ws.max_row) + ] + assert 3000.0 in vals + assert 1200.0 in vals + + +def test_extract_pdf_field_bboxes(): + pdf_bytes = _make_text_pdf_for_bbox() + bboxes = extract_pdf_field_bboxes( + pdf_bytes, + { + "invoice_number": "26310000009999111111", + "issue_date": "2026-11-24", + "buyer_tax_id": "91310115MA1K4B238X", + "seller_tax_id": "91330106MA2H9C512K", + "amount": "3207.55", + "tax_amount": "192.45", + "total_with_tax": "3400.00", + }, + ) + assert "invoice_number" in bboxes + assert "total_with_tax" in bboxes + for key, box in bboxes.items(): + assert len(box) == 4, f"invalid box for {key}" + x0, y0, x1, y1 = box + assert 0.0 <= x0 <= x1 <= 1.0 + assert 0.0 <= y0 <= y1 <= 1.0 + + +def test_idempotent_sqlite_column_migration(): + engine = create_engine("sqlite://", connect_args={"check_same_thread": False}, poolclass=StaticPool) + with engine.begin() as conn: + conn.execute( + text( + "CREATE TABLE invoices (id INTEGER PRIMARY KEY, file_name VARCHAR(255) NOT NULL)" + ) + ) + # First pass adds all 3 columns + _ensure_invoice_columns_sync(conn) + # Second pass must be a safe no-op + _ensure_invoice_columns_sync(conn) + cols = {row[1] for row in conn.execute(text("PRAGMA table_info(invoices)")).fetchall()} + assert {"reimbursable_amount", "reimbursement_note", "field_bboxes"}.issubset(cols) + engine.dispose() + + +def test_demo_seed_idempotent_and_cleanup(test_env): + client, _ = test_env + r1 = client.post("/api/invoices/demo-seed") + assert r1.status_code == 200 + assert r1.json()["seeded"] is True + assert r1.json()["count"] == 5 + + # Second call is idempotent + r2 = client.post("/api/invoices/demo-seed") + assert r2.status_code == 200 + assert r2.json()["seeded"] is False + assert r2.json()["count"] == 5 + + r_del = client.delete("/api/invoices/demo-seed") + assert r_del.status_code == 200 + assert r_del.json()["deleted_count"] == 5 + + +def test_disable_llm_switches_to_ocr_only(tmp_path, monkeypatch): + import app.config as config_module + from app.routers import settings as settings_router + from app.services.llm_service import reset_llm_service + + env_file = tmp_path / ".env" + monkeypatch.setenv("INVOICE_ENV_FILE", str(env_file)) + monkeypatch.setenv("LLM_PROVIDER", "deepseek") + monkeypatch.setenv("DEEPSEEK_API_KEY", "sk-test-fake-key-123456") + config_module.clear_settings_cache() + reset_llm_service() + + app = FastAPI() + app.include_router(settings_router.router, prefix="/api/settings") + c = TestClient(app) + + assert c.get("/api/settings/llm/status").json()["is_configured"] is True + + r_dis = c.post("/api/settings/llm/disable") + assert r_dis.status_code == 200 + assert r_dis.json()["provider"] == "ocr_only" + assert c.get("/api/settings/llm/status").json()["is_configured"] is False + assert "LLM_PROVIDER=ocr_only" in env_file.read_text(encoding="utf-8") + + # Cleanup env + monkeypatch.delenv("LLM_PROVIDER", raising=False) + monkeypatch.delenv("DEEPSEEK_API_KEY", raising=False) + config_module.clear_settings_cache() + reset_llm_service() diff --git a/packages/invoice-core/src/invoice_core/parsers/pdf_text.py b/packages/invoice-core/src/invoice_core/parsers/pdf_text.py index a9770a2..a263cf1 100644 --- a/packages/invoice-core/src/invoice_core/parsers/pdf_text.py +++ b/packages/invoice-core/src/invoice_core/parsers/pdf_text.py @@ -60,6 +60,141 @@ def extract_pdf_text_layer(pdf_data: bytes) -> tuple[str, bool]: return "", False +def _clamp01(value: float) -> float: + return round(max(0.0, min(1.0, value)), 4) + + +def extract_pdf_field_bboxes( + pdf_data: bytes, + fields: dict[str, Optional[str]], +) -> dict[str, list[float]]: + """Best-effort extraction of normalized [x0, y0, x1, y1] (0..1) bounding boxes on page 1. + + Uses pdfplumber word coordinates when an embedded text layer is present. + Returns an empty dict when coordinates cannot be reliably extracted. + """ + if not pdf_data or not fields: + return {} + + target_keys = ( + "invoice_number", + "issue_date", + "buyer_name", + "buyer_tax_id", + "seller_name", + "seller_tax_id", + "item_name", + "amount", + "tax_amount", + "total_with_tax", + ) + + try: + import pdfplumber + + with pdfplumber.open(BytesIO(pdf_data)) as pdf: + if not pdf.pages: + return {} + page = pdf.pages[0] + width = float(page.width or 0) + height = float(page.height or 0) + if width <= 0 or height <= 0: + return {} + + words = page.extract_words(keep_blank_chars=False, use_text_flow=False) or [] + if not words: + return {} + + # Group words into visual lines (tolerance ~4pt on top coordinate) + sorted_words = sorted(words, key=lambda w: (round(float(w["top"]) / 4), float(w["x0"]))) + lines: list[dict] = [] + for w in sorted_words: + top = float(w["top"]) + bottom = float(w["bottom"]) + x0 = float(w["x0"]) + x1 = float(w["x1"]) + txt = str(w.get("text") or "").strip() + if not txt: + continue + if lines and abs(lines[-1]["top"] - top) <= 4.5 and x0 >= lines[-1]["x1"] - 6: + # Only merge horizontally nearby words into the same segment (avoid spanning buyer+seller columns) + if x0 - lines[-1]["x1"] <= width * 0.08: + lines[-1]["text"] += txt + lines[-1]["x1"] = max(lines[-1]["x1"], x1) + lines[-1]["top"] = min(lines[-1]["top"], top) + lines[-1]["bottom"] = max(lines[-1]["bottom"], bottom) + continue + lines.append({"text": txt, "x0": x0, "top": top, "x1": x1, "bottom": bottom}) + + def _normalize_search(raw: str) -> str: + return re.sub(r"[\s¥¥,,::]+", "", raw).lower() + + def _candidates(key: str, raw_val: str) -> list[str]: + val = raw_val.strip() + if not val: + return [] + cands = [_normalize_search(val)] + if key == "issue_date" and re.match(r"^\d{4}-\d{2}-\d{2}$", val): + y, m, d = val.split("-") + cands.append(f"{y}年{m}月{d}日") + cands.append(f"{y}年{int(m)}月{int(d)}日") + if key in ("amount", "tax_amount", "total_with_tax"): + try: + num = float(val.replace(",", "").replace("¥", "").replace("¥", "")) + cands.append(f"{num:.2f}") + except ValueError: + pass + if key == "item_name" and len(cands[0]) > 10: + cands.append(cands[0][:10]) + return [c for c in dict.fromkeys(cands) if len(c) >= 2] + + bboxes: dict[str, list[float]] = {} + for key in target_keys: + raw_val = fields.get(key) + if raw_val is None: + continue + val_str = str(raw_val).strip() + if not val_str: + continue + cands = _candidates(key, val_str) + if not cands: + continue + + matched_box = None + # Prefer exact/substring match in compact line segments first + for seg in lines: + norm_seg = _normalize_search(seg["text"]) + if any(c in norm_seg for c in cands): + # Disambiguate buyer vs seller if both halves contain similar label + if key in ("buyer_name", "buyer_tax_id") and seg["x0"] > width * 0.55: + continue + if key in ("seller_name", "seller_tax_id") and seg["x1"] < width * 0.45: + continue + matched_box = seg + break + + if matched_box is None: + # Fallback without side preference + for seg in lines: + norm_seg = _normalize_search(seg["text"]) + if any(c in norm_seg for c in cands): + matched_box = seg + break + + if matched_box is not None: + bboxes[key] = [ + _clamp01(matched_box["x0"] / width), + _clamp01(matched_box["top"] / height), + _clamp01(matched_box["x1"] / width), + _clamp01(matched_box["bottom"] / height), + ] + + return bboxes + except Exception as e: + logger.debug("PDF field bbox extraction skipped: %s", e) + return {} + + def render_pdf_pages( pdf_data: bytes, dpi: int = 300, From 44af5046300f4b9c4f96d9c100ca974b11a88e1a Mon Sep 17 00:00:00 2001 From: stone16 <12712299+stone16@users.noreply.github.com> Date: Sat, 28 Nov 2026 18:03:17 +0800 Subject: [PATCH 2/4] feat(ui): implement Swiss Ledger v2 design system, Obsidian Darkroom theme, Sidebar, CommandPalette, and OG preview --- frontend/index.html | 15 +- frontend/src/App.tsx | 160 ++++---- .../src/components/CommandPalette.module.css | 144 +++++++ frontend/src/components/CommandPalette.tsx | 303 ++++++++++++++ .../src/components/OgPreviewModal.module.css | 371 ++++++++++++++++++ frontend/src/components/OgPreviewModal.tsx | 168 ++++++++ .../components/layout/MainLayout.module.css | 32 +- frontend/src/components/layout/MainLayout.tsx | 68 ++-- .../layout/Sidebar/Sidebar.module.css | 358 ++++++++++++----- .../src/components/layout/Sidebar/Sidebar.tsx | 331 +++++++++++++--- frontend/src/contexts/ThemeContext.tsx | 74 ++++ frontend/src/index.css | 42 -- frontend/src/main.tsx | 132 ++++++- frontend/src/services/api.ts | 91 ++++- frontend/src/styles/antd-overrides.css | 350 +++++++---------- frontend/src/styles/global.css | 155 ++++---- frontend/src/styles/variables.css | 282 ++++++++++--- frontend/src/types/invoice.ts | 49 ++- 18 files changed, 2373 insertions(+), 752 deletions(-) create mode 100644 frontend/src/components/CommandPalette.module.css create mode 100644 frontend/src/components/CommandPalette.tsx create mode 100644 frontend/src/components/OgPreviewModal.module.css create mode 100644 frontend/src/components/OgPreviewModal.tsx create mode 100644 frontend/src/contexts/ThemeContext.tsx delete mode 100644 frontend/src/index.css diff --git a/frontend/index.html b/frontend/index.html index 1e2413d..efebcbe 100644 --- a/frontend/index.html +++ b/frontend/index.html @@ -1,10 +1,19 @@ - +
- -