SPB Git

Repository Public

directory.py 6.1 KB 152 lines python

1# -----------------------------------------------------------------------------2# Lou-Ka — Agrégateur de logements à louer (province de Québec)3# Auteur : Simon-Pierre Boucher — contact@spboucher.ai4# directory.py : annuaire des gestionnaires immobiliers.5#6# Tous les gestionnaires recensés dans data/sources.json apparaissent, qu'un7# connecteur les synchronise ou non : un gestionnaire sans inventaire en ligne8# reste listé avec un lien vers son site. Les portails et petites annonces9# (dedup.PORTALS / CLASSIFIEDS) ne sont pas des gestionnaires et sont exclus,10# tout comme les sources hors Québec mises en pause.11# -----------------------------------------------------------------------------12from __future__ import annotations1314import json15import statistics16import threading17import time18from pathlib import Path1920from . import db21from .dedup import CLASSIFIEDS, PORTALS2223SOURCES_PATH = Path(__file__).resolve().parent.parent / "data" / "sources.json"2425# bornes de plausibilité d'un loyer mensuel (mêmes bornes que seo.py)26PRICE_MIN, PRICE_MAX = 195, 150002728# sources provinciales qui ne sont pas des gestionnaires29PLATFORMS = {"kangalou", "apartments_com", "ubee"}            # portails d'annonces30BROKERAGES = {"remax_quebec", "sutton", "royal_lepage",        # bannières de courtage31              "via_capitale", "proprio_direct"}3233_TTL = 600  # secondes34_CACHE: dict = {"ts": 0.0, "data": None}35_LOCK = threading.Lock()363738def _state(status: str) -> str:39    """Statut détaillé de sources.json → état simple pour l'annuaire."""40    s = (status or "").lower()41    if s.startswith("actif"):42        return "connecte"43    if s.startswith("couvert"):44        return "couvert"45    if s.startswith(("pause", "inactif", "retir", "suspendu")):46        return "pause"47    return "site"          # non connectable : on renvoie vers le site484950def _build() -> dict:51    registry = json.loads(SOURCES_PATH.read_text(encoding="utf-8"))["sources"]52    con = db.connect()53    try:54        agg: dict[str, dict] = {}55        for r in con.execute(56                """SELECT source, COUNT(*) n, MIN(price) pmin, MAX(updated_at) last,57                          COUNT(DISTINCT building_key) immeubles58                   FROM listings59                   WHERE active=1 AND published=1 AND dup_of IS NULL60                   GROUP BY source"""):61            agg[r["source"]] = dict(r)62        prices: dict[str, list[float]] = {}63        cities: dict[str, dict[str, int]] = {}64        for r in con.execute(65                """SELECT source, city, price FROM listings66                   WHERE active=1 AND published=1 AND dup_of IS NULL"""):67            if r["price"] is not None and PRICE_MIN <= r["price"] <= PRICE_MAX:68                prices.setdefault(r["source"], []).append(r["price"])69            if r["city"]:70                c = cities.setdefault(r["source"], {})71                c[r["city"]] = c.get(r["city"], 0) + 172        ratings = {r["source_id"]: dict(r) for r in con.execute(73            """SELECT source_id, phone, gmaps_rating, gmaps_reviews, gmaps_address,74                      resolve_failed, gmaps_place_id FROM managers""")}75        last_sync = {r["source"]: r["ts"] for r in con.execute(76            "SELECT source, MAX(ts) ts FROM sync_log WHERE ok=1 GROUP BY source")}77    finally:78        con.close()7980    managers = []81    for s in registry:82        sid = s.get("id")83        if not sid or sid in PORTALS or sid in CLASSIFIEDS or sid in PLATFORMS:84            continue85        state = _state(s.get("status") or "")86        region = s.get("region") or ""87        if state == "pause" and "ontario" in (region + " " + (s.get("note_pause") or "")).lower():88            continue89        if region.lower().startswith("ontario"):90            continue91        a = agg.get(sid, {})92        p = sorted(prices.get(sid, []))93        top = sorted(cities.get(sid, {}).items(), key=lambda kv: -kv[1])94        g = ratings.get(sid) or {}95        rated = bool(g.get("gmaps_place_id")) and not g.get("resolve_failed")96        managers.append({97            "id": sid,98            "name": s.get("name") or sid,99            "url": s.get("url") or "",100            "listing_url": s.get("listing_url") or "",101            "region": region,102            "sectors": s.get("sectors") or "",103            "state": state,104            "kind": "courtage" if sid in BROKERAGES else "gestionnaire",105            "active_listings": a.get("n", 0),106            "buildings": a.get("immeubles", 0),107            "price_min": p[0] if p else None,108            "price_median": round(statistics.median(p)) if p else None,109            "cities": [c for c, _ in top[:6]],110            "cities_total": len(top),111            "rating": g.get("gmaps_rating") if rated else None,112            "reviews": g.get("gmaps_reviews") if rated else None,113            "phone": g.get("phone") or None,114            "address": (g.get("gmaps_address") if rated else None) or None,115            "last_sync": last_sync.get(sid),116            "updated_at": a.get("last"),117        })118    managers.sort(key=lambda m: (-m["active_listings"], m["name"].lower()))119120    regions: dict[str, dict] = {}121    for m in managers:122        r = regions.setdefault(m["region"] or "Autres", {"managers": 0, "listings": 0})123        r["managers"] += 1124        r["listings"] += m["active_listings"]125    return {126        "total": len(managers),127        "with_listings": sum(1 for m in managers if m["active_listings"]),128        "listings": sum(m["active_listings"] for m in managers),129        "regions": [{"region": k, **v} for k, v in130                    sorted(regions.items(), key=lambda kv: -kv[1]["listings"])],131        "managers": managers,132        "computed_at": time.time(),133    }134135136def compute() -> dict:137    """Annuaire en cache (10 min), recalcul à un seul fil (voir web._stats_aggregates)."""138    cached = _CACHE["data"]139    if cached is not None and time.time() - _CACHE["ts"] < _TTL:140        return cached141    if not _LOCK.acquire(blocking=cached is None):142        return cached143    try:144        cached = _CACHE["data"]145        if cached is not None and time.time() - _CACHE["ts"] < _TTL:146            return cached147        data = _build()148        _CACHE.update(ts=time.time(), data=data)149        return data150    finally:151        _LOCK.release()152
Files main
Menu

Theme