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:
@@ -29,6 +29,12 @@ def is_fee(item) -> bool:
|
||||
return getattr(item, "system_key", None) is not None
|
||||
|
||||
|
||||
def _fee_products(db) -> set[int]:
|
||||
"""The system products (the delivery fee…): one query, instead of loading each line's product."""
|
||||
from models.product import Product
|
||||
return {pid for (pid,) in db.query(Product.id).filter(Product.system_key.isnot(None)).all()}
|
||||
|
||||
|
||||
@dataclass
|
||||
class Line:
|
||||
item: object
|
||||
@@ -54,11 +60,12 @@ def lines(db, items) -> list[Line]:
|
||||
from services.refunds import refunded_quantities
|
||||
sold = [i for i in items if i.status in SOLD]
|
||||
back = refunded_quantities(db, [i.id for i in sold if i.status == "paid"])
|
||||
fees = _fee_products(db) if sold else set()
|
||||
out = []
|
||||
for i in sold:
|
||||
r = min(back.get(i.id, 0.0), i.quantity)
|
||||
q = max(i.quantity - r, 0.0)
|
||||
out.append(Line(item=i, quantity=round(q, 3), value=gross(i, q), refunded=gross(i, r), fee=is_fee(i)))
|
||||
out.append(Line(item=i, quantity=round(q, 3), value=gross(i, q), refunded=gross(i, r), fee=i.product_id in fees))
|
||||
return out
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user