Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : KA Maps Engine9// File : server/km-geo/src/search.rs10// Module : server11// Repository : https://git.spboucher.ai/ka-maps-engine12// Created : 2026-12-0113// Last Modified : 2026-12-0114//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: support@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//! `GET /v1/search` — géocodage direct et autocomplétion.88//!89//! 1. Analyse : numéro civique, code postal, jetons normalisés, contexte (ville, arrondissement, quartier).90//! 2. Candidats « rue » : égalité ou préfixe sur la forme normalisée (B-tree), puis trigrammes si rien.91//! 3. Numéro demandé : adresse exacte sur les meilleures rues, sinon numéro connu le plus proche (`approx`).92//! 4. Lieux (municipalités, arrondissements, quartiers, points d'intérêt) : même mécanique.93//! 5. Score = texte + importance + proximité (`near` ou contexte), tri, coupe.9495use crate::err::{db_err, ApiError};96use crate::geom::{from_merc, round1, round6, to_merc};97use crate::parse::{self, Alias};98use crate::{norm, AppState};99use serde_json::{json, Value};100use std::collections::HashSet;101use std::sync::Arc;102103pub struct SearchParams {104 pub q: String,105 pub near: Option<(f64, f64)>,106 pub limit: usize,107 pub types: Types,108}109110#[derive(Clone, Copy)]111pub struct Types {112 pub address: bool,113 pub street: bool,114 pub place: bool,115 pub poi: bool,116 pub postcode: bool,117}118119impl Types {120 pub fn all() -> Self {121 Self { address: true, street: true, place: true, poi: true, postcode: true }122 }123 pub fn parse(s: &str) -> Result<Self, ApiError> {124 let mut t = Self { address: false, street: false, place: false, poi: false, postcode: false };125 for part in s.split(',').map(|p| p.trim()).filter(|p| !p.is_empty()) {126 match part {127 "address" | "adresse" => t.address = true,128 "street" | "rue" => t.street = true,129 "place" | "lieu" => t.place = true,130 "poi" => t.poi = true,131 "postcode" | "code_postal" => t.postcode = true,132 _ => return Err(ApiError::bad("types : valeurs admises address, street, place, poi, postcode")),133 }134 }135 Ok(t)136 }137}138139const STRONG_GENERICS: &[&str] = &[140 "rue", "avenue", "boulevard", "chemin", "route", "rang", "montee", "terrasse", "impasse", "croissant", "autoroute",141 "allee", "carre", "cercle", "ruelle", "sentier", "passage", "voie", "desserte", "concession", "drive", "lane", "court",142];143144struct Cand {145 score: f64,146 key: String,147 v: Value,148}149150struct StreetRow {151 id: i32,152 area: Option<String>,153 multi: bool,154 name: String,155 mun: String,156 mun_id: i32,157 x: f64,158 y: f64,159 score: f64,160 dist: Option<f64>,161}162163const SQL_STREET_A: &str = "164WITH c AS (165 SELECT s.id, s.name, s.mun_id, s.imp, s.area, s.multi, ST_X(s.pt) AS x, ST_Y(s.pt) AS y,166 CASE WHEN s.norm = $1 THEN 1.0 WHEN s.core = $1 THEN 0.97167 ELSE 0.80 + 0.12 * length($1)::float8 / greatest(length(s.norm), 1) END AS t168 FROM street s169 WHERE (s.norm = $1 OR s.core = $1 OR (s.norm ~>=~ $1 AND s.norm ~<~ $2) OR (s.core ~>=~ $1 AND s.core ~<~ $2))170 AND ($3::int[] IS NULL OR s.mun_id = ANY($3))171), d AS (172 SELECT c.*, (SELECT min(sqrt((c.x - u.x)^2 + (c.y - u.y)^2)) FROM unnest($4::float8[], $5::float8[]) AS u(x, y)) * $6::float8 AS dist FROM c173)174SELECT d.id, d.name, d.mun_id, m.name, d.x, d.y, d.dist,175 (CASE WHEN d.dist IS NULL THEN 0.84 * d.t + 0.16 * d.imp176 ELSE 0.70 * d.t + 0.12 * d.imp + 0.18 * exp(-d.dist / 15000.0) END177 + 0.03 * ln(1 + m.n_addr) / 13.4)::float8 AS score, d.area, d.multi178FROM d JOIN mun m ON m.id = d.mun_id179ORDER BY score DESC, d.id LIMIT 40";180181const SQL_STREET_B: &str = "182WITH c AS (183 SELECT s.id, s.name, s.mun_id, s.imp, s.area, s.multi, ST_X(s.pt) AS x, ST_Y(s.pt) AS y,184 0.40 + 0.55 * word_similarity($1, s.norm_ctx) AS t185 FROM street s186 WHERE $1 <% s.norm_ctx AND word_similarity($1, s.norm) >= 0.45187 AND ($3::int[] IS NULL OR s.mun_id = ANY($3)) AND $2::text IS NOT NULL188), d AS (189 SELECT c.*, (SELECT min(sqrt((c.x - u.x)^2 + (c.y - u.y)^2)) FROM unnest($4::float8[], $5::float8[]) AS u(x, y)) * $6::float8 AS dist FROM c190)191SELECT d.id, d.name, d.mun_id, m.name, d.x, d.y, d.dist,192 (CASE WHEN d.dist IS NULL THEN 0.84 * d.t + 0.16 * d.imp193 ELSE 0.70 * d.t + 0.12 * d.imp + 0.18 * exp(-d.dist / 15000.0) END194 + 0.03 * ln(1 + m.n_addr) / 13.4)::float8 AS score, d.area, d.multi195FROM d JOIN mun m ON m.id = d.mun_id196ORDER BY score DESC, d.id LIMIT 40";197198const SQL_PLACE_A: &str = "199WITH c AS (200 SELECT p.id, p.kind, p.sub, p.name, p.mun_id, p.imp, p.ref, ST_X(p.pt) AS x, ST_Y(p.pt) AS y,201 CASE WHEN p.norm = $1 OR p.norm_ctx = $1 THEN 1.0202 WHEN p.norm ~>=~ $1 AND p.norm ~<~ $2 THEN 0.78 + 0.14 * length($1)::float8 / greatest(length(p.norm), 1)203 ELSE 0.78 + 0.14 * length($1)::float8 / greatest(length(p.norm_ctx), 1) END AS t204 FROM place p205 WHERE (p.norm = $1 OR (p.norm ~>=~ $1 AND p.norm ~<~ $2) OR (p.norm_ctx ~>=~ $1 AND p.norm_ctx ~<~ $2))206 AND p.kind = ANY($3::text[])207), d AS (208 SELECT c.*, (SELECT min(sqrt((c.x - u.x)^2 + (c.y - u.y)^2)) FROM unnest($4::float8[], $5::float8[]) AS u(x, y)) * $6::float8 AS dist FROM c209)210SELECT d.id, d.kind, d.sub, d.name, d.mun_id, m.name, d.ref, d.x, d.y, d.dist,211 (CASE WHEN d.dist IS NULL THEN 0.72 * d.t + 0.28 * d.imp212 ELSE 0.62 * d.t + 0.24 * d.imp + 0.14 * exp(-d.dist / 15000.0) END)::float8 AS score213FROM d LEFT JOIN mun m ON m.id = d.mun_id214ORDER BY score DESC, d.id LIMIT 30";215216const SQL_PLACE_B: &str = "217WITH c AS (218 SELECT p.id, p.kind, p.sub, p.name, p.mun_id, p.imp, p.ref, ST_X(p.pt) AS x, ST_Y(p.pt) AS y,219 0.45 + 0.25 * word_similarity($1, p.norm_ctx) + 0.25 * greatest(similarity($1, p.norm), similarity($1, p.norm_ctx)) AS t220 FROM place p221 WHERE $1 <% p.norm_ctx AND p.kind = ANY($3::text[]) AND $2::text IS NOT NULL222), d AS (223 SELECT c.*, (SELECT min(sqrt((c.x - u.x)^2 + (c.y - u.y)^2)) FROM unnest($4::float8[], $5::float8[]) AS u(x, y)) * $6::float8 AS dist FROM c224)225SELECT d.id, d.kind, d.sub, d.name, d.mun_id, m.name, d.ref, d.x, d.y, d.dist,226 (CASE WHEN d.dist IS NULL THEN 0.72 * d.t + 0.28 * d.imp227 ELSE 0.62 * d.t + 0.24 * d.imp + 0.14 * exp(-d.dist / 15000.0) END)::float8 AS score228FROM d LEFT JOIN mun m ON m.id = d.mun_id229ORDER BY score DESC, d.id LIMIT 30";230231const SQL_ADDR_EXACT: &str = "232SELECT a.street_id, a.id, a.num, a.suffix, a.postcode, ST_X(a.pt), ST_Y(a.pt), a.src, a.srcs233FROM address a WHERE a.street_id = ANY($1::int[]) AND a.num = $2 ORDER BY a.street_id, a.suffix";234235const SQL_ADDR_NEAR: &str = "236SELECT DISTINCT ON (a.street_id) a.street_id, a.id, a.num, a.suffix, a.postcode, ST_X(a.pt), ST_Y(a.pt), a.src, a.srcs237FROM address a238WHERE a.street_id = ANY($1::int[]) AND a.num BETWEEN $2 - 300 AND $2 + 300239ORDER BY a.street_id, abs(a.num - $2) + (CASE WHEN (a.num - $2) % 2 = 0 THEN 0 ELSE 1 END), a.num";240241/// Voisins connus de même parité, de part et d'autre du numéro demandé, pour chaque rue.242const SQL_ADDR_BRACKET: &str = "243SELECT s.id, lo.num, ST_X(lo.pt), ST_Y(lo.pt), lo.postcode, hi.num, ST_X(hi.pt), ST_Y(hi.pt), hi.postcode244FROM unnest($1::int[]) AS s(id)245JOIN LATERAL (SELECT a.num, a.pt, a.postcode FROM address a246 WHERE a.street_id = s.id AND a.num < $2 AND a.num >= $2 - 400 AND (a.num - $2) % 2 = 0247 ORDER BY a.num DESC LIMIT 1) lo ON true248JOIN LATERAL (SELECT a.num, a.pt, a.postcode FROM address a249 WHERE a.street_id = s.id AND a.num > $2 AND a.num <= $2 + 400 AND (a.num - $2) % 2 = 0250 ORDER BY a.num ASC LIMIT 1) hi ON true";251252/// Rabat un point interpolé sur la rue : point le plus proche de la voie, et distance des deux voisins à la voie.253const SQL_SNAP_STREET: &str = "254WITH p AS (SELECT ST_SetSRID(ST_MakePoint($2, $3), 3857) AS g, ST_SetSRID(ST_MakePoint($4, $5), 3857) AS lo,255 ST_SetSRID(ST_MakePoint($6, $7), 3857) AS hi)256SELECT ST_X(q.c), ST_Y(q.c),257 (SELECT min(ST_Distance(g.geom, p.lo)) FROM street_seg g WHERE g.street_id = $1 AND g.geom && ST_Expand(p.lo, 400)),258 (SELECT min(ST_Distance(g.geom, p.hi)) FROM street_seg g WHERE g.street_id = $1 AND g.geom && ST_Expand(p.hi, 400))259FROM p, LATERAL (SELECT ST_ClosestPoint(g.geom, p.g) AS c FROM street_seg g260 WHERE g.street_id = $1 AND g.geom && ST_Expand(p.g, 600) ORDER BY g.geom <-> p.g LIMIT 1) q";261262const SQL_POSTCODE: &str = "263SELECT p.code, ST_X(p.pt), ST_Y(p.pt), m.name, p.src264FROM postcode p LEFT JOIN mun m ON m.id = p.mun_id265WHERE p.code ~>=~ $1 AND p.code ~<~ $2 ORDER BY p.n DESC, p.code LIMIT $3";266267/// « Rue Saint-Denis » → « rue Saint-Denis » (générique en minuscule dans une adresse, usage québécois).268fn street_in_address(name: &str) -> String {269 let first = name.split(' ').next().unwrap_or("");270 if norm::is_generic(&norm::norm(first)) && name.split(' ').count() > 1 {271 let mut c = name.chars();272 match c.next() {273 Some(f) => f.to_lowercase().collect::<String>() + c.as_str(),274 None => String::new(),275 }276 } else {277 name.to_string()278 }279}280281fn fmt_postcode(pc: &str) -> String {282 if pc.len() == 6 { format!("{} {}", &pc[..3], &pc[3..]) } else { pc.to_string() }283}284285fn dist_json(d: Option<f64>, near: bool) -> Value {286 match (near, d) {287 (true, Some(d)) => json!(d.round()),288 _ => Value::Null,289 }290}291292fn kind_label(kind: &str, sub: Option<&str>) -> &'static str {293 match (kind, sub.unwrap_or("")) {294 ("municipality", _) => "Municipalité",295 ("borough", _) => "Arrondissement",296 ("neighbourhood", _) => "Quartier",297 ("mrc", _) => "MRC",298 ("region", _) => "Région administrative",299 ("locality", _) => "Localité",300 ("poi", "university") => "Université",301 ("poi", "college") => "Cégep ou collège",302 ("poi", "hospital") => "Hôpital",303 ("poi", "metro") => "Station de métro",304 ("poi", "rem") => "Station du REM",305 ("poi", "train") => "Gare",306 ("poi", "bus_terminal") => "Terminus d'autobus",307 ("poi", "park") => "Parc",308 ("poi", "school") => "École",309 ("poi", "library") => "Bibliothèque",310 ("poi", "airport") => "Aéroport",311 _ => "Lieu",312 }313}314315pub async fn run(app: &Arc<AppState>, p: SearchParams) -> Result<Value, ApiError> {316 let parsed = parse::parse(&p.q);317 let near = p.near.map(|(lon, lat)| to_merc(lon, lat));318 let mut cands: Vec<Cand> = Vec::new();319 let client = app.pool.get().await.map_err(|e| db_err("search", e))?;320321 // Début de code postal seul322 if let Some(prefix) = &parsed.postcode_prefix {323 if p.types.postcode {324 let st = client.prepare_cached(SQL_POSTCODE).await.map_err(|e| db_err("search", e))?;325 let hi = format!("{prefix}{{");326 let rows = client.query(&st, &[prefix, &hi, &(p.limit as i64)]).await.map_err(|e| db_err("search", e))?;327 for (i, r) in rows.iter().enumerate() {328 cands.push(postcode_cand(r, 0.9 - i as f64 * 0.001));329 }330 }331 return Ok(finish(cands, p.limit));332 }333334 // Code postal complet : résultat + point de contexte335 let mut ctx_pts: Vec<(f64, f64)> = Vec::new();336 if let Some(pc) = &parsed.postcode {337 let st = client.prepare_cached(SQL_POSTCODE).await.map_err(|e| db_err("search", e))?;338 let hi = format!("{pc}{{");339 let rows = client.query(&st, &[pc, &hi, &1i64]).await.map_err(|e| db_err("search", e))?;340 if let Some(r) = rows.first() {341 ctx_pts.push((r.get(1), r.get(2)));342 if p.types.postcode {343 cands.push(postcode_cand(r, if parsed.tokens.is_empty() { 1.0 } else { 0.55 }));344 }345 } else {346 // Code absent des sources (codes d'entreprise ou récents) : repli sur le plus long préfixe connu, signalé.347 for k in [5usize, 4, 3] {348 let pre = &pc[..k];349 let hi = format!("{pre}{{");350 let rows = client.query(&st, &[&pre, &hi, &1i64]).await.map_err(|e| db_err("search", e))?;351 if let Some(r) = rows.first() {352 ctx_pts.push((r.get(1), r.get(2)));353 if p.types.postcode && parsed.tokens.is_empty() {354 let mut c = postcode_cand(r, 0.6);355 c.v["approx"] = json!(true);356 c.v["requested"] = json!(fmt_postcode(pc));357 c.v["matched_prefix"] = json!(pre);358 cands.push(c);359 }360 break;361 }362 }363 }364 }365 if parsed.tokens.is_empty() {366 return Ok(finish(cands, p.limit));367 }368369 let aliases = app.aliases.read().unwrap().clone();370 let mut parsed = parsed;371 let mut split = parse::split_context(&parsed.tokens, &aliases);372 // « rue Sherbrooke Ouest 845 Montréal » : numéro entre la voie et la ville373 if parsed.civic.is_none() && !split.ctx.is_empty() {374 if let Some(v) = parse::take_trailing_civic(&mut split.street) {375 parsed.civic = Some(v);376 }377 }378 // Générique « fort » en tête (« rue… », « boul… ») : la requête vise une voie. « parc », « place », « île »,379 // « jardin », « quai » nomment aussi des lieux et ne tranchent pas.380 let has_generic = split.street.first().map(|t| STRONG_GENERICS.contains(&t.as_str())).unwrap_or(false)381 || split.street.get(1).map(|t| STRONG_GENERICS.contains(&t.as_str()) && split.street[0].bytes().all(|b| b.is_ascii_digit())).unwrap_or(false);382 let street_bias = if !has_generic && parsed.civic.is_none() { -0.08 } else { 0.0 };383 let q_full = parsed.tokens.join(" ");384 let q_street = split.street.join(" ");385 let muns: Option<Vec<i32>> = if split.ctx.is_empty() {386 None387 } else {388 let mut v: Vec<i32> = split.ctx.iter().filter_map(|a| a.mun_id).collect();389 v.sort_unstable();390 v.dedup();391 if v.is_empty() { None } else { Some(v) }392 };393 // Contexte fin (arrondissement, quartier, localité) : sert de point de proximité394 for a in split.ctx.iter().filter(|a: &&Alias| a.kind != "municipality").take(8) {395 ctx_pts.push((a.x, a.y));396 }397 let (px, py, cosf): (Vec<f64>, Vec<f64>, f64) = match (near, ctx_pts.is_empty()) {398 (_, false) => {399 let (_, lat) = from_merc(ctx_pts[0].0, ctx_pts[0].1);400 (ctx_pts.iter().map(|c| c.0).collect(), ctx_pts.iter().map(|c| c.1).collect(), lat.to_radians().cos())401 }402 (Some((x, y)), true) => (vec![x], vec![y], p.near.unwrap().1.to_radians().cos()),403 (None, true) => (vec![], vec![], 1.0),404 };405 let report_dist = near.is_some() && ctx_pts.is_empty();406407 // --- Rues et adresses ---408 // Au moins deux caractères de spécifique (« rue s » est trop vague), ou un nombre (« 1re Avenue »).409 let specifics: Vec<&String> = split.street.iter().filter(|t| !norm::is_generic(t)).collect();410 let street_core_len: usize = specifics.iter().map(|t| t.len()).sum();411 let numbered = specifics.iter().any(|t| t.bytes().all(|b| b.is_ascii_digit()));412 let want_streets = (p.types.address || p.types.street) && (street_core_len >= 2 || numbered);413 let mut streets: Vec<StreetRow> = Vec::new();414 if want_streets {415 let attempts: Vec<(String, Option<Vec<i32>>)> = {416 let mut a = vec![(q_street.clone(), muns.clone())];417 if muns.is_some() {418 a.push((q_full.clone(), None));419 }420 a421 };422 for (q, m) in attempts {423 streets = street_query(&client, SQL_STREET_A, &q, &m, &px, &py, cosf).await?;424 if streets.is_empty() {425 streets = street_query(&client, SQL_STREET_B, &q, &m, &px, &py, cosf).await?;426 }427 if !streets.is_empty() {428 break;429 }430 }431 // « 5 avenue » : le nombre lu comme numéro civique fait peut-être partie du nom432 if streets.is_empty() {433 if let (Some(tok), true) = (&parsed.civic_token, parsed.civic.is_some()) {434 let q = format!("{tok} {q_street}");435 streets = street_query(&client, SQL_STREET_A, &q, &muns, &px, &py, cosf).await?;436 if !streets.is_empty() {437 for s in &streets {438 cands.push(street_cand(s, s.score, report_dist));439 }440 streets.clear();441 parsed.civic = None;442 }443 }444 }445 }446447 if let (Some(num), false) = (parsed.civic, streets.is_empty()) {448 let top: Vec<i32> = streets.iter().take(15).map(|s| s.id).collect();449 let requested = format!("{num}{}", parsed.suffix.clone().unwrap_or_default());450 let mut found: HashSet<i32> = HashSet::new();451 if p.types.address {452 let st = client.prepare_cached(SQL_ADDR_EXACT).await.map_err(|e| db_err("search", e))?;453 let mut rows = client.query(&st, &[&top, &(num as i32)]).await.map_err(|e| db_err("search", e))?;454 if rows.is_empty() {455 if let Some(alt) = parsed.civic_alt {456 rows = client.query(&st, &[&top, &(alt as i32)]).await.map_err(|e| db_err("search", e))?;457 }458 }459 // Par rue : le suffixe demandé s'il existe, sinon le numéro sans suffixe, sinon le premier460 let want_suffix = parsed.suffix.clone().unwrap_or_default();461 for s in streets.iter().take(15) {462 let mine: Vec<&tokio_postgres::Row> = rows.iter().filter(|r| r.get::<_, i32>(0) == s.id).collect();463 let pick = mine464 .iter()465 .find(|r| r.get::<_, String>(3) == want_suffix)466 .or_else(|| mine.iter().find(|r| r.get::<_, String>(3).is_empty()))467 .or(mine.first());468 if let Some(r) = pick {469 found.insert(s.id);470 cands.push(address_cand(r, s, s.score + 0.08, false, report_dist, &px, &py, cosf, &requested));471 }472 }473 // Numéro inconnu : interpolation entre les deux voisins connus de même parité (même côté de la rue)…474 let missing: Vec<i32> = top.iter().filter(|id| !found.contains(id)).cloned().collect();475 if !missing.is_empty() {476 let st = client.prepare_cached(SQL_ADDR_BRACKET).await.map_err(|e| db_err("search", e))?;477 let rows = client.query(&st, &[&missing, &(num as i32)]).await.map_err(|e| db_err("search", e))?;478 for r in rows.iter().take(6) {479 let sid: i32 = r.get(0);480 let Some(s) = streets.iter().find(|s| s.id == sid) else { continue };481 let (lo, lx, ly): (i32, f64, f64) = (r.get(1), r.get(2), r.get(3));482 let (hi, hx, hy): (i32, f64, f64) = (r.get(5), r.get(6), r.get(7));483 let (_, lat) = from_merc(lx, ly);484 let cos_here = lat.to_radians().cos();485 let gap_m = ((hx - lx).powi(2) + (hy - ly).powi(2)).sqrt() * cos_here;486 // Voisins trop éloignés (autre tronçon homonyme, longue section sans adresse) : pas d'interpolation.487 if gap_m > 1500.0 {488 continue;489 }490 let t = (num as f64 - lo as f64) / (hi as f64 - lo as f64);491 let (mut x, mut y) = (lx + (hx - lx) * t, ly + (hy - ly) * t);492 // …rabattue le long de la voie quand la rue tourne entre les deux voisins.493 if gap_m > 60.0 {494 let st = client.prepare_cached(SQL_SNAP_STREET).await.map_err(|e| db_err("search", e))?;495 if let Some(q) = client.query_opt(&st, &[&sid, &x, &y, &lx, &ly, &hx, &hy]).await.map_err(|e| db_err("search", e))? {496 let (qx, qy): (f64, f64) = (q.get(0), q.get(1));497 if let (Some(dl), Some(dh)) = (q.get::<_, Option<f64>>(2), q.get::<_, Option<f64>>(3)) {498 let off = (dl + dh) / 2.0;499 let d = ((x - qx).powi(2) + (y - qy).powi(2)).sqrt();500 if d > off && d > 1e-6 && d * cos_here < 400.0 {501 x = qx + (x - qx) / d * off;502 y = qy + (y - qy) / d * off;503 }504 }505 }506 }507 found.insert(sid);508 let (lon, lat) = from_merc(x, y);509 let (pl, ph): (Option<String>, Option<String>) = (r.get(4), r.get(8));510 let pc = if pl == ph { pl } else { None };511 let mut label = format!("{requested}, {}, {} (Québec)", street_in_address(&s.name), s.mun);512 if let Some(pc) = &pc {513 label.push_str(&format!(" {}", fmt_postcode(pc)));514 }515 let dist = px.iter().zip(&py).map(|(a, b)| ((x - a).powi(2) + (y - b).powi(2)).sqrt() * cosf).fold(None, |m: Option<f64>, d| Some(m.map_or(d, |m| m.min(d))));516 cands.push(Cand {517 score: s.score + 0.02,518 key: format!("i{sid}:{num}"),519 v: json!({520 "type": "address", "id": format!("address:interp:{sid}:{num}"),521 "label": label, "housenumber": requested, "street": s.name,522 "municipality": s.mun, "municipality_id": s.mun_id,523 "postcode": pc.as_deref().map(fmt_postcode),524 "lon": round6(lon), "lat": round6(lat),525 "approx": true, "method": "interpolated", "requested_housenumber": requested,526 "between": [lo, hi], "span_m": gap_m.round(),527 "distance_m": dist_json(dist, report_dist),528 }),529 });530 }531 }532 // …sinon le numéro connu le plus proche sur la même rue.533 let missing: Vec<i32> = top.iter().filter(|id| !found.contains(id)).cloned().collect();534 if !missing.is_empty() {535 let st = client.prepare_cached(SQL_ADDR_NEAR).await.map_err(|e| db_err("search", e))?;536 let rows = client.query(&st, &[&missing, &(num as i32)]).await.map_err(|e| db_err("search", e))?;537 for r in &rows {538 let sid: i32 = r.get(0);539 if let Some(s) = streets.iter().find(|s| s.id == sid) {540 found.insert(sid);541 cands.push(address_cand(r, s, s.score - 0.06, true, report_dist, &px, &py, cosf, &requested));542 }543 }544 }545 }546 if p.types.street {547 for s in streets.iter().filter(|s| !found.contains(&s.id)) {548 cands.push(street_cand(s, s.score - 0.12, report_dist));549 }550 }551 } else if p.types.street {552 for s in &streets {553 cands.push(street_cand(s, s.score + street_bias, report_dist));554 }555 }556557 // --- Lieux (pas quand un numéro civique a trouvé des adresses) ---558 let have_addr = parsed.civic.is_some() && !cands.is_empty();559 if (p.types.place || p.types.poi) && !have_addr && q_full.len() >= 2 {560 let mut kinds: Vec<&str> = Vec::new();561 if p.types.place {562 kinds.extend(["municipality", "borough", "neighbourhood", "mrc", "region", "locality"]);563 }564 if p.types.poi {565 kinds.push("poi");566 }567 // « station Berri-UQAM », « métro Jean-Talon » : le mot d'usage n'est pas dans le nom de la station.568 let q_full = match parsed.tokens.first().map(|s| s.as_str()) {569 Some("station" | "metro" | "arret") if parsed.tokens.len() >= 2 => parsed.tokens[1..].join(" "),570 _ => q_full.clone(),571 };572 let station_hint = matches!(parsed.tokens.first().map(|s| s.as_str()), Some("station" | "metro" | "arret" | "gare"));573 let hi = format!("{q_full}{{");574 let st = client.prepare_cached(SQL_PLACE_A).await.map_err(|e| db_err("search", e))?;575 let mut rows = client.query(&st, &[&q_full, &hi, &kinds, &px, &py, &cosf]).await.map_err(|e| db_err("search", e))?;576 if rows.len() < 3 && q_full.len() >= 4 {577 let st = client.prepare_cached(SQL_PLACE_B).await.map_err(|e| db_err("search", e))?;578 let more = client.query(&st, &[&q_full, &hi, &kinds, &px, &py, &cosf]).await.map_err(|e| db_err("search", e))?;579 let seen: HashSet<i32> = rows.iter().map(|r| r.get::<_, i32>(0)).collect();580 rows.extend(more.into_iter().filter(|r| !seen.contains(&r.get::<_, i32>(0))));581 }582 for r in &rows {583 let kind: String = r.get(1);584 let sub: Option<String> = r.get(2);585 let name: String = r.get(3);586 let mun: Option<String> = r.get(5);587 let (lon, lat) = from_merc(r.get(7), r.get(8));588 let label = match (&mun, kind.as_str()) {589 (Some(m), k) if k != "municipality" && k != "mrc" && k != "region" && *m != name => format!("{name}, {m}"),590 _ => name.clone(),591 };592 let typ = if kind == "poi" { "poi" } else { "place" };593 // Sans générique ni numéro, la requête désigne plutôt un lieu ; avec un générique, plutôt une voie.594 let bias = if has_generic { -0.06 } else if parsed.civic.is_none() { 0.08 } else { 0.0 }595 // À nom égal, le quartier ou la ville passe devant la station ou la gare homonyme.596 + if kind != "poi" && !station_hint { 0.05 } else { 0.0 };597 cands.push(Cand {598 score: r.get::<_, f64>(10) + bias,599 // Un même objet peut avoir plusieurs noms (nom court, autre nom) : une seule entrée par objet.600 key: r.get::<_, Option<String>>(6).map(|x| format!("r{x}")).unwrap_or_else(|| format!("p{}", r.get::<_, i32>(0))),601 v: json!({602 "type": typ, "kind": if kind == "poi" { sub.clone().unwrap_or_default() } else { kind.clone() },603 "kind_label": kind_label(&kind, sub.as_deref()),604 "id": format!("place:{}", r.get::<_, i32>(0)),605 "label": label, "name": name, "municipality": mun,606 "boundary": r.get::<_, Option<String>>(6).filter(|s| s.contains('/')),607 "lon": round6(lon), "lat": round6(lat),608 "distance_m": dist_json(r.get(9), report_dist),609 }),610 });611 }612 }613 Ok(finish(cands, p.limit))614}615616async fn street_query(617 client: &deadpool_postgres::Object,618 sql: &str,619 q: &str,620 muns: &Option<Vec<i32>>,621 px: &Vec<f64>,622 py: &Vec<f64>,623 cosf: f64,624) -> Result<Vec<StreetRow>, ApiError> {625 let st = client.prepare_cached(sql).await.map_err(|e| db_err("search", e))?;626 let hi = format!("{q}{{");627 let rows = client.query(&st, &[&q, &hi, muns, px, py, &cosf]).await.map_err(|e| db_err("search", e))?;628 Ok(rows629 .iter()630 .map(|r| StreetRow { id: r.get(0), name: r.get(1), mun_id: r.get(2), mun: r.get(3), x: r.get(4), y: r.get(5), dist: r.get(6), score: r.get(7), area: r.get(8), multi: r.get(9) })631 .collect())632}633634fn street_cand(s: &StreetRow, score: f64, report_dist: bool) -> Cand {635 let (lon, lat) = from_merc(s.x, s.y);636 Cand {637 score,638 key: format!("s{}", s.id),639 v: json!({640 "type": "street", "id": format!("street:{}", s.id),641 "label": match (&s.area, s.multi) {642 (Some(a), true) => format!("{}, {}, {}", s.name, a, s.mun),643 _ => format!("{}, {}", s.name, s.mun),644 },645 "name": s.name, "street": s.name, "borough": s.area,646 "municipality": s.mun, "municipality_id": s.mun_id,647 "lon": round6(lon), "lat": round6(lat),648 "distance_m": dist_json(s.dist, report_dist),649 }),650 }651}652653#[allow(clippy::too_many_arguments)]654fn address_cand(r: &tokio_postgres::Row, s: &StreetRow, score: f64, approx: bool, report_dist: bool, px: &[f64], py: &[f64], cosf: f64, requested: &str) -> Cand {655 let num: i32 = r.get(2);656 let suffix: String = r.get(3);657 let pc: Option<String> = r.get(4);658 let (x, y): (f64, f64) = (r.get(5), r.get(6));659 let (lon, lat) = from_merc(x, y);660 let house = format!("{num}{suffix}");661 let mut label = format!("{house}, {}, {} (Québec)", street_in_address(&s.name), s.mun);662 if let Some(pc) = &pc {663 label.push_str(&format!(" {}", fmt_postcode(pc)));664 }665 let dist = px.iter().zip(py).map(|(a, b)| ((x - a).powi(2) + (y - b).powi(2)).sqrt() * cosf).fold(None, |m: Option<f64>, d| Some(m.map_or(d, |m| m.min(d))));666 Cand {667 score,668 key: format!("a{}", r.get::<_, i64>(1)),669 v: json!({670 "type": "address", "id": format!("address:{}", r.get::<_, i64>(1)),671 "label": label, "housenumber": house, "street": s.name,672 "municipality": s.mun, "municipality_id": s.mun_id,673 "postcode": pc.as_deref().map(fmt_postcode),674 "lon": round6(lon), "lat": round6(lat),675 "approx": approx, "method": if approx { "nearest" } else { "exact" },676 "requested_housenumber": if approx { json!(requested) } else { Value::Null },677 "source": r.get::<_, String>(7), "sources": r.get::<_, Vec<String>>(8),678 "distance_m": dist_json(dist, report_dist),679 }),680 }681}682683fn postcode_cand(r: &tokio_postgres::Row, score: f64) -> Cand {684 let code: String = r.get(0);685 let (lon, lat) = from_merc(r.get(1), r.get(2));686 let mun: Option<String> = r.get(3);687 let pretty = fmt_postcode(&code);688 Cand {689 score,690 key: format!("c{code}"),691 v: json!({692 "type": "postcode", "id": format!("postcode:{code}"),693 "label": match &mun { Some(m) => format!("{pretty}, {m}"), None => pretty.clone() },694 "postcode": pretty, "municipality": mun,695 "lon": round6(lon), "lat": round6(lat), "source": r.get::<_, String>(4),696 }),697 }698}699700fn finish(mut cands: Vec<Cand>, limit: usize) -> Value {701 cands.sort_by(|a, b| b.score.partial_cmp(&a.score).unwrap_or(std::cmp::Ordering::Equal).then_with(|| a.key.cmp(&b.key)));702 let mut seen = HashSet::new();703 let mut out = Vec::new();704 for c in cands {705 if !seen.insert(c.key.clone()) {706 continue;707 }708 let mut v = c.v;709 v["score"] = json!((c.score.clamp(0.0, 1.5) * 1000.0).round() / 1000.0);710 if v.get("distance_m").map(|d| d.is_null()).unwrap_or(false) {711 v.as_object_mut().unwrap().remove("distance_m");712 }713 out.push(v);714 if out.len() >= limit {715 break;716 }717 }718 let _ = round1;719 json!({ "results": out, "attribution": crate::ATTRIBUTION })720}721722#[cfg(test)]723mod tests {724 use super::*;725726 #[test]727 fn labels() {728 assert_eq!(street_in_address("Rue Saint-Denis"), "rue Saint-Denis");729 assert_eq!(street_in_address("1re Avenue"), "1re Avenue");730 assert_eq!(street_in_address("Queen Mary Road"), "Queen Mary Road");731 assert_eq!(street_in_address("Boulevard René-Lévesque Ouest"), "boulevard René-Lévesque Ouest");732 assert_eq!(fmt_postcode("H2X3K8"), "H2X 3K8");733 }734735 #[test]736 fn types_filter() {737 let t = Types::parse("address, street").unwrap();738 assert!(t.address && t.street && !t.place && !t.poi && !t.postcode);739 assert!(Types::parse("address,evil").is_err());740 }741742 #[test]743 fn finish_sorts_dedupes_and_cuts() {744 let c = |k: &str, s: f64| Cand { score: s, key: k.into(), v: json!({"id": k, "distance_m": null}) };745 let v = finish(vec![c("a", 0.2), c("b", 0.9), c("b", 0.5), c("c", 0.7)], 2);746 let r = v["results"].as_array().unwrap();747 assert_eq!(r.len(), 2);748 assert_eq!(r[0]["id"], "b");749 assert_eq!(r[0]["score"], 0.9);750 assert_eq!(r[1]["id"], "c");751 assert!(r[0].get("distance_m").is_none());752 }753}754