Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions backend/app/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,10 @@ class Settings(BaseSettings):
max_file_size: int = 10 * 1024 * 1024 # 10MB
allowed_extensions: list[str] = ["pdf", "jpg", "jpeg", "png"]

# Reimbursement bundle export safety limits
reimbursement_export_max_items: int = 200
reimbursement_export_max_bytes: int = 200 * 1024 * 1024 # 200MB

# Parallel processing settings
# Separate pools for OCR and LLM to maximize throughput
# OCR is CPU-bound (image processing), limit based on available cores
Expand Down
8 changes: 7 additions & 1 deletion backend/app/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
from slowapi.errors import RateLimitExceeded

from app.config import get_settings
from app.routers import health, invoices, settings as settings_router
from app.routers import health, invoices, reimbursement_sets, settings as settings_router
from app.rate_limit import limiter

settings = get_settings()
Expand Down Expand Up @@ -40,12 +40,18 @@ async def rate_limit_handler(request: Request, exc: RateLimitExceeded):
# Include routers
app.include_router(health.router, prefix="/api", tags=["Health"])
app.include_router(invoices.router, prefix="/api/invoices", tags=["Invoices"])
app.include_router(
reimbursement_sets.router,
prefix="/api/reimbursement-sets",
tags=["Reimbursement Sets"],
)
app.include_router(settings_router.router, prefix="/api/settings", tags=["Settings"])


@app.on_event("startup")
async def startup():
from app.database import engine, Base
from app.models import reimbursement_set as _reimbursement_set # noqa: F401
async with engine.begin() as conn:
await conn.run_sync(Base.metadata.create_all)

Expand Down
14 changes: 14 additions & 0 deletions backend/app/models/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
from app.models.audit_log import AuditLog
from app.models.invoice import Invoice, InvoiceStatus, LlmResult, OcrResult, ParsingDiff
from app.models.reimbursement_set import ReimbursementSet, ReimbursementSetItem

__all__ = [
"AuditLog",
"Invoice",
"InvoiceStatus",
"LlmResult",
"OcrResult",
"ParsingDiff",
"ReimbursementSet",
"ReimbursementSetItem",
]
50 changes: 50 additions & 0 deletions backend/app/models/reimbursement_set.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
"""SQLAlchemy models for reimbursement sets and ordered invoice membership."""

from datetime import datetime
from sqlalchemy import Column, DateTime, ForeignKey, Integer, String, Text, UniqueConstraint
from sqlalchemy.orm import relationship

from app.database import Base


class ReimbursementSet(Base):
__tablename__ = "reimbursement_sets"

id = Column(Integer, primary_key=True, index=True)
name = Column(String(200), nullable=False)
description = Column(Text, nullable=True)
created_at = Column(DateTime, default=datetime.utcnow, nullable=False)
updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)

items = relationship(
"ReimbursementSetItem",
back_populates="reimbursement_set",
cascade="all, delete-orphan",
order_by="ReimbursementSetItem.position",
)


class ReimbursementSetItem(Base):
__tablename__ = "reimbursement_set_items"
__table_args__ = (
UniqueConstraint("set_id", "position", name="uq_reimbursement_set_items_set_position"),
)

id = Column(Integer, primary_key=True, index=True)
set_id = Column(
Integer,
ForeignKey("reimbursement_sets.id", ondelete="CASCADE"),
nullable=False,
index=True,
)
invoice_id = Column(
Integer,
ForeignKey("invoices.id", ondelete="CASCADE"),
nullable=False,
unique=True,
)
position = Column(Integer, nullable=False)
created_at = Column(DateTime, default=datetime.utcnow, nullable=False)

reimbursement_set = relationship("ReimbursementSet", back_populates="items")
invoice = relationship("Invoice")
31 changes: 29 additions & 2 deletions backend/app/routers/invoices.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,10 @@
)
from app.config import get_settings
from app.services.audit_service import log_audit_no_commit, get_client_info
from app.services.reimbursement_service import (
compute_duplicate_warnings_for_invoices,
detect_upload_duplicate_warning,
)
from app.rate_limit import limiter

settings = get_settings()
Expand Down Expand Up @@ -60,6 +64,8 @@ async def upload_invoices(
results = []
invoice_ids_to_process = []
client_info = get_client_info(request)
batch_seen_hashes: dict[str, str] = {}
batch_seen_numbers: dict[str, str] = {}

for file in files:
# Validate file type
Expand All @@ -86,6 +92,16 @@ async def upload_invoices(
))
continue

# Non-blocking duplicate detection (20-digit invoice number or identical SHA-256)
duplicate_warning = await detect_upload_duplicate_warning(
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
db=db,
content=content,
file_type=ext,
batch_seen_hashes=batch_seen_hashes,
batch_seen_numbers=batch_seen_numbers,
current_file_name=file.filename or "unknown",
)

# Create invoice record with UPLOADED status (not yet processed)
invoice = Invoice(
file_name=file.filename or "unknown",
Expand Down Expand Up @@ -113,7 +129,8 @@ async def upload_invoices(
id=invoice.id,
file_name=invoice.file_name,
status="success",
message="上传成功,等待解析"
message="上传成功,等待解析",
duplicate_warning=duplicate_warning,
))

await db.commit()
Expand Down Expand Up @@ -260,9 +277,16 @@ async def list_invoices(

result = await db.execute(query)
invoices = result.scalars().all()
dup_warnings = await compute_duplicate_warnings_for_invoices(db, invoices)
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

items = []
for inv in invoices:
resp = InvoiceResponse.model_validate(inv)
resp.duplicate_warning = dup_warnings.get(inv.id)
items.append(resp)

return InvoiceListResponse(
items=[InvoiceResponse.model_validate(inv) for inv in invoices],
items=items,
total=total,
page=page,
page_size=page_size
Expand Down Expand Up @@ -329,13 +353,16 @@ async def get_invoice(
diff_result = await db.execute(diff_query)
diffs = diff_result.scalars().all()

dup_warnings = await compute_duplicate_warnings_for_invoices(db, [invoice])

# Build response dict from invoice to avoid lazy loading issues
invoice_dict = {
"id": invoice.id,
"file_name": invoice.file_name,
"file_type": invoice.file_type,
"status": invoice.status,
"owner": invoice.owner,
"duplicate_warning": dup_warnings.get(invoice.id),
"invoice_number": invoice.invoice_number,
"issue_date": invoice.issue_date,
"buyer_name": invoice.buyer_name,
Expand Down
Loading
Loading