SPB Git

Repository Public

places.rs 24.4 KB 488 lines rust

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : KA Maps Engine9// File             : server/km-geo/src/places.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/reverse`, `/v1/boundaries…`, `/v1/nearby`, `/v1/elevation`.8889use crate::err::{db_err, ApiError};90use crate::geom::{from_merc, round1, round6, to_merc};91use crate::{norm, AppState};92use serde_json::{json, Value};93use std::sync::Arc;9495/// Géocodage inverse : rues les plus proches (distance point-tronçon sur AQréseau), adresse la plus proche de chacune,96/// adresse la plus proche toutes rues confondues, limites contenant le point.97const SQL_REVERSE: &str = "98WITH p AS (SELECT ST_SetSRID(ST_MakePoint($1, $2), 3857) AS g, ST_SetSRID(ST_MakePoint($3, $4), 4326) AS g4),99segs AS (100  SELECT g.street_id, g.ref, ST_Distance(g.geom, p.g) AS d101  FROM street_seg g, p WHERE ST_DWithin(g.geom, p.g, 500.0 / $5::float8)102  ORDER BY g.geom <-> p.g LIMIT 24103),104-- Les tronçons sans vrai nom (« Voie », « Bretelle »…) ne désignent pas une rue pour un humain.105st AS (SELECT x.street_id, min(x.d) AS d, max(x.ref) AS ref FROM segs x JOIN street s ON s.id = x.street_id106       WHERE s.norm NOT IN ('voie', 'bretelle', 'ruelle', 'acces', 'stationnement', 'sentier', 'passage', 'piste cyclable', 'voie desserte')107       GROUP BY x.street_id ORDER BY 2 LIMIT 4),108sj AS (109  SELECT coalesce(json_agg(json_build_object(110           'id', s.id, 'name', s.name, 'ref', st.ref, 'mun', m.name, 'd', st.d * $5::float8,111           'addr', (SELECT json_build_object('id', a.id, 'num', a.num, 'suffix', a.suffix, 'postcode', a.postcode, 'src', a.src,112                                             'srcs', a.srcs, 'x', ST_X(a.pt), 'y', ST_Y(a.pt),113                                             'd', ST_Distance(a.pt, p.g) * $5::float8, 'street', s.name, 'street_id', s.id,114                                             'mun', m.name)115                    FROM address a, p116                    WHERE a.street_id = st.street_id AND a.pt && ST_Expand(p.g, 300.0 / $5::float8)117                    ORDER BY a.pt <-> p.g LIMIT 1)) ORDER BY st.d), '[]'::json) AS j118  FROM st JOIN street s ON s.id = st.street_id JOIN mun m ON m.id = s.mun_id119),120near AS (SELECT a.id, a.street_id, ST_Distance(a.pt, p.g) AS da FROM p, LATERAL (SELECT * FROM address a ORDER BY a.pt <-> p.g LIMIT 12) a),121cand AS (SELECT DISTINCT ON (street_id) street_id, id, da FROM near ORDER BY street_id, da),122a AS (123  SELECT coalesce(json_agg(json_build_object(124           'id', a.id, 'num', a.num, 'suffix', a.suffix, 'postcode', a.postcode, 'src', a.src, 'srcs', a.srcs,125           'x', ST_X(a.pt), 'y', ST_Y(a.pt), 'd', c.da * $5::float8, 'street', s.name, 'street_id', s.id, 'mun', m.name,126           'ds', (SELECT min(ST_Distance(g.geom, p.g)) * $5::float8 FROM street_seg g, p127                  WHERE g.street_id = c.street_id AND g.geom && ST_Expand(p.g, 300.0 / $5::float8))) ORDER BY c.da), '[]'::json) AS j128  FROM cand c JOIN address a ON a.id = c.id JOIN street s ON s.id = a.street_id JOIN mun m ON m.id = s.mun_id129),130b AS (131  SELECT coalesce(json_agg(json_build_object('id', b.id, 'level', b.level, 'code', b.code, 'name', b.name, 'kind', b.kind,132                                             'area_km2', b.area_km2) ORDER BY b.area_km2 DESC), '[]'::json) AS j133  FROM boundary b134  WHERE b.id IN (SELECT bs.id FROM boundary_sub bs, p WHERE ST_Covers(bs.geom, p.g4))135)136SELECT (SELECT j FROM a), (SELECT j FROM sj), (SELECT j FROM b)";137138const SQL_BOUNDARY: &str = "139SELECT json_build_object(140  'type', 'Feature', 'id', b.id,141  'properties', json_build_object('id', b.id, 'level', b.level, 'code', b.code, 'name', b.name, 'kind', b.kind,142     'municipality', b.mun_name, 'municipality_id', b.mun_id, 'mrc', b.mrc_name, 'mrc_code', b.mrc_code,143     'region', b.reg_name, 'region_code', b.reg_code, 'area_km2', b.area_km2, 'source', b.src,144     'center', json_build_array(round(ST_X(b.pt)::numeric, 6), round(ST_Y(b.pt)::numeric, 6)),145     'bbox', json_build_array(round(ST_XMin(b.geom)::numeric, 6), round(ST_YMin(b.geom)::numeric, 6),146                              round(ST_XMax(b.geom)::numeric, 6), round(ST_YMax(b.geom)::numeric, 6)),147     'simplification_m', (ARRAY[0, 10, 100, 1000])[$2::int + 1]),148  'geometry', ST_AsGeoJSON(CASE $2::int WHEN 0 THEN b.geom WHEN 1 THEN b.g1 WHEN 2 THEN b.g2 ELSE b.g3 END,149                           CASE WHEN $2::int >= 2 THEN 5 ELSE 6 END)::json)150FROM boundary b WHERE b.id = $1";151152const SQL_BOUNDARY_SEARCH: &str = "153SELECT b.id, b.level, b.code, b.name, b.kind, b.mun_name, b.mrc_name, b.reg_name, b.area_km2, ST_X(b.pt), ST_Y(b.pt),154       (CASE WHEN b.norm = $1 THEN 1.0 WHEN b.norm ~>=~ $1 AND b.norm ~<~ $2 THEN 0.9 ELSE 0.5 + 0.4 * similarity($1, b.norm) END)::float8 AS t155FROM boundary b156WHERE (b.norm = $1 OR (b.norm ~>=~ $1 AND b.norm ~<~ $2) OR similarity($1, b.norm) > 0.45 OR word_similarity($1, b.norm) > 0.7)157  AND ($3::text IS NULL OR b.level = $3)158ORDER BY t DESC, (b.level = 'municipalite') DESC, b.area_km2 DESC LIMIT $4";159160const SQL_NEARBY: &str = "161WITH p AS (SELECT ST_SetSRID(ST_MakePoint($1, $2), 3857) AS g),162c AS (163  SELECT a.kind, a.name, a.ref, ST_X(a.pt) AS x, ST_Y(a.pt) AS y, ST_Distance(a.pt, p.g) * $3::float8 AS d,164         row_number() OVER (PARTITION BY a.kind ORDER BY a.pt <-> p.g) AS rn165  FROM amenity a, p166  WHERE ST_DWithin(a.pt, p.g, $4::float8) AND a.kind = ANY($5::text[])167)168SELECT kind, name, ref, x, y, d FROM c WHERE rn <= $6 ORDER BY d";169170pub const KINDS: &[(&str, &str)] = &[171    ("metro", "Station de métro"),172    ("rem", "Station du REM"),173    ("train", "Gare"),174    ("bus_terminal", "Terminus d'autobus"),175    ("bus_stop", "Arrêt d'autobus"),176    ("university", "Université"),177    ("college", "Cégep ou collège"),178    ("school", "École"),179    ("daycare", "Garderie ou CPE"),180    ("grocery", "Épicerie"),181    ("convenience", "Dépanneur"),182    ("food_shop", "Boulangerie, boucherie"),183    ("pharmacy", "Pharmacie"),184    ("park", "Parc"),185    ("playground", "Aire de jeux"),186    ("sports", "Centre sportif ou piscine"),187    ("hospital", "Hôpital"),188    ("clinic", "Clinique"),189    ("library", "Bibliothèque"),190    ("community_centre", "Centre communautaire"),191    ("airport", "Aéroport"),192];193194/// Groupes pratiques pour `kinds=` : transit, education, commerces, sante, loisirs.195pub fn expand_kinds(s: &str) -> Result<Vec<&'static str>, ApiError> {196    let mut out: Vec<&'static str> = Vec::new();197    for part in s.split(',').map(|p| p.trim()).filter(|p| !p.is_empty()) {198        let group: &[&'static str] = match part {199            "transit" | "transport" => &["metro", "rem", "train", "bus_terminal", "bus_stop"],200            "education" => &["university", "college", "school", "daycare"],201            "commerces" | "services" => &["grocery", "convenience", "food_shop", "pharmacy"],202            "sante" => &["hospital", "clinic", "pharmacy"],203            "loisirs" => &["park", "playground", "sports", "library", "community_centre"],204            other => match KINDS.iter().find(|(k, _)| *k == other) {205                Some((k, _)) => {206                    if !out.contains(k) {207                        out.push(k);208                    }209                    continue;210                }211                None => return Err(ApiError::bad("kinds : catégorie inconnue (voir /v1/nearby/kinds)")),212            },213        };214        for k in group {215            if !out.contains(k) {216                out.push(k);217            }218        }219    }220    Ok(out)221}222223fn boundary_summary(b: &Value) -> Value {224    json!({ "id": b["id"], "code": b["code"], "name": b["name"], "kind": b["kind"] })225}226227/// Choix de l'adresse. Deux lectures indépendantes :228///  S1 — la rue dont un tronçon (AQréseau) est le plus proche du point, et sa plus proche adresse (≤ 300 m) ;229///  S2 — parmi les rues des 12 points d'adresse les plus proches, celle qui minimise230///       distance à l'adresse + 2,5 × (distance à la rue − distance à la rue la plus proche).231/// On rend S1 si elle existe (sinon S2). Quand S1 et S2 désignent la même rue, la confiance est haute232/// (mesuré : même rue qu'OSM dans 92 % de ces cas, contre 84 % en tout).233/// Renvoie (adresse, les deux lectures s'accordent ?).234pub fn pick_address(cands: &[Value], streets: &[Value]) -> Option<(Value, bool)> {235    let d = |v: &Value| v["d"].as_f64().unwrap_or(f64::MAX);236    let d0 = streets.first().map(d).unwrap_or(25.0);237    let s1 = streets.first().map(|s| &s["addr"]).filter(|a| !a.is_null() && d(a) <= 300.0);238    let s2 = cands239        .iter()240        .filter(|a| d(a) <= 300.0)241        .map(|a| (a, d(a) + 2.5 * (a["ds"].as_f64().unwrap_or(d0 + 25.0) - d0)))242        .min_by(|x, y| x.1.partial_cmp(&y.1).unwrap_or(std::cmp::Ordering::Equal))243        .map(|x| x.0);244    // Le point demandé est (à 3 m près) un point d'adresse connu : c'est cette adresse.245    if let Some(n) = cands.first().filter(|a| d(a) <= 3.0) {246        return Some((n.clone(), true));247    }248    match (s1, s2) {249        (Some(a), Some(b)) => Some((a.clone(), a["street_id"] == b["street_id"])),250        (Some(a), None) => Some((a.clone(), false)),251        (None, Some(b)) => Some((b.clone(), false)),252        (None, None) => None,253    }254}255256pub async fn reverse(app: &Arc<AppState>, lon: f64, lat: f64) -> Result<Value, ApiError> {257    let (x, y) = to_merc(lon, lat);258    let cosf = lat.to_radians().cos();259    let client = app.pool.get().await.map_err(|e| db_err("reverse", e))?;260    let st = client.prepare_cached(SQL_REVERSE).await.map_err(|e| db_err("reverse", e))?;261    let row = client.query_one(&st, &[&x, &y, &lon, &lat, &cosf]).await.map_err(|e| db_err("reverse", e))?;262    let cj: Value = row.get::<_, Option<Value>>(0).unwrap_or_else(|| json!([]));263    let sj: Value = row.get::<_, Option<Value>>(1).unwrap_or_else(|| json!([]));264    let b: Value = row.get::<_, Option<Value>>(2).unwrap_or_else(|| json!([]));265    let none = vec![];266    let streets = sj.as_array().unwrap_or(&none);267    let cands = cj.as_array().unwrap_or(&none);268269    let picked = pick_address(cands, streets);270    let s0 = streets.first();271    // Confiance : « high » si les deux lectures s'accordent et que l'adresse est proche ; « medium » sinon ;272    // « low » si l'adresse est à plus de 75 m ; « street » s'il n'y a qu'une rue ; « none » sinon.273    let confidence = match (&picked, s0) {274        (Some((a, true)), _) if a["d"].as_f64().unwrap_or(1e9) <= 60.0 => "high",275        (Some((a, _)), _) if a["d"].as_f64().unwrap_or(1e9) <= 75.0 => "medium",276        (Some(_), _) => "low",277        (None, Some(s)) if s["d"].as_f64().unwrap_or(1e9) <= 30.0 => "street",278        _ => "none",279    };280    let nearest_sid = s0.map(|s| s["id"].clone());281    let address = picked.map(|(a, _)| {282        let on_nearest = nearest_sid.as_ref().map(|sid| a["street_id"] == *sid).unwrap_or(false);283        let (alon, alat) = from_merc(a["x"].as_f64().unwrap_or(0.0), a["y"].as_f64().unwrap_or(0.0));284        let house = format!("{}{}", a["num"], a["suffix"].as_str().unwrap_or(""));285        let street = a["street"].as_str().unwrap_or("");286        let mun = a["mun"].as_str().unwrap_or("");287        let pc = a["postcode"].as_str().map(|p| if p.len() == 6 { format!("{} {}", &p[..3], &p[3..]) } else { p.to_string() });288        let mut label = format!("{house}, {}, {mun} (Québec)", lower_generic(street));289        if let Some(pc) = &pc {290            label.push_str(&format!(" {pc}"));291        }292        json!({293            "id": format!("address:{}", a["id"]), "label": label, "housenumber": house, "street": street,294            "municipality": mun, "postcode": pc, "lon": round6(alon), "lat": round6(alat),295            "distance_m": round1(a["d"].as_f64().unwrap_or(0.0)), "on_nearest_street": on_nearest,296            "source": a["src"], "sources": a["srcs"],297        })298    });299    let street = s0.map(|s| {300        json!({ "id": format!("street:{}", s["id"]), "name": s["name"], "route": s["ref"], "municipality": s["mun"],301                "distance_m": round1(s["d"].as_f64().unwrap_or(0.0)) })302    });303    let empty = vec![];304    let bl = b.as_array().unwrap_or(&empty);305    let pick = |level: &str| bl.iter().find(|x| x["level"] == level).map(boundary_summary);306    let quartiers: Vec<Value> = bl.iter().filter(|x| x["level"] == "quartier").map(boundary_summary).collect();307    let label = match (&address, &street, pick("municipalite")) {308        (Some(a), _, _) if confidence != "low" => a["label"].clone(),309        (_, Some(s), Some(m)) => json!(format!("{}, {}", s["name"].as_str().unwrap_or(""), m["name"].as_str().unwrap_or(""))),310        (Some(a), _, _) => a["label"].clone(),311        (None, None, Some(m)) => m["name"].clone(),312        _ => Value::Null,313    };314    Ok(json!({315        "label": label, "confidence": confidence,316        "address": address, "street": street,317        "municipality": pick("municipalite"), "borough": pick("arrondissement"),318        "neighbourhoods": quartiers, "mrc": pick("mrc"), "region": pick("region"),319        "in_quebec": pick("region").is_some(),320        "attribution": crate::ATTRIBUTION,321    }))322}323324fn lower_generic(name: &str) -> String {325    let first = name.split(' ').next().unwrap_or("");326    if norm::is_generic(&norm::norm(first)) && name.contains(' ') {327        let mut c = name.chars();328        c.next().map(|f| f.to_lowercase().collect::<String>() + c.as_str()).unwrap_or_default()329    } else {330        name.to_string()331    }332}333334pub async fn boundaries_at(app: &Arc<AppState>, lon: f64, lat: f64) -> Result<Value, ApiError> {335    let client = app.pool.get().await.map_err(|e| db_err("boundaries", e))?;336    let st = client337        .prepare_cached(338            "SELECT coalesce(json_agg(json_build_object('id', b.id, 'level', b.level, 'code', b.code, 'name', b.name, 'kind', b.kind,339                    'municipality', b.mun_name, 'mrc', b.mrc_name, 'region', b.reg_name, 'area_km2', b.area_km2, 'source', b.src)340                    ORDER BY b.area_km2 DESC), '[]'::json)341             FROM boundary b342             WHERE b.id IN (SELECT bs.id FROM boundary_sub bs WHERE ST_Covers(bs.geom, ST_SetSRID(ST_MakePoint($1, $2), 4326)))",343        )344        .await345        .map_err(|e| db_err("boundaries", e))?;346    let row = client.query_one(&st, &[&lon, &lat]).await.map_err(|e| db_err("boundaries", e))?;347    let b: Value = row.get(0);348    Ok(json!({ "boundaries": b, "attribution": crate::ATTRIBUTION }))349}350351/// `detail` : 0 complet, 1 ≈ 10 m, 2 ≈ 100 m, 3 ≈ 1 km.352pub async fn boundary(app: &Arc<AppState>, id: &str, detail: i32) -> Result<Value, ApiError> {353    let client = app.pool.get().await.map_err(|e| db_err("boundary", e))?;354    let st = client.prepare_cached(SQL_BOUNDARY).await.map_err(|e| db_err("boundary", e))?;355    let row = client.query_opt(&st, &[&id, &detail]).await.map_err(|e| db_err("boundary", e))?;356    match row {357        Some(r) => Ok(r.get(0)),358        None => Err(ApiError::not_found("Limite inconnue.")),359    }360}361362pub async fn boundary_search(app: &Arc<AppState>, q: &str, level: Option<&str>, limit: i64) -> Result<Value, ApiError> {363    let qn = norm::norm(q);364    if qn.len() < 2 {365        return Ok(json!({ "results": [], "attribution": crate::ATTRIBUTION }));366    }367    let hi = format!("{qn}{{");368    let client = app.pool.get().await.map_err(|e| db_err("boundary_search", e))?;369    let st = client.prepare_cached(SQL_BOUNDARY_SEARCH).await.map_err(|e| db_err("boundary_search", e))?;370    let rows = client.query(&st, &[&qn, &hi, &level, &limit]).await.map_err(|e| db_err("boundary_search", e))?;371    let out: Vec<Value> = rows372        .iter()373        .map(|r| {374            json!({375                "id": r.get::<_, String>(0), "level": r.get::<_, String>(1), "code": r.get::<_, String>(2),376                "name": r.get::<_, String>(3), "kind": r.get::<_, Option<String>>(4),377                "municipality": r.get::<_, Option<String>>(5), "mrc": r.get::<_, Option<String>>(6),378                "region": r.get::<_, Option<String>>(7), "area_km2": r.get::<_, Option<f64>>(8),379                "lon": round6(r.get(9)), "lat": round6(r.get(10)),380                "score": (r.get::<_, f64>(11) * 1000.0).round() / 1000.0,381            })382        })383        .collect();384    Ok(json!({ "results": out, "attribution": crate::ATTRIBUTION }))385}386387pub async fn nearby(app: &Arc<AppState>, lon: f64, lat: f64, radius: f64, kinds: &[&str], per_kind: i64) -> Result<Value, ApiError> {388    let (x, y) = to_merc(lon, lat);389    let cosf = lat.to_radians().cos();390    let client = app.pool.get().await.map_err(|e| db_err("nearby", e))?;391    let st = client.prepare_cached(SQL_NEARBY).await.map_err(|e| db_err("nearby", e))?;392    let kinds_v: Vec<&str> = kinds.to_vec();393    let rows = client.query(&st, &[&x, &y, &cosf, &(radius / cosf), &kinds_v, &per_kind]).await.map_err(|e| db_err("nearby", e))?;394    let mut items = Vec::with_capacity(rows.len());395    let mut nearest = serde_json::Map::new();396    for r in &rows {397        let kind: String = r.get(0);398        let (ilon, ilat) = from_merc(r.get(3), r.get(4));399        let d: f64 = r.get(5);400        if d > radius {401            continue;402        }403        let label = KINDS.iter().find(|(k, _)| *k == kind).map(|(_, l)| *l).unwrap_or("");404        let item = json!({405            "kind": kind, "kind_label": label, "name": r.get::<_, Option<String>>(1),406            "lon": round6(ilon), "lat": round6(ilat), "distance_m": d.round(), "osm": r.get::<_, Option<String>>(2),407        });408        if !nearest.contains_key(&kind) {409            nearest.insert(kind.clone(), json!({ "name": item["name"], "distance_m": item["distance_m"] }));410        }411        items.push(item);412    }413    Ok(json!({414        "radius_m": radius, "count": items.len(), "nearest": nearest, "items": items,415        "note": "Distances à vol d'oiseau ; pour un parc, distance à son centre.",416        "attribution": "© les contributeurs d'OpenStreetMap (ODbL)",417    }))418}419420pub async fn elevation(app: &Arc<AppState>, lon: f64, lat: f64) -> Result<Value, ApiError> {421    let app2 = app.clone();422    let e = tokio::task::spawn_blocking(move || app2.dem.elevation(lon, lat, app2.dem_maxzoom, 0))423        .await424        .map_err(|_| ApiError::unavailable())?;425    match e {426        Some(e) => {427            let regional = e.zoom >= 8;428            Ok(json!({429                "lon": lon, "lat": lat,430                "elevation_m": round1(e.metres),431                "zoom": e.zoom,432                "resolution_m": round1(40075016.686 * lat.to_radians().cos() / (256.0 * (1u64 << e.zoom) as f64)),433                "source": if regional { "MRDEM-30 (RNCan) ; hors Canada : Copernicus GLO-30" } else { "ETOPO 2022 (NOAA)" },434                "vertical_datum": if regional { "CGVD2013 (hors Canada : EGM2008)" } else { "EGM2008" },435                "surface": if regional { "terrain nu (MNT)" } else { "surface, glace comprise" },436            }))437        }438        None => Err(ApiError::not_found("Aucune donnée d'altitude en ce point.")),439    }440}441442#[cfg(test)]443mod tests {444    use super::*;445446    fn addr(id: i64, sid: i64, d: f64, ds: Option<f64>) -> Value {447        json!({"id": id, "street_id": sid, "d": d, "ds": ds})448    }449    fn street(sid: i64, d: f64, a: Value) -> Value {450        json!({"id": sid, "d": d, "addr": a})451    }452453    #[test]454    fn reverse_prefers_the_nearest_street() {455        // Le point d'adresse le plus proche (rue d'en arrière, 18 m) perd contre l'adresse de la rue la plus proche (26 m).456        let cands = vec![addr(1, 99, 18.0, Some(41.0)), addr(2, 7, 26.0, Some(9.0))];457        let streets = vec![street(7, 9.0, addr(2, 7, 26.0, None)), street(99, 41.0, addr(1, 99, 18.0, None))];458        let (a, agree) = pick_address(&cands, &streets).unwrap();459        assert_eq!((a["id"].as_i64(), agree), (Some(2), true));460        // Désaccord : la rue la plus proche garde la main, la confiance baisse.461        let cands = vec![addr(1, 99, 4.0, Some(20.0)), addr(2, 7, 60.0, Some(9.0))];462        let streets = vec![street(7, 9.0, addr(2, 7, 60.0, None))];463        let (a, agree) = pick_address(&cands, &streets).unwrap();464        assert_eq!((a["id"].as_i64(), agree), (Some(2), false));465        // Rue la plus proche sans adresse à portée : meilleure candidate parmi les points proches.466        let cands = vec![addr(1, 99, 40.0, Some(35.0)), addr(3, 5, 55.0, None)];467        let streets = vec![street(7, 9.0, Value::Null)];468        let (a, agree) = pick_address(&cands, &streets).unwrap();469        assert_eq!((a["id"].as_i64(), agree), (Some(1), false));470        // Aucune rue à proximité (voie absente d'AQréseau) : le point d'adresse le plus proche.471        let cands = vec![addr(1, 99, 12.0, None), addr(2, 98, 30.0, None)];472        assert_eq!(pick_address(&cands, &[]).unwrap().0["id"].as_i64(), Some(1));473        // Point posé sur une adresse connue : elle-même, quelle que soit la rue la plus proche.474        let cands = vec![addr(9, 99, 0.0, Some(30.0)), addr(2, 7, 14.0, Some(9.0))];475        let streets = vec![street(7, 9.0, addr(2, 7, 14.0, None))];476        assert_eq!(pick_address(&cands, &streets).unwrap().0["id"].as_i64(), Some(9));477        assert!(pick_address(&[], &[]).is_none());478        assert!(pick_address(&[addr(1, 1, 900.0, None)], &[]).is_none());479    }480481    #[test]482    fn kinds_groups() {483        assert_eq!(expand_kinds("transit").unwrap(), vec!["metro", "rem", "train", "bus_terminal", "bus_stop"]);484        assert_eq!(expand_kinds("park, sante,park").unwrap(), vec!["park", "hospital", "clinic", "pharmacy"]);485        assert!(expand_kinds("armes").is_err());486    }487}488
Files main
Menu

Theme