perf(backend): index the lookup columns and load order lines in batches

Order lines had no index on their order, orders none on their day/customer/status, and each
line's product was loaded to tell a fee apart: with ~3000 orders Customers took ~2 s and
Reports -> Days ~15 s. Migration 0038 adds the indexes (models carry index=True), Order.items
loads with selectin, sales.lines looks the fee products up once, cancellations and prep-zones
load their orders with the lines. Days 15 s -> 0.2 s (a month), customers 2 s -> 0.1 s.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-20 14:42:09 +02:00
co-authored by Claude Opus 5.5
parent fd917797a7
commit 618fef53ef
17 changed files with 167 additions and 62 deletions
+4 -11
View File
@@ -10,7 +10,7 @@ import json
from fastapi import APIRouter, Depends, Query, BackgroundTasks, Request
from fastapi.responses import StreamingResponse
from pydantic import BaseModel
from sqlalchemy.orm import Session
from sqlalchemy.orm import Session, contains_eager, selectinload
from sqlalchemy import func
from datetime import date, datetime, timedelta, timezone
from typing import Optional, List
@@ -1386,7 +1386,7 @@ def cancellations_log(
db: Session = Depends(get_db),
user: User = Depends(require_reports),
):
q = db.query(OrderItem).filter(OrderItem.status == "cancelled")
q = db.query(OrderItem).filter(OrderItem.status == "cancelled").options(selectinload(OrderItem.order))
# Date filter on cancelled_at if available, otherwise fall back to added_at
dt_from = history_since(from_dt, 'reports') # clamped even without a "from" (D-6)
@@ -1416,16 +1416,9 @@ def cancellations_log(
items = q.order_by(OrderItem.added_at.desc()).all()
waiters_db = {u.id: u for u in db.query(User).all()}
tables_db = {t.id: (t.label or f"T{t.number}") for t in db.query(Table).all()}
orders_cache = {}
def _get_order(oid):
if oid not in orders_cache:
orders_cache[oid] = db.query(Order).filter(Order.id == oid).first()
return orders_cache[oid]
result = []
for item in items:
order = _get_order(item.order_id)
order = item.order # loaded with the items (selectinload above)
table_name = tables_db.get(order.table_id, f"#{order.table_id}") if order else "—"
waiter = waiters_db.get(item.added_by)
waiter_name = (waiter.full_name or waiter.username) if waiter else f"#{item.added_by}"
@@ -1712,7 +1705,7 @@ def prep_zones_report(
product_zone_map[product.id].append(zone.id)
# Query order items in the requested range
q = db.query(OrderItem).join(Order)
q = db.query(OrderItem).join(Order).options(contains_eager(OrderItem.order))
_since = history_since(from_dt, 'reports')
if _since:
q = q.filter(Order.opened_at >= _since)