SPB Git

Repository Public

Endpoints.swift 8.4 KB 177 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : Vrai-Prix iOS9// File             : VraiPrix/Core/API/Endpoints.swift10// Description      : les routes de l'API Vrai-Prix v2 utilisées par l'app11//                    (contrat : API.md du service).12// Module           : VraiPrix13// Repository       : https://git.spboucher.ai/vrai-prix-ios-v314// Project Website  : https://www.vrai-prix.com15// Created          : 2026-11-2616// Last Modified    : 2026-11-2617//18// =============================================================================19// AUTHOR & PROFESSIONAL AFFILIATION20// =============================================================================21//22// Author           : Simon-Pierre Boucher23// Position         : Professor of Finance24// Institution      : Université du Québec en Outaouais (UQO)25// Department       : Département des sciences administratives26// Organization     : SP Boucher27//28// Website          : https://spboucher.ai29// Git              : https://git.spboucher.ai30//31// =============================================================================32// OFFICIAL CONTACT DIRECTORY33// =============================================================================34//35// General          : info@spboucher.ai36// Professional     : contact@spboucher.ai37// Direct           : simon@spboucher.ai38// Research         : research@spboucher.ai39// Development      : dev@spboucher.ai40// Support          : support@spboucher.ai41// Security/Admin   : admin@spboucher.ai42// Notifications    : notifications@spboucher.ai43//44// Preferred Contact: support@spboucher.ai45//46// =============================================================================47// COPYRIGHT & INTELLECTUAL PROPERTY48// =============================================================================49//50// Copyright (c) 202651// Simon-Pierre Boucher52//53// All rights reserved where applicable.54//55// This file is governed by the applicable project license,56// copyright notices, institutional agreements and relevant law.57//58// Unless expressly authorized by the applicable license or59// rights holder, copying, redistribution, sublicensing,60// publication and commercial exploitation are not permitted.61//62// Existing third-party rights and notices remain unaffected.63//64// =============================================================================65// CONFIDENTIALITY & SECURITY66// =============================================================================67//68// Classification   : Public69// Distribution     : Public repository; use is governed by the project license70// Security Contact : admin@spboucher.ai71//72// Access to this source does not independently grant permission73// to redistribute or disclose confidential materials.74//75// Do not embed credentials, private keys, access tokens,76// certificates or confidential personal information.77//78// =============================================================================79// LICENSE & MAINTENANCE80// =============================================================================81//82// License          : None specified (no license file in this repository)83// Maintainer       : Simon-Pierre Boucher84// Technical Contact: dev@spboucher.ai85//86// =============================================================================87// END OF SP BOUCHER SOURCE HEADER88// =============================================================================8990import Foundation9192extension APIClient {93    /// Autocomplétion d'adresse (au moins 3 caractères).94    /// Recherche : adresses (3 caractères), municipalités (dès 2) et rues.95    func search(_ q: String, limit: Int = 10) async throws -> SearchResponse {96        let t = q.trimmingCharacters(in: .whitespacesAndNewlines)97        return try await get("api/search", query: ["q": t, "limit": String(limit)], as: SearchResponse.self)98    }99100    /// Fiche complète d'une unité : identité, estimation, comparables, contexte, ventes de l'adresse.101    func unit(_ id: String) async throws -> Fetched<UnitDetail> {102        try await fetch("api/units/" + (id.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? id))103    }104105    /// Estimation sans adresse : municipalité, type et caractéristiques facultatives.106    func estimateManual(municipality: String, typeProp: String, floorArea: Double?, yearBuilt: Int?, landArea: Double?) async throws -> UnitDetail {107        var body: [String: Any] = ["municipality": municipality, "typeProp": typeProp]108        if let floorArea { body["floorArea"] = floorArea }109        if let yearBuilt { body["yearBuilt"] = yearBuilt }110        if let landArea { body["landArea"] = landArea }111        return try await post("api/estimate", body: JSONSerialization.data(withJSONObject: body))112    }113114    func sales(_ f: SaleFilters, page: Int = 1, limit: Int = 30) async throws -> Fetched<SalesPage> {115        var q = f.query116        q["page"] = String(page); q["limit"] = String(limit)117        return try await fetch("api/ventes", query: q)118    }119120    func salesOverview() async throws -> SalesOverview { try await get("api/ventes/overview") }121122    func municipalities() async throws -> [Municipality] {123        try await get("api/municipalites", as: MunicipalityList.self).municipalites124    }125126    func municipality(_ slug: String) async throws -> Fetched<MunicipalityDetail> {127        try await fetch("api/municipalites/" + slug, query: ["ventes": "20", "echantillon": "12"])128    }129130    func marketIndex() async throws -> IndexResponse { try await get("api/indice") }131    func parkStats() async throws -> ParkStats { try await get("api/stats") }132    func marketTest() async throws -> MarketTest { try await get("api/stats/marche") }133134    func listings(_ f: ListingFilters, page: Int = 1, per: Int = 24) async throws -> Fetched<ListingsPage> {135        var q = f.query136        q["page"] = String(page); q["per"] = String(per)137        return try await fetch("api/avendre", query: q)138    }139140    func listing(_ uid: String) async throws -> Fetched<ListingDetail> {141        // l'uid contient « : » : tout est encodé142        var allowed = CharacterSet.alphanumerics143        allowed.insert(charactersIn: "-_.~")144        return try await fetch("api/avendre/" + (uid.addingPercentEncoding(withAllowedCharacters: allowed) ?? uid))145    }146147    func listingComps(_ uid: String) async throws -> [Comparable] {148        let all = try await get("api/avendre/comps", query: ["uid": uid, "listings": "0", "limit": "12"], as: ListingComps.self).comps149        // d'abord les ventes retenues par le moteur150        return all.filter { $0.kind != "listing" }.sorted { ($0.engineUsed ?? false ? 0 : 1, -($0.weight ?? 0)) < ($1.engineUsed ?? false ? 0 : 1, -($1.weight ?? 0)) }151    }152153    /// Points de carte d'une couche dans la zone visible (au plus 0,5° de côté).154    func mapPoints(layer: MapLayer, bbox: MapBounds, months: Int? = nil, limit: Int? = nil) async throws -> MapResponse {155        try await get("api/map", query: ["layer": layer.rawValue, "bbox": bbox.bbox, "months": months.map(String.init), "limit": limit.map(String.init)])156    }157158    /// Méthode du coût d'une propriété du rôle : préremplissage puis calcul (non sauvegardé).159    func costPrefill(_ id: String) async throws -> CostPrefill {160        try CostPrefill(data: try await raw("api/cost/property", query: ["id": id]))161    }162163    func costEstimate(_ prefill: CostPrefill) async throws -> CostEstimate {164        // agrégats seulement (5 ko au lieu de 190 ko), calcul non enregistré165        try await post("api/cost/estimate", query: ["summary": "1"], body: prefill.inputJSON)166    }167168    /// Rapport PDF d'une estimation (standard ou professionnel).169    func report(id: String, pro: Bool, name: String) async throws -> URL {170        let slug = name.folding(options: .diacriticInsensitive, locale: nil).lowercased()171            .map { $0.isLetter || $0.isNumber ? $0 : "-" }.reduce(into: "") { if !($0.hasSuffix("-") && $1 == "-") { $0.append($1) } }172            .trimmingCharacters(in: CharacterSet(charactersIn: "-"))173        return try await download(pro ? "api/report/pro" : "api/report", query: ["id": id],174                                  fileName: "vrai-prix-\(slug.isEmpty ? "propriete" : slug)\(pro ? "-professionnel" : "").pdf")175    }176}177
Files main
Menu

Theme