From 2a6e972b68a509093f990c306c4cf742a9d03258 Mon Sep 17 00:00:00 2001 From: grabowski Date: Wed, 18 Nov 2026 11:56:26 +0700 Subject: [PATCH] A company's office: its GPS position and a photo 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. --- README.md | 5 +- docs/PLAN.md | 16 +- migrations/0004_company_office.sql | 9 + src/companies.rs | 9 + src/gps.rs | 281 +++++++++++++++++++++++++++++ src/lib.rs | 1 + src/records.rs | 16 +- src/seed.rs | 1 + src/web/companies.rs | 16 +- src/web/documents.rs | 49 ++++- static/app.css | 60 ++++++ templates/company.html | 41 +++++ tests/companies.rs | 73 ++++++++ tests/documents.rs | 73 ++++++++ 14 files changed, 642 insertions(+), 8 deletions(-) create mode 100644 migrations/0004_company_office.sql create mode 100644 src/gps.rs diff --git a/README.md b/README.md index 9be066d..8f62f8a 100644 --- a/README.md +++ b/README.md @@ -38,7 +38,10 @@ Data Protection Act (PDPA) asks. - Companies with their Thai name, registration number (the check digit is verified), address and signing director. A person's employer and the employer on a work permit are chosen from them, and a company's page adds - people to it. + people to it. The page's Office card shows the office's GPS position, + with links to OpenStreetMap and Google Maps, and the newest photo of the + office; the position may be pasted as Google Maps copies it or as a link + to the place. - New people and passports from the passport's machine-readable zone: paste the two lines at the bottom of the photo page and the form fills itself in. The check digits catch typing errors. diff --git a/docs/PLAN.md b/docs/PLAN.md index 67fefc7..661e644 100644 --- a/docs/PLAN.md +++ b/docs/PLAN.md @@ -2,7 +2,8 @@ > Phases 1 to 3 built on November 17, 2026, and phase 4's app side on > November 18, 2026; the app is live at https://visa.buildfor.life. **Resume -> here: task 4.6, the fleet side of the documents, then phase 5.** +> here: phase 5, the filled-in forms.** Task 4.6, the fleet side of the +> documents, waits in cnx-network-clan PR #126. visa.buildfor.life keeps the immigration records of the foreigners that B4L looks after: their passports, addresses in Thailand, arrivals with the Thailand @@ -84,7 +85,7 @@ made of. | `addresses` | the address in Thailand in the order Thai forms use, moving dates, the house master and the TM.30 receipt | 1 | | `sessions` | signed-in sessions | 1 | | `audit_log` | who viewed or changed which record, append-only | 1 | -| `companies` | name in English and Thai, the 13-digit registration number with its check digit, address, the director who signs; archiving | 2 | +| `companies` | name in English and Thai, the 13-digit registration number with its check digit, address, the office's GPS position, the director who signs; archiving | 2, 4 | | `visas` | visa category (Non-B, Non-O, DTV and others), number, place and date of issue, validity, entries | 2 | | `arrivals` | arrival date, port, flight, visa used, permitted-until date, TDAC number; departure date when the person left | 2 | | `extensions` | extensions of stay: approval date, new permitted-until date, reason, office, receipt | 2 | @@ -168,7 +169,7 @@ dark at desktop and phone width, a commit and a push. | 1 | App, Kanidm login, people, passports with MRZ reading, addresses in Thailand, audit log, demo data, CI | built Nov 17, 2026 | | 2 | Companies; stays: visas, arrivals with TDAC, extensions, re-entry permits, 90-day reports, work permits; deadlines | built Nov 17, 2026 | | 3 | On cnx01: flake package, fleet module, Kanidm client and group, bkk01 site, backups; real data from here on | live Nov 17, 2026 | -| 4 | Documents: encrypted uploads (passport pages, TDAC, receipts, photo) on the dataset `zroot/visa` with a key var, viewing and download, all audited | app built Nov 18, 2026; fleet next | +| 4 | Documents: encrypted uploads (passport pages, TDAC, receipts, photo) on the dataset `zroot/visa` with a key var, viewing and download, all audited; the office's GPS position and photo | app built Nov 18, 2026; fleet in PR #126 | | 5 | Filled-in forms: TM.7, STM.2, the overstay acknowledgment, TM.47, TM.8 and STM.1 as PDF | | | 6 | The Non-B extension pack: B4L's company documents, the checklist, one PDF to print | | | 7 | Reminders by Matrix room message and by email | | @@ -264,6 +265,15 @@ one `Kind`. Nov 18, 2026); Alex merges and deploys it, together with the flake update #125 that cnx01 and control do not run yet. After the deploy: `visa-admin files-check` on cnx01 and an upload on the live app. +- [x] 4.7 A company's office, asked for on November 18, 2026: its GPS + position on the company form, read from the numbers Google Maps + copies, a link to the place on Google Maps or OpenStreetMap, or + degrees, minutes and seconds, kept as decimal degrees and checked to + lie in Thailand (`src/gps.rs`); an Office card on the company's page + with the position, links that open it on either map, the newest photo + of the office, and a strip that adds a photo and returns to the card. + The photos are documents of the kind "Photo of the office", so they + are encrypted and audited like every other file. ## Open questions diff --git a/migrations/0004_company_office.sql b/migrations/0004_company_office.sql new file mode 100644 index 0000000..7ef86c8 --- /dev/null +++ b/migrations/0004_company_office.sql @@ -0,0 +1,9 @@ +-- The GPS position of a company's office, as decimal degrees with six +-- decimals ("18.796500, 99.008200"); empty when not recorded. Photos of the +-- office are documents of the kind office-photo (0003). + +ALTER TABLE companies ADD COLUMN office_gps TEXT NOT NULL DEFAULT '' + CONSTRAINT companies_office_gps_check CHECK ( + office_gps = '' + OR office_gps ~ '^-?[0-9]{1,2}\.[0-9]{6}, -?[0-9]{1,3}\.[0-9]{6}$' + ); diff --git a/src/companies.rs b/src/companies.rs index 605d87c..aee508f 100644 --- a/src/companies.rs +++ b/src/companies.rs @@ -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>) -> 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>) -> 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(), diff --git a/src/gps.rs b/src/gps.rs new file mode 100644 index 0000000..3380e32 --- /dev/null +++ b/src/gps.rs @@ -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 { + 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 { + 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 { + 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 { + 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 { + 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 = part + .split(|c: char| !(c.is_ascii_digit() || c == '.')) + .filter(|t| !t.is_empty()) + .map(|t| t.parse().ok()) + .collect::>()?; + 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 { + 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 { + 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" + ); + } +} diff --git a/src/lib.rs b/src/lib.rs index 5d1c07a..75d3577 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -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; diff --git a/src/records.rs b/src/records.rs index 8f97124..acf0391 100644 --- a/src/records.rs +++ b/src/records.rs @@ -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 { 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, diff --git a/src/seed.rs b/src/seed.rs index e3aa050..6dd1594 100644 --- a/src/seed.rs +++ b/src/seed.rs @@ -168,6 +168,7 @@ fn companies() -> Vec { "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", diff --git a/src/web/companies.rs b/src/web/companies.rs index c4b1f01..784d29f 100644 --- a/src/web/companies.rs +++ b/src/web/companies.rs @@ -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 }, )) } diff --git a/src/web/documents.rs b/src/web/documents.rs index 2eef291..5470a04 100644 --- a/src/web/documents.rs +++ b/src/web/documents.rs @@ -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) -> 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, 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)] diff --git a/static/app.css b/static/app.css index aeab551..5c03cb2 100644 --- a/static/app.css +++ b/static/app.css @@ -937,6 +937,66 @@ textarea.mrz { .upload-row .field { min-width: 0; } +/* ---- a company's office: its photo beside the position on the map */ +.office { + display: grid; + grid-template-columns: minmax(0, 300px) minmax(0, 1fr); + gap: 16px 24px; + align-items: start; +} +.office-pic img, +.office-none { + display: block; + width: 100%; + aspect-ratio: 4 / 3; + border-radius: 10px; + border: 1px solid var(--line); + background: var(--panel2); +} +.office-pic img { + object-fit: cover; +} +.office-pic p { + margin: 6px 0 0; +} +.office-none { + display: grid; + place-items: center; + border: 1.5px dashed var(--stroke); + color: var(--mute); + font-size: 13.5px; +} +.maplinks { + display: inline-flex; + flex-wrap: wrap; + gap: 2px 14px; + margin-left: 14px; +} +.office-info .hint { + margin: 10px 0 0; +} +.office-up { + display: grid; + grid-template-columns: minmax(0, 1fr) auto; + gap: 8px 10px; + align-items: center; + margin: 14px 0 0; +} +.office-up > .notice { + grid-column: 1 / -1; + margin: 0; +} +@media (max-width: 700px) { + .office, + .office-up { + grid-template-columns: minmax(0, 1fr); + } + .maplinks { + display: flex; + margin: 2px 0 0; + } +} + /* the list runs to the card's edges */ .tblwrap.bleed { margin: 0 -20px -18px; diff --git a/templates/company.html b/templates/company.html index 823184b..be17286 100644 --- a/templates/company.html +++ b/templates/company.html @@ -67,6 +67,47 @@ {% endif %} +
+

Office

{% if c.gps %}Change the position{% else %}Add the GPS position{% endif %}
+
+
+ {%- if office.photo %} + Photo of the office of {{ c.name }} +

{% if office.photo.dated_on %}Taken {{ office.photo.dated_on }}{% else %}Added {{ office.photo.uploaded }}{% endif %}{% if office.more %} · {{ office.more }} more under Company documents{% endif %}

+ {%- else %} +
No photo of the office yet
+ {%- if office.more %} +

{{ office.more }} as PDF under Company documents

+ {%- endif %} + {%- endif %} +
+
+
+
GPS position
+
{% if c.gps %}{{ c.gps }}{% if c.osm %}OpenStreetMapGoogle Maps{% endif %}{% else %}not recorded{% endif %}
+
+

The position and the photo help the officers who visit the workplace, and go into the extension packs of the people employed here.

+ {%- if office.files_on %} +
+ + + + {%- if office.errors %} +
Nothing was uploaded. {{ office.errors.file or office.errors.kind or office.errors.note or "Choose the photo again." }}
+ {%- endif %} +
+ + + + + JPEG, PNG or WebP, up to {{ office.file_limit_mb }} MB +
+ +
+ {%- endif %} +
+
+

Company documents

for the extension packs of the people employed here
{{ dm.upload(upload, csrf, person=false) }} diff --git a/tests/companies.rs b/tests/companies.rs index 63ca756..dbefe6a 100644 --- a/tests/companies.rs +++ b/tests/companies.rs @@ -263,3 +263,76 @@ async fn an_archived_company_is_no_longer_offered(pool: PgPool) { .unwrap(); assert_eq!(actions, vec!["create", "archive", "restore"]); } + +#[sqlx::test(migrator = "visa::db::MIGRATOR")] +async fn the_office_position_is_read_from_what_people_paste(pool: PgPool) { + let app = local(pool.clone()); + let name = ("name", "Test Works Co., Ltd."); + for (pasted, message) in [ + ("99.0082, 18.7965", "outside Thailand"), + ( + "https://maps.app.goo.gl/AbCdEf123", + "A short link holds no position", + ), + ("next to the market", "Enter the latitude and longitude"), + ] { + let r = app + .post("/companies", &[name, ("office_gps", pasted)]) + .await; + assert_eq!(r.status, StatusCode::UNPROCESSABLE_ENTITY, "{pasted}"); + assert!(r.text().contains(message), "{pasted}: {}", r.text()); + } + + // a link to the place on Google Maps + let r = app + .post( + "/companies", + &[ + name, + ( + "office_gps", + "https://www.google.com/maps/place/Demo+Tower/@18.7965,99.0082,17z/data=!3m1", + ), + ], + ) + .await; + assert_eq!(r.status, StatusCode::SEE_OTHER, "{}", r.body); + let id = company_from(r.location()); + let stored = || async { + sqlx::query_scalar::<_, String>("SELECT office_gps FROM companies WHERE id = $1") + .bind(id) + .fetch_one(&pool) + .await + .unwrap() + }; + assert_eq!(stored().await, "18.796500, 99.008200"); + let page = app.get(&format!("/companies/{id}")).await.text(); + assert!(page.contains("18.796500, 99.008200"), "{page}"); + assert!( + page.contains("https://www.openstreetmap.org/?mlat=18.796500&mlon=99.008200"), + "{page}" + ); + assert!(page.contains("https://www.google.com/maps/search/?api=1&query=18.796500,99.008200")); + assert!(page.contains("No photo of the office yet")); + + // degrees, minutes and seconds; the audit log names the field + let r = app + .post( + &format!("/companies/{id}"), + &[name, ("office_gps", "18°47'47.4\"N 99°00'29.5\"E")], + ) + .await; + assert_eq!(r.status, StatusCode::SEE_OTHER, "{}", r.body); + assert_eq!(stored().await, "18.796500, 99.008194"); + assert_eq!( + audit_fields(&pool, "company", id, "update").await, + vec![vec!["office_gps".to_string()]] + ); + + // and it can be taken out again + let r = app.post(&format!("/companies/{id}"), &[name]).await; + assert_eq!(r.status, StatusCode::SEE_OTHER, "{}", r.body); + assert_eq!(stored().await, ""); + let page = app.get(&format!("/companies/{id}")).await.text(); + assert!(page.contains("Add the GPS position"), "{page}"); +} diff --git a/tests/documents.rs b/tests/documents.rs index cccdabd..713a718 100644 --- a/tests/documents.rs +++ b/tests/documents.rs @@ -610,3 +610,76 @@ async fn the_demo_documents_open_as_what_they_are(pool: PgPool) { .is_empty() ); } + +/// A 1 x 1 PNG. +const DOT_PNG: &[u8] = &[ + 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x0d, 0x49, 0x48, 0x44, 0x52, + 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x08, 0x06, 0x00, 0x00, 0x00, 0x1f, 0x15, 0xc4, + 0x89, 0x00, 0x00, 0x00, 0x0d, 0x49, 0x44, 0x41, 0x54, 0x78, 0x9c, 0x63, 0x00, 0x01, 0x00, 0x00, + 0x05, 0x00, 0x01, 0x0d, 0x0a, 0x2d, 0xb4, 0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x4e, 0x44, 0xae, + 0x42, 0x60, 0x82, +]; + +#[sqlx::test(migrator = "visa::db::MIGRATOR")] +async fn the_office_card_takes_a_photo_and_shows_it(pool: PgPool) { + visa::seed::demo(&pool, visa::dates::today()).await.unwrap(); + let app = local(pool.clone()); + let company: i64 = + sqlx::query_scalar("SELECT id FROM companies WHERE name = 'Demo Engineering Co., Ltd.'") + .fetch_one(&pool) + .await + .unwrap(); + let base = format!("/companies/{company}/documents"); + let office = [("kind", "office-photo"), ("back", "office")]; + + // refused from the card: the card says so, the documents' strip does not + let r = app.upload(&base, &office, &[("office.png", b"")]).await; + assert_eq!(r.status, StatusCode::UNPROCESSABLE_ENTITY); + let t = r.text(); + let (card, list) = ( + t.find("id=\"office\"").unwrap(), + t.find("id=\"documents\"").unwrap(), + ); + let notice = t + .find("Nothing was uploaded") + .expect("the card has the notice"); + assert!( + card < notice && notice < list, + "the notice is on the office card" + ); + assert_eq!(t.matches("Nothing was uploaded").count(), 1, "{t}"); + + let r = app.upload(&base, &office, &[("office.png", DOT_PNG)]).await; + assert_eq!(r.status, StatusCode::SEE_OTHER, "{}", r.body); + assert_eq!(r.location(), format!("/companies/{company}#office")); + let did: i64 = sqlx::query_scalar("SELECT id FROM documents WHERE company_id = $1") + .bind(company) + .fetch_one(&pool) + .await + .unwrap(); + let t = app.get(&format!("/companies/{company}")).await.text(); + assert!( + t.contains(&format!("