Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project : Lou·Ka9# File : louka/connectors/gestion_isr.py10# Module : louka11# Repository : https://git.spboucher.ai/lou-ka12# Created : 2026-08-0913# Last Modified : 2026-10-2014#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# Lou-Ka — Agrégateur de logements à louer (province de Québec)89# Auteur : Simon-Pierre Boucher — contact@spboucher.ai90# connectors/gestion_isr.py : connecteur Gestion ISR (gestion-isr.com)91# Le site vitrine (SPA Vite/React) renvoie vers le portail public92# location.gestion-isr.com, propulsé par Supabase. On lit l'URL, la clé93# anonyme ET le chemin REST des annonces (const LISTINGS_URL) embarqués dans94# le HTML du portail — depuis 2026-10 c'est la vue publique expurgée95# /rest/v1/listings_public?statut=eq.Actif (la table listings est passée96# derrière RLS et renvoie 200 []). JSON structuré (loyer, type, ville, GPS,97# photos, unités par immeuble).98# 2 requêtes par sync ; lien profond ?fiche=<id_app> par annonce.99# -----------------------------------------------------------------------------100from __future__ import annotations101102import re103import time104105from ..schema import Listing, normalize_unit_type, strip_accents106from .base import BaseConnector107108PORTAL = "https://location.gestion-isr.com/"109110_URL_RE = re.compile(r"SUPABASE_URL\s*=\s*'([^']+)'")111_KEY_RE = re.compile(r"SUPABASE_ANON\s*=\s*'([^']+)'")112# Chemin REST que le portail requête lui-même (vue publique) — suivi113# dynamiquement pour survivre aux renommages de table/vue côté Supabase.114_LIST_RE = re.compile(r"LISTINGS_URL\s*=\s*`\$\{SUPABASE_URL\}([^`]+)`")115116117def _pets_value(raw: str) -> str | None:118 """Champ « animaux » structuré -> oui/non/conditions (jamais deviné)."""119 k = strip_accents((raw or "").strip().lower())120 if not k:121 return None122 if k in ("aucun", "non") or k.startswith("non") or "refus" in k:123 return "non"124 if "animaux acceptes" in k or k in ("oui",):125 return "oui"126 # « Chat », « Chat, petit chien », « Petits compagnons »… = sous conditions127 if re.search(r"chat|chien|compagnon|condition|accepte", k):128 return "conditions"129 return None130131132class GestionIsrConnector(BaseConnector):133 source_id = "gestion_isr"134 request_delay = 0.6135136 def fetch(self) -> list[Listing]:137 html = self.get(PORTAL).text138 m_url, m_key = _URL_RE.search(html), _KEY_RE.search(html)139 if not (m_url and m_key):140 raise RuntimeError("clé/URL Supabase introuvables dans le portail")141 base, key = m_url.group(1).rstrip("/"), m_key.group(1)142143 m_list = _LIST_RE.search(html)144 if not m_list:145 # erreur FRANCHE plutôt qu'un found=0 silencieux (cf. 2026-10-20 :146 # listings → listings_public, l'ancienne table renvoyait 200 [])147 raise RuntimeError("const LISTINGS_URL introuvable dans le portail")148149 # La vue listings_public est coûteuse côté Postgres : « canceling150 # statement due to statement timeout » (57014 → 500) observé 2 runs151 # sur 4 le 2026-10-20. Retry avant l'erreur franche (pattern solaris152 # 8eff094) ; même URL — timeout serveur, pas un problème de cache.153 last_err: Exception | None = None154 for attempt in range(3):155 if attempt:156 time.sleep(4 * attempt)157 try:158 rows = self.get(159 base + m_list.group(1),160 headers={"apikey": key, "Authorization": f"Bearer {key}"},161 ).json()162 break163 except Exception as err:164 last_err = err165 else:166 raise last_err167168 listings: list[Listing] = []169 for row in rows:170 try:171 lst = self._parse_row(row)172 except Exception:173 continue174 if lst:175 listings.append(lst)176 return listings177178 def _parse_row(self, row: dict) -> Listing | None:179 ext_id = str(row.get("pk") or "")180 title = (row.get("titre") or "").strip()181 if not ext_id or not title:182 return None183 # exclusions : locaux commerciaux, stationnements, rangements184 if re.search(r"commercial|bureau|stationnement|rangement|entrep[ôo]t",185 title, re.I):186 return None187188 id_app = (row.get("id_app") or "").strip()189 url = f"{PORTAL}?fiche={id_app}" if id_app else f"{PORTAL}#{ext_id}"190191 # loyer structuré (le plus bas des unités dispo pour un immeuble)192 loyer = row.get("loyer")193 price = float(loyer) if isinstance(loyer, (int, float)) else None194195 # GPS : champ « adresse_geo » = "45.754…, -72.501…"196 lat = lng = None197 geo = (row.get("adresse_geo") or "").split(",")198 if len(geo) == 2:199 try:200 lat, lng = float(geo[0]), float(geo[1])201 except ValueError:202 lat = lng = None203204 # description source + inventaire des unités disponibles (immeubles)205 description = (row.get("description") or "").strip()206 units = row.get("units") or []207 dispo = [u for u in units if (u or {}).get("statut") == "Disponible"]208 if dispo:209 groups: dict[tuple, int] = {}210 for u in dispo:211 groups[(u.get("type") or "", u.get("prix"))] = \212 groups.get((u.get("type") or "", u.get("prix")), 0) + 1213 lines = [f"• {n} × {t} à {p} $" if n > 1 else f"• {t} à {p} $"214 for (t, p), n in sorted(groups.items()) if t and p]215 if lines:216 description += "\n\nUnités disponibles :\n" + "\n".join(lines)217218 images = [u for u in (row.get("photos") or []) if str(u).startswith("http")]219 if not images:220 # repli : albums par modèle d'unité (photo_variants), puis main_photo221 for var in row.get("photo_variants") or []:222 for u in ([var.get("main")] + list(var.get("photos") or [])):223 if str(u or "").startswith("http") and u not in images:224 images.append(u)225 if not images and str(row.get("main_photo") or "").startswith("http"):226 images = [row["main_photo"]]227228 return Listing(229 source=self.source_id,230 external_id=ext_id,231 url=url,232 title=title,233 address=(row.get("id") or "").strip(), # « id » = adresse civique complète234 sector=(row.get("secteur") or "").strip(),235 city=(row.get("ville") or "").strip(),236 unit_type=normalize_unit_type(row.get("grandeur") or ""),237 price=price,238 availability=(row.get("date_dispo_affichage")239 or row.get("date_dispo") or "").strip(),240 pets=_pets_value(row.get("animaux") or ""),241 description=description[:2000],242 images=images[:30],243 lat=lat,244 lng=lng,245 )246