SPB Git

Repository Public

statsdash.py 35.9 KB 832 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Auto·Ka9# File             : autoka/statsdash.py10# Module           : autoka11# Repository       : https://git.spboucher.ai/auto-ka12# Created          : 2026-08-1713# Last Modified    : 2026-08-1914#15# =============================================================================16# AUTHOR & PROFESSIONAL AFFILIATION17# =============================================================================18#19# Author           : Simon-Pierre Boucher20# Position         : Professor of Finance21# Institution      : Université du Québec en Outaouais (UQO)22# Department       : Département des sciences administratives23# Organization     : SP Boucher24#25# Website          : https://spboucher.ai26# Git              : https://git.spboucher.ai27#28# =============================================================================29# OFFICIAL CONTACT DIRECTORY30# =============================================================================31#32# General          : info@spboucher.ai33# Professional     : contact@spboucher.ai34# Direct           : simon@spboucher.ai35# Research         : research@spboucher.ai36# Development      : dev@spboucher.ai37# Support          : support@spboucher.ai38# Security/Admin   : admin@spboucher.ai39# Notifications    : notifications@spboucher.ai40#41# Preferred Contact: contact@spboucher.ai42#43# =============================================================================44# COPYRIGHT & INTELLECTUAL PROPERTY45# =============================================================================46#47# Copyright (c) 202648# Simon-Pierre Boucher49#50# All rights reserved where applicable.51#52# This file is governed by the applicable project license,53# copyright notices, institutional agreements and relevant law.54#55# Unless expressly authorized by the applicable license or56# rights holder, copying, redistribution, sublicensing,57# publication and commercial exploitation are not permitted.58#59# Existing third-party rights and notices remain unaffected.60#61# =============================================================================62# CONFIDENTIALITY & SECURITY63# =============================================================================64#65# Classification   : Public66# Distribution     : Public repository; use is governed by the project license67# Security Contact : admin@spboucher.ai68#69# Access to this source does not independently grant permission70# to redistribute or disclose confidential materials.71#72# Do not embed credentials, private keys, access tokens,73# certificates or confidential personal information.74#75# =============================================================================76# LICENSE & MAINTENANCE77# =============================================================================78#79# License          : None specified (no license file in this repository)80# Maintainer       : Simon-Pierre Boucher81# Technical Contact: dev@spboucher.ai82#83# =============================================================================84# END OF SP BOUCHER SOURCE HEADER85# =============================================================================8687# -----------------------------------------------------------------------------88# Auto-Ka — Agrégateur de voitures usagées à vendre (province de Québec)89# Auteur : Simon-Pierre Boucher — contact@spboucher.ai90# statsdash.py : tableau de bord analytique — construit le JSON du contrat91#                par période (/api/stats/dashboard)92#                à partir des données réelles (vehicles, price_log, sync_log).93#                Sert aussi de source unique aux rapports PDF (autoka/rapportpdf.py).94#95# Principes :96#   - AUCUNE statistique inventée : tout vient de la base SQLite. Un champ sans97#     donnée mesurable est simplement omis (le front affiche « Pas encore98#     mesuré »).99#   - L'« inventaire à la date t » est reconstruit depuis le cycle de vie réel100#     des annonces : first_seen (arrivée) et updated_at des annonces101#     désactivées (retrait). Les prix/km historiques par jour utilisent le102#     dernier prix/km connu de chaque véhicule (approximation documentée).103#   - Les séries sont bornées au début réel des données (12 août 2026) :104#     avant, rien n'était mesuré — on ne trace pas de faux zéros. De même,105#     les deltas vs période précédente ne sont émis que si la référence106#     existait déjà (start > début des données).107#   - Cache serveur de 5 minutes par période.108# -----------------------------------------------------------------------------109from __future__ import annotations110111import threading112import time113from collections import Counter, defaultdict114from datetime import date, datetime, timedelta115from zoneinfo import ZoneInfo116117from . import db118119TZ = ZoneInfo("America/Toronto")120CACHE_TTL = 240  # secondes : le rythme du catalogue121122_cache: dict[tuple, tuple[float, dict]] = {}123_cache_lock = threading.Lock()124125PERIOD_LABELS = {126    "auj": "Aujourd'hui",127    "7j": "7 jours",128    "30j": "30 jours",129    "3m": "3 mois",130    "6m": "6 mois",131    "12m": "12 mois",132    "annee": "Année en cours",133    "tout": "Toute la période",134}135PERIOD_DAYS = {"auj": 1, "7j": 7, "30j": 30, "3m": 90, "6m": 180, "12m": 365}136137# Filtre « type de vendeur » : les annonces de particuliers (Kijiji) portent138# un dealer_name « Particulier (…) » — tout le reste vient de commerces.139PRIV = "dealer_name LIKE 'Particulier%'"140141142# --- utilitaires ---------------------------------------------------------------143144def _day_start(d: date) -> float:145    return datetime(d.year, d.month, d.day, tzinfo=TZ).timestamp()146147148def _to_date(ts: float) -> date:149    return datetime.fromtimestamp(ts, TZ).date()150151152def _fr_int(n) -> str:153    return f"{int(round(n)):,}".replace(",", " ")154155156def _fr_money(p) -> str:157    if p is None:158        return "—"159    return _fr_int(p) + " $"160161162def _fr_km(k) -> str:163    if k is None:164        return "—"165    return _fr_int(k) + " km"166167168def _fr_pct(p) -> str:169    if p is None:170        return "—"171    return ("+" if p >= 0 else "−") + f"{abs(p):.1f}".replace(".", ",") + " %"172173174def _delta(cur, prev) -> tuple[float | None, str | None]:175    """Variation en % vs période précédente ; None si non mesurable."""176    if cur is None or prev is None or not prev:177        return None, None178    pct = round(100.0 * (cur - prev) / prev, 1)179    return pct, ("up" if pct >= 0 else "down")180181182def _resolve_period(period: str, from_: str | None, to: str | None):183    """(start_ts, end_ts, prev_start_ts, prev_end_ts, label, from_iso, to_iso)."""184    now = datetime.now(TZ)185    today = now.date()186    if from_ and to:187        d0 = date.fromisoformat(from_)188        d1 = date.fromisoformat(to)189        if d1 < d0:190            d0, d1 = d1, d0191        start = _day_start(d0)192        end = min(now.timestamp(), _day_start(d1 + timedelta(days=1)))193        label = f"du {d0.isoformat()} au {d1.isoformat()}"194    elif period == "tout":195        con = db.connect_analytique()196        row = con.execute("SELECT MIN(first_seen) m FROM vehicles").fetchone()197        con.close()198        start = row["m"] or now.timestamp()199        end = now.timestamp()200        label = PERIOD_LABELS["tout"]201    elif period == "annee":202        start = _day_start(date(today.year, 1, 1))203        end = now.timestamp()204        label = f"Année {today.year}"205    else:206        days = PERIOD_DAYS.get(period, 30)207        start = _day_start(today - timedelta(days=days - 1))208        end = now.timestamp()209        label = PERIOD_LABELS.get(period, PERIOD_LABELS["30j"])210    span = max(end - start, 1.0)211    return start, end, start - span, start, label, \212        _to_date(start).isoformat(), _to_date(end - 1).isoformat()213214215# --- reconstruction de l'inventaire par jour ------------------------------------216217def _lifecycle_rows(con):218    """(arrivée, retrait|None, prix, km, marque) pour chaque annonce auto."""219    return [220        (r["first_seen"], r["updated_at"] if not r["active"] else None,221         r["price"], r["mileage_km"], r["make"])222        for r in con.execute(223            "SELECT first_seen, active, updated_at, price, mileage_km, make"224            " FROM vehicles WHERE kind='auto' AND first_seen IS NOT NULL")225    ]226227228def _daily_series(rows, start_ts: float, end_ts: float):229    """Par jour : inventaire actif, prix/km moyens de l'inventaire, arrivées,230    retraits.231232    Balayage d'événements (arrivées/retraits triés) — l'inventaire au soir du233    jour J = annonces arrivées avant la fin de J et pas encore retirées.234    """235    if not rows:236        return []237    data_start = min(r[0] for r in rows)238    d = max(_to_date(start_ts), _to_date(data_start))239    d_end = _to_date(end_ts - 1)240    if d > d_end:241        return []242    adds = sorted(rows, key=lambda r: r[0])243    rems = sorted((r for r in rows if r[1] is not None), key=lambda r: r[1])244    new_by_day = Counter(_to_date(r[0]) for r in rows)245    gone_by_day = Counter(_to_date(r[1]) for r in rows if r[1] is not None)246    ai = ri = count = n_price = n_km = 0247    sum_price = sum_km = 0.0248    out = []249    while d <= d_end:250        cutoff = _day_start(d + timedelta(days=1))251        while ai < len(adds) and adds[ai][0] < cutoff:252            count += 1253            if adds[ai][2] is not None:254                sum_price += adds[ai][2]255                n_price += 1256            if adds[ai][3] is not None:257                sum_km += adds[ai][3]258                n_km += 1259            ai += 1260        while ri < len(rems) and rems[ri][1] < cutoff:261            count -= 1262            if rems[ri][2] is not None:263                sum_price -= rems[ri][2]264                n_price -= 1265            if rems[ri][3] is not None:266                sum_km -= rems[ri][3]267                n_km -= 1268            ri += 1269        out.append({270            "t": d.isoformat(),271            "inv": count,272            "avg_price": round(sum_price / n_price) if n_price else None,273            "avg_km": round(sum_km / n_km) if n_km else None,274            "new": new_by_day.get(d, 0),275            "gone": gone_by_day.get(d, 0),276        })277        d += timedelta(days=1)278    return out279280281def _snapshot(con, t: float):282    """Indicateurs de l'inventaire actif reconstitué à l'instant t."""283    return dict(con.execute(284        """SELECT COUNT(*) n, AVG(price) avg_price, AVG(mileage_km) avg_km,285                  AVG(year) avg_year,286                  COUNT(DISTINCT CASE WHEN NOT {priv} THEN dealer_name END) dealers,287                  SUM(CASE WHEN {priv} THEN 1 ELSE 0 END) private,288                  COUNT(DISTINCT source) sources289           FROM vehicles WHERE kind='auto' AND first_seen<=?290             AND (active=1 OR updated_at>?)""".format(priv=PRIV),291        (t, t)).fetchone())292293294def _snapshot_counts(con, t: float, expr: str) -> dict[str, int]:295    """Effectifs par catégorie de l'inventaire reconstitué à l'instant t."""296    return {r["lab"]: r["n"] for r in con.execute(297        f"""SELECT {expr} lab, COUNT(*) n FROM vehicles298            WHERE kind='auto' AND first_seen<=? AND (active=1 OR updated_at>?)299            GROUP BY lab""", (t, t))}300301302def _price_drops(con, t0: float, t1: float) -> int:303    """Baisses de prix observées dans price_log entre t0 et t1."""304    return con.execute(305        """WITH pl AS (306             SELECT uid, ts, price,307                    LAG(price) OVER (PARTITION BY uid ORDER BY ts) prev_price308             FROM price_log WHERE price IS NOT NULL)309           SELECT COUNT(*) n FROM pl310           WHERE ts>=? AND ts<? AND prev_price IS NOT NULL311             AND prev_price > price""", (t0, t1)).fetchone()["n"]312313314# --- construction du dashboard ---------------------------------------------------315316def _build(period: str, from_: str | None, to: str | None) -> dict:317    start, end, pstart, pend, label, f_iso, t_iso = _resolve_period(period, from_, to)318    con = db.connect_analytique()319    now_ts = time.time()320321    # --- KPI : maintenant vs début de période / période précédente -------------322    cur = _snapshot(con, min(end, now_ts))323    # Pas de delta si la période commence avant le début réel des données :324    # l'inventaire de référence n'existait pas encore (rien d'inventé).325    data_start = con.execute(326        "SELECT MIN(first_seen) m FROM vehicles WHERE kind='auto'").fetchone()["m"]327    has_ref = data_start is not None and start > data_start328    if has_ref:329        ref = _snapshot(con, start)330    else:331        ref = {"n": None, "avg_price": None, "avg_km": None, "avg_year": None,332               "dealers": None, "private": None, "sources": None}333334    def _count(sql, args):335        return con.execute(sql, args).fetchone()["n"]336337    new_cur = _count("SELECT COUNT(*) n FROM vehicles WHERE kind='auto'"338                     " AND first_seen>=? AND first_seen<?", (start, end))339    new_prev = _count("SELECT COUNT(*) n FROM vehicles WHERE kind='auto'"340                      " AND first_seen>=? AND first_seen<?", (pstart, pend))341    gone_cur = _count("SELECT COUNT(*) n FROM vehicles WHERE kind='auto'"342                      " AND active=0 AND updated_at>=? AND updated_at<?", (start, end))343    gone_prev = _count("SELECT COUNT(*) n FROM vehicles WHERE kind='auto'"344                       " AND active=0 AND updated_at>=? AND updated_at<?", (pstart, pend))345    drops_cur = _price_drops(con, start, end)346    drops_prev = _price_drops(con, pstart, pend) if has_ref else None347348    # --- séries quotidiennes (avant les KPI : sparklines) -----------------------349    rows = _lifecycle_rows(con)350    daily = _daily_series(rows, start, end)351    prev_daily = _daily_series(rows, pstart, pend)352    full_prev = len(prev_daily) == len(daily) and len(daily) > 1353354    def _spark(key):355        pts = [{"t": p["t"], "v": p[key]} for p in daily if p[key] is not None]356        return pts if len(pts) >= 2 else None357358    def _kpi(id_, label_, value, unit="", prev=None, spark=None):359        pct, direction = _delta(value, prev)360        k = {"id": id_, "label": label_, "value": value, "unit": unit,361             "delta_pct": pct, "direction": direction}362        if spark:363            k["spark"] = spark364        return k365366    kpis = [367        _kpi("actifs", "Véhicules actifs", cur["n"], "", ref["n"], _spark("inv")),368        _kpi("nouveaux", "Nouveaux véhicules (période)", new_cur, "",369             new_prev if has_ref else None, _spark("new")),370        _kpi("retires", "Vendus / retirés (période)", gone_cur, "",371             gone_prev if has_ref else None, _spark("gone")),372        _kpi("prix", "Prix moyen (inventaire actif)",373             round(cur["avg_price"]) if cur["avg_price"] else None, "$",374             round(ref["avg_price"]) if ref["avg_price"] else None,375             _spark("avg_price")),376        _kpi("km", "Km moyen (inventaire actif)",377             round(cur["avg_km"]) if cur["avg_km"] else None, "km",378             round(ref["avg_km"]) if ref["avg_km"] else None, _spark("avg_km")),379        # année moyenne : valeur pré-formatée (« 2021,1 » — pas de séparateur380        # de milliers) ; un delta en % n'aurait aucun sens sur un millésime.381        _kpi("annee", "Année-modèle moyenne",382             f"{cur['avg_year']:.1f}".replace(".", ",")383             if cur["avg_year"] else None, ""),384        _kpi("dealers", "Concessionnaires actifs", cur["dealers"], "", ref["dealers"]),385        _kpi("particuliers", "Annonces de particuliers", cur["private"], "",386             ref["private"]),387        _kpi("baisses", "Baisses de prix (période)", drops_cur, "", drops_prev),388        _kpi("sources", "Sources actives", cur["sources"], "", ref["sources"]),389    ]390    kpis = [k for k in kpis if k["value"] is not None]391392    # --- jauges : complétude des fiches de l'inventaire actif -------------------393    cov = con.execute(394        """SELECT COUNT(*) n,395                  SUM(CASE WHEN images IS NOT NULL AND images<>'[]'396                           AND images<>'' THEN 1 ELSE 0 END) img,397                  SUM(CASE WHEN mileage_km IS NOT NULL THEN 1 ELSE 0 END) km,398                  SUM(CASE WHEN price IS NOT NULL THEN 1 ELSE 0 END) prix,399                  SUM(CASE WHEN vin<>'' THEN 1 ELSE 0 END) vin,400                  SUM(CASE WHEN carfax_url<>'' THEN 1 ELSE 0 END) carfax,401                  SUM(CASE WHEN lat IS NOT NULL THEN 1 ELSE 0 END) geo402           FROM vehicles WHERE active=1 AND kind='auto'""").fetchone()403    gauges = []404    if cov["n"]:405        def _gauge(id_, label_, num, help_=None):406            g = {"id": id_, "label": label_,407                 "value": round(100.0 * num / cov["n"], 1), "max": 100, "unit": "%"}408            if help_:409                g["help"] = help_410            return g411        gauges = [412            _gauge("photos", "Fiches avec photos", cov["img"]),413            _gauge("km", "Kilométrage renseigné", cov["km"]),414            _gauge("prix", "Prix affiché", cov["prix"]),415            _gauge("vin", "NIV (VIN) connu", cov["vin"]),416            _gauge("geo", "Fiches géolocalisées", cov["geo"]),417            _gauge("carfax", "Rapport Carfax lié", cov["carfax"],418                   "Part des annonces actives dont la source publie un lien Carfax"),419        ]420421    # --- séries d'évolution ------------------------------------------------------422    series = []423    if daily:424        series.append({425            "id": "inv", "title": "Inventaire actif par jour", "unit": "véhicules",426            "kind": "line", "points": [{"t": p["t"], "v": p["inv"]} for p in daily],427            **({"compare": [{"t": p["t"], "v": p["inv"]} for p in prev_daily]}428               if full_prev else {}),429        })430        series.append({431            "id": "new", "title": "Nouveaux véhicules par jour", "unit": "véhicules",432            "kind": "bar", "points": [{"t": p["t"], "v": p["new"]} for p in daily],433        })434        series.append({435            "id": "gone", "title": "Véhicules vendus / retirés par jour",436            "unit": "véhicules", "kind": "bar",437            "points": [{"t": p["t"], "v": p["gone"]} for p in daily],438        })439        price_pts = [{"t": p["t"], "v": p["avg_price"]} for p in daily440                     if p["avg_price"] is not None]441        if price_pts:442            series.append({443                "id": "avg_price", "title": "Prix moyen de l'inventaire par jour",444                "unit": "$", "kind": "area", "points": price_pts,445            })446447    # --- multi-courbes : prix moyen par grande marque ----------------------------448    multiseries = []449    top_makes = [r["make"] for r in con.execute(450        "SELECT make FROM vehicles WHERE active=1 AND kind='auto' AND make<>''"451        " GROUP BY make ORDER BY COUNT(*) DESC LIMIT 4")]452    if top_makes and daily:453        by_make_rows = defaultdict(list)454        for r in rows:455            if r[4] in top_makes:456                by_make_rows[r[4]].append(r)457        make_daily = {m: _daily_series(by_make_rows[m], start, end)458                      for m in top_makes}459        # domaine commun : jours où chaque marque a un prix moyen mesuré460        commons = None461        for m in top_makes:462            days_m = {p["t"] for p in make_daily[m] if p["avg_price"] is not None}463            commons = days_m if commons is None else commons & days_m464        commons = commons or set()465        if len(commons) >= 2:466            ms_series = [{467                "label": m,468                "points": [{"t": p["t"], "v": p["avg_price"]}469                           for p in make_daily[m] if p["t"] in commons],470            } for m in top_makes]471            multiseries.append({472                "id": "prix_marques",473                "title": "Prix moyen de l'inventaire — top 4 des marques",474                "unit": "$", "series": ms_series,475            })476477    # --- barres empilées : arrivées par source ------------------------------------478    stacked = []479    src_day = defaultdict(Counter)   # jour -> source -> n480    src_tot = Counter()481    for r in con.execute(482            "SELECT first_seen, source FROM vehicles WHERE kind='auto'"483            " AND first_seen>=? AND first_seen<?", (start, end)):484        d_ = _to_date(r["first_seen"]).isoformat()485        src_day[d_][r["source"]] += 1486        src_tot[r["source"]] += 1487    if src_tot:488        SRC_LABELS = {"otogo": "Otogo", "kijiji": "Kijiji",489                      "autotrader": "AutoTrader", "cargurus": "CarGurus",490                      "automobileendirect": "AutomobileEnDirect",491                      "hgregoire": "HGrégoire"}492        tops = [s for s, _ in src_tot.most_common(4)]493        keys = [SRC_LABELS.get(s, s) for s in tops]494        others = len(src_tot) > len(tops)495        if others:496            keys.append("Autres")497        pts = []498        for d_ in sorted(src_day):499            vals = [src_day[d_].get(s, 0) for s in tops]500            if others:501                vals.append(sum(src_day[d_].values()) - sum(vals))502            pts.append({"t": d_, "values": vals})503        if len(pts) >= 2:504            stacked.append({"id": "src", "title": "Nouveaux véhicules par source",505                            "unit": "véhicules", "keys": keys, "points": pts})506507    # --- répartitions (inventaire actif, deltas vs début de période) --------------508    FUEL_EXPR = ("CASE WHEN fuel IN ('', 'N.D.') THEN 'Non précisé'"509                 " ELSE fuel END")510    TRANS_EXPR = ("CASE WHEN transmission IN ('', 'NA', 'N.D.')"511                  " THEN 'Non précisé' ELSE transmission END")512    BODY_EXPR = "CASE WHEN body_type='' THEN 'Non précisé' ELSE body_type END"513    SELLER_EXPR = (f"CASE WHEN {PRIV} THEN 'Particuliers'"514                   " ELSE 'Concessionnaires' END")515516    def _items(expr, limit=None, where=""):517        cur_rows = con.execute(518            f"SELECT {expr} lab, COUNT(*) n FROM vehicles"519            f" WHERE active=1 AND kind='auto'{where}"520            f" GROUP BY lab ORDER BY n DESC" + (f" LIMIT {limit}" if limit else "")521        ).fetchall()522        prev_counts = _snapshot_counts(con, start, expr) if has_ref else {}523        out = []524        for r in cur_rows:525            pct, _ = _delta(r["n"], prev_counts.get(r["lab"]))526            out.append({"label": r["lab"] or "Non précisé", "value": r["n"],527                        **({"delta_pct": pct} if pct is not None else {})})528        return out529530    by_fuel = _items(FUEL_EXPR)531    by_trans = _items(TRANS_EXPR, limit=8)532    by_body = _items(BODY_EXPR, limit=10)533    by_seller = _items(SELLER_EXPR)534    by_make = _items("make", limit=12, where=" AND make<>''")535536    year_rows = con.execute(537        "SELECT year, COUNT(*) n FROM vehicles WHERE active=1 AND kind='auto'"538        " AND year IS NOT NULL GROUP BY year ORDER BY year").fetchall()539    # 11 années récentes + un groupe « antérieures » = 12 barres max, aucune540    # année récente escamotée par la limite d'affichage des graphiques.541    by_year, older = [], 0542    cutoff = max((r["year"] for r in year_rows), default=0) - 10543    for r in year_rows:544        if r["year"] < cutoff:545            older += r["n"]546        else:547            by_year.append({"label": str(r["year"]), "value": r["n"]})548    if older:549        by_year.insert(0, {"label": f"≤ {cutoff - 1}", "value": older})550551    breakdowns = [552        {"id": "make", "title": "Top 12 des marques", "kind": "donut", "items": by_make},553        {"id": "fuel", "title": "Par carburant", "kind": "donut", "items": by_fuel},554        {"id": "seller", "title": "Concessionnaires vs particuliers",555         "kind": "donut", "items": by_seller},556        {"id": "trans", "title": "Par boîte de vitesses", "kind": "bar", "items": by_trans},557        {"id": "body", "title": "Par carrosserie", "kind": "bar", "items": by_body},558        {"id": "year", "title": "Par année-modèle", "kind": "bar", "items": by_year},559    ]560    breakdowns = [b for b in breakdowns if len(b["items"]) > 1]561562    # --- distributions : prix et kilométrage --------------------------------------563    def _histo(col, width, cap, fmt):564        rows_ = con.execute(565            f"SELECT CAST({col}/{width} AS INTEGER) b, COUNT(*) n FROM vehicles"566            f" WHERE active=1 AND kind='auto' AND {col} IS NOT NULL AND {col}>=0"567            " GROUP BY b ORDER BY b").fetchall()568        if not rows_:569            return None570        n_bins = cap // width571        bins = [{"label": fmt(i), "value": 0} for i in range(n_bins)]572        over = {"label": fmt(n_bins), "value": 0}573        for r in rows_:574            if r["b"] < n_bins:575                bins[r["b"]]["value"] += r["n"]576            else:577                over["value"] += r["n"]578        if over["value"]:579            bins.append(over)580        while bins and bins[0]["value"] == 0:581            bins.pop(0)582        return bins583584    def _fmt_price_bin(i):585        lo, hi = i * 5, i * 5 + 5586        return f"{lo}–{hi} k$" if hi <= 100 else "100 k$ +"587588    def _fmt_km_bin(i):589        lo, hi = i * 25, i * 25 + 25590        return f"{lo}–{hi} k km" if hi <= 300 else "300 k km +"591592    distributions = []593    price_bins = _histo("price", 5000, 100000, _fmt_price_bin)594    if price_bins:595        distributions.append({596            "id": "prix", "title": "Distribution des prix (tranches de 5 000 $)",597            "unit": "véhicules", "bins": price_bins})598    km_bins = _histo("mileage_km", 25000, 300000, _fmt_km_bin)599    if km_bins:600        distributions.append({601            "id": "km", "title": "Distribution du kilométrage (tranches de 25 000 km)",602            "unit": "véhicules", "bins": km_bins})603604    # --- répartition géographique ---------------------------------------------------605    geo = {"title": "Par région", "items": _items("region", where=" AND region<>''")}606607    # --- calendrier + activité horaire ----------------------------------------------608    heatmap = {"title": "Nouveaux véhicules par jour",609               "cells": [{"date": p["t"], "value": p["new"]} for p in daily]}610611    hour_counter = Counter()612    for r in con.execute(613            "SELECT first_seen FROM vehicles WHERE kind='auto'"614            " AND first_seen>=? AND first_seen<?", (start, end)):615        dt = datetime.fromtimestamp(r["first_seen"], TZ)616        hour_counter[(dt.weekday(), dt.hour)] += 1617    hourly = None618    if hour_counter:619        hourly = {"title": "Nouveaux véhicules détectés par heure (synchros)",620                  "cells": [{"dow": k[0], "hour": k[1], "value": v}621                            for k, v in sorted(hour_counter.items())]}622623    # --- tableaux détaillés (inventaire actif) ------------------------------------624    def _table_rows(sql, args=()):625        return [list(r) for r in con.execute(sql, args).fetchall()]626627    make_prev = _snapshot_counts(con, start, "make") if has_ref else {}628629    def _mk_delta(make_, n):630        pct, _ = _delta(n, make_prev.get(make_))631        return _fr_pct(pct)632633    tables = [634        {"id": "makes", "title": "Top marques — volume, prix et km moyens",635         "columns": ["Marque", "Véhicules", "Prix moyen", "Km moyen", "Δ période"],636         "rows": [[m, n, _fr_money(p), _fr_km(k), _mk_delta(m, n)]637                  for m, n, p, k in _table_rows(638             "SELECT make, COUNT(*), AVG(price), AVG(mileage_km) FROM vehicles"639             " WHERE active=1 AND kind='auto' AND make<>''"640             " GROUP BY make ORDER BY COUNT(*) DESC LIMIT 25")]},641        {"id": "models", "title": "Top modèles — volume, prix et km moyens",642         "columns": ["Modèle", "Véhicules", "Prix moyen", "Km moyen"],643         "rows": [[m, n, _fr_money(p), _fr_km(k)] for m, n, p, k in _table_rows(644             "SELECT make || ' ' || model, COUNT(*), AVG(price), AVG(mileage_km)"645             " FROM vehicles WHERE active=1 AND kind='auto' AND make<>''"646             " AND model<>'' GROUP BY make, model ORDER BY COUNT(*) DESC LIMIT 25")]},647        {"id": "cities", "title": "Top villes — inventaire, prix et km moyens",648         "columns": ["Ville", "Région", "Véhicules", "Prix moyen", "Km moyen"],649         "rows": [[c, rg or "—", n, _fr_money(p), _fr_km(k)]650                  for c, rg, n, p, k in _table_rows(651             "SELECT city, MAX(region), COUNT(*), AVG(price), AVG(mileage_km)"652             " FROM vehicles WHERE active=1 AND kind='auto' AND city<>''"653             " GROUP BY city ORDER BY COUNT(*) DESC LIMIT 25")]},654        {"id": "dealers", "title": "Top concessionnaires — inventaire et prix moyen",655         "columns": ["Concessionnaire", "Région", "Véhicules", "Prix moyen"],656         "rows": [[d, rg or "—", n, _fr_money(p)] for d, rg, n, p in _table_rows(657             "SELECT dealer_name, MAX(region), COUNT(*), AVG(price) FROM vehicles"658             " WHERE active=1 AND kind='auto' AND dealer_name<>''"659             f" AND NOT {PRIV}"660             " GROUP BY dealer_name ORDER BY COUNT(*) DESC LIMIT 25")]},661    ]662663    # sources & fraîcheur : inventaire actif + arrivées de la période + dernière664    # synchro réussie (sync_log = journal réel du pipeline d'ingestion)665    last_sync = {r["source"]: r for r in con.execute(666        """SELECT source, MAX(ts) ts, ok FROM sync_log GROUP BY source""")}667    src_rows = _table_rows(668        """SELECT source, COUNT(*),669                  SUM(CASE WHEN first_seen>=? AND first_seen<? THEN 1 ELSE 0 END)670           FROM vehicles WHERE active=1 AND kind='auto'671           GROUP BY source ORDER BY COUNT(*) DESC LIMIT 25""", (start, end))672    if src_rows:673        rows_out = []674        for s, n, added in src_rows:675            ls = last_sync.get(s)676            when = (datetime.fromtimestamp(ls["ts"], TZ)677                    .strftime("%Y-%m-%d %H:%M") if ls else "—")678            ok = ("OK" if ls and ls["ok"] else ("Erreur" if ls else "—"))679            rows_out.append([s, n, added, when, ok])680        tables.append({681            "id": "sources", "title": "Sources — inventaire, ajouts et fraîcheur",682            "columns": ["Source", "Véhicules actifs", "Ajouts (période)",683                        "Dernière synchro", "Statut"],684            "rows": rows_out})685686    # --- records & faits marquants -------------------------------------------------687    records = []688    if daily:689        best = max(daily, key=lambda p: p["new"])690        if best["new"]:691            records.append({"label": "Jour record d'arrivées",692                            "value": _fr_int(best["new"]) + " véhicules",693                            "date": best["t"]})694    fastest = con.execute(695        """SELECT title, year, updated_at - first_seen dur, updated_at696           FROM vehicles WHERE kind='auto' AND active=0697             AND updated_at>=? AND updated_at<? AND updated_at>first_seen698           ORDER BY dur ASC LIMIT 1""", (start, end)).fetchone()699    if fastest:700        days_ = fastest["dur"] / 86400701        dur_txt = (f"{fastest['dur'] / 3600:.0f} h" if days_ < 1702                   else f"{days_:.1f} jours".replace(".", ","))703        records.append({"label": f"Vente la plus rapide — {fastest['title']}",704                        "value": dur_txt,705                        "date": _to_date(fastest["updated_at"]).isoformat()})706    drop = con.execute(707        """WITH pl AS (708             SELECT uid, ts, price,709                    LAG(price) OVER (PARTITION BY uid ORDER BY ts) prev_price710             FROM price_log WHERE price IS NOT NULL)711           SELECT v.title, pl.prev_price - pl.price baisse, pl.ts712           FROM pl JOIN vehicles v ON v.uid=pl.uid AND v.kind='auto'713           WHERE pl.ts>=? AND pl.ts<? AND pl.prev_price > pl.price714           ORDER BY baisse DESC LIMIT 1""", (start, end)).fetchone()715    if drop:716        records.append({"label": f"Plus forte baisse de prix — {drop['title']}",717                        "value": "−" + _fr_money(drop["baisse"]),718                        "date": _to_date(drop["ts"]).isoformat()})719    busiest = con.execute(720        f"""SELECT dealer_name, COUNT(*) n FROM vehicles721           WHERE kind='auto' AND dealer_name<>'' AND NOT {PRIV}722             AND first_seen>=? AND first_seen<?723           GROUP BY dealer_name ORDER BY n DESC LIMIT 1""",724        (start, end)).fetchone()725    if busiest and busiest["n"]:726        records.append({"label": f"Concessionnaire le plus actif — {busiest['dealer_name']}",727                        "value": _fr_int(busiest["n"]) + " nouveautés",728                        "date": None})729    top_price = con.execute(730        "SELECT title, price FROM vehicles WHERE active=1 AND kind='auto'"731        " AND price IS NOT NULL ORDER BY price DESC LIMIT 1").fetchone()732    if top_price:733        records.append({"label": f"Véhicule le plus cher en vente — {top_price['title']}",734                        "value": _fr_money(top_price["price"]), "date": None})735    oldest = con.execute(736        "SELECT title, year FROM vehicles WHERE active=1 AND kind='auto'"737        " AND year IS NOT NULL ORDER BY year ASC LIMIT 1").fetchone()738    if oldest:739        records.append({"label": f"Doyen de l'inventaire — {oldest['title']}",740                        "value": f"année {oldest['year']}", "date": None})741    top_km = con.execute(742        "SELECT title, mileage_km FROM vehicles WHERE active=1 AND kind='auto'"743        " AND mileage_km IS NOT NULL ORDER BY mileage_km DESC LIMIT 1").fetchone()744    if top_km:745        records.append({"label": f"Odomètre le plus élevé — {top_km['title']}",746                        "value": _fr_km(top_km["mileage_km"]), "date": None})747    if has_ref and make_prev:748        make_cur = {r["lab"]: r["n"] for r in con.execute(749            "SELECT make lab, COUNT(*) n FROM vehicles WHERE active=1"750            " AND kind='auto' AND make<>'' GROUP BY lab HAVING n>=100")}751        gains = [(m, _delta(n, make_prev.get(m))[0]) for m, n in make_cur.items()]752        gains = [(m, p) for m, p in gains if p is not None]753        if gains:754            m, p = max(gains, key=lambda x: x[1])755            if p > 0:756                records.append({757                    "label": f"Marque en plus forte hausse — {m}",758                    "value": _fr_pct(p) + " d'inventaire", "date": None})759    top_region = con.execute(760        """SELECT region, COUNT(*) n FROM vehicles WHERE kind='auto'761           AND region<>'' AND first_seen>=? AND first_seen<?762           GROUP BY region ORDER BY n DESC LIMIT 1""", (start, end)).fetchone()763    if top_region and top_region["n"]:764        records.append({"label": f"Région la plus active — {top_region['region']}",765                        "value": _fr_int(top_region["n"]) + " nouveautés",766                        "date": None})767768    con.close()769    out = {770        "updated": datetime.now(TZ).isoformat(timespec="seconds"),771        "period": {"from": f_iso, "to": t_iso, "label": label},772        "kpis": kpis,773        "series": series,774        "breakdowns": breakdowns,775        "geo": geo,776        "heatmap": heatmap,777        "tables": tables,778        "records": records,779    }780    if gauges:781        out["gauges"] = gauges782    if multiseries:783        out["multiseries"] = multiseries784    if stacked:785        out["stacked"] = stacked786    if distributions:787        out["distributions"] = distributions788    if hourly:789        out["hourly"] = hourly790    return out791792793_en_cours: set = set()794795796def _recalcul(key, period, from_, to) -> None:797    try:798        data = _build(period, from_, to)799        with _cache_lock:800            _cache[key] = (time.time(), data)801    except Exception:  # noqa: BLE001802        import traceback803        traceback.print_exc()804    finally:805        with _cache_lock:806            _en_cours.discard(key)807808809def dashboard(period: str = "30j", from_: str | None = None,810              to: str | None = None) -> dict:811    """Tableau de bord par période. Le premier appel d'une période calcule ;812    ensuite la réponse en cache est servie tout de suite et, si elle a plus de813    CACHE_TTL secondes, recalculée en arrière-plan (jamais d'attente à chaud)."""814    if period not in PERIOD_LABELS and not (from_ and to):815        period = "30j"816    key = (period, from_ or "", to or "")817    now = time.time()818    with _cache_lock:819        hit = _cache.get(key)820        if hit:821            if now - hit[0] >= CACHE_TTL and key not in _en_cours:822                _en_cours.add(key)823                threading.Thread(target=_recalcul, args=(key, period, from_, to),824                                 daemon=True).start()825            return hit[1]826    data = _build(period, from_, to)827    with _cache_lock:828        _cache[key] = (now, data)829        while len(_cache) > 64:830            _cache.pop(next(iter(_cache)))831    return data832
Files main
Menu

Theme