A company's office: its GPS position and a photo
CI / secret scan (push) Successful in 4s
CI / fmt, clippy, tests (push) Successful in 22s

The company form has a field for the office's GPS position (migration
0004, column companies.office_gps). It takes what people have at hand:
the numbers Google Maps copies, a link to the place on Google Maps or
OpenStreetMap, a geo: URI, or degrees, minutes and seconds. It keeps
decimal degrees with six decimals and refuses a position outside Thailand,
which catches a swapped pair; a short maps.app.goo.gl link is refused with
a hint, as it holds no position (src/gps.rs, with unit tests).

The company's page has an Office card: the position with links that open
it on OpenStreetMap and Google Maps, the newest photo of the office, and a
strip that uploads a photo (kind "Photo of the office") and returns to the
card. The photos are documents like any other: encrypted on the server and
audited. A refused photo shows its errors on the card only; office photos
that are PDFs are counted under Company documents.

The demo company has a position. Tests: the position read from a link,
from degrees, minutes and seconds, the three refusals, the audit entry and
its removal; a photo uploaded from the card, shown, and its errors placed.
This commit is contained in:
grabowski committed 2026-11-18 11:56:26 +07:00
1 parent e88bb74e1e
commit 2a6e972b68
14 files changed
+642 -8

No files matched your search

+9
View File
@@ -11,6 +11,7 @@ use sqlx::{PgConnection, PgPool};
use crate::countries;
use crate::dates::{self, Status};
use crate::gps;
use crate::people::{self, AddressInput};
use crate::records::Record;
@@ -265,6 +266,10 @@ pub struct View {
pub registration_no: String,
pub business: String,
pub address: String,
/// The office's GPS position as stored, and links that open it on a map.
pub gps: String,
pub osm: String,
pub gmaps: String,
pub phone: String,
pub email: String,
pub signatory: String,
@@ -292,6 +297,7 @@ pub fn view(r: &Record, archived_at: Option<DateTime<Utc>>) -> View {
tm30_reported_on: None,
tm30_receipt_no: String::new(),
});
let position = gps::parse(r.get("office_gps"));
View {
id: r.id,
name: r.get("name").into(),
@@ -299,6 +305,9 @@ pub fn view(r: &Record, archived_at: Option<DateTime<Utc>>) -> View {
registration_no: r.get("registration_no").into(),
business: r.get("business").into(),
address,
gps: r.get("office_gps").into(),
osm: position.map(|p| p.openstreetmap()).unwrap_or_default(),
gmaps: position.map(|p| p.google_maps()).unwrap_or_default(),
phone: r.get("phone").into(),
email: r.get("email").into(),
signatory: r.get("signatory").into(),
+281
View File
@@ -0,0 +1,281 @@
//! The GPS position of a company's office. People paste it in whatever form
//! they have: the numbers Google Maps copies ("18.796500, 99.008200"), a
//! link to the place on Google Maps or OpenStreetMap, or degrees, minutes
//! and seconds (18°47'47.4"N 99°00'29.5"E). It is kept as decimal degrees
//! with six decimals, about 10 cm, and opens on either map.
/// A position in decimal degrees.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Position {
pub lat: f64,
pub lon: f64,
}
/// What the form says when a position cannot be read.
pub const UNREADABLE: &str =
"Enter the latitude and longitude, such as 18.796500, 99.008200, or paste a link to the place.";
pub const SHORT_LINK: &str = "A short link holds no position. Open it, then copy the numbers that Google Maps shows for the place.";
pub const OUTSIDE: &str = "This position is outside Thailand. The latitude comes first: about 18.8 in Chiang Mai, then the longitude, about 99.0.";
impl Position {
/// The stored form.
pub fn text(&self) -> String {
format!("{:.6}, {:.6}", self.lat, self.lon)
}
/// Inside Thailand's bounding box; a swapped pair or a lost minus sign
/// lands outside it.
pub fn in_thailand(&self) -> bool {
(5.0..=21.0).contains(&self.lat) && (97.0..=106.0).contains(&self.lon)
}
pub fn openstreetmap(&self) -> String {
format!(
"https://www.openstreetmap.org/?mlat={0:.6}&mlon={1:.6}#map=18/{0:.6}/{1:.6}",
self.lat, self.lon
)
}
pub fn google_maps(&self) -> String {
format!(
"https://www.google.com/maps/search/?api=1&query={:.6},{:.6}",
self.lat, self.lon
)
}
}
/// The two numbers in what was pasted, whatever they are.
fn read(s: &str) -> Option<Position> {
let s = s.trim();
if s.is_empty() {
return None;
}
from_link(s)
.or_else(|| from_dms(s))
.or_else(|| pair(s, true))
.filter(|p| p.lat.is_finite() && p.lon.is_finite())
}
/// Reads a position from what was pasted: one on the globe.
pub fn parse(s: &str) -> Option<Position> {
read(s).filter(|p| p.lat.abs() <= 90.0 && p.lon.abs() <= 180.0)
}
/// The message for a value that is not a position in Thailand, or None.
pub fn problem(s: &str) -> Option<&'static str> {
match read(s) {
Some(p) if p.in_thailand() => None,
Some(_) => Some(OUTSIDE),
None if s.contains("goo.gl") || s.contains("maps.app") => Some(SHORT_LINK),
None => Some(UNREADABLE),
}
}
/// The number at the start of `s`: "18.7965,99.0082,17z" gives 18.7965.
fn leading_number(s: &str) -> Option<f64> {
let end = s
.char_indices()
.find(|&(i, c)| !(c.is_ascii_digit() || c == '.' || (i == 0 && (c == '-' || c == '+'))))
.map_or(s.len(), |(i, _)| i);
s[..end].parse().ok()
}
/// Two numbers separated by a comma, a semicolon or spaces. `exact` refuses
/// anything after the second: a typed value is the pair and nothing else,
/// while a link may go on ("@18.79,99.00,17z").
fn pair(s: &str, exact: bool) -> Option<Position> {
let s = s
.replace("%2C", ",")
.replace("%2c", ",")
.replace("%20", " ")
.replace('+', " ");
let mut parts = s
.split([',', ';', ' ', '\t'])
.filter(|t| !t.trim().is_empty());
let lat = parts.next()?.trim();
let lon = parts.next()?.trim();
if exact {
if parts.next().is_some() {
return None;
}
return Some(Position {
lat: lat.parse().ok()?,
lon: lon.parse().ok()?,
});
}
Some(Position {
lat: leading_number(lat)?,
lon: leading_number(lon)?,
})
}
/// A link to the place: Google Maps (`/@lat,lon,zoom`, `?q=`, `query=`,
/// `ll=`, `destination=`), OpenStreetMap (`mlat=`/`mlon=`, `#map=z/lat/lon`)
/// or a `geo:` URI.
fn from_link(s: &str) -> Option<Position> {
if !(s.contains("://") || s.starts_with("geo:") || s.starts_with("www.")) {
return None;
}
if let (Some((_, a)), Some((_, b))) = (s.split_once("mlat="), s.split_once("mlon=")) {
return Some(Position {
lat: leading_number(a)?,
lon: leading_number(b)?,
});
}
if let Some((_, rest)) = s.split_once("#map=") {
let mut it = rest.split('/').skip(1);
return Some(Position {
lat: leading_number(it.next()?)?,
lon: leading_number(it.next()?)?,
});
}
for key in ["/@", "?q=", "&q=", "query=", "ll=", "destination=", "geo:"] {
if let Some((_, rest)) = s.split_once(key) {
let value = rest.split(['&', '#', '?']).next().unwrap_or("");
if let Some(p) = pair(value, false) {
return Some(p);
}
}
}
None
}
/// One half of a position in degrees, minutes and seconds, with its
/// hemisphere letter before or after the numbers.
fn dms_half(part: &str) -> Option<(f64, char)> {
let part = part.trim();
let hemisphere = part
.chars()
.rev()
.find(char::is_ascii_alphabetic)
.or_else(|| part.chars().find(char::is_ascii_alphabetic))?
.to_ascii_uppercase();
let numbers: Vec<f64> = part
.split(|c: char| !(c.is_ascii_digit() || c == '.'))
.filter(|t| !t.is_empty())
.map(|t| t.parse().ok())
.collect::<Option<_>>()?;
let (d, m, sec) = match numbers.as_slice() {
[d] => (*d, 0.0, 0.0),
[d, m] => (*d, *m, 0.0),
[d, m, sec] => (*d, *m, *sec),
_ => return None,
};
if m >= 60.0 || sec >= 60.0 {
return None;
}
let value = d + m / 60.0 + sec / 3600.0;
let value = if matches!(hemisphere, 'S' | 'W') {
-value
} else {
value
};
Some((value, hemisphere))
}
fn from_dms(s: &str) -> Option<Position> {
if !s.contains('°') {
return None;
}
// the latitude ends at its N or S
let end = s.find(['N', 'S', 'n', 's'])? + 1;
let (lat, lon) = s.split_at(end);
let (lat, h1) = dms_half(lat)?;
let (lon, h2) = dms_half(lon.trim_start_matches([',', ' ', ';']))?;
(matches!(h1, 'N' | 'S') && matches!(h2, 'E' | 'W')).then_some(Position { lat, lon })
}
#[cfg(test)]
mod tests {
use super::*;
fn text(s: &str) -> Option<String> {
parse(s).map(|p| p.text())
}
#[test]
fn numbers_as_google_maps_copies_them() {
assert_eq!(
text("18.796500, 99.008200").as_deref(),
Some("18.796500, 99.008200")
);
assert_eq!(
text(" 18.7965,99.0082 ").as_deref(),
Some("18.796500, 99.008200")
);
assert_eq!(
text("18.7965 99.0082").as_deref(),
Some("18.796500, 99.008200")
);
assert_eq!(
text("-33.8688; 151.2093").as_deref(),
Some("-33.868800, 151.209300")
);
}
#[test]
fn links_to_the_place() {
let want = Some("18.796500, 99.008200");
for link in [
"https://www.google.com/maps/place/Demo+Tower/@18.7965,99.0082,17z/data=!3m1",
"https://maps.google.com/?q=18.7965,99.0082",
"https://www.google.com/maps/search/?api=1&query=18.7965%2C99.0082",
"https://www.google.com/maps/dir/?api=1&destination=18.7965,99.0082",
"https://www.openstreetmap.org/?mlat=18.7965&mlon=99.0082#map=18/18.7965/99.0082",
"https://www.openstreetmap.org/#map=18/18.7965/99.0082",
"geo:18.7965,99.0082",
] {
assert_eq!(text(link).as_deref(), want, "{link}");
}
}
#[test]
fn degrees_minutes_and_seconds() {
let p = parse("18°47'47.4\"N 99°00'29.5\"E").unwrap();
assert!((p.lat - 18.796_5).abs() < 1e-6, "{p:?}");
assert!((p.lon - 99.008_194).abs() < 1e-5, "{p:?}");
let p = parse("33°52′07.7″S, 151°12′33.5″E").unwrap();
assert!(p.lat < -33.8 && p.lon > 151.2, "{p:?}");
assert!(parse("18°75'00\"N 99°00'00\"E").is_none(), "75 minutes");
}
#[test]
fn what_is_no_position() {
for s in [
"",
"Chiang Mai",
"18.7965",
"18.7965, 99.0082, 12",
"95.0, 99.0",
"18.7, 199.0",
"https://maps.app.goo.gl/AbCdEf123",
] {
assert!(parse(s).is_none(), "{s:?} gave {:?}", parse(s));
}
}
#[test]
fn the_messages() {
assert_eq!(problem("18.796500, 99.008200"), None);
assert_eq!(problem("99.0082, 18.7965"), Some(OUTSIDE));
assert_eq!(problem("48.137154, 11.576124"), Some(OUTSIDE));
assert_eq!(
problem("https://maps.app.goo.gl/AbCdEf123"),
Some(SHORT_LINK)
);
assert_eq!(problem("next to the market"), Some(UNREADABLE));
}
#[test]
fn the_map_links() {
let p = parse("18.7965, 99.0082").unwrap();
assert_eq!(
p.openstreetmap(),
"https://www.openstreetmap.org/?mlat=18.796500&mlon=99.008200#map=18/18.796500/99.008200"
);
assert_eq!(
p.google_maps(),
"https://www.google.com/maps/search/?api=1&query=18.796500,99.008200"
);
}
}
+1
View File
@@ -12,6 +12,7 @@ pub mod documents;
pub mod embedded;
pub mod files;
pub mod forms;
pub mod gps;
pub mod mrz;
pub mod oidc;
pub mod people;
+15 -1
View File
@@ -16,6 +16,7 @@ use sqlx::{PgConnection, PgPool, Postgres, QueryBuilder, Row};
use crate::audit::Entity;
use crate::dates::{self, Status};
use crate::forms::{Errors, Fields, compact_upper, err};
use crate::gps;
/// A record's values as text by field name: what the form shows and the
/// checks read. Dates are `YYYY-MM-DD`; references are ids.
@@ -39,6 +40,8 @@ pub enum Input {
Visa,
/// One of the companies.
Company,
/// A GPS position, kept as "18.796500, 99.008200" (`gps`).
Gps,
}
#[derive(Debug)]
@@ -438,6 +441,11 @@ const COMPANY_FIELDS: &[Field] = &[
field("district", "District (amphoe)", Input::Text),
field("province", "Province", Input::Text).suggest("provinces"),
field("postal_code", "Postal code", Input::Digits),
field("office_gps", "GPS position of the office", Input::Gps)
.hint(
"As Google Maps copies it: right-click the office on the map and click the numbers. A link to the place works too.",
)
.wide(),
field("phone", "Phone", Input::Text),
field("email", "Email", Input::Text),
field("signatory", "Authorized director", Input::Text)
@@ -643,6 +651,7 @@ pub fn read(kind: &Kind, f: &Fields) -> Values {
Input::Digits => raw.trim().replace([' ', '-'], ""),
Input::Money => raw.trim().replace([',', ' '], ""),
Input::Area => raw.trim().replace("\r\n", "\n"),
Input::Gps => gps::parse(raw).map_or_else(|| raw.trim().to_string(), |p| p.text()),
_ => raw.trim().to_string(),
};
(fl.name.to_string(), v)
@@ -694,6 +703,11 @@ pub fn validate(kind: &Kind, v: &Values, opts: &Options) -> Errors {
err(&mut e, fl.name, "Choose from the list.");
}
}
Input::Gps => {
if let Some(msg) = gps::problem(value) {
err(&mut e, fl.name, msg);
}
}
Input::Text | Input::Code | Input::Area => {}
}
}
@@ -946,7 +960,7 @@ pub fn form_fields(kind: &Kind, opts: &Options) -> Vec<FormField> {
Input::Passport | Input::Visa | Input::Company => {
("select", opts.list(fl.input).to_vec())
}
Input::Text | Input::Code | Input::Digits => ("text", vec![]),
Input::Text | Input::Code | Input::Digits | Input::Gps => ("text", vec![]),
};
FormField {
name: fl.name,
+1
View File
@@ -168,6 +168,7 @@ fn companies() -> Vec<Values> {
"district" => "Mueang Chiang Mai",
"province" => "Chiang Mai",
"postal_code" => "50000",
"office_gps" => "18.796500, 99.008200",
"phone" => "+66 53 000 000",
"email" => "office@demo-engineering.example",
"signatory" => "Malee Jaidee",
+14 -2
View File
@@ -195,7 +195,19 @@ pub async fn company_page(
let candidates = companies::candidates(&st.db, id).await?;
let owner = Owner::Company(id);
let docs = documents::views(st, owner, &HashMap::new()).await?;
let upload = documents::upload_context(st, owner, values, errors, &[]);
let office = documents::office_context(st, &docs, values, errors);
// a refused office photo shows its errors on the office card only
let upload = if values.from_office() {
documents::upload_context(
st,
owner,
&documents::Values::default(),
&Errors::new(),
&[],
)
} else {
documents::upload_context(st, owner, values, errors, &[])
};
let title = c.name.clone();
Ok(page(
st,
@@ -204,7 +216,7 @@ pub async fn company_page(
&title,
"companies",
status,
context! { c, employees, candidates, docs, upload },
context! { c, employees, candidates, docs, upload, office },
))
}
+48 -1
View File
@@ -51,6 +51,9 @@ pub struct Values {
pub link: String,
pub dated_on: String,
pub note: String,
/// Where an upload came from: "office" for the office card of a
/// company's page, which it returns to.
pub back: String,
}
impl Values {
@@ -60,6 +63,7 @@ impl Values {
link: documents::link_value(d.link()),
dated_on: d.dated_on.map(|d| d.to_string()).unwrap_or_default(),
note: d.note.clone(),
back: String::new(),
}
}
@@ -69,14 +73,21 @@ impl Values {
link: forms::get(f, "link"),
dated_on: forms::get(f, "dated_on"),
note: forms::get(f, "note"),
back: String::new(),
}
}
/// The upload came from the office card of a company's page.
pub fn from_office(&self) -> bool {
self.back == "office"
}
}
/// A document as the pages show it.
#[derive(Debug, Serialize)]
pub struct DocView {
pub id: i64,
pub kind: String,
pub kind_label: String,
pub link_label: String,
pub link_href: String,
@@ -209,6 +220,7 @@ fn view(d: &Document, names: &HashMap<String, (String, String)>) -> DocView {
.unwrap_or_default();
DocView {
id: d.id,
kind: d.kind.clone(),
kind_label: documents::kind_label(owner, &d.kind),
link_label,
link_href,
@@ -265,6 +277,36 @@ fn kinds(owner: Owner) -> Vec<(&'static str, &'static str)> {
owner.kinds().iter().map(|k| (k.slug, k.label)).collect()
}
/// The office card of a company's page: the newest photo of the office that
/// is an image, how many more there are, and the strip that adds one (with
/// its errors when an upload from it was refused).
pub fn office_context(
st: &AppState,
docs: &[DocView],
values: &Values,
errors: &Errors,
) -> minijinja::Value {
let all = docs.iter().filter(|d| d.kind == "office-photo").count();
let photo = docs
.iter()
.filter(|d| d.kind == "office-photo" && d.image)
.max_by_key(|d| d.id);
let errors = if values.from_office() {
errors.clone()
} else {
Errors::new()
};
context! {
files_on => st.files.is_some(),
photo,
// the other photos of the office, PDFs among them
more => all - usize::from(photo.is_some()),
errors,
file_limit_mb => FILE_LIMIT / (1024 * 1024),
file_limit => FILE_LIMIT,
}
}
/// The upload part of a page: on the Documents tab and the company's page.
pub fn upload_context(
st: &AppState,
@@ -475,6 +517,7 @@ async fn read_upload(
"link" => up.values.link = text,
"dated_on" => up.values.dated_on = text,
"note" => up.values.note = text,
"back" => up.values.back = text,
_ => {}
}
}
@@ -704,7 +747,11 @@ pub async fn upload(st: Arc<AppState>, user: User, owner: Owner, mp: Multipart)
};
}
let first = save(&st, &user, &store, owner, &meta, checked).await?;
Ok(Redirect::to(&format!("{}#doc-{first}", list_page(owner))).into_response())
let to = match owner {
Owner::Company(id) if values.from_office() => format!("/companies/{id}#office"),
_ => format!("{}#doc-{first}", list_page(owner)),
};
Ok(Redirect::to(&to).into_response())
}
#[derive(Debug, Deserialize)]