SPB Git

Repository Public

bannieres.py 7.5 KB 180 lines python

1#!/usr/bin/env python32# =============================================================================3#                  SP BOUCHER | SOFTWARE & RESEARCH4#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5# =============================================================================6#7# PROJECT METADATA8# -----------------------------------------------------------------------------9# Project          : Immo·Ka10# File             : immoka/bannieres.py11# Module           : immoka12# Repository       : https://git.spboucher.ai/immo-ka13# Created          : 2026-08-2514# Last Modified    : 2026-08-2515#16# =============================================================================17# AUTHOR & PROFESSIONAL AFFILIATION18# =============================================================================19#20# Author           : Simon-Pierre Boucher21# Position         : Professor of Finance22# Institution      : Université du Québec en Outaouais (UQO)23# Department       : Département des sciences administratives24# Organization     : SP Boucher25#26# Website          : https://spboucher.ai27# Git              : https://git.spboucher.ai28#29# =============================================================================30# OFFICIAL CONTACT DIRECTORY31# =============================================================================32#33# General          : info@spboucher.ai34# Professional     : contact@spboucher.ai35# Direct           : simon@spboucher.ai36# Research         : research@spboucher.ai37# Development      : dev@spboucher.ai38# Support          : support@spboucher.ai39# Security/Admin   : admin@spboucher.ai40# Notifications    : notifications@spboucher.ai41#42# Preferred Contact: contact@spboucher.ai43#44# =============================================================================45# COPYRIGHT & INTELLECTUAL PROPERTY46# =============================================================================47#48# Copyright (c) 202649# Simon-Pierre Boucher50#51# All rights reserved where applicable.52#53# This file is governed by the applicable project license,54# copyright notices, institutional agreements and relevant law.55#56# Unless expressly authorized by the applicable license or57# rights holder, copying, redistribution, sublicensing,58# publication and commercial exploitation are not permitted.59#60# Existing third-party rights and notices remain unaffected.61#62# =============================================================================63# CONFIDENTIALITY & SECURITY64# =============================================================================65#66# Classification   : Public67# Distribution     : Public repository; use is governed by the project license68# Security Contact : admin@spboucher.ai69#70# Access to this source does not independently grant permission71# to redistribute or disclose confidential materials.72#73# Do not embed credentials, private keys, access tokens,74# certificates or confidential personal information.75#76# =============================================================================77# LICENSE & MAINTENANCE78# =============================================================================79#80# License          : None specified (no license file in this repository)81# Maintainer       : Simon-Pierre Boucher82# Technical Contact: dev@spboucher.ai83#84# =============================================================================85# END OF SP BOUCHER SOURCE HEADER86# =============================================================================8788# -----------------------------------------------------------------------------89# Immo-Ka — Annuaire des bannières & courtiers immobiliers du Québec90# bannieres.py : sert data/bannieres.json — les ~690 agences (bannières) du91# registre OACIQ et leurs 17 357 courtiers (recensement complet, 17 régions).92# Régénération du dataset : rescraper registre.oaciq.com (voir93# data/oaciq_census.json pour la méthode) puis reconstruire le JSON.94# -----------------------------------------------------------------------------95from __future__ import annotations9697import json98import threading99from pathlib import Path100101from fastapi import APIRouter, HTTPException102103ROOT = Path(__file__).resolve().parent.parent104DATA = ROOT / "data" / "bannieres.json"105106router = APIRouter()107_cache: dict = {"mtime": None, "doc": None, "index": None, "light": None}108_lock = threading.Lock()109110111def load() -> dict:112    """Charge (avec cache par mtime) l'annuaire canonique des bannières."""113    try:114        mtime = DATA.stat().st_mtime115    except FileNotFoundError:116        return {"generated": None, "count": 0, "brokers_total": 0,117                "bannieres": [], "regions": []}118    with _lock:119        if _cache["doc"] is None or mtime != _cache["mtime"]:120            from . import public121            doc = json.loads(DATA.read_text(encoding="utf-8"))122            regs: dict[str, int] = {}123            indep = 0124            for b in doc.get("bannieres", []):125                # graphie des 17 régions administratives (le registre écrit126                # « Bas Saint-Laurent », « Saguenay-Lac-Saint-Jean »…)127                b["regions"] = [public.region_name(r) or r for r in b.get("regions", [])]128                for br in b.get("brokers", []):129                    if br.get("region"):130                        br["region"] = public.region_name(br["region"]) or br["region"]131                if b["name"].lower().startswith("courtiers à leur compte"):132                    b["independent"] = True133                    indep += b.get("brokers_n") or 0134                for r in b["regions"]:135                    regs[r] = regs.get(r, 0) + 1136            doc["independent_brokers"] = indep137            doc["agencies_total"] = len(doc.get("bannieres", [])) - (1 if indep else 0)138            doc["agency_brokers_total"] = doc.get("brokers_total", 0) - indep139            doc["regions"] = [{"region": r, "n": n}140                              for r, n in sorted(regs.items(),141                                                 key=lambda x: (-x[1], x[0]))]142            _cache["doc"], _cache["mtime"] = doc, mtime143            _cache["index"] = {b["id"]: b for b in doc.get("bannieres", [])}144            _cache["light"] = [{k: v for k, v in b.items() if k != "brokers"}145                               for b in doc.get("bannieres", [])]146        return _cache["doc"]147148149@router.get("/api/bannieres")150def api_bannieres(region: str | None = None, q: str | None = None):151    """Liste des bannières (sans le détail des courtiers) — filtres région/texte."""152    doc = load()153    items = _cache["light"] or []154    if region:155        items = [b for b in items if region in b.get("regions", [])]156    if q:157        needle = q.strip().lower()158        items = [b for b in items if needle in b["name"].lower()]159    return {"generated": doc.get("generated"),160            "total": doc.get("count", 0),161            "brokers_total": doc.get("brokers_total", 0),162            # mêmes nombres que /api/agences : `total` compte aussi l'entrée163            # « Courtiers à leur compte (sans bannière) », qui n'est pas une agence164            "agencies_total": doc.get("agencies_total", 0),165            "agency_brokers_total": doc.get("agency_brokers_total", 0),166            "independent_brokers": doc.get("independent_brokers", 0),167            "count": len(items),168            "regions": doc.get("regions", []),169            "bannieres": items}170171172@router.get("/api/bannieres/{banniere_id}")173def api_banniere(banniere_id: str):174    """Une bannière avec la liste complète de ses courtiers."""175    load()176    b = (_cache["index"] or {}).get(banniere_id)177    if b is None:178        raise HTTPException(status_code=404, detail="bannière inconnue")179    return b180
Files main
Menu

Theme