SPB Git

Repository Public

_planpoint.py 9.7 KB 238 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Lou·Ka9# File             : louka/connectors/_planpoint.py10# Module           : louka11# Repository       : https://git.spboucher.ai/lou-ka12# Created          : 2026-08-2513# Last Modified    : 2026-08-2514#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/_planpoint.py : helper PARTAGÉ pour le widget Planpoint91#   (app.planpoint.io — même API JSON publique que cosoltec/devimco :92#   POST /api/{groups,projects}/find avec {namespace, hostName}).93#   Utilisé par espace_w, m3_laval, quartier_7 et lac_jerome (Rive-Nord).94#   Pas un connecteur : aucun source_id, ignoré par le registre auto-découvrant.95# -----------------------------------------------------------------------------96from __future__ import annotations9798import time99100from ..schema import Listing, normalize_unit_type101102PLANPOINT_API = "https://app.planpoint.io/api"103104105def planpoint_projects(conn, kind: str, namespace: str, host_name: str) -> list[dict]:106    """Projets d'un compte Planpoint (kind = « groups » ou « projects »).107108    POST throttlé via la session du connecteur ; `groups/find` renvoie109    {projects: [...]}, `projects/find` renvoie un projet unique.110    """111    wait = conn.request_delay - (time.time() - conn._last_request)112    if wait > 0:113        time.sleep(wait)114    resp = conn.session.post(f"{PLANPOINT_API}/{kind}/find",115                             json={"namespace": namespace, "hostName": host_name},116                             timeout=conn.timeout)117    conn._last_request = time.time()118    resp.raise_for_status()119    data = resp.json()120    if kind == "groups":121        return data.get("projects") or []122    return [data] if isinstance(data, dict) else []123124125def project_images(project: dict) -> list[str]:126    """Galerie du projet (photos communes) + image de couverture."""127    imgs = [i for i in (project.get("images") or [])128            if isinstance(i, str) and i.startswith("http")]129    cover = project.get("projectImageUrl")130    if isinstance(cover, str) and cover.startswith("http") and cover not in imgs:131        imgs.append(cover)132    return imgs133134135def unit_listing(source_id: str, project: dict, floor: dict, unit: dict, *,136                 page_url: str, default_city: str,137                 building: str = "", extra_amenities: list[str] | None = None,138                 ) -> Listing | None:139    """Une unité Planpoint « Available » -> Listing standard (sinon None).140141    Champs communs aux sites Planpoint : external_id = ObjectId de l'unité142    (stable), prix mensuel s'il est publié (>0, jamais inventé), pi²,143    inclusions françaises (inclusionsArr), plans + photos d'unité puis144    galerie du projet, date de livraison -> disponibilité.145    """146    if (unit.get("availability") or "").lower() != "available":147        return None148    uid = unit.get("_id") or ""149    if not uid:150        return None151    name = (project.get("name") or "").strip()152    raw_addr = (project.get("address") or "").strip()153    addr_parts = [p.strip() for p in raw_addr.split(",") if p.strip()]154    street = addr_parts[0] if addr_parts else ""155    city = addr_parts[1] if len(addr_parts) > 1 else default_city156    lat, lng = project.get("lat"), project.get("lon")157158    price = unit.get("price")159    price = float(price) if isinstance(price, (int, float)) and price > 0 else None160    area = unit.get("squareFeet")161    area = float(area) if isinstance(area, (int, float)) and area > 0 else None162163    # type d'unité : champ `type` s'il ressemble à « 4 1/2 » / « 4,5-G »,164    # sinon dérivé du nombre de chambres (« 2 bedrooms » -> 4½)165    unit_type = normalize_unit_type(unit.get("type") or "")166    if not unit_type.endswith("½") and unit_type != "6½+":167        unit_type = normalize_unit_type(unit.get("bedrooms") or "") or unit_type168169    images = [i for i in (unit.get("images") or [])170              if isinstance(i, str) and i.startswith("http")]171    images += [i for i in (unit.get("layoutGallery") or [])172               if isinstance(i, str) and i.startswith("http") and i not in images]173    images += [i for i in project_images(project) if i not in images]174175    amenities: list[str] = []176    for inc in unit.get("inclusionsArr") or []:177        lbl = ((inc.get("fr") or inc.get("en") or "").strip()178               if isinstance(inc, dict) else str(inc).strip())179        if lbl and lbl not in amenities:180            amenities.append(lbl[0].upper() + lbl[1:])181    for lbl in extra_amenities or []:182        if lbl not in amenities:183            amenities.append(lbl)184185    details: dict = {}186    if isinstance(unit.get("bathrooms"), (int, float)):187        details["bathrooms"] = unit["bathrooms"]188    if floor.get("name"):189        details["floor"] = floor["name"]190    if unit.get("orientation"):191        details["orientation"] = unit["orientation"]192    if unit.get("type"):193        details["model"] = unit["type"]194195    delivery = str(unit.get("deliveryDate") or "")[:10]196    availability = f"Disponible le {delivery}" if delivery else "Disponible"197198    facts: list[str] = []199    where = building or name200    if unit.get("name"):201        facts.append(f"Unité {unit['name']}"202                     + (f" — {where}" if where else "") + f", {city}.")203    bits: list[str] = []204    if unit.get("type"):205        bits.append(f"modèle {unit['type']}")206    if floor.get("name"):207        bits.append(f"étage {floor['name']}")208    if area:209        bits.append(f"{area:g} pi²")210    if isinstance(unit.get("bathrooms"), (int, float)):211        bits.append(f"{unit['bathrooms']:g} salle(s) de bain")212    if bits:213        facts.append(", ".join(bits).capitalize() + ".")214    if amenities:215        facts.append("Inclusions : " + ", ".join(amenities) + ".")216217    return Listing(218        source=source_id,219        external_id=uid,                    # ObjectId Planpoint de l'unité220        url=page_url,                       # pas de page publique par unité221        title=f"{name} — Unité {unit.get('name', '')}".strip(" —"),222        address=street,223        city=city,224        unit_type=unit_type,225        price=price,226        price_label=f"{price:.0f} $ /mois" if price else "",227        availability=availability,228        availability_date=delivery or None,229        area_sqft=area,230        furnished=unit["furnished"] if isinstance(unit.get("furnished"), bool) else None,231        description=" ".join(facts)[:2000],232        amenities=amenities,233        details=details,234        images=images[:30],235        lat=lat if (lat is not None and lng is not None) else None,236        lng=lng if (lat is not None and lng is not None) else None,237    )238
Files main
Menu

Theme