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/frontend/index.html b/frontend/index.html
index 1e2413d..efebcbe 100644
--- a/frontend/index.html
+++ b/frontend/index.html
@@ -1,10 +1,19 @@
-
+
-
- 发票管理系统
+ Invoice Manager · 印鉴账本票据台
+
diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx
index 42d5ed5..7e62589 100644
--- a/frontend/src/App.tsx
+++ b/frontend/src/App.tsx
@@ -1,122 +1,91 @@
import { useState, useEffect, useCallback } from 'react';
-import { BrowserRouter, Routes, Route, useLocation } from 'react-router-dom';
-import { message } from 'antd';
+import { BrowserRouter, Routes, Route } from 'react-router-dom';
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 CommandPalette from './components/CommandPalette';
+import OgPreviewModal from './components/OgPreviewModal';
import { MainLayout } from './components/layout';
-import { getLLMStatus, listInvoices } from './services/api';
+import {
+ getLLMStatus,
+ getFilteredStatistics,
+ listReimbursementSets,
+} from './services/api';
import type { LLMStatusResponse } from './types/invoice';
-const ONBOARDING_DISMISSED_KEY = 'invoice_onboarding_dismissed';
-
-function readOnboardingDismissed(): boolean {
- try {
- return window.localStorage.getItem(ONBOARDING_DISMISSED_KEY) === 'true';
- } catch {
- return false;
- }
-}
-
function AppContent() {
- const location = useLocation();
const [llmConfigOpen, setLlmConfigOpen] = useState(false);
- const [llmConfigured, setLlmConfigured] = useState(null);
+ const [cmdPaletteOpen, setCmdPaletteOpen] = useState(false);
+ const [ogPreviewOpen, setOgPreviewOpen] = useState(false);
const [llmStatus, setLlmStatus] = useState(null);
- const [backendConnected, setBackendConnected] = useState(false);
- const [onboardingDismissed, setOnboardingDismissed] = useState(() =>
- readOnboardingDismissed()
- );
- const [onboardingActive, setOnboardingActive] = useState(false);
- const [showLlmPromo, setShowLlmPromo] = useState(false);
+ const [pendingAlertCount, setPendingAlertCount] = useState(0);
+ const [reimbursementSetCount, setReimbursementSetCount] = useState(0);
- const refreshBootstrapState = useCallback(async () => {
+ const refreshShellState = useCallback(async () => {
try {
- const [status, invoicesResp] = await Promise.all([
+ const [status, stats, sets] = await Promise.all([
getLLMStatus(),
- listInvoices({ page: 1, page_size: 1 }),
+ getFilteredStatistics(),
+ listReimbursementSets(),
]);
- setBackendConnected(true);
setLlmStatus(status);
- setLlmConfigured(status.is_configured);
-
- const dismissed = readOnboardingDismissed();
- setOnboardingDismissed(dismissed);
- // Show lightweight promo banner only when user already has invoices (not in first-time onboarding)
- // and hasn't dismissed onboarding/OCR-only preference
- const willShowOnboarding =
- !status.is_configured && invoicesResp.total === 0 && !dismissed;
- setOnboardingActive(willShowOnboarding);
- setShowLlmPromo(!status.is_configured && !willShowOnboarding && !dismissed);
+ const pending = stats.global_counts?.pending ?? stats.pending_count ?? 0;
+ const dup = stats.global_counts?.duplicate ?? stats.duplicate_count ?? 0;
+ setPendingAlertCount(pending + dup);
+ setReimbursementSetCount(sets.length);
} catch (error) {
- console.error('Failed to check initial backend status:', error);
- setBackendConnected(false);
- setLlmConfigured(false);
+ console.error('Failed to refresh shell state:', error);
}
}, []);
useEffect(() => {
- void refreshBootstrapState();
- }, [refreshBootstrapState]);
+ void refreshShellState();
+ }, [refreshShellState]);
- const handleLLMConfigured = async (closeOnboarding: boolean) => {
- try {
- const status = await getLLMStatus();
- setLlmStatus(status);
- setLlmConfigured(status.is_configured);
- if (status.is_configured) {
- setShowLlmPromo(false);
- if (closeOnboarding) {
- setOnboardingActive(false);
- }
- }
- } catch {
- setLlmConfigured(true);
- setShowLlmPromo(false);
- if (closeOnboarding) {
- setOnboardingActive(false);
+ // Global Cmd+K / Ctrl+K listener + custom events from pages
+ useEffect(() => {
+ const handleKeyDown = (e: KeyboardEvent) => {
+ if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === 'k') {
+ e.preventDefault();
+ setCmdPaletteOpen((prev) => !prev);
}
- }
- };
+ };
+ const handleOpenCmd = () => setCmdPaletteOpen(true);
+ const handleOpenSettings = () => setLlmConfigOpen(true);
+ const handleOpenOG = () => setOgPreviewOpen(true);
+ const handleRefreshCounts = () => {
+ void refreshShellState();
+ };
- const handleSkipOcrOnly = () => {
- try {
- window.localStorage.setItem(ONBOARDING_DISMISSED_KEY, 'true');
- } catch {
- // Ignore storage failures in restricted browsers
- }
- setOnboardingDismissed(true);
- setOnboardingActive(false);
- setShowLlmPromo(false);
- message.info('已切换为纯本地 OCR 模式,可随时在左侧「设置」中配置模型服务');
- };
+ window.addEventListener('keydown', handleKeyDown);
+ window.addEventListener('invoice:open-cmd', handleOpenCmd);
+ window.addEventListener('invoice:open-settings', handleOpenSettings);
+ window.addEventListener('invoice:open-og', handleOpenOG);
+ window.addEventListener('invoice:refresh-shell', handleRefreshCounts);
- const shouldShowOnboarding =
- location.pathname === '/' &&
- backendConnected &&
- llmStatus !== null &&
- onboardingActive &&
- !onboardingDismissed;
+ return () => {
+ window.removeEventListener('keydown', handleKeyDown);
+ window.removeEventListener('invoice:open-cmd', handleOpenCmd);
+ window.removeEventListener('invoice:open-settings', handleOpenSettings);
+ window.removeEventListener('invoice:open-og', handleOpenOG);
+ window.removeEventListener('invoice:refresh-shell', handleRefreshCounts);
+ };
+ }, [refreshShellState]);
+
+ const handleLLMConfigured = async () => {
+ await refreshShellState();
+ };
return (
setLlmConfigOpen(true)}
- onCloseLLMPromo={() => setShowLlmPromo(false)}
+ onOpenOGPreview={() => setOgPreviewOpen(true)}
>
- {shouldShowOnboarding && (
- handleLLMConfigured(false)}
- onSkipOcrOnly={handleSkipOcrOnly}
- onFinish={() => setOnboardingActive(false)}
- />
- )}
-
} />
} />
@@ -127,7 +96,20 @@ function AppContent() {
setLlmConfigOpen(false)}
- onConfigured={() => handleLLMConfigured(true)}
+ onConfigured={handleLLMConfigured}
+ />
+
+ setCmdPaletteOpen(false)}
+ onOpenSettings={() => setLlmConfigOpen(true)}
+ onOpenOGPreview={() => setOgPreviewOpen(true)}
+ reimbursementSetCount={reimbursementSetCount}
+ />
+
+ setOgPreviewOpen(false)}
/>
);
diff --git a/frontend/src/components/CommandPalette.module.css b/frontend/src/components/CommandPalette.module.css
new file mode 100644
index 0000000..593c4f3
--- /dev/null
+++ b/frontend/src/components/CommandPalette.module.css
@@ -0,0 +1,144 @@
+.backdrop {
+ position: fixed;
+ inset: 0;
+ background: var(--backdrop);
+ backdrop-filter: blur(4px);
+ z-index: 1050;
+ display: flex;
+ align-items: flex-start;
+ justify-content: center;
+ padding: 10vh 20px 20px;
+}
+
+.modal {
+ width: 580px;
+ max-width: 100%;
+ background: var(--bg-surface);
+ border: 1px solid var(--border-default);
+ border-radius: var(--radius-xl);
+ box-shadow: var(--shadow-modal);
+ overflow: hidden;
+ animation: cmdPop 150ms var(--ease-spring);
+}
+
+@keyframes cmdPop {
+ from {
+ opacity: 0;
+ transform: scale(0.97) translateY(6px);
+ }
+ to {
+ opacity: 1;
+ transform: scale(1) translateY(0);
+ }
+}
+
+.inputRow {
+ display: flex;
+ align-items: center;
+ gap: 10px;
+ padding: 14px 16px;
+ border-bottom: 1px solid var(--border-default);
+}
+
+.searchIcon {
+ color: var(--text-muted);
+ flex-shrink: 0;
+}
+
+.input {
+ flex: 1;
+ border: none;
+ background: transparent;
+ outline: none;
+ font-size: 14px;
+ color: var(--text-primary);
+}
+
+.input::placeholder {
+ color: var(--text-muted);
+}
+
+.kbd {
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ padding: 1px 6px;
+ border-radius: 4px;
+ border: 1px solid var(--border-default);
+ background: var(--bg-subtle);
+ color: var(--text-secondary);
+ font-family: var(--font-mono);
+ font-size: 11px;
+ line-height: 1.4;
+}
+
+.results {
+ max-height: 360px;
+ overflow-y: auto;
+ padding: 8px;
+ display: flex;
+ flex-direction: column;
+ gap: 2px;
+}
+
+.groupLabel {
+ font-size: 12px;
+ color: var(--text-muted);
+ padding: 6px 10px 4px;
+ font-weight: 500;
+}
+
+.item {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 12px;
+ width: 100%;
+ padding: 9px 10px;
+ border-radius: var(--radius-md);
+ border: none;
+ background: transparent;
+ text-align: left;
+ color: var(--text-primary);
+ font-size: 13px;
+ cursor: pointer;
+}
+
+.item:hover,
+.itemActive {
+ background: var(--bg-subtle);
+}
+
+.itemActive {
+ box-shadow: inset 3px 0 0 var(--brand-seal);
+}
+
+.itemLabel {
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+
+.itemHint {
+ font-size: 12px;
+ color: var(--text-muted);
+ flex-shrink: 0;
+}
+
+.empty {
+ padding: 28px;
+ text-align: center;
+ color: var(--text-muted);
+ font-size: 13px;
+}
+
+.footer {
+ padding: 8px 14px;
+ border-top: 1px solid var(--border-subtle);
+ background: var(--bg-table-head);
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ font-size: 12px;
+ color: var(--text-muted);
+}
diff --git a/frontend/src/components/CommandPalette.tsx b/frontend/src/components/CommandPalette.tsx
new file mode 100644
index 0000000..a917aab
--- /dev/null
+++ b/frontend/src/components/CommandPalette.tsx
@@ -0,0 +1,303 @@
+import { useState, useEffect, useRef, useMemo } from 'react';
+import { useNavigate } from 'react-router-dom';
+import { listInvoices } from '../services/api';
+import { useTheme } from '../contexts/ThemeContext';
+import type { Invoice } from '../types/invoice';
+import styles from './CommandPalette.module.css';
+
+interface CommandPaletteProps {
+ open: boolean;
+ onClose: () => void;
+ onOpenSettings: () => void;
+ onOpenOGPreview: () => void;
+ reimbursementSetCount: number;
+}
+
+interface PaletteEntry {
+ id: string;
+ group: string;
+ label: string;
+ hint: string;
+ searchText: string;
+ run: () => void;
+}
+
+function fmtMoney(val: number | string | null | undefined): string {
+ const num = Number(val ?? 0);
+ if (Number.isNaN(num)) return '¥0.00';
+ return '¥' + num.toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
+}
+
+export default function CommandPalette({
+ open,
+ onClose,
+ onOpenSettings,
+ onOpenOGPreview,
+ reimbursementSetCount,
+}: CommandPaletteProps) {
+ const navigate = useNavigate();
+ const { isDark, toggleTheme } = useTheme();
+ const [query, setQuery] = useState('');
+ const [activeIdx, setActiveIdx] = useState(0);
+ const [invoices, setInvoices] = useState([]);
+ const [loading, setLoading] = useState(false);
+ const inputRef = useRef(null);
+
+ useEffect(() => {
+ if (!open) return;
+ setQuery('');
+ setActiveIdx(0);
+ const timer = window.setTimeout(() => {
+ inputRef.current?.focus();
+ }, 20);
+ return () => window.clearTimeout(timer);
+ }, [open]);
+
+ useEffect(() => {
+ if (!open) return;
+ let cancelled = false;
+ const fetchItems = async () => {
+ setLoading(true);
+ try {
+ const resp = await listInvoices({
+ page: 1,
+ page_size: 12,
+ q: query.trim() || undefined,
+ });
+ if (!cancelled) {
+ setInvoices(resp.items);
+ }
+ } catch {
+ if (!cancelled) {
+ setInvoices([]);
+ }
+ } finally {
+ if (!cancelled) {
+ setLoading(false);
+ }
+ }
+ };
+ const debounce = window.setTimeout(() => {
+ void fetchItems();
+ }, 120);
+ return () => {
+ cancelled = true;
+ window.clearTimeout(debounce);
+ };
+ }, [open, query]);
+
+ const entries = useMemo(() => {
+ const q = query.trim().toLowerCase();
+ const systemCommands: PaletteEntry[] = [
+ {
+ id: 'cmd-upload',
+ group: '快捷动作',
+ label: '上传并实时解析发票',
+ hint: '跳转上传队列',
+ searchText: 'upload 上传 解析 队列 导入',
+ run: () => {
+ onClose();
+ navigate('/upload');
+ },
+ },
+ {
+ id: 'cmd-theme',
+ group: '快捷动作',
+ label: isDark ? '切换主题:暖纸日间 · 印鉴账本' : '切换主题:深墨夜间 · 暗房审票',
+ hint: 'Theme',
+ searchText: 'theme dark light 暗房 日间 夜间 主题',
+ run: () => {
+ onClose();
+ toggleTheme();
+ },
+ },
+ {
+ id: 'cmd-settings',
+ group: '快捷动作',
+ label: '打开识别引擎与模型设置中心',
+ hint: 'LLM / OCR',
+ searchText: 'settings llm ocr api key 设置 引擎 模型 deepseek qwen',
+ run: () => {
+ onClose();
+ onOpenSettings();
+ },
+ },
+ {
+ id: 'cmd-og',
+ group: '快捷动作',
+ label: '预览 GitHub 开源名片 (OG 1280×640)',
+ hint: 'Social Card',
+ searchText: 'og social preview card 开源 名片 github',
+ run: () => {
+ onClose();
+ onOpenOGPreview();
+ },
+ },
+ {
+ id: 'cmd-sets',
+ group: '快捷动作',
+ label: '查看报销集与导出打包',
+ hint: `${reimbursementSetCount} 个集合`,
+ searchText: 'reimbursement set 报销集 打包 导出 excel pdf zip',
+ run: () => {
+ onClose();
+ navigate('/reimbursement-sets');
+ },
+ },
+ {
+ id: 'cmd-workbench',
+ group: '快捷动作',
+ label: '返回发票工作台首页',
+ hint: '工作台',
+ searchText: 'home list workbench 首页 发票 列表 工作台',
+ run: () => {
+ onClose();
+ navigate('/');
+ },
+ },
+ {
+ id: 'cmd-filter-review',
+ group: '快捷动作',
+ label: '筛选全部待校对发票',
+ hint: '待校对',
+ searchText: 'pending review 待校对 待审核',
+ run: () => {
+ onClose();
+ navigate('/?tab=pending');
+ },
+ },
+ ];
+
+ const matchedSystem = q
+ ? systemCommands.filter((c) =>
+ `${c.label} ${c.hint} ${c.searchText}`.toLowerCase().includes(q)
+ )
+ : systemCommands;
+
+ const invoiceEntries: PaletteEntry[] = invoices.map((inv) => ({
+ id: `inv-${inv.id}`,
+ group: '直达发票空间校对',
+ label: `${inv.seller_name || inv.file_name} · ${fmtMoney(inv.total_with_tax)}`,
+ hint: inv.invoice_number || `#${inv.id}`,
+ searchText: `${inv.invoice_number || ''} ${inv.seller_name || ''} ${inv.buyer_name || ''} ${inv.item_name || ''}`.toLowerCase(),
+ run: () => {
+ onClose();
+ navigate(`/invoices/${inv.id}`);
+ },
+ }));
+
+ return [...matchedSystem, ...invoiceEntries];
+ }, [query, invoices, isDark, onClose, navigate, toggleTheme, onOpenSettings, onOpenOGPreview, reimbursementSetCount]);
+
+ useEffect(() => {
+ if (activeIdx >= entries.length) {
+ setActiveIdx(0);
+ }
+ }, [entries.length, activeIdx]);
+
+ useEffect(() => {
+ if (!open) return;
+ const handleKeyDown = (e: KeyboardEvent) => {
+ if (e.key === 'Escape') {
+ e.preventDefault();
+ onClose();
+ } else if (e.key === 'ArrowDown') {
+ e.preventDefault();
+ setActiveIdx((prev) => (entries.length ? (prev + 1) % entries.length : 0));
+ } else if (e.key === 'ArrowUp') {
+ e.preventDefault();
+ setActiveIdx((prev) =>
+ entries.length ? (prev - 1 + entries.length) % entries.length : 0
+ );
+ } else if (e.key === 'Enter') {
+ e.preventDefault();
+ entries[activeIdx]?.run();
+ }
+ };
+ window.addEventListener('keydown', handleKeyDown);
+ return () => window.removeEventListener('keydown', handleKeyDown);
+ }, [open, entries, activeIdx, onClose]);
+
+ if (!open) return null;
+
+ let lastGroup = '';
+
+ return (
+ {
+ if (e.target === e.currentTarget) onClose();
+ }}
+ data-testid="command-palette-backdrop"
+ >
+
+
+
+ {
+ setQuery(e.target.value);
+ setActiveIdx(0);
+ }}
+ placeholder="搜索 20 位票号、销售方,或输入命令(暗房 / 上传 / 设置 / OG)..."
+ data-testid="command-palette-input"
+ />
+ ESC
+
+
+
+ {entries.length === 0 ? (
+
+ {loading ? '正在检索发票与命令...' : '未找到匹配的命令或发票'}
+
+ ) : (
+ entries.map((item, idx) => {
+ const showGroup = item.group !== lastGroup;
+ lastGroup = item.group;
+ return (
+
+ {showGroup &&
{item.group}
}
+
+
+ );
+ })
+ )}
+
+
+
+ ↑↓ 选择 · ↵ 执行 · ⌘K 快速唤起
+ Invoice Manager Command Palette
+
+
+
+ );
+}
diff --git a/frontend/src/components/LLMConfigModal.module.css b/frontend/src/components/LLMConfigModal.module.css
new file mode 100644
index 0000000..2c051ef
--- /dev/null
+++ b/frontend/src/components/LLMConfigModal.module.css
@@ -0,0 +1,441 @@
+.backdrop {
+ position: fixed;
+ inset: 0;
+ background: var(--backdrop);
+ backdrop-filter: blur(4px);
+ z-index: 1040;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ padding: 20px;
+}
+
+.modal {
+ width: 720px;
+ max-width: calc(100vw - 32px);
+ max-height: calc(100vh - 44px);
+ background: var(--bg-surface);
+ border-radius: var(--radius-xl);
+ border: 1px solid var(--border-default);
+ box-shadow: var(--shadow-modal);
+ display: flex;
+ flex-direction: column;
+ overflow: hidden;
+ animation: modalPop 180ms var(--ease-spring);
+}
+
+@keyframes modalPop {
+ from {
+ opacity: 0;
+ transform: scale(0.97) translateY(6px);
+ }
+ to {
+ opacity: 1;
+ transform: scale(1) translateY(0);
+ }
+}
+
+.header {
+ padding: 15px 20px;
+ border-bottom: 1px solid var(--border-default);
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 12px;
+ flex-shrink: 0;
+}
+
+.headerTitle {
+ font-size: 16px;
+ font-weight: 650;
+ color: var(--text-primary);
+}
+
+.headerSub {
+ font-size: 12px;
+ color: var(--text-muted);
+ margin-top: 2px;
+}
+
+.closeBtn {
+ width: 28px;
+ height: 28px;
+ border-radius: var(--radius-md);
+ border: none;
+ background: transparent;
+ color: var(--text-secondary);
+ font-size: 14px;
+ cursor: pointer;
+}
+
+.closeBtn:hover {
+ background: var(--bg-subtle);
+ color: var(--text-primary);
+}
+
+.body {
+ padding: 16px 20px;
+ overflow-y: auto;
+ display: flex;
+ flex-direction: column;
+ gap: 14px;
+ flex: 1;
+ min-height: 0;
+}
+
+.loadingWrap {
+ padding: 48px 0;
+ text-align: center;
+}
+
+.groupTitle {
+ font-size: 12px;
+ font-weight: 600;
+ color: var(--text-secondary);
+ margin-bottom: 8px;
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+}
+
+.groupMeta {
+ font-weight: 400;
+ color: var(--text-muted);
+}
+
+.providerGrid {
+ display: grid;
+ grid-template-columns: repeat(3, minmax(0, 1fr));
+ gap: 8px;
+}
+
+.providerCard {
+ padding: 10px 12px;
+ border-radius: var(--radius-md);
+ border: 1px solid var(--border-default);
+ background: var(--bg-surface);
+ text-align: left;
+ display: flex;
+ flex-direction: column;
+ gap: 4px;
+ cursor: pointer;
+ width: 100%;
+ transition: all 140ms ease;
+}
+
+.providerCard:hover {
+ border-color: var(--border-strong);
+ background: var(--bg-hover);
+}
+
+.providerCardSelected {
+ border-color: var(--action-primary);
+ background: var(--bg-subtle);
+ box-shadow: inset 0 0 0 1px var(--action-primary);
+}
+
+.offlineCard {
+ width: 100%;
+}
+
+.providerCardTop {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 6px;
+}
+
+.providerName {
+ font-weight: 600;
+ font-size: 13px;
+ color: var(--text-primary);
+ white-space: nowrap;
+ overflow: hidden;
+ text-overflow: ellipsis;
+}
+
+.cardBadges {
+ display: flex;
+ align-items: center;
+ gap: 4px;
+ flex-shrink: 0;
+}
+
+.providerDesc {
+ font-size: 12px;
+ color: var(--text-muted);
+ white-space: nowrap;
+ overflow: hidden;
+ text-overflow: ellipsis;
+}
+
+.miniTag {
+ font-size: 11px;
+ padding: 1px 6px;
+ border-radius: 4px;
+ font-weight: 500;
+ white-space: nowrap;
+}
+
+.miniTagActive {
+ background: var(--status-success-bg);
+ color: var(--status-success-text);
+}
+
+.miniTagSaved {
+ background: var(--brand-seal-soft);
+ color: var(--brand-seal-text);
+}
+
+.miniTagVision {
+ background: var(--status-info-bg);
+ color: var(--status-info-text);
+}
+
+.miniTagFree {
+ background: var(--bg-subtle);
+ color: var(--text-secondary);
+}
+
+.configPanel {
+ background: var(--bg-canvas);
+ border: 1px solid var(--border-default);
+ border-radius: var(--radius-lg);
+ padding: 14px 16px;
+ display: flex;
+ flex-direction: column;
+ gap: 12px;
+}
+
+.offlineInfo {
+ display: flex;
+ flex-direction: column;
+ gap: 4px;
+}
+
+.offlineTitle {
+ font-size: 13px;
+ font-weight: 600;
+ color: var(--text-primary);
+}
+
+.offlineText {
+ font-size: 12px;
+ color: var(--text-secondary);
+ line-height: 1.5;
+}
+
+.configPanelHead {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 8px;
+}
+
+.configPanelTitle {
+ font-weight: 600;
+ font-size: 13px;
+ color: var(--text-primary);
+}
+
+.configPanelMeta {
+ display: flex;
+ align-items: center;
+ gap: 10px;
+}
+
+.docsLink {
+ font-size: 12px;
+ color: var(--brand-seal-text);
+ font-weight: 500;
+}
+
+.formGrid2 {
+ display: grid;
+ grid-template-columns: 1fr 1fr;
+ gap: 12px;
+}
+
+.formLabel {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ font-size: 12px;
+ font-weight: 500;
+ color: var(--text-secondary);
+ margin-bottom: 5px;
+}
+
+.requiredTag {
+ color: var(--brand-seal-text);
+}
+
+.mutedLabel {
+ color: var(--text-muted);
+}
+
+.inputText {
+ width: 100%;
+ height: 34px;
+ border-radius: var(--radius-md);
+ border: 1px solid var(--border-default);
+ background: var(--bg-surface);
+ color: var(--text-primary);
+ padding: 0 10px;
+ font-size: 13px;
+ outline: none;
+}
+
+.inputText:focus {
+ border-color: var(--action-primary);
+ box-shadow: 0 0 0 2px var(--brand-seal-glow);
+}
+
+.modelChips {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 5px;
+ margin-top: 6px;
+}
+
+.modelChip {
+ font-size: 11px;
+ padding: 2px 8px;
+ border-radius: 99px;
+ border: 1px solid var(--border-default);
+ background: var(--bg-surface);
+ color: var(--text-secondary);
+ cursor: pointer;
+}
+
+.modelChip:hover {
+ border-color: var(--border-strong);
+ color: var(--text-primary);
+}
+
+.modelChipActive {
+ border-color: var(--action-primary);
+ background: var(--action-primary);
+ color: var(--action-primary-text);
+}
+
+.visionRow {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 12px;
+ padding: 8px 10px;
+ border-radius: var(--radius-md);
+ background: var(--bg-surface);
+ border: 1px solid var(--border-subtle);
+}
+
+.visionLabel {
+ font-size: 12px;
+ font-weight: 600;
+ color: var(--text-primary);
+}
+
+.visionSub {
+ font-size: 12px;
+ color: var(--text-muted);
+ margin-top: 1px;
+}
+
+.advancedToggle {
+ font-size: 12px;
+ color: var(--text-secondary);
+ background: none;
+ border: none;
+ text-align: left;
+ width: fit-content;
+ cursor: pointer;
+ padding: 0;
+}
+
+.advancedToggle:hover {
+ color: var(--text-primary);
+}
+
+.footer {
+ padding: 12px 20px;
+ border-top: 1px solid var(--border-default);
+ background: var(--bg-table-head);
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 12px;
+ flex-shrink: 0;
+}
+
+.feedbackSlot {
+ font-size: 12px;
+ min-width: 0;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+
+.fbMuted {
+ color: var(--text-muted);
+}
+
+.fbInfo {
+ color: var(--status-info-text);
+ font-weight: 500;
+}
+
+.fbSuccess {
+ color: var(--status-success-text);
+ font-weight: 600;
+}
+
+.fbError {
+ color: var(--status-danger-text);
+ font-weight: 600;
+}
+
+.footerActions {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ flex-shrink: 0;
+}
+
+.btn {
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ height: 34px;
+ padding: 0 13px;
+ border-radius: var(--radius-md);
+ border: 1px solid var(--border-default);
+ background: var(--bg-surface);
+ color: var(--text-primary);
+ font-size: 13px;
+ font-weight: 500;
+ cursor: pointer;
+ white-space: nowrap;
+}
+
+.btn:hover:not(:disabled) {
+ background: var(--bg-subtle);
+ border-color: var(--border-strong);
+}
+
+.btn:disabled {
+ opacity: 0.48;
+ cursor: not-allowed;
+}
+
+.btnPrimary {
+ background: var(--action-primary);
+ border-color: var(--action-primary);
+ color: var(--action-primary-text);
+}
+
+.btnPrimary:hover:not(:disabled) {
+ background: var(--action-primary-hover);
+ border-color: var(--action-primary-hover);
+ color: var(--action-primary-text);
+}
diff --git a/frontend/src/components/LLMConfigModal.tsx b/frontend/src/components/LLMConfigModal.tsx
index fd67f87..c0b751f 100644
--- a/frontend/src/components/LLMConfigModal.tsx
+++ b/frontend/src/components/LLMConfigModal.tsx
@@ -1,190 +1,121 @@
-import { useState, useEffect, useRef, useMemo } from 'react';
+import { useState, useEffect, useMemo, useRef } from 'react';
+import { Spin, Switch, message } from 'antd';
import {
- Modal,
- Form,
- Select,
- Input,
- Button,
- Space,
- message,
- Alert,
- Spin,
- Tag,
- Divider,
- Tooltip,
- AutoComplete,
- Switch,
- Typography,
-} from 'antd';
-import {
- SettingOutlined,
- CheckCircleOutlined,
- ExclamationCircleOutlined,
- ApiOutlined,
- EyeOutlined,
- LinkOutlined,
-} from '@ant-design/icons';
-import { getLLMStatus, configureLLM, testLLMConfig, getAvailableModels } from '../services/api';
+ getLLMStatus,
+ configureLLM,
+ disableLLM,
+ testLLMConfig,
+} from '../services/api';
import type {
LLMStatusResponse,
- ModelInfo,
ProviderPresetInfo,
} from '../types/invoice';
-
-const { Text } = Typography;
+import styles from './LLMConfigModal.module.css';
interface LLMConfigModalProps {
open: boolean;
onClose: () => void;
- onConfigured?: () => void;
+ onConfigured?: () => Promise | void;
}
interface TestFeedback {
- success: boolean;
+ state: 'idle' | 'testing' | 'success' | 'error';
message: string;
responseTimeMs?: number;
}
-function LLMConfigModal({ open, onClose, onConfigured }: LLMConfigModalProps) {
+const OFFLINE_ID = 'ocr_only';
+
+export default function LLMConfigModal({
+ open,
+ onClose,
+ onConfigured,
+}: LLMConfigModalProps) {
const [loading, setLoading] = useState(true);
- const [testingConfig, setTestingConfig] = useState(false);
- const [configuring, setConfiguring] = useState(false);
+ const [saving, setSaving] = useState(false);
const [status, setStatus] = useState(null);
- const [selectedProvider, setSelectedProvider] = useState('');
- const [models, setModels] = useState([]);
- const [modelsLoading, setModelsLoading] = useState(false);
- const [modelsSource, setModelsSource] = useState<'openrouter' | 'fallback'>('fallback');
- const [testFeedback, setTestFeedback] = useState(null);
- const modelsRequestSeqRef = useRef(0);
- const testRequestSeqRef = useRef(0);
- const [form] = Form.useForm();
- const presets: ProviderPresetInfo[] = useMemo(() => status?.presets || [], [status]);
+ const [selectedProvider, setSelectedProvider] = useState(OFFLINE_ID);
+ const [apiKey, setApiKey] = useState('');
+ const [model, setModel] = useState('');
+ const [baseUrl, setBaseUrl] = useState('');
+ const [supportsVision, setSupportsVision] = useState(true);
+ const [configToken, setConfigToken] = useState('');
+ const [showAdvanced, setShowAdvanced] = useState(false);
+ const [testFeedback, setTestFeedback] = useState({
+ state: 'idle',
+ message: '配置更改仅在点击「保存并启用」后生效',
+ });
+ const testSeqRef = useRef(0);
+
+ const presets: ProviderPresetInfo[] = useMemo(() => status?.presets || [], [status]);
const recommendedPresets = useMemo(
() => presets.filter((p) => p.recommended),
[presets]
);
+ const domesticPresets = useMemo(
+ () => presets.filter((p) => !p.recommended && p.category === 'domestic'),
+ [presets]
+ );
+ const intlPresets = useMemo(
+ () =>
+ presets.filter(
+ (p) => !p.recommended && (p.category === 'global' || p.category === 'custom')
+ ),
+ [presets]
+ );
const selectedPreset = useMemo(
() => presets.find((p) => p.id === selectedProvider) || null,
[presets, selectedProvider]
);
- const groupedSelectOptions = useMemo(() => {
- const groups: Array<{
- label: string;
- options: Array<{ label: string; value: string }>;
- }> = [];
-
- // Recommended group is ONLY rendered when at least one preset has recommended=true
- if (recommendedPresets.length > 0) {
- groups.push({
- label: '推荐',
- options: recommendedPresets.map((p) => ({ label: p.name, value: p.id })),
- });
- }
-
- const domestic = presets.filter((p) => !p.recommended && p.category === 'domestic');
- if (domestic.length > 0) {
- groups.push({
- label: '国内常用',
- options: domestic.map((p) => ({ label: p.name, value: p.id })),
- });
- }
-
- const global = presets.filter((p) => !p.recommended && p.category === 'global');
- if (global.length > 0) {
- groups.push({
- label: '海外服务',
- options: global.map((p) => ({ label: p.name, value: p.id })),
- });
- }
-
- const custom = presets.filter((p) => !p.recommended && p.category === 'custom');
- if (custom.length > 0) {
- groups.push({
- label: '自定义',
- options: custom.map((p) => ({ label: p.name, value: p.id })),
- });
- }
-
- return groups;
- }, [presets, recommendedPresets]);
+ const applyProviderSelection = (providerId: string, statusData: LLMStatusResponse) => {
+ testSeqRef.current += 1;
+ setSelectedProvider(providerId);
+ setApiKey('');
+ setConfigToken('');
+ setTestFeedback({
+ state: 'idle',
+ message: '各服务商模型与密钥状态完全隔离',
+ });
- const enrichModelsAsync = async (providerId: string, presetModels: ModelInfo[]) => {
- const reqId = ++modelsRequestSeqRef.current;
- setModels(presetModels);
- setModelsSource('fallback');
- setModelsLoading(true);
- try {
- const response = await getAvailableModels(providerId, false);
- // Guard against stale async callbacks from an earlier request
- if (modelsRequestSeqRef.current !== reqId) {
- return;
- }
- if (response.models && response.models.length > 0) {
- setModels(response.models);
- setModelsSource(response.source);
- }
- } catch (error) {
- if (modelsRequestSeqRef.current === reqId) {
- setModels(presetModels);
- setModelsSource('fallback');
- }
- console.error('Failed to fetch models:', error);
- } finally {
- if (modelsRequestSeqRef.current === reqId) {
- setModelsLoading(false);
- }
+ if (providerId === OFFLINE_ID) {
+ setModel('');
+ setBaseUrl('');
+ setSupportsVision(false);
+ setShowAdvanced(false);
+ return;
}
- };
-
- const applyPresetToForm = (providerId: string, statusData: LLMStatusResponse) => {
- testRequestSeqRef.current += 1;
- setTestingConfig(false);
- setSelectedProvider(providerId);
- setTestFeedback(null);
const preset = (statusData.presets || []).find((p) => p.id === providerId);
- const savedProvider = statusData.available_providers.find((p) => p.name === providerId);
+ const saved = statusData.available_providers.find((p) => p.name === providerId);
const isActive = statusData.is_configured && statusData.active_provider === providerId;
const nextModel = isActive
? (statusData.active_model ?? preset?.default_model ?? '')
- : savedProvider?.is_configured
- ? (savedProvider.model ?? preset?.default_model ?? '')
+ : saved?.is_configured
+ ? (saved.model ?? preset?.default_model ?? '')
: (preset?.default_model ?? '');
- const nextBaseUrl = isActive
+ const nextBase = isActive
? (statusData.active_base_url ?? preset?.base_url ?? '')
- : savedProvider?.is_configured
- ? (savedProvider.base_url ?? preset?.base_url ?? '')
+ : saved?.is_configured
+ ? (saved.base_url ?? preset?.base_url ?? '')
: (preset?.base_url ?? '');
- const matchedPresetModel = (preset?.models || []).find((m) => m.id === nextModel);
- const nextSupportsVision = isActive
+ const matchedModel = (preset?.models || []).find((m) => m.id === nextModel);
+ const nextVision = isActive
? Boolean(statusData.supports_vision)
- : matchedPresetModel
- ? matchedPresetModel.vision
+ : matchedModel
+ ? matchedModel.vision
: Boolean(preset?.supports_vision);
- // Unconditionally reset all form fields for the chosen provider (prevents model/base_url bleed)
- form.setFieldsValue({
- provider: providerId,
- model: nextModel,
- base_url: nextBaseUrl,
- supports_vision: nextSupportsVision,
- api_key: '',
- config_token: '',
- });
-
- const staticModels: ModelInfo[] = (preset?.models || []).map((m) => ({
- id: m.id,
- name: m.name,
- vision: m.vision,
- }));
- void enrichModelsAsync(providerId, staticModels);
+ setModel(nextModel);
+ setBaseUrl(nextBase);
+ setSupportsVision(nextVision);
+ setShowAdvanced(preset?.category === 'custom');
};
const fetchStatus = async (preferredProvider?: string) => {
@@ -192,14 +123,13 @@ function LLMConfigModal({ open, onClose, onConfigured }: LLMConfigModalProps) {
try {
const data = await getLLMStatus();
setStatus(data);
- const targetProvider =
+ const target =
preferredProvider ||
- (data.is_configured && data.active_provider) ||
- data.presets?.[0]?.id ||
- 'qwen';
- applyPresetToForm(targetProvider, data);
+ (data.is_configured && data.active_provider ? data.active_provider : OFFLINE_ID);
+ applyProviderSelection(target, data);
} catch (error) {
console.error('Failed to fetch LLM status:', error);
+ message.error('加载引擎配置状态失败');
} finally {
setLoading(false);
}
@@ -207,410 +137,469 @@ function LLMConfigModal({ open, onClose, onConfigured }: LLMConfigModalProps) {
useEffect(() => {
if (open) {
- modelsRequestSeqRef.current += 1;
- testRequestSeqRef.current += 1;
- setTestingConfig(false);
- setTestFeedback(null);
- form.resetFields();
void fetchStatus();
} else {
- modelsRequestSeqRef.current += 1;
- testRequestSeqRef.current += 1;
- setTestingConfig(false);
+ testSeqRef.current += 1;
}
}, [open]);
- const handleProviderChange = (providerId: string) => {
+ useEffect(() => {
+ if (!open) return;
+ const onKey = (e: KeyboardEvent) => {
+ if (e.key === 'Escape') onClose();
+ };
+ window.addEventListener('keydown', onKey);
+ return () => window.removeEventListener('keydown', onKey);
+ }, [open, onClose]);
+
+ const handleSelectCard = (providerId: string) => {
if (!status) return;
- applyPresetToForm(providerId, status);
+ applyProviderSelection(providerId, status);
};
- const handleModelSelect = (modelId: string) => {
- const matched = models.find((m) => m.id === modelId);
- if (matched) {
- form.setFieldValue('supports_vision', matched.vision);
- }
- };
-
- const handleConfigure = async () => {
- try {
- const values = await form.validateFields();
- setConfiguring(true);
-
- const config = {
- provider: values.provider,
- api_key: values.api_key.trim(),
- model: values.model?.trim() || undefined,
- base_url: values.base_url?.trim() || undefined,
- supports_vision: Boolean(values.supports_vision),
- };
-
- const configToken = values.config_token?.trim();
- const result = await configureLLM(config, configToken || undefined);
- if (result.success) {
- message.success(result.message);
- await fetchStatus(result.provider || values.provider);
- onConfigured?.();
- }
- } catch (error: unknown) {
- if (error && typeof error === 'object' && 'response' in error) {
- const axiosError = error as { response?: { data?: { detail?: string } } };
- if (axiosError.response?.data?.detail) {
- message.error(axiosError.response.data.detail);
- return;
- }
- }
- if (error && typeof error === 'object' && 'errorFields' in error) {
- return;
- }
- message.error('配置失败');
- } finally {
- setConfiguring(false);
- }
+ const handlePickModelChip = (modelId: string, isVision: boolean) => {
+ setModel(modelId);
+ setSupportsVision(isVision);
+ setTestFeedback({ state: 'idle', message: '已切换推荐模型,点击「测试连接」验证' });
};
- const handleTestConfig = async () => {
- const values = form.getFieldsValue();
- if (!values.provider) {
- message.warning('请先选择模型服务商');
- return;
- }
- if (!values.api_key?.trim()) {
- message.warning('请先输入 API 密钥');
+ const handleTestConnection = async () => {
+ if (selectedProvider === OFFLINE_ID) return;
+ const trimmedKey = apiKey.trim();
+ if (!trimmedKey) {
+ setTestFeedback({ state: 'error', message: '请先输入 API 密钥' });
return;
}
- if (selectedPreset?.category === 'custom' && !values.base_url?.trim()) {
- message.warning('自定义服务请先填写 API 地址 (Base URL)');
+ if (selectedPreset?.category === 'custom' && !baseUrl.trim()) {
+ setTestFeedback({ state: 'error', message: '自定义服务请先填写 API 地址 (Base URL)' });
return;
}
- const reqId = ++testRequestSeqRef.current;
- setTestingConfig(true);
- setTestFeedback(null);
+ const seq = ++testSeqRef.current;
+ setTestFeedback({ state: 'testing', message: '正在测试模型连通性...' });
try {
- const configToken = values.config_token?.trim() || undefined;
- const result = await testLLMConfig(
+ const res = await testLLMConfig(
{
- provider: values.provider,
- api_key: values.api_key.trim(),
- model: values.model?.trim() || undefined,
- base_url: values.base_url?.trim() || undefined,
- supports_vision: Boolean(values.supports_vision),
+ provider: selectedProvider,
+ api_key: trimmedKey,
+ model: model.trim() || undefined,
+ base_url: baseUrl.trim() || undefined,
+ supports_vision: supportsVision,
},
- configToken
+ configToken.trim() || undefined
);
- if (testRequestSeqRef.current !== reqId) {
- return;
- }
+ if (testSeqRef.current !== seq) return;
setTestFeedback({
- success: result.success,
- message: result.message,
- responseTimeMs: result.response_time_ms,
+ state: res.success ? 'success' : 'error',
+ message: res.message,
+ responseTimeMs: res.response_time_ms,
});
- if (result.success) {
- message.success(
- result.response_time_ms != null
- ? `${result.message} (${result.response_time_ms}ms)`
- : result.message
- );
- } else {
- message.error(result.message);
- }
} catch (error: unknown) {
- if (testRequestSeqRef.current !== reqId) {
+ if (testSeqRef.current !== seq) return;
+ let detail = '连接测试失败';
+ if (error && typeof error === 'object' && 'response' in error) {
+ const ax = error as { response?: { data?: { detail?: string } } };
+ if (ax.response?.data?.detail) detail = ax.response.data.detail;
+ }
+ setTestFeedback({ state: 'error', message: detail });
+ }
+ };
+
+ const handleSave = async () => {
+ setSaving(true);
+ try {
+ if (selectedProvider === OFFLINE_ID) {
+ const res = await disableLLM(configToken.trim() || undefined);
+ message.success(res.message);
+ await onConfigured?.();
+ onClose();
+ return;
+ }
+
+ const trimmedKey = apiKey.trim();
+ if (!trimmedKey) {
+ setTestFeedback({ state: 'error', message: '保存前请输入 API 密钥' });
+ setSaving(false);
return;
}
- let detail = '配置测试失败';
+ if (selectedPreset?.category === 'custom' && !baseUrl.trim()) {
+ setTestFeedback({ state: 'error', message: '自定义服务必须填写 API Base URL' });
+ setSaving(false);
+ return;
+ }
+ if (selectedPreset?.category === 'custom' && !model.trim()) {
+ setTestFeedback({ state: 'error', message: '自定义服务必须填写模型 ID' });
+ setSaving(false);
+ return;
+ }
+
+ const res = await configureLLM(
+ {
+ provider: selectedProvider,
+ api_key: trimmedKey,
+ model: model.trim() || undefined,
+ base_url: baseUrl.trim() || undefined,
+ supports_vision: supportsVision,
+ },
+ configToken.trim() || undefined
+ );
+ if (res.success) {
+ message.success(res.message);
+ await onConfigured?.();
+ onClose();
+ }
+ } catch (error: unknown) {
+ let detail = '保存配置失败';
if (error && typeof error === 'object' && 'response' in error) {
- const axiosError = error as { response?: { data?: { detail?: string } } };
- if (axiosError.response?.data?.detail) {
- detail = axiosError.response.data.detail;
- }
+ const ax = error as { response?: { data?: { detail?: string } } };
+ if (ax.response?.data?.detail) detail = ax.response.data.detail;
}
- setTestFeedback({ success: false, message: detail });
+ setTestFeedback({ state: 'error', message: detail });
message.error(detail);
} finally {
- if (testRequestSeqRef.current === reqId) {
- setTestingConfig(false);
- }
+ setSaving(false);
}
};
- const isCustomProvider = selectedPreset?.category === 'custom';
+ if (!open) return null;
+
+ const activeProviderId = status?.is_configured ? status.active_provider : OFFLINE_ID;
+
+ const renderProviderCard = (p: ProviderPresetInfo) => {
+ const isSelected = p.id === selectedProvider;
+ const isActive = p.id === activeProviderId;
+ const isConfigured = Boolean(status?.configured_providers.includes(p.id));
+ return (
+
+ );
+ };
return (
-
-
- 模型服务配置
-
- }
- open={open}
- onCancel={onClose}
- footer={null}
- width={640}
- destroyOnClose={false}
+ {
+ if (e.target === e.currentTarget) onClose();
+ }}
+ data-testid="settings-modal-backdrop"
>
- {loading ? (
-
-
-
- ) : (
- <>
- {/* Current Status Banner */}
- {status?.is_configured ? (
-
-
- 当前使用: {status.active_provider_display}
- {status.active_model && {status.active_model}}
-
- {status.supports_vision ? '视觉看图:已开启' : '视觉看图:未开启'}
-
-
- }
- type="success"
- showIcon={false}
- style={{ marginBottom: 16 }}
- />
- ) : (
- }
- style={{ marginBottom: 16 }}
- />
- )}
-
- {/* Recommended Preset Card — ONLY rendered when recommended presets exist */}
- {recommendedPresets.length > 0 && (
-
- {recommendedPresets.map((preset) => (
-
- 推荐
- {preset.name}
- {preset.docs_url && (
-
- 获取 Key
-
- )}
-
- }
- description={preset.description}
- style={{ marginBottom: 8 }}
- />
- ))}
+
+ {/* Fixed Header */}
+
+
+
识别引擎与模型配置
+
+ 内置免费本地 OCR;接入 LLM 后自动交叉校验抬头、税额与明细差异
- )}
+
+
+
- {/* Configured Providers Summary */}
- {status && status.configured_providers.length > 0 && (
-
-
- 已保存密钥的服务商:
-
-
- {status.available_providers
- .filter((p) => p.is_configured)
- .map((p) => (
- handleProviderChange(p.name)}
- >
- {p.display_name}
- {p.model ? ` · ${p.model}` : ''}
-
- ))}
-
+ {/* Scrollable Body (never clips Footer) */}
+
+ {loading ? (
+
+
+ ) : (
+ <>
+ {/* Recommended group — strictly hidden when recommendedPresets.length === 0 */}
+ {recommendedPresets.length > 0 && (
+
+
+ 推荐通道
+
+
+ {recommendedPresets.map(renderProviderCard)}
+
+
+ )}
+
+ {/* Domestic Providers */}
+
+
+ 国内直连常用
+ 低延迟 · 人民币结算
+
+
+ {domesticPresets.map(renderProviderCard)}
+
+
+
+ {/* International & OpenAI-Compatible */}
+
+
+ 海外与 OpenAI 兼容聚合
+ 兼容 Ollama / 自定义网关
+
+
+ {intlPresets.map(renderProviderCard)}
+
+
+
+ {/* Zero-cost Local Offline OCR Card */}
+
+
+ 零成本离线方案
+
+
+
+
+ {/* Active Configuration Panel */}
+
+ {selectedProvider === OFFLINE_ID ? (
+
+
纯本地 OCR 离线模式
+
+ 不向任何外部模型发送发票数据;直接读取数电 PDF 矢量文本层并对扫描件启用 PaddleOCR。点击下方「保存并启用」即可持久化该模式。
+
+
+ ) : (
+ selectedPreset && (
+ <>
+
+
+ {selectedPreset.name} 参数配置
+
+
+
+
+
+
+
+ {
+ setApiKey(e.target.value);
+ setTestFeedback({
+ state: 'idle',
+ message: '点击「测试连接」验证密钥与模型可用性',
+ });
+ }}
+ placeholder={`粘贴 ${selectedPreset.name} API Key...`}
+ data-testid="api-key-input"
+ />
+
+
+
+
+
setModel(e.target.value)}
+ placeholder={selectedPreset.default_model || '例如 vendor/vision-pro'}
+ data-testid="model-input"
+ />
+ {selectedPreset.models.length > 0 && (
+
+ {selectedPreset.models.slice(0, 4).map((m) => (
+
+ ))}
+
+ )}
+
+
+
+
+
+
启用视觉看图识别(Vision)
+
+ 开启后将发票图像送入多模态模型交叉核验;纯文本模型建议关闭
+
+
+
setSupportsVision(checked)}
+ checkedChildren="开启看图"
+ unCheckedChildren="仅文本"
+ data-testid="supports-vision-switch"
+ />
+
+
+
+
+ {showAdvanced && (
+
+ )}
+ >
+ )
+ )}
+
+ >
)}
+
-
-
-
-
-
-
-
- API 密钥
- {selectedPreset?.docs_url && (
-
- 获取 Key
-
- )}
-
- }
- rules={[{ required: true, message: '请输入 API 密钥' }]}
- >
- }
- data-testid="api-key-input"
- />
-
-
-
-
-
-
-
- 模型名称
- {modelsSource === 'openrouter' && (
-
- 实时目录
-
- )}
-
- }
- rules={
- isCustomProvider
- ? [{ required: true, message: '请填写模型 ID(如 vendor/vision-pro)' }]
- : undefined
- }
- >
- ({
- label: (
-
- {m.name || m.id}
- {m.vision && (
-
-
-
- )}
-
- ),
- value: m.id,
- }))}
- filterOption={(input, option) =>
- (option?.value as string)?.toLowerCase().includes(input.toLowerCase())
- }
- data-testid="model-input"
- />
-
-
-
-
-
-
-
-
-
-
- {testFeedback && (
-
+ {/* Fixed Footer (always visible in viewport) */}
+
+
+ {testFeedback.state === 'testing' && (
+ ◌ {testFeedback.message}
)}
-
-
-
-
-
-
-
-
-
- >
- )}
-
+ {testFeedback.state === 'success' && (
+
+ ✓ {testFeedback.message}
+ {testFeedback.responseTimeMs != null ? ` · ${testFeedback.responseTimeMs}ms` : ''}
+
+ )}
+ {testFeedback.state === 'error' && (
+
+ ✕ {testFeedback.message}
+ {testFeedback.responseTimeMs != null ? ` · ${testFeedback.responseTimeMs}ms` : ''}
+
+ )}
+ {testFeedback.state === 'idle' && (
+ {testFeedback.message}
+ )}
+
+
+
+
+ {selectedProvider !== OFFLINE_ID && (
+
+ )}
+
+
+
+
+
);
}
-
-export default LLMConfigModal;
diff --git a/frontend/src/components/OgPreviewModal.module.css b/frontend/src/components/OgPreviewModal.module.css
new file mode 100644
index 0000000..292c45c
--- /dev/null
+++ b/frontend/src/components/OgPreviewModal.module.css
@@ -0,0 +1,371 @@
+.backdrop {
+ position: fixed;
+ inset: 0;
+ background: var(--backdrop);
+ backdrop-filter: blur(4px);
+ z-index: 1050;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ padding: 20px;
+}
+
+.modal {
+ width: 980px;
+ max-width: calc(100vw - 32px);
+ background: var(--bg-surface);
+ border: 1px solid var(--border-default);
+ border-radius: var(--radius-xl);
+ box-shadow: var(--shadow-modal);
+ overflow: hidden;
+ display: flex;
+ flex-direction: column;
+}
+
+.header {
+ padding: 15px 20px;
+ border-bottom: 1px solid var(--border-default);
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 12px;
+}
+
+.headerTitle {
+ font-size: 15px;
+ font-weight: 650;
+ color: var(--text-primary);
+}
+
+.headerSub {
+ font-size: 12px;
+ color: var(--text-muted);
+ margin-top: 2px;
+}
+
+.headerActions {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+}
+
+.actionBtn,
+.closeBtn {
+ height: 30px;
+ padding: 0 11px;
+ border-radius: var(--radius-md);
+ border: 1px solid var(--border-default);
+ background: var(--bg-surface);
+ color: var(--text-primary);
+ font-size: 12px;
+ font-weight: 500;
+ cursor: pointer;
+}
+
+.actionBtn:hover,
+.closeBtn:hover {
+ background: var(--bg-subtle);
+ border-color: var(--border-strong);
+}
+
+.closeBtn {
+ border-color: transparent;
+ background: transparent;
+ color: var(--text-secondary);
+}
+
+.stage {
+ padding: 22px;
+ background: var(--bg-preview);
+ display: flex;
+ justify-content: center;
+ align-items: center;
+}
+
+/* Aspect-locked 2:1 (1280x640 proportional) GitHub Social Card */
+.canvas {
+ width: 920px;
+ max-width: 100%;
+ aspect-ratio: 2 / 1;
+ border-radius: 12px;
+ border: 1px solid #DFDCD2;
+ background-color: #F5F4F0;
+ background-image: radial-gradient(rgba(23, 23, 21, 0.06) 1px, transparent 1px);
+ background-size: 18px 18px;
+ padding: 38px 42px;
+ display: grid;
+ grid-template-columns: 1.05fr 1fr;
+ gap: 30px;
+ align-items: center;
+ color: #171715;
+ position: relative;
+ overflow: hidden;
+ box-shadow: 0 20px 50px rgba(0, 0, 0, 0.24);
+}
+
+.canvasDark {
+ background-color: #101114;
+ background-image: radial-gradient(rgba(255, 255, 255, 0.07) 1px, transparent 1px);
+ border-color: #2A2D36;
+ color: #F3F2ED;
+}
+
+.left {
+ display: flex;
+ flex-direction: column;
+ gap: 15px;
+}
+
+.badge {
+ display: inline-flex;
+ align-items: center;
+ gap: 7px;
+ width: fit-content;
+ padding: 4px 10px;
+ border-radius: 99px;
+ background: #FDF2F1;
+ border: 1px solid #F2C5C0;
+ color: #A81E15;
+ font-size: 12px;
+ font-weight: 600;
+}
+
+.canvasDark .badge {
+ background: #2B1818;
+ border-color: #5C2826;
+ color: #F78177;
+}
+
+.badgeDot {
+ width: 7px;
+ height: 7px;
+ border-radius: 50%;
+ background: #C2271D;
+}
+
+.canvasDark .badgeDot {
+ background: #F26457;
+}
+
+.brandRow {
+ display: flex;
+ align-items: center;
+ gap: 12px;
+}
+
+.brandSeal {
+ width: 42px;
+ height: 42px;
+ border-radius: 10px;
+ background: linear-gradient(145deg, #D12F24 0%, #AC1E15 100%);
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ flex-shrink: 0;
+ box-shadow: 0 4px 14px rgba(194, 39, 29, 0.28);
+}
+
+.h1 {
+ font-size: 32px;
+ font-weight: 700;
+ letter-spacing: -0.03em;
+ line-height: 1.15;
+}
+
+.sub {
+ font-size: 14px;
+ line-height: 1.55;
+ color: #4F4D46;
+}
+
+.canvasDark .sub {
+ color: #BDBAB1;
+}
+
+.pills {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 8px;
+}
+
+.pill {
+ padding: 4px 10px;
+ border-radius: 6px;
+ border: 1px solid #DFDCD2;
+ background: #FFFFFF;
+ font-size: 12px;
+ font-weight: 500;
+ color: #171715;
+}
+
+.canvasDark .pill {
+ border-color: #2D303A;
+ background: #181A20;
+ color: #F3F2ED;
+}
+
+.repoLine {
+ font-size: 12px;
+ color: #6D6A61;
+ margin-top: 2px;
+}
+
+.canvasDark .repoLine {
+ color: #959288;
+}
+
+.mockWindow {
+ background: #FFFFFF;
+ border: 1px solid #DFDCD2;
+ border-radius: 10px;
+ box-shadow: 0 16px 36px rgba(23, 23, 21, 0.12);
+ overflow: hidden;
+ display: flex;
+ flex-direction: column;
+}
+
+.canvasDark .mockWindow {
+ background: #17181C;
+ border-color: #2B2E38;
+ box-shadow: 0 18px 42px rgba(0, 0, 0, 0.55);
+}
+
+.mockTopbar {
+ padding: 10px 14px;
+ border-bottom: 1px solid rgba(128, 128, 128, 0.2);
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ font-size: 12px;
+}
+
+.mockDots {
+ display: flex;
+ gap: 6px;
+ align-items: center;
+}
+
+.mockDots > span:not(.mockTitle) {
+ width: 9px;
+ height: 9px;
+ border-radius: 50%;
+ display: inline-block;
+}
+
+.mockTitle {
+ margin-left: 6px;
+ opacity: 0.78;
+}
+
+.mockVerified {
+ padding: 1px 7px;
+ border-radius: 99px;
+ background: rgba(22, 163, 74, 0.14);
+ color: #16A34A;
+ font-weight: 600;
+ font-size: 12px;
+}
+
+.canvasDark .mockVerified {
+ background: #10281C;
+ color: #6EE7A8;
+}
+
+.mockBody {
+ padding: 14px;
+ display: flex;
+ flex-direction: column;
+ gap: 10px;
+}
+
+.mockKpiGrid {
+ display: grid;
+ grid-template-columns: 1fr 1fr;
+ gap: 8px;
+}
+
+.mockKpiBox {
+ padding: 10px;
+ border-radius: 8px;
+ border: 1px solid rgba(128, 128, 128, 0.22);
+}
+
+.mockKpiLabel {
+ font-size: 11px;
+ opacity: 0.72;
+}
+
+.mockKpiVal {
+ font-size: 20px;
+ font-weight: 700;
+ margin-top: 2px;
+}
+
+.mockKpiDec {
+ font-size: 13px;
+ opacity: 0.65;
+}
+
+.mockRiskBox {
+ padding: 10px;
+ border-radius: 8px;
+ border: 1px solid rgba(194, 39, 29, 0.45);
+ background: rgba(194, 39, 29, 0.08);
+}
+
+.mockRiskLabel {
+ font-size: 11px;
+ color: #C2271D;
+ font-weight: 600;
+}
+
+.canvasDark .mockRiskLabel {
+ color: #F78177;
+}
+
+.mockRiskVal {
+ font-size: 13px;
+ font-weight: 650;
+ margin-top: 4px;
+}
+
+.mockPaper {
+ border: 1.5px solid #B4382A;
+ border-radius: 7px;
+ padding: 10px 12px;
+ background: #FFFEFA;
+ color: #3D2B24;
+}
+
+.mockPaperHead {
+ display: flex;
+ justify-content: space-between;
+ font-size: 11px;
+ color: #A8281D;
+ font-weight: 700;
+ border-bottom: 1px solid rgba(168, 40, 29, 0.3);
+ padding-bottom: 5px;
+}
+
+.mockPaperMid {
+ margin-top: 8px;
+ display: flex;
+ justify-content: space-between;
+ align-items: center;
+ font-size: 12px;
+}
+
+.mockPaperHighlight {
+ padding: 2px 7px;
+ border-radius: 4px;
+ background: rgba(194, 39, 29, 0.14);
+ border: 1.5px solid #C2271D;
+ color: #A81E15;
+ font-weight: 700;
+}
+
+.mockPaperFoot {
+ margin-top: 6px;
+ font-size: 11px;
+ color: #6B574F;
+}
diff --git a/frontend/src/components/OgPreviewModal.tsx b/frontend/src/components/OgPreviewModal.tsx
new file mode 100644
index 0000000..741c303
--- /dev/null
+++ b/frontend/src/components/OgPreviewModal.tsx
@@ -0,0 +1,168 @@
+import { useState, useEffect } from 'react';
+import { useTheme } from '../contexts/ThemeContext';
+import styles from './OgPreviewModal.module.css';
+
+interface OgPreviewModalProps {
+ open: boolean;
+ onClose: () => void;
+}
+
+export default function OgPreviewModal({ open, onClose }: OgPreviewModalProps) {
+ const { isDark } = useTheme();
+ const [cardDark, setCardDark] = useState(isDark);
+
+ useEffect(() => {
+ if (open) {
+ setCardDark(isDark);
+ }
+ }, [open, isDark]);
+
+ useEffect(() => {
+ if (!open) return;
+ const onKey = (e: KeyboardEvent) => {
+ if (e.key === 'Escape') onClose();
+ };
+ window.addEventListener('keydown', onKey);
+ return () => window.removeEventListener('keydown', onKey);
+ }, [open, onClose]);
+
+ if (!open) return null;
+
+ return (
+ {
+ if (e.target === e.currentTarget) onClose();
+ }}
+ data-testid="og-preview-backdrop"
+ >
+
+
+
+
+ 开源名片预览 · GitHub Social Preview (1280×640)
+
+
+ 站外第一触点与产品 UI 同源「印鉴账本」设计语言,支持暖纸日间 / 暗房夜间双版
+
+
+
+
+
+
+
+
+
+
+
+
+
+ Open Source · Docker / NAS 自部署
+
+
+
+
+
+ 面向个人、财务与 NAS 玩家的开源智能票据工作台。
+
+ 本地 OCR + AI 双引擎交叉校对,空间联动核验,自动去重,一键打包报销单。
+
+
+
+ PDF 矢量无损提取
+ 原件 ↔ 字段空间联动
+ 20 位票号自动查重
+ 国内模型直连 / 纯离线
+
+
+
+ github.com/stone16/Invoice-Manager · MIT License
+
+
+
+
+
+
+
+
+
+ 空间对照校对
+
+
双引擎已核验
+
+
+
+
+
+
本月价税合计
+
+ ¥8,794.00
+
+
+
+
智能风控拦截
+
1 重复 · 2 差异已定位
+
+
+
+
+
+ 电子发票(增值税专用发票)
+ 26310000008800000101
+
+
+ 云杉网络技术(杭州)有限公司
+ ¥3,400.00
+
+
+ *信息技术服务*企业级对象存储与算力资源年包 · 税率 6%
+
+
+
+
+
+
+
+
+ );
+}
diff --git a/frontend/src/components/dashboard/LedgerKpiStrip/LedgerKpiStrip.module.css b/frontend/src/components/dashboard/LedgerKpiStrip/LedgerKpiStrip.module.css
new file mode 100644
index 0000000..3c3ebfc
--- /dev/null
+++ b/frontend/src/components/dashboard/LedgerKpiStrip/LedgerKpiStrip.module.css
@@ -0,0 +1,161 @@
+.kpiStrip {
+ display: grid;
+ grid-template-columns: repeat(4, minmax(0, 1fr));
+ background: var(--bg-surface);
+ border: 1px solid var(--border-default);
+ border-radius: var(--radius-lg);
+ box-shadow: var(--shadow-card);
+ overflow: hidden;
+}
+
+.kpiCell {
+ padding: 14px 16px 13px;
+ position: relative;
+ display: flex;
+ flex-direction: column;
+ justify-content: space-between;
+ gap: 6px;
+ min-width: 0;
+ transition: background-color 150ms ease;
+}
+
+.kpiCell + .kpiCell::before {
+ content: "";
+ position: absolute;
+ left: 0;
+ top: 14px;
+ bottom: 14px;
+ width: 1px;
+ background: var(--border-subtle);
+}
+
+.kpiHead {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 6px;
+ font-size: 12px;
+ line-height: 1.4;
+ color: var(--text-secondary);
+ font-weight: 500;
+}
+
+.kpiUnit {
+ font-size: 11px;
+ color: var(--text-muted);
+ white-space: nowrap;
+}
+
+.kpiValue {
+ font-size: 23px;
+ font-weight: 650;
+ letter-spacing: -0.025em;
+ color: var(--text-primary);
+ line-height: 1.18;
+ white-space: nowrap;
+ overflow: hidden;
+ text-overflow: ellipsis;
+}
+
+.cur {
+ font-size: 15px;
+ font-weight: 500;
+ color: var(--text-secondary);
+ margin-right: 1px;
+}
+
+.dec {
+ font-size: 15px;
+ font-weight: 500;
+ color: var(--text-muted);
+}
+
+.kpiFoot {
+ font-size: 12px;
+ color: var(--text-muted);
+ line-height: 1.4;
+ height: 18px;
+ white-space: nowrap;
+ overflow: hidden;
+ text-overflow: ellipsis;
+}
+
+.footWarn {
+ color: var(--status-warn-text);
+ font-weight: 500;
+}
+
+.footSeal {
+ color: var(--brand-seal-text);
+ font-weight: 500;
+}
+
+.catLegend {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ font-size: 12px;
+ line-height: 1.4;
+ height: 18px;
+ color: var(--text-muted);
+ white-space: nowrap;
+ overflow: hidden;
+}
+
+.catLegendItem {
+ display: inline-flex;
+ align-items: center;
+ gap: 4px;
+ border: none;
+ background: transparent;
+ padding: 0;
+ color: inherit;
+ font-size: 12px;
+ cursor: pointer;
+ white-space: nowrap;
+}
+
+.catLegendItem:hover,
+.catLegendActive {
+ color: var(--text-primary);
+ font-weight: 600;
+}
+
+.catSwatch {
+ width: 6px;
+ height: 6px;
+ border-radius: 2px;
+ flex-shrink: 0;
+}
+
+.microBar {
+ display: flex;
+ height: 5px;
+ width: 100%;
+ border-radius: 99px;
+ background: var(--bg-subtle);
+ overflow: hidden;
+ gap: 2px;
+ margin-top: 2px;
+}
+
+.microSeg {
+ height: 100%;
+ border-radius: 99px;
+ cursor: pointer;
+ transition: opacity 150ms ease;
+}
+
+.microSeg:hover {
+ opacity: 0.78;
+}
+
+@media (max-width: 1320px) {
+ .kpiCell {
+ padding: 12px 13px;
+ }
+
+ .kpiValue {
+ font-size: 20px;
+ }
+}
diff --git a/frontend/src/components/dashboard/LedgerKpiStrip/LedgerKpiStrip.tsx b/frontend/src/components/dashboard/LedgerKpiStrip/LedgerKpiStrip.tsx
new file mode 100644
index 0000000..3de528e
--- /dev/null
+++ b/frontend/src/components/dashboard/LedgerKpiStrip/LedgerKpiStrip.tsx
@@ -0,0 +1,255 @@
+import type { Statistics } from '../../../types/invoice';
+import styles from './LedgerKpiStrip.module.css';
+
+interface LedgerKpiStripProps {
+ stats: Statistics | null;
+ highlightCategory: string | null;
+ onToggleCategory: (category: string) => void;
+}
+
+const CAT_COLORS: Record = {
+ '云服务': 'var(--cat-cloud)',
+ '住宿': 'var(--cat-hotel)',
+ '交通': 'var(--cat-travel)',
+ '餐饮': 'var(--cat-dining)',
+ '办公': 'var(--cat-office)',
+ '其他': 'var(--status-neutral-dot)',
+};
+
+function splitCurrency(val: number | string | null | undefined): { intPart: string; decPart: string } {
+ const n = Number(val ?? 0);
+ const safe = Number.isNaN(n) ? 0 : n;
+ const [intPart, decPart] = safe
+ .toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 })
+ .split('.');
+ return { intPart, decPart };
+}
+
+function fmtPlain(val: number | string | null | undefined): string {
+ const n = Number(val ?? 0);
+ const safe = Number.isNaN(n) ? 0 : n;
+ return '¥' + safe.toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
+}
+
+export default function LedgerKpiStrip({
+ stats,
+ highlightCategory,
+ onToggleCategory,
+}: LedgerKpiStripProps) {
+ const totalCount = stats?.total_count ?? stats?.count ?? 0;
+ const pendingCount = stats?.pending_count ?? 0;
+ const dupCount = stats?.duplicate_count ?? 0;
+ const verifiedCount = Math.max(0, totalCount - pendingCount);
+
+ const totalAmount = Number(stats?.total_amount ?? 0);
+ const totalTax = Number(stats?.total_tax ?? 0);
+ const totalWithTax = Number(stats?.total_with_tax ?? 0);
+ const totalReimb = Number(stats?.total_reimbursable ?? totalWithTax);
+ const reimbDiff = Math.max(0, totalWithTax - totalReimb);
+
+ const amtParts = splitCurrency(totalAmount);
+ const taxParts = splitCurrency(totalTax);
+ const wtParts = splitCurrency(totalWithTax);
+
+ // Status bar ratios
+ const denomCount = Math.max(1, totalCount);
+ const okPct = (verifiedCount / denomCount) * 100;
+ const pendPct = (pendingCount / denomCount) * 100;
+ const dupPct = Math.min(100, (dupCount / denomCount) * 100);
+
+ // Category breakdown (top 4)
+ const categories = (stats?.category_breakdown || []).filter((c) => Number(c.amount) > 0 || c.count > 0);
+ const denomCatAmt = Math.max(
+ 0.01,
+ categories.reduce((acc, item) => acc + Math.max(0, Number(item.amount || item.total_with_tax || 0)), 0)
+ );
+
+ // Tax rate breakdown
+ const taxRates = stats?.tax_rate_breakdown || [];
+ const denomTax = Math.max(0.01, totalTax);
+ const topRates = taxRates.slice(0, 3);
+ const taxSummaryText =
+ topRates.length > 0 && totalTax > 0
+ ? topRates
+ .slice(0, 2)
+ .map((t) => `${t.tax_rate} 占 ${Math.round((Number(t.tax_amount) / denomTax) * 100)}%`)
+ .join(' · ')
+ : '暂无可抵扣进项税额构成';
+
+ const reimbPct = totalWithTax > 0 ? Math.min(100, (totalReimb / totalWithTax) * 100) : 100;
+
+ return (
+
+ {/* Cell 1: Filtered Count & Status */}
+
+
+ 当前筛选票据
+ 张
+
+
{totalCount}
+
0 ? styles.footWarn : ''}`}
+ title={`${pendingCount} 待校对 · ${dupCount} 重复 · ${verifiedCount} 已核验`}
+ >
+ {totalCount === 0
+ ? '暂未录入发票数据'
+ : pendingCount + dupCount > 0
+ ? `${pendingCount} 待校对 · ${dupCount} 重复 · ${verifiedCount} 已核验`
+ : `筛选范围内 ${verifiedCount} 张已核验通过`}
+
+
+ {verifiedCount > 0 && (
+
+ )}
+ {pendingCount > 0 && (
+
+ )}
+ {dupCount > 0 && (
+
+ )}
+
+
+
+ {/* Cell 2: Amount (Ex-Tax) & Category Breakdown */}
+
+
+ 不含税金额
+ 科目占比
+
+
+ ¥
+ {amtParts.intPart}
+ .{amtParts.decPart}
+
+
+ {categories.length === 0 ? (
+ 按货物与服务自动归类
+ ) : (
+ categories.slice(0, 3).map((cat) => {
+ const catVal = Math.max(0, Number(cat.amount || cat.total_with_tax || 0));
+ const pct = Math.round((catVal / denomCatAmt) * 100);
+ const color = CAT_COLORS[cat.category] || 'var(--cat-cloud)';
+ const active = highlightCategory === cat.category;
+ return (
+
+ );
+ })
+ )}
+
+
+ {categories.map((cat) => {
+ const catVal = Math.max(0, Number(cat.amount || cat.total_with_tax || 0));
+ const pct = Math.max(4, (catVal / denomCatAmt) * 100);
+ const color = CAT_COLORS[cat.category] || 'var(--cat-cloud)';
+ return (
+
onToggleCategory(cat.category)}
+ />
+ );
+ })}
+
+
+
+ {/* Cell 3: Deductible Tax & Tax Rate Structure */}
+
+
+ 可抵扣税额
+ 税率结构
+
+
+ ¥
+ {taxParts.intPart}
+ .{taxParts.decPart}
+
+
+ {taxSummaryText}
+
+
+ {topRates.map((tr, i) => {
+ const colors = ['var(--cat-cloud)', 'var(--cat-travel)', 'var(--cat-dining)'];
+ const pct = totalTax > 0 ? Math.max(4, (Number(tr.tax_amount) / denomTax) * 100) : 0;
+ return pct > 0 ? (
+
+ ) : null;
+ })}
+
+
+
+ {/* Cell 4: Total With Tax & Approved Reimbursable */}
+
+
+ 价税合计
+ 核定实报
+
+
+ ¥
+ {wtParts.intPart}
+ .{wtParts.decPart}
+
+
0.01 ? styles.footSeal : ''}`}
+ title={
+ reimbDiff > 0.01
+ ? `实报 ${fmtPlain(totalReimb)} · 核减 ${fmtPlain(reimbDiff)}`
+ : `实报 ${fmtPlain(totalReimb)} · 全额合规`
+ }
+ >
+ {reimbDiff > 0.01
+ ? `实报 ${fmtPlain(totalReimb)} · 核减 ${fmtPlain(reimbDiff)}`
+ : `实报 ${fmtPlain(totalReimb)} · 全额合规`}
+
+
+
+ {reimbDiff > 0.01 && (
+
+ )}
+
+
+
+ );
+}
diff --git a/frontend/src/components/layout/MainLayout.module.css b/frontend/src/components/layout/MainLayout.module.css
index a5a61d3..0a4c490 100644
--- a/frontend/src/components/layout/MainLayout.module.css
+++ b/frontend/src/components/layout/MainLayout.module.css
@@ -1,11 +1,12 @@
-/* Main Layout Container */
.layoutContainer {
display: flex;
min-height: 100vh;
- background-color: var(--background);
+ width: 100%;
+ max-width: 100vw;
+ overflow-x: hidden;
+ background-color: var(--bg-canvas);
}
-/* Main Content Area */
.mainContent {
flex: 1;
min-width: 0;
@@ -13,25 +14,22 @@
min-height: 100vh;
display: flex;
flex-direction: column;
+ overflow-x: hidden;
+ transition: margin-left 180ms var(--ease-spring);
+}
+
+.mainContent.mainCollapsed {
+ margin-left: var(--sidebar-collapsed-width);
}
-/* Content Wrapper */
.contentWrapper {
flex: 1;
min-width: 0;
- padding: var(--content-padding-y) var(--content-padding-x);
-}
-
-/* LLM Promo Alert */
-.llmPromoAlert {
- margin-bottom: var(--spacing-xl);
+ padding: 18px 24px 24px;
}
-/* Footer */
-.footer {
- text-align: center;
- padding: var(--spacing-base) var(--content-padding-x);
- color: var(--muted-foreground);
- font-size: var(--font-size-sm);
- border-top: 1px solid var(--border);
+@media (max-width: 1320px) {
+ .contentWrapper {
+ padding: 16px 18px 20px;
+ }
}
diff --git a/frontend/src/components/layout/MainLayout.tsx b/frontend/src/components/layout/MainLayout.tsx
index f342239..de38b96 100644
--- a/frontend/src/components/layout/MainLayout.tsx
+++ b/frontend/src/components/layout/MainLayout.tsx
@@ -1,61 +1,43 @@
-import { ReactNode } from 'react';
-import { Alert, Button } from 'antd';
-import { RocketOutlined } from '@ant-design/icons';
+import { ReactNode, useState } from 'react';
import Sidebar from './Sidebar';
+import type { LLMStatusResponse } from '../../types/invoice';
import styles from './MainLayout.module.css';
interface MainLayoutProps {
children: ReactNode;
- llmConfigured: boolean | null;
- showLlmPromo: boolean;
+ llmStatus: LLMStatusResponse | null;
+ pendingAlertCount: number;
+ reimbursementSetCount: number;
onOpenLLMConfig: () => void;
- onCloseLLMPromo: () => void;
+ onOpenOGPreview: () => void;
}
export default function MainLayout({
children,
- llmConfigured,
- showLlmPromo,
+ llmStatus,
+ pendingAlertCount,
+ reimbursementSetCount,
onOpenLLMConfig,
- onCloseLLMPromo,
+ onOpenOGPreview,
}: MainLayoutProps) {
+ const [collapsed, setCollapsed] = useState(false);
+
return (
-
-
-
-
- {/* LLM Configuration Promo Banner */}
- {showLlmPromo && !llmConfigured && (
-
- 当前使用免费OCR预处理服务。配置LLM服务后可获得更精准的发票信息提取和智能比对功能。
- }
- onClick={onOpenLLMConfig}
- style={{ padding: '0 4px' }}
- >
- 立即配置
-
-
- }
- type="info"
- showIcon
- closable
- onClose={onCloseLLMPromo}
- />
- )}
-
- {children}
-
+ setCollapsed((prev) => !prev)}
+ onOpenLLMConfig={onOpenLLMConfig}
+ onOpenOGPreview={onOpenOGPreview}
+ />
-
+
+ {children}
);
diff --git a/frontend/src/components/layout/Sidebar/Sidebar.module.css b/frontend/src/components/layout/Sidebar/Sidebar.module.css
index 38a6843..4f64eb0 100644
--- a/frontend/src/components/layout/Sidebar/Sidebar.module.css
+++ b/frontend/src/components/layout/Sidebar/Sidebar.module.css
@@ -1,181 +1,333 @@
-/* Sidebar Container */
.sidebar {
width: var(--sidebar-width);
- height: 100vh;
- background-color: var(--background);
- border-right: 1px solid var(--border);
+ flex-shrink: 0;
+ background-color: var(--bg-sidebar);
+ border-right: 1px solid var(--border-default);
display: flex;
flex-direction: column;
justify-content: space-between;
- padding: var(--sidebar-padding-y) var(--sidebar-padding-x);
+ padding: 16px 12px 14px;
position: fixed;
- left: 0;
- top: 0;
- z-index: var(--z-fixed);
+ inset: 0 auto 0 0;
+ z-index: 40;
+ transition: width 180ms var(--ease-spring), background-color 200ms ease, border-color 200ms ease;
+}
+
+.sidebar.collapsed {
+ width: var(--sidebar-collapsed-width);
+ padding: 16px 8px 14px;
+}
+
+/* Subtle ledger ruler tick accent along sidebar right edge */
+.sidebar::after {
+ content: "";
+ position: absolute;
+ right: 0;
+ top: 68px;
+ bottom: 120px;
+ width: 4px;
+ background-image: repeating-linear-gradient(
+ to bottom,
+ transparent 0px,
+ transparent 19px,
+ var(--border-default) 19px,
+ var(--border-default) 20px
+ );
+ opacity: 0.65;
+ pointer-events: none;
}
-/* Sidebar Top Section */
-.sidebarTop {
+.topSection {
display: flex;
flex-direction: column;
- gap: 48px;
}
-/* Logo Section */
-.logo {
+.brand {
display: flex;
align-items: center;
- gap: 12px;
+ gap: 10px;
+ padding: 4px 6px 15px;
+ border-bottom: 1px solid var(--border-subtle);
+ margin-bottom: 12px;
+ text-decoration: none;
}
-.logoMark {
+.collapsed .brand {
+ justify-content: center;
+ padding: 4px 0 15px;
+}
+
+.brandSeal {
width: 28px;
height: 28px;
- background-color: var(--red-primary);
- border-radius: var(--radius-base);
+ border-radius: 7px;
+ background: linear-gradient(145deg, #D12F24 0%, #AC1E15 100%);
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ flex-shrink: 0;
+ box-shadow: 0 2px 8px var(--brand-seal-glow), inset 0 1px 0 rgba(255, 255, 255, 0.28);
+}
+
+.brandText {
+ display: flex;
+ flex-direction: column;
+ line-height: 1.25;
+ min-width: 0;
+}
+
+.brandTitle {
+ font-size: 14px;
+ font-weight: 650;
+ letter-spacing: -0.015em;
+ color: var(--text-primary);
+ white-space: nowrap;
}
-.logoText {
- font-family: var(--font-primary);
- font-size: var(--font-size-lg);
- font-weight: var(--font-weight-semibold);
- color: var(--foreground);
+.brandSub {
+ font-size: 12px;
+ color: var(--text-muted);
+ margin-top: 1px;
+ white-space: nowrap;
}
-/* Navigation Section */
-.navigation {
+.navGroupLabel {
+ font-size: 12px;
+ font-weight: 500;
+ color: var(--text-muted);
+ padding: 6px 8px;
+}
+
+.navList {
display: flex;
flex-direction: column;
- gap: 4px;
+ gap: 3px;
}
.navItem {
+ position: relative;
display: flex;
align-items: center;
- gap: 12px;
- padding: 12px 0;
- cursor: pointer;
+ justify-content: space-between;
+ gap: 8px;
+ width: 100%;
+ padding: 8px 10px;
+ border-radius: var(--radius-md);
+ border: 1px solid transparent;
+ background: transparent;
+ color: var(--text-secondary);
+ font-size: 13px;
+ font-weight: 500;
+ text-align: left;
text-decoration: none;
- transition: color var(--transition-fast);
+ cursor: pointer;
+ transition: all 160ms var(--ease-spring);
+}
+
+.collapsed .navItem {
+ justify-content: center;
+ padding: 9px 0;
+}
+
+.navItem:hover {
+ background: var(--bg-subtle);
+ color: var(--text-primary);
}
-.navItem:hover .navLabel {
- color: var(--foreground);
+.navItem.active {
+ background: var(--bg-surface);
+ color: var(--text-primary);
+ border-color: var(--border-default);
+ box-shadow: var(--shadow-card);
}
-.navItem:focus-visible {
- outline: 2px solid var(--red-primary);
- outline-offset: 2px;
+.navItem.active::before {
+ content: "";
+ position: absolute;
+ left: -1px;
+ top: 7px;
+ bottom: 7px;
+ width: 3px;
+ border-radius: 0 3px 3px 0;
+ background: var(--brand-seal);
}
-.navDot {
- width: 6px;
- height: 6px;
- border-radius: var(--radius-full);
- background-color: transparent;
+.navItemLeft {
+ display: flex;
+ align-items: center;
+ gap: 9px;
+ min-width: 0;
+}
+
+.navItem svg {
+ width: 15px;
+ height: 15px;
flex-shrink: 0;
+ opacity: 0.78;
}
-.navItem.active .navDot {
- background-color: var(--red-primary);
+.navItem.active svg {
+ opacity: 1;
}
-.navLabel {
- font-family: var(--font-primary);
- font-size: var(--font-size-base);
- font-weight: var(--font-weight-normal);
- color: var(--muted-foreground);
- transition: color var(--transition-fast);
+.navBadge {
+ font-size: 11px;
+ padding: 1px 6px;
+ border-radius: 99px;
+ background: var(--brand-seal-soft);
+ color: var(--brand-seal-text);
+ border: 1px solid var(--brand-seal-border);
+ font-weight: 600;
+ line-height: 1.4;
}
-.navItem.active .navLabel {
- color: var(--foreground);
- font-weight: var(--font-weight-medium);
+.navBadge.neutral {
+ background: var(--bg-subtle);
+ color: var(--text-muted-on-subtle);
+ border-color: transparent;
+ font-weight: 500;
}
-/* Sidebar Bottom Section */
-.sidebarBottom {
+/* Sidebar Footer */
+.sidebarFooter {
display: flex;
flex-direction: column;
- gap: 24px;
+ gap: 8px;
+ padding-top: 12px;
+ border-top: 1px solid var(--border-subtle);
}
-/* User Profile Section */
-.userProfile {
+.enginePill {
display: flex;
- align-items: center;
- gap: 12px;
+ flex-direction: column;
+ gap: 4px;
+ padding: 10px 11px;
+ border-radius: var(--radius-lg);
+ background: var(--bg-surface);
+ border: 1px solid var(--border-default);
+ box-shadow: var(--shadow-card);
+ text-align: left;
+ cursor: pointer;
+ width: 100%;
+ transition: all 160ms var(--ease-spring);
}
-.userAvatar {
- width: 36px;
- height: 36px;
- border-radius: var(--radius-full);
- background-color: var(--black-primary);
- display: flex;
+.collapsed .enginePill {
align-items: center;
justify-content: center;
- flex-shrink: 0;
+ padding: 10px 0;
}
-.userInitial {
- font-family: var(--font-primary);
- font-size: 11px;
- font-weight: var(--font-weight-medium);
- color: var(--background);
+.enginePill:hover {
+ border-color: var(--border-strong);
+ transform: translateY(-1px);
+ box-shadow: var(--shadow-lift);
}
-.userInfo {
+.enginePillTop {
display: flex;
- flex-direction: column;
- gap: 2px;
+ align-items: center;
+ justify-content: space-between;
+ gap: 6px;
+ font-size: 12px;
+ font-weight: 600;
+ color: var(--text-primary);
}
-.userName {
- font-family: var(--font-primary);
- font-size: var(--font-size-sm);
- font-weight: var(--font-weight-medium);
- color: var(--foreground);
+.engineDotWrap {
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ min-width: 0;
}
-.userRole {
- font-family: var(--font-secondary);
- font-size: 11px;
- font-weight: var(--font-weight-normal);
- color: var(--muted-foreground);
+.engineName {
+ white-space: nowrap;
+ overflow: hidden;
+ text-overflow: ellipsis;
+}
+
+.engineSwitchHint {
+ color: var(--text-muted);
+ font-size: 12px;
+ font-weight: 500;
+ flex-shrink: 0;
+}
+
+.dot {
+ width: 7px;
+ height: 7px;
+ border-radius: 50%;
+ flex-shrink: 0;
+}
+
+.dotOk {
+ background: var(--status-success-dot);
+ box-shadow: 0 0 0 3px rgba(22, 163, 74, 0.16);
+}
+
+.dotOcr {
+ background: var(--status-warn-dot);
+ box-shadow: 0 0 0 3px rgba(217, 119, 6, 0.16);
}
-/* LLM Config Button */
-.llmConfigButton {
+.enginePillSub {
+ font-size: 11px;
+ color: var(--text-muted);
display: flex;
align-items: center;
- gap: 8px;
- padding: 8px 12px;
- background-color: var(--surface);
- border: 1px solid var(--border);
- border-radius: var(--radius-base);
- cursor: pointer;
- transition: all var(--transition-fast);
+ justify-content: space-between;
+ gap: 6px;
}
-.llmConfigButton:hover {
- border-color: var(--red-primary);
+.engineModel {
+ white-space: nowrap;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ min-width: 0;
}
-.llmConfigButton .statusIcon {
- font-size: 16px;
+.sidebarTools {
+ display: grid;
+ grid-template-columns: 1fr 1fr 28px;
+ gap: 5px;
}
-.llmConfigButton .statusIcon.configured {
- color: var(--success);
+.collapsedTools {
+ display: flex;
+ flex-direction: column;
+ gap: 6px;
}
-.llmConfigButton .statusIcon.notConfigured {
- color: var(--warning);
+.sidebarToolBtn,
+.collapseBtn {
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ gap: 4px;
+ height: 30px;
+ border-radius: var(--radius-md);
+ border: 1px solid var(--border-default);
+ background: var(--bg-surface);
+ color: var(--text-secondary);
+ font-size: 12px;
+ font-weight: 500;
+ cursor: pointer;
+ padding: 0 4px;
+ white-space: nowrap;
+ transition: all 150ms ease;
+}
+
+.sidebarToolBtn:hover,
+.collapseBtn:hover {
+ background: var(--bg-subtle);
+ color: var(--text-primary);
+ border-color: var(--border-strong);
}
-.llmConfigButton .configText {
- font-family: var(--font-secondary);
- font-size: var(--font-size-xs);
- color: var(--muted-foreground);
+.sidebarToolBtn svg,
+.collapseBtn svg {
+ width: 13px;
+ height: 13px;
+ flex-shrink: 0;
}
diff --git a/frontend/src/components/layout/Sidebar/Sidebar.tsx b/frontend/src/components/layout/Sidebar/Sidebar.tsx
index ee1b50c..afc3604 100644
--- a/frontend/src/components/layout/Sidebar/Sidebar.tsx
+++ b/frontend/src/components/layout/Sidebar/Sidebar.tsx
@@ -1,93 +1,294 @@
import { Link, useLocation } from 'react-router-dom';
import { Tooltip } from 'antd';
-import {
- CheckCircleOutlined,
- ExclamationCircleOutlined,
-} from '@ant-design/icons';
+import { useTheme } from '../../../contexts/ThemeContext';
+import type { LLMStatusResponse } from '../../../types/invoice';
import styles from './Sidebar.module.css';
-interface NavItem {
- path: string;
- label: string;
-}
-
interface SidebarProps {
- llmConfigured: boolean | null;
+ llmStatus: LLMStatusResponse | null;
+ pendingAlertCount: number;
+ reimbursementSetCount: number;
+ collapsed: boolean;
+ onToggleCollapse: () => void;
onOpenLLMConfig: () => void;
+ onOpenOGPreview: () => void;
}
-const navItems: NavItem[] = [
- { path: '/', label: '发票列表' },
- { path: '/upload', label: '上传发票' },
- { path: '/reimbursement-sets', label: '报销集' },
-];
-
-export default function Sidebar({ llmConfigured, onOpenLLMConfig }: SidebarProps) {
+export default function Sidebar({
+ llmStatus,
+ pendingAlertCount,
+ reimbursementSetCount,
+ collapsed,
+ onToggleCollapse,
+ onOpenLLMConfig,
+ onOpenOGPreview,
+}: SidebarProps) {
const location = useLocation();
+ const { isDark, toggleTheme } = useTheme();
+
+ const isWorkbenchActive =
+ location.pathname === '/' || location.pathname.startsWith('/invoices/');
+ const isUploadActive = location.pathname === '/upload';
+ const isSetsActive = location.pathname.startsWith('/reimbursement-sets');
+
+ const isConfigured = Boolean(llmStatus?.is_configured);
+ const providerDisplay = llmStatus?.active_provider_display || llmStatus?.active_provider || '';
+ const activeModel = llmStatus?.active_model || '';
return (
-