SPB Git

Repository Public

socle.py 22.3 KB 475 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Valo-Plex9# File             : moteur/plexmoteur/socle.py10# Description      : Socle de données : le parc des plex, leurs ventes, les11#                    inscriptions à revenus et les loyers demandés, réunis dans12#                    ``valoplex.db``.13# Module           : moteur14# Repository       : https://git.spboucher.ai/valo-plex15# Project Website  : https://www.valo-plex.com16# Created          : 2026-12-0117# Last Modified    : 2026-12-0318#19# =============================================================================20# AUTHOR & PROFESSIONAL AFFILIATION21# =============================================================================22#23# Author           : Simon-Pierre Boucher24# Position         : Professor of Finance25# Institution      : Université du Québec en Outaouais (UQO)26# Department       : Département des sciences administratives27# Organization     : SP Boucher28#29# Website          : https://spboucher.ai30# Git              : https://git.spboucher.ai31#32# =============================================================================33# OFFICIAL CONTACT DIRECTORY34# =============================================================================35#36# General          : info@spboucher.ai37# Professional     : contact@spboucher.ai38# Direct           : simon@spboucher.ai39# Research         : research@spboucher.ai40# Development      : dev@spboucher.ai41# Support          : support@spboucher.ai42# Security/Admin   : admin@spboucher.ai43# Notifications    : notifications@spboucher.ai44#45# Preferred Contact: contact@spboucher.ai46#47# =============================================================================48# COPYRIGHT & INTELLECTUAL PROPERTY49# =============================================================================50#51# Copyright (c) 202652# Simon-Pierre Boucher53#54# All rights reserved where applicable.55#56# This file is governed by the applicable project license,57# copyright notices, institutional agreements and relevant law.58#59# Unless expressly authorized by the applicable license or60# rights holder, copying, redistribution, sublicensing,61# publication and commercial exploitation are not permitted.62#63# Existing third-party rights and notices remain unaffected.64#65# =============================================================================66# CONFIDENTIALITY & SECURITY67# =============================================================================68#69# Classification   : Public70# Distribution     : Public repository; use is governed by the project license71# Security Contact : admin@spboucher.ai72#73# Access to this source does not independently grant permission74# to redistribute or disclose confidential materials.75#76# Do not embed credentials, private keys, access tokens,77# certificates or confidential personal information.78#79# =============================================================================80# LICENSE & MAINTENANCE81# =============================================================================82#83# License          : None specified (no license file in this repository)84# Maintainer       : Simon-Pierre Boucher85# Technical Contact: dev@spboucher.ai86#87# =============================================================================88# END OF SP BOUCHER SOURCE HEADER89# =============================================================================9091"""Socle de données : le parc des immeubles de rapport (plex, multilogements,92immeubles commerciaux), leurs ventes, les inscriptions et les loyers demandés,93réunis dans ``valoplex.db``.9495Rien n'est écrit dans les bases sources. Un champ inconnu reste NUL : aucune96valeur n'est inventée ici.97"""98from __future__ import annotations99100import csv101import io102import json103import re104import sqlite3105import subprocess106import time107108from . import config, typologie109110CLASSES = ((2, "duplex"), (3, "triplex"), (4, "quadruplex"), (5, "quintuplex"),111           (11, "6-11"), (23, "12-23"), (10**9, "24+"))112113114def classe(logements: int) -> str:115    for borne, nom in CLASSES:116        if logements <= borne:117            return nom118    return "24+"119120121SCHEMA = """122CREATE TABLE IF NOT EXISTS meta (cle TEXT PRIMARY KEY, valeur TEXT NOT NULL, maj TEXT NOT NULL);123"""124125126def noter(con, cle: str, valeur) -> None:127    con.execute("INSERT INTO meta VALUES (?,?,datetime('now')) ON CONFLICT(cle) DO UPDATE SET "128                "valeur=excluded.valeur, maj=excluded.maj", (cle, json.dumps(valeur, ensure_ascii=False)))129130131def lire_meta(con, cle: str, defaut=None):132    try:133        r = con.execute("SELECT valeur FROM meta WHERE cle=?", (cle,)).fetchone()134    except sqlite3.OperationalError:135        return defaut136    return json.loads(r[0]) if r else defaut137138139def _territoires(con) -> None:140    config.script(con, """141    DROP TABLE IF EXISTS territoire;142    CREATE TABLE territoire AS143    SELECT m.code code_mun, m.nom municipalite, m.slug, m.place_id, m.mrc_id, mrc.nom mrc,144           m.region_id, reg.code region_code, reg.nom region, m.lat, m.lng145    FROM v3.v3_place m146    LEFT JOIN v3.v3_place mrc ON mrc.place_id = m.mrc_id147    LEFT JOIN v3.v3_place reg ON reg.place_id = m.region_id148    WHERE m.kind = 'municipalite';149    CREATE UNIQUE INDEX territoire_code ON territoire (code_mun);150    DROP TABLE IF EXISTS arrondissement;151    CREATE TABLE arrondissement AS152    SELECT a.code, a.nom, a.slug, substr(a.municipalite_id, 5) code_mun, a.lat, a.lng153    FROM v3.v3_place a WHERE a.kind = 'arrondissement';154    """)155156157COLONNES_DERIVEES = ("loyer_porte", "loyer_3", "loyer_4", "loyer_5", "x16", "y16")158159160def _immeubles(con) -> int:161    # les colonnes dérivées (loyers estimés, case de carte) survivent à la reconstruction : le site les lit162    # entre le socle et les étapes qui les recalculent163    con.execute("DROP TABLE IF EXISTS temp._garde")164    anciennes = [r[1] for r in con.execute("PRAGMA table_info(immeuble)")]165    garde = [c for c in COLONNES_DERIVEES if c in anciennes]166    if garde:167        con.execute(f"CREATE TEMP TABLE _garde AS SELECT id, {', '.join(garde)} FROM immeuble")168        con.execute("CREATE INDEX temp._garde_id ON _garde (id)")169    codes = [r[0] for r in con.execute("SELECT DISTINCT cubf FROM role.units WHERE cubf <> 1000")]170    con.execute("DROP TABLE IF EXISTS temp._typologie")171    con.execute("CREATE TEMP TABLE _typologie (cubf INTEGER PRIMARY KEY, categorie TEXT NOT NULL)")172    con.executemany("INSERT INTO temp._typologie VALUES (?,?)", typologie.table_cubf(codes))173    config.script(con, """174    DROP TABLE IF EXISTS immeuble;175    CREATE TABLE immeuble (176      id TEXT PRIMARY KEY, adresse TEXT, municipalite TEXT, arrond TEXT, code_mun TEXT,177      lat REAL, lng REAL, logements INTEGER NOT NULL, classe TEXT NOT NULL, etages REAL, annee INTEGER,178      aire_m2 REAL, terrain_m2 REAL, front_m REAL, lien TEXT, construction TEXT,179      locaux_nr INTEGER, chambres INTEGER, role REAL NOT NULL, role_terrain REAL, role_batiment REAL,180      role_anterieur REAL, role_reference TEXT, voisinage TEXT, cubf INTEGER, voie TEXT, civ INTEGER,181      loyer_porte REAL, loyer_3 REAL, loyer_4 REAL, loyer_5 REAL, x16 INTEGER, y16 INTEGER,182      marche TEXT NOT NULL DEFAULT 'residentiel', categorie TEXT NOT NULL DEFAULT 'plex', usage TEXT,183      tranche TEXT, forme TEXT, mixte INTEGER184    ) WITHOUT ROWID;185    INSERT INTO immeuble (id, adresse, municipalite, arrond, code_mun, lat, lng, logements, classe, etages, annee,186      aire_m2, terrain_m2, front_m, lien, construction, locaux_nr, chambres, role, role_terrain, role_batiment,187      role_anterieur, role_reference, voisinage, cubf, voie, civ, marche, categorie, usage)188    SELECT u.id_provinc, r.adresse, r.municipalite, NULLIF(r.arrond, ''), u.code_mun, r.lat, r.lng,189           u.nb_logements, '', r.nb_etages, u.annee, u.aire_m2, u.terrain_m2, NULLIF(r.front_terrain_m, 0),190           NULLIF(r.lien_physique, ''), NULLIF(r.genre_construction, ''),191           r.nb_locaux_non_resid, r.nb_chambres_locatives, r.valeur_role, r.valeur_terrain,192           r.valeur_batiment, NULLIF(r.valeur_anterieure, 0), u.role_reference, r.unite_voisinage,193           r.cubf, u.voie, u.civ_min, 'residentiel', CASE WHEN u.nb_logements <= 5 THEN 'plex' ELSE 'multilogement' END,194           NULLIF(r.cubf_libelle, '')195    FROM v3.v3_unit u JOIN role.units r ON r.id_provinc = u.id_provinc196    WHERE u.nb_logements >= 2 AND u.genre IN ('plex', 'immeuble')197      AND r.valeur_role >= 10000 AND r.lat IS NOT NULL AND r.lng IS NOT NULL;198    UPDATE immeuble SET classe = CASE WHEN logements = 2 THEN 'duplex' WHEN logements = 3 THEN 'triplex'199      WHEN logements = 4 THEN 'quadruplex' WHEN logements = 5 THEN 'quintuplex'200      WHEN logements <= 11 THEN '6-11' WHEN logements <= 23 THEN '12-23' ELSE '24+' END;201    UPDATE immeuble SET202      tranche = CASE WHEN logements = 2 THEN 'duplex' WHEN logements = 3 THEN 'triplex' WHEN logements <= 5 THEN '4-5'203        WHEN logements <= 11 THEN '6-11' WHEN logements <= 23 THEN '12-23' WHEN logements <= 49 THEN '24-49'204        ELSE '50+' END,205      forme = CASE WHEN etages IS NULL OR etages <= 0 THEN NULL WHEN etages >= 5 THEN 'tour' ELSE 'bas' END,206      mixte = COALESCE(locaux_nr, 0) > 0;207    """)208    if typologie.COMMERCIAL in typologie.marches_actifs():209        config.script(con, """210    INSERT INTO immeuble (id, adresse, municipalite, arrond, code_mun, lat, lng, logements, classe, etages, annee,211      aire_m2, terrain_m2, front_m, lien, construction, locaux_nr, chambres, role, role_terrain, role_batiment,212      role_anterieur, role_reference, voisinage, cubf, voie, civ, marche, categorie, usage)213    SELECT u.id_provinc, r.adresse, r.municipalite, NULLIF(r.arrond, ''), u.code_mun, r.lat, r.lng,214           COALESCE(r.nb_logements, 0), y.categorie, r.nb_etages, u.annee, u.aire_m2, u.terrain_m2,215           NULLIF(r.front_terrain_m, 0), NULLIF(r.lien_physique, ''), NULLIF(r.genre_construction, ''),216           r.nb_locaux_non_resid, r.nb_chambres_locatives, r.valeur_role, r.valeur_terrain,217           r.valeur_batiment, NULLIF(r.valeur_anterieure, 0), u.role_reference, r.unite_voisinage,218           r.cubf, u.voie, u.civ_min, 'commercial', y.categorie, NULLIF(r.cubf_libelle, '')219    FROM v3.v3_unit u JOIN role.units r ON r.id_provinc = u.id_provinc220    JOIN temp._typologie y ON y.cubf = r.cubf221    WHERE u.genre = 'autre' AND COALESCE(u.motif_hors_champ, '') IN ('genre-autre', 'institution')222      AND r.valeur_role >= 10000 AND r.valeur_batiment > 0 AND r.lat IS NOT NULL AND r.lng IS NOT NULL;223        """)224    config.script(con, """225    DROP TABLE temp._typologie;226    CREATE INDEX immeuble_mun ON immeuble (code_mun, classe);227    CREATE INDEX immeuble_geo ON immeuble (lat, lng);228    CREATE INDEX immeuble_categorie ON immeuble (categorie, code_mun);229    """)230    if garde:231        con.execute(f"UPDATE immeuble SET {', '.join(f'{c} = g.{c}' for c in garde)} FROM temp._garde g "232                    "WHERE g.id = immeuble.id")233        con.execute("DROP TABLE temp._garde")234    return con.execute("SELECT COUNT(*) FROM immeuble").fetchone()[0]235236237def _ventes(con) -> int:238    config.script(con, """239    DROP TABLE IF EXISTS vente;240    CREATE TABLE vente (241      sale_id TEXT PRIMARY KEY, id TEXT NOT NULL, date TEXT NOT NULL, jour INTEGER NOT NULL, prix REAL NOT NULL,242      de_marche INTEGER NOT NULL, motifs TEXT, role_vente REAL, role_ref_annee INTEGER,243      repere_ratio REAL, repere_n INTEGER, lot_taille INTEGER, doublon INTEGER NOT NULL,244      annee_pub INTEGER, aire_pub REAL245    ) WITHOUT ROWID;246    INSERT INTO vente247    SELECT t.id, l.id_provinc, t.date, CAST(julianday(t.date) - 2440587.5 AS INTEGER), t.amount,248           q.de_marche, q.motifs, q.role_vente, q.role_ref_annee, q.repere_ratio, q.repere_n,249           q.lot_taille, q.doublon_de IS NOT NULL, t.year_built, t.floor_area250    FROM role.transactions t251    JOIN v3.v3_sale_link l ON l.sale_id = t.id AND l.niveau = 'unite'252    JOIN v3.v3_sale_quality q ON q.sale_id = t.id253    JOIN immeuble i ON i.id = l.id_provinc254    WHERE t.amount > 0 AND t.date IS NOT NULL;255    CREATE INDEX vente_id ON vente (id, jour);256    CREATE INDEX vente_jour ON vente (jour);257    """)258    return con.execute("SELECT COUNT(*) FROM vente").fetchone()[0]259260261def _ventes_tous(con) -> int:262    """Ventes de marché de TOUS les genres (maisons, copropriétés, plex) avec263    leur écart au repère sans fuite de Vrai-Prix : le voisinage d'un plex se lit264    aussi dans ce qui se vend autour de lui."""265    config.script(con, """266    DROP TABLE IF EXISTS vente_tous;267    CREATE TABLE vente_tous (sale_id TEXT PRIMARY KEY, id TEXT, jour INTEGER NOT NULL, lat REAL NOT NULL,268      lng REAL NOT NULL, e REAL NOT NULL, plex INTEGER NOT NULL) WITHOUT ROWID;269    INSERT INTO vente_tous270    SELECT t.id, l.id_provinc, CAST(julianday(t.date) - 2440587.5 AS INTEGER), r.lat, r.lng,271           ln(t.amount / (q.role_vente * q.repere_ratio)), u.genre IN ('plex', 'immeuble')272    FROM role.transactions t273    JOIN v3.v3_sale_link l ON l.sale_id = t.id AND l.niveau = 'unite'274    JOIN v3.v3_sale_quality q ON q.sale_id = t.id AND q.de_marche = 1275    JOIN v3.v3_unit u ON u.id_provinc = l.id_provinc276    JOIN role.units r ON r.id_provinc = l.id_provinc277    WHERE t.amount > 0 AND q.role_vente >= 10000 AND q.repere_ratio > 0 AND r.lat IS NOT NULL278      AND u.genre IN ('maison', 'condo', 'plex', 'immeuble');279    CREATE INDEX vente_tous_jour ON vente_tous (jour);280    """)281    return con.execute("SELECT COUNT(*) FROM vente_tous").fetchone()[0]282283284_NOMBRE = re.compile(r"-?\d[\d\s  ]*(?:[.,]\d+)?")285_MIX = re.compile(r"^\s*(\d)\s*(?:1/2|½)(?:\s*et plus)?\s*$")286287288def nombre(texte) -> float | None:289    """« 163 596,00 $ » → 163596.0 ; rien de lisible → None."""290    if texte is None:291        return None292    if isinstance(texte, (int, float)):293        return float(texte)294    m = _NOMBRE.search(str(texte))295    if not m:296        return None297    brut = re.sub(r"[\s  ]", "", m.group(0)).replace(",", ".")298    try:299        return float(brut)300    except ValueError:301        return None302303304CLES_REVENU = ("Revenus annuels", "Revenu", "Revenus bruts potentiels", "Revenus bruts", "Revenu brut",305               "Revenus", "Revenus résidentiels")306307308def lire_details(details: str | None) -> dict:309    """Champs à revenus lus d'une inscription : revenu annuel, taxes, énergie,310    répartition des logements par taille (« 4 1/2 » : 2), taux d'occupation."""311    try:312        d = json.loads(details) if details else {}313    except (ValueError, TypeError):314        d = {}315    if not isinstance(d, dict):316        return {}317    out: dict = {}318    for cle in CLES_REVENU:319        v = nombre(d.get(cle))320        if v and v > 0:321            out["revenu"] = v322            break323    for cle, nom in (("Taxes municipales", "taxe_mun"), ("Taxes scolaires", "taxe_scol"),324                     ("Coût d'énergie", "energie"), ("Assurances", "assurances"),325                     ("Taux d'occupation", "occupation")):326        v = nombre(d.get(cle))327        if v is not None and v >= 0:328            out[nom] = v329    mix = {}330    for cle, val in d.items():331        m = _MIX.match(str(cle))332        n = nombre(val)333        if m and n and 0 < n < 500:334            mix[int(m.group(1))] = int(n)335    if mix:336        out["mix"] = mix337    return out338339340def _annonces(con) -> int:341    config.script(con, """342    DROP TABLE IF EXISTS annonce;343    CREATE TABLE annonce (344      uid TEXT PRIMARY KEY, source TEXT, url TEXT, titre TEXT, adresse TEXT, ville TEXT, type TEXT,345      lat REAL, lng REAL, prix REAL, logements INTEGER, annee INTEGER, aire_pi2 REAL,346      revenu REAL, taxe_mun REAL, taxe_scol REAL, energie REAL, assurances REAL, occupation REAL,347      mix TEXT, id TEXT, lien_niveau TEXT, code_mun TEXT, eval_ratio REAL,348      active INTEGER NOT NULL, vue_debut REAL, vue_fin REAL, statut TEXT, image TEXT, n_images INTEGER349    ) WITHOUT ROWID;350    CREATE INDEX annonce_id ON annonce (id) WHERE id IS NOT NULL;351    CREATE INDEX annonce_active ON annonce (active, code_mun);352    """)353    sql = """354    SELECT l.uid, l.source, l.url, l.title, l.address, l.city, l.property_type, l.lat, l.lng, l.price,355           l.year_built, l.area_sqft, l.details, l.active, l.first_seen, l.last_seen, l.images,356           v.units, v.income, v.tax_municipal, v.tax_school, v.image, v.n_images, v.family,357           k.id_provinc, k.niveau, k.code_mun, k.eval_ratio, k.groupe, s.status358    FROM ik.listings l359    LEFT JOIN ik.v3_listing v ON v.uid = l.uid360    LEFT JOIN v3.v3_listing_link k ON k.uid = l.uid361    LEFT JOIN ik.v3_listing_status s ON s.uid = l.uid362    WHERE l.price > 20000 AND COALESCE(l.dup_hidden, 0) = 0363      AND (v.family = 'plex' OR k.groupe = 'plex'364           OR lower(l.property_type) IN ('duplex','triplex','quadruplex','quintuplex','multiplex','plex',365                                         'immeuble à revenus','multi-logements','multilogement')366           OR k.id_provinc IN (SELECT id FROM immeuble))367    """368    lignes = []369    for r in con.execute(sql):370        d = lire_details(r["details"])371        revenu = d.get("revenu") or (r["income"] if r["income"] and r["income"] > 0 else None)372        mix = d.get("mix")373        logements = r["units"] if r["units"] and r["units"] > 0 else (sum(mix.values()) if mix else None)374        image = r["image"]375        if not image and r["images"]:376            try:377                imgs = json.loads(r["images"])378                image = imgs[0] if imgs else None379                if isinstance(image, dict):380                    image = image.get("url")381            except (ValueError, TypeError):382                image = None383        lignes.append((384            r["uid"], r["source"], r["url"], r["title"], r["address"], r["city"], r["property_type"],385            r["lat"], r["lng"], r["price"], logements, r["year_built"], r["area_sqft"], revenu,386            d.get("taxe_mun", r["tax_municipal"]), d.get("taxe_scol", r["tax_school"]), d.get("energie"),387            d.get("assurances"), d.get("occupation"), json.dumps(mix) if mix else None,388            r["id_provinc"], r["niveau"], r["code_mun"], r["eval_ratio"], int(r["active"] or 0),389            r["first_seen"], r["last_seen"], r["status"], image, r["n_images"]))390    con.executemany("INSERT OR REPLACE INTO annonce VALUES (" + ",".join("?" * 30) + ")", lignes)391    return len(lignes)392393394def _loyers_locaux(sql: str) -> tuple[list[tuple], str]:395    """Loyers lus sur place (``VX_LOUKA_FICHIER``), base ouverte en lecture seule."""396    chemin = config.LOUKA_FICHIER397    try:398        src = sqlite3.connect(f"file:{chemin}?mode=ro", uri=True, timeout=120)399        try:400            lignes = [tuple(r) for r in src.execute(sql)]401        finally:402            src.close()403    except sqlite3.Error as e:404        raise RuntimeError(f"loyers Lou-Ka illisibles ({chemin}) : {e}") from e405    return lignes, chemin406407408def _loyers_ssh(sql: str) -> tuple[list[tuple], str]:409    """Loyers lus sur un autre nœud, par SSH (``VX_LOUKA_HOTE``, ``VX_LOUKA_DB``)."""410    cmd = ["ssh", "-o", "BatchMode=yes", "-o", "ConnectTimeout=15", config.LOUKA_HOTE,411           f"sqlite3 -readonly -csv -header ~/{config.LOUKA_DB} \"{sql}\""]412    res = subprocess.run(cmd, capture_output=True, text=True, timeout=600)413    if res.returncode != 0 or not res.stdout.strip():414        raise RuntimeError(f"loyers Lou-Ka illisibles : {res.stderr.strip()[:300]}")415    lecteur = csv.DictReader(io.StringIO(res.stdout))416    cols = lecteur.fieldnames or []417    lignes = [tuple(None if r[c] == "" else r[c] for c in cols) for r in lecteur]418    return lignes, f"{config.LOUKA_HOTE}:{config.LOUKA_DB}"419420421def synchroniser_loyers(con) -> int:422    """Copie les loyers demandés de Lou-Ka : sur place si ``VX_LOUKA_FICHIER``423    est posé, sinon d'un autre nœud par SSH. En cas d'échec la table précédente424    est gardée telle quelle."""425    sql = ("SELECT uid, lat, lng, city, kind, unit_type, rooms, bedrooms, bathrooms, area_sqft, price, year_built, "426           "f_heat_incl, f_elec_incl, f_hotwater_incl, furnished, f_parking_incl, f_elevator, first_seen, last_seen, "427           "building_key FROM v3_listing WHERE price BETWEEN 300 AND 12000 AND lat IS NOT NULL AND lng IS NOT NULL")428    lignes, source = _loyers_locaux(sql) if config.LOUKA_FICHIER else _loyers_ssh(sql)429    if len(lignes) < 1000:430        raise RuntimeError(f"loyers Lou-Ka : {len(lignes)} lignes seulement, copie refusée")431    config.script(con, """432    DROP TABLE IF EXISTS loyer;433    CREATE TABLE loyer (434      uid TEXT PRIMARY KEY, lat REAL, lng REAL, ville TEXT, genre TEXT, type_logement TEXT, pieces REAL,435      chambres REAL, sdb REAL, aire_pi2 REAL, loyer REAL, annee INTEGER, chauffe INTEGER, eclaire INTEGER,436      eau_chaude INTEGER, meuble INTEGER, stationnement INTEGER, ascenseur INTEGER,437      vue_debut REAL, vue_fin REAL, immeuble_cle TEXT438    ) WITHOUT ROWID;439    """)440    con.executemany("INSERT OR REPLACE INTO loyer VALUES (" + ",".join("?" * 21) + ")", lignes)441    noter(con, "loyers", {"n": len(lignes), "source": source})442    return len(lignes)443444445def construire(verbose: bool = True, loyers: bool = True) -> dict:446    t0 = time.time()447    con = config.ouvrir(ecriture=True)448    config.script(con, SCHEMA)449    config.attacher_sources(con)450    bilan = {}451    with config.transaction(con):452        _territoires(con)453        bilan["immeubles"] = _immeubles(con)454        bilan["categories"] = {r[0]: r[1] for r in con.execute("SELECT categorie, COUNT(*) FROM immeuble GROUP BY 1")}455        bilan["ventes"] = _ventes(con)456        bilan["ventes_commerciales"] = con.execute(457            "SELECT COUNT(*) FROM vente v JOIN immeuble i ON i.id = v.id WHERE i.marche = 'commercial'").fetchone()[0]458        bilan["ventes_tous_genres"] = _ventes_tous(con)459        bilan["annonces"] = _annonces(con)460        bilan["annonces_revenu"] = con.execute("SELECT COUNT(*) FROM annonce WHERE revenu > 0").fetchone()[0]461        bilan["derniere_vente"] = con.execute("SELECT MAX(date) FROM vente").fetchone()[0]462    if loyers:463        try:464            with config.transaction(con):465                bilan["loyers"] = synchroniser_loyers(con)466        except Exception as e:  # la passe continue avec les loyers de la veille467            bilan["loyers_erreur"] = str(e)468    bilan["secondes"] = round(time.time() - t0, 1)469    with config.transaction(con):470        noter(con, "socle", bilan)471    con.close()472    if verbose:473        print(json.dumps(bilan, ensure_ascii=False, indent=1))474    return bilan475
Files main
Menu

Theme