1use serde_json::{json, Value};
9
10use crate::query::{hit_is_weak, match_level, Hit};
11use crate::serve::{display_name, half_width, place_id};
12
13pub fn location_type(h: &Hit) -> &'static str {
15 match match_level(h).0 {
16 "PointAddress" | "POI" => "ROOFTOP",
17 "StreetAddress" => "RANGE_INTERPOLATED",
18 "StreetName" | "StreetInt" => "GEOMETRIC_CENTER",
19 _ => "APPROXIMATE",
21 }
22}
23
24fn result_types(h: &Hit) -> Vec<&'static str> {
26 match match_level(h).0 {
27 "PointAddress" | "StreetAddress" | "StreetAddressExt" => vec!["street_address"],
28 "POI" => vec!["establishment", "point_of_interest"],
29 "StreetName" => vec!["route"],
30 "StreetInt" => vec!["intersection"],
31 "Postal" => vec!["postal_code"],
32 _ => vec!["locality", "political"],
33 }
34}
35
36fn component(name: &str, types: &[&str]) -> Value {
37 json!({ "long_name": name, "short_name": name, "types": types })
38}
39
40pub fn result(h: &Hit, country: &str) -> Value {
42 let mut parts = Vec::new();
43 if let Some(number) = &h.housenumber {
44 parts.push(component(number, &["street_number"]));
45 }
46 if !h.street.is_empty() {
47 parts.push(component(&h.street, &["route"]));
48 }
49 if !h.commune.is_empty() {
50 parts.push(component(&h.commune, &["locality", "political"]));
51 }
52 if let Some(region) = &h.region {
53 parts.push(component(
54 region,
55 &["administrative_area_level_1", "political"],
56 ));
57 }
58 if !country.is_empty() {
59 parts.push(component(
60 &country.to_uppercase(),
61 &["country", "political"],
62 ));
63 }
64 if !h.postcode.is_empty() {
65 parts.push(component(&h.postcode, &["postal_code"]));
66 }
67 let w = half_width(h.precision);
68 let mut out = json!({
69 "address_components": parts,
70 "formatted_address": display_name(h),
71 "geometry": {
72 "location": { "lat": h.lat, "lng": h.lon },
73 "location_type": location_type(h),
74 "viewport": {
75 "northeast": { "lat": h.lat + w, "lng": h.lon + w },
76 "southwest": { "lat": h.lat - w, "lng": h.lon - w },
77 },
78 },
79 "place_id": format!("gridpin:{}", place_id(h)),
80 "types": result_types(h),
81 });
82 if hit_is_weak(h) || h.precision == "near" {
84 out["partial_match"] = json!(true);
85 }
86 out
87}
88
89pub fn response(hits: &[Hit], country: &str) -> Value {
91 json!({
92 "results": hits.iter().map(|h| result(h, country)).collect::<Vec<_>>(),
93 "status": if hits.is_empty() { "ZERO_RESULTS" } else { "OK" },
94 })
95}
96
97pub fn invalid(message: &str) -> Value {
99 json!({ "results": [], "status": "INVALID_REQUEST", "error_message": message })
100}
101
102pub fn component_filter<'a>(components: Option<&'a str>, name: &str) -> Option<&'a str> {
104 components?
105 .split('|')
106 .filter_map(|part| part.split_once(':'))
107 .find(|(key, _)| key.trim().eq_ignore_ascii_case(name))
108 .map(|(_, value)| value.trim())
109}
110
111#[cfg(test)]
112mod tests {
113 use super::*;
114
115 fn hit(precision: &'static str, flags: Vec<&'static str>) -> Hit {
116 Hit {
117 lat: 38.8976751,
118 lon: -77.036547,
119 precision,
120 score: 7.0,
121 confidence: 0.95,
122 street: "Pennsylvania Avenue Northwest".into(),
123 housenumber: (precision != "street" && precision != "city").then(|| "1600".to_string()),
124 commune: "Washington".into(),
125 postcode: "20500".into(),
126 flags,
127 region: Some("DC".into()),
128 distance_m: None,
129 }
130 }
131
132 fn exact(precision: &'static str) -> Hit {
133 hit(precision, vec!["street_exact"])
134 }
135
136 #[test]
137 fn every_documented_field_of_a_result_is_there_with_its_shape() {
138 let r = result(&exact("house"), "us");
139 assert_eq!(
140 r["formatted_address"],
141 "1600 Pennsylvania Avenue Northwest, Washington, DC, 20500"
142 );
143 assert_eq!(r["geometry"]["location"]["lat"], 38.8976751);
144 assert_eq!(r["geometry"]["location"]["lng"], -77.036547);
145 assert_eq!(r["geometry"]["location_type"], "ROOFTOP");
146 let view = &r["geometry"]["viewport"];
147 assert!(view["northeast"]["lat"].as_f64() > view["southwest"]["lat"].as_f64());
148 assert!(view["northeast"]["lng"].as_f64() > view["southwest"]["lng"].as_f64());
149 assert!(r["place_id"].as_str().unwrap().starts_with("gridpin:"));
150 assert_eq!(r["types"], json!(["street_address"]));
151 assert!(r.get("partial_match").is_none());
152 let of = |t: &str| {
153 r["address_components"]
154 .as_array()
155 .unwrap()
156 .iter()
157 .find(|c| c["types"].as_array().unwrap().iter().any(|x| x == t))
158 .map(|c| c["long_name"].as_str().unwrap().to_string())
159 };
160 assert_eq!(of("street_number").as_deref(), Some("1600"));
161 assert_eq!(
162 of("route").as_deref(),
163 Some("Pennsylvania Avenue Northwest")
164 );
165 assert_eq!(of("locality").as_deref(), Some("Washington"));
166 assert_eq!(of("administrative_area_level_1").as_deref(), Some("DC"));
167 assert_eq!(of("country").as_deref(), Some("US"));
168 assert_eq!(of("postal_code").as_deref(), Some("20500"));
169 for c in r["address_components"].as_array().unwrap() {
170 assert!(c.get("short_name").is_some() && c.get("types").is_some());
171 }
172 }
173
174 #[test]
175 fn location_type_and_types_follow_the_match_level() {
176 for (h, location, kind) in [
177 (exact("house"), "ROOFTOP", "street_address"),
178 (exact("interp"), "RANGE_INTERPOLATED", "street_address"),
179 (exact("near"), "APPROXIMATE", "street_address"),
180 (exact("street"), "GEOMETRIC_CENTER", "route"),
181 (
182 hit("intersection", vec!["intersection", "street_exact"]),
183 "GEOMETRIC_CENTER",
184 "intersection",
185 ),
186 (hit("city", vec!["place_exact"]), "APPROXIMATE", "locality"),
187 (
188 hit("city", vec!["place_prefix_group", "postal_place"]),
189 "APPROXIMATE",
190 "postal_code",
191 ),
192 (
193 hit("house", vec!["poi_layer"]),
194 "ROOFTOP",
195 "point_of_interest",
196 ),
197 ] {
198 let r = result(&h, "us");
199 assert_eq!(r["geometry"]["location_type"], location, "{}", h.precision);
200 assert!(
201 r["types"].as_array().unwrap().iter().any(|t| t == kind),
202 "{kind}: {r}"
203 );
204 }
205 }
206
207 #[test]
208 fn a_partial_match_is_what_the_engine_itself_doubts() {
209 assert_eq!(result(&exact("near"), "us")["partial_match"], true);
210 assert_eq!(
211 result(&hit("city", vec!["place_exact"]), "us")["partial_match"],
212 true
213 );
214 assert!(result(&exact("street"), "us")
215 .get("partial_match")
216 .is_none());
217 }
218
219 #[test]
220 fn parts_the_answer_does_not_have_are_left_out() {
221 let mut h = hit("street", vec!["street_exact"]);
222 h.region = None;
223 h.postcode.clear();
224 let r = result(&h, "");
225 let kinds: Vec<String> = r["address_components"]
226 .as_array()
227 .unwrap()
228 .iter()
229 .map(|c| c["types"][0].as_str().unwrap().to_string())
230 .collect();
231 assert_eq!(kinds, ["route", "locality"]);
232 }
233
234 #[test]
235 fn the_status_says_whether_anything_was_found() {
236 assert_eq!(response(&[exact("house")], "us")["status"], "OK");
237 let none = response(&[], "us");
238 assert_eq!(none["status"], "ZERO_RESULTS");
239 assert_eq!(none["results"], json!([]));
240 assert_eq!(invalid("x")["status"], "INVALID_REQUEST");
241 assert_eq!(invalid("x")["error_message"], "x");
242 }
243
244 #[test]
245 fn a_component_filter_is_found_by_its_name() {
246 let c = Some("Country:US|postal_code: 20500 ");
247 assert_eq!(component_filter(c, "country"), Some("US"));
248 assert_eq!(component_filter(c, "postal_code"), Some("20500"));
249 assert_eq!(component_filter(c, "route"), None);
250 assert_eq!(component_filter(None, "country"), None);
251 }
252}