diff --git a/web/app.py b/web/app.py index dc0924d..a23f9e1 100644 --- a/web/app.py +++ b/web/app.py @@ -400,6 +400,9 @@ def _wohnungen_context(user) -> dict: age_cutoff = None if max_age_hours: age_cutoff = datetime.now(timezone.utc) - timedelta(hours=int(max_age_hours)) + # One query for this user's latest application per flat, instead of a + # per-flat query inside the loop. + latest_apps = db.latest_applications_by_flat(uid) flats_view = [] for f in flats: if f["id"] in rejected: @@ -417,8 +420,7 @@ def _wohnungen_context(user) -> dict: "wbs": f["wbs"], }, filters): continue - last = db.last_application_for_flat(uid, f["id"]) - flats_view.append({"row": f, "last": last}) + flats_view.append({"row": f, "last": latest_apps.get(f["id"])}) rejected_view = db.rejected_flats(uid) enrichment_counts = db.enrichment_counts() diff --git a/web/db.py b/web/db.py index 86e8e7a..43a763e 100644 --- a/web/db.py +++ b/web/db.py @@ -675,6 +675,24 @@ def last_application_for_flat(user_id: int, flat_id: str) -> Optional[sqlite3.Ro ).fetchone() +def latest_applications_by_flat(user_id: int) -> dict: + """Return a dict {flat_id: latest-application-row} for all flats the user + has interacted with. One query instead of N.""" + rows = _get_conn().execute( + """SELECT a.* + FROM applications a + JOIN ( + SELECT flat_id, MAX(started_at) AS maxstart + FROM applications + WHERE user_id = ? + GROUP BY flat_id + ) m ON m.flat_id = a.flat_id AND m.maxstart = a.started_at + WHERE a.user_id = ?""", + (user_id, user_id), + ).fetchall() + return {r["flat_id"]: r for r in rows} + + def has_running_application(user_id: int) -> bool: row = _get_conn().execute( "SELECT 1 FROM applications WHERE user_id = ? AND finished_at IS NULL LIMIT 1",