Files
visa/src/web/originals.rs
T
grabowski ff716eb9d3
CI / secret scan (push) Successful in 8s
CI / fmt, clippy, tests (push) Successful in 1m23s
CI / release (push) Skipped
Originals in our care (phase 12, step 1)
What clients hand Lanna Desk for a while (a passport for an extension, a
signed contract, a title deed) gets a code and a label (OR-2026-0001), and
a record of where it is: held at a place in the office, out with someone
such as Chiang Mai Immigration until a date, or returned.

- Migration 0013: table originals, owned by a client or a person; the
  database refuses a delete and a change of what it is, whose it is and
  how it came.
- Every intake and move is a journal entry starting with the code; the
  item's page reads its history from there. The audit log has the new
  entity "original", with a view when a person's original is shown.
- Pages: Legal, Originals (in our care, out, held, returned, all; a find
  box for a typed or scanned code), the item's page with the move form,
  intake from a client's or a person's page, and the label with a QR code
  to the item's page. Cards on the client's and the person's pages.
- A field can show only for some choices of a selection
  (data-shown-when), so the move form asks "Where it lies", "With whom"
  or "Returned to" as fits.
- Demo data: a passport out at Immigration, a title deed and a house
  registration held, a company certificate returned.
- PLAN: phase 12, with step 2 (the inbox that files a pile of scans) and
  step 3 planned.
2026-11-23 14:06:50 +07:00

560 lines
16 KiB
Rust

//! The originals register's pages (phase 12, `crate::originals`): the list
//! under Legal, intake from a client's or a person's page, the item's page
//! (the address in its label's QR code) with its moves and history, and the
//! label. Intake and moves go into the journal (in `originals`) and the
//! audit log (here); a page that shows a person's original writes a view.
use std::sync::Arc;
use axum::extract::{Path, Query, State};
use axum::http::StatusCode;
use axum::response::{IntoResponse, Redirect};
use axum::{Extension, Form};
use minijinja::context;
use serde::{Deserialize, Serialize};
use super::{AppState, Res, message, not_found_page, page};
use crate::audit::{self, Action, Entity, Entry};
use crate::dates;
use crate::forms::{self, Errors, Fields, err};
use crate::originals::{self, Listed, Move, New, Owner, Show};
use crate::session::User;
fn audit_entry<'a>(user: &'a User, action: Action, o: &Listed, fields: &'a [String]) -> Entry<'a> {
Entry {
actor: &user.login,
action,
entity: Entity::Original,
entity_id: Some(o.o.id),
person_id: o.o.person_id,
company_id: None,
fields,
}
}
/// An original as a row of a list or a card.
#[derive(Debug, Serialize)]
pub struct Row {
id: i64,
code: String,
href: String,
kind: &'static str,
what: String,
owner: String,
owner_href: String,
contract_code: Option<String>,
state: String,
state_label: &'static str,
/// where it lies, or whom it is with
place: String,
since: String,
chip: Option<(&'static str, String)>,
/// the list filter's text, lower case
q: String,
/// the kind, unless the description starts with it ("Passport ...")
kind_note: &'static str,
}
pub fn row(l: &Listed, today: chrono::NaiveDate) -> Row {
let o = &l.o;
Row {
id: o.id,
code: o.code.clone(),
href: format!("/originals/{}", o.code),
kind: originals::kind_label(&o.kind),
what: o.what.clone(),
owner: l.owner.clone(),
owner_href: l.owner_href(),
contract_code: l.contract_code.clone(),
state: o.state.clone(),
state_label: originals::state_label(&o.state),
place: match o.state.as_str() {
"held" => o.location.clone(),
"out" => format!("with {}", o.holder),
_ => format!("to {}", o.holder),
},
since: dates::fmt_date(o.moved_at.with_timezone(&dates::bangkok()).date_naive()),
chip: originals::chip(o, today),
q: format!("{} {} {} {}", o.code, o.what, l.owner, o.holder).to_lowercase(),
kind_note: kind_note(o),
}
}
/// The kind, unless what the original is already says it: "Passport
/// C01X00T47" needs no "Passport" beside it.
fn kind_note(o: &originals::Original) -> &'static str {
let kind = originals::kind_label(&o.kind);
let first = kind.split(' ').next().unwrap_or(kind).to_lowercase();
if o.what.to_lowercase().starts_with(&first) {
""
} else {
kind
}
}
/// An owner's originals for the card on their page.
pub async fn card(st: &AppState, owner: Owner) -> anyhow::Result<Vec<Row>> {
let today = dates::today();
Ok(originals::of(&st.db, owner)
.await?
.iter()
.map(|l| row(l, today))
.collect())
}
#[derive(Debug, Default, Deserialize)]
pub struct ListQuery {
#[serde(default)]
show: String,
/// a code typed or scanned into the find box
#[serde(default)]
code: String,
}
pub async fn list(
State(st): State<Arc<AppState>>,
Extension(user): Extension<User>,
Query(q): Query<ListQuery>,
) -> Res {
if !q.code.trim().is_empty() {
return found(&st, &q.code).await;
}
let show = Show::from_slug(&q.show);
let today = dates::today();
let rows: Vec<Row> = originals::list(&st.db, show)
.await?
.iter()
.map(|l| row(l, today))
.collect();
let (held, out) = originals::counts(&st.db).await?;
let tab = |s: Show, label: String| {
let href = match s.slug() {
"" => "/originals".to_string(),
slug => format!("/originals?show={slug}"),
};
(href, label, s == show)
};
let tabs = vec![
tab(Show::InCare, format!("In our care ({})", held + out)),
tab(Show::Out, format!("Out ({out})")),
tab(Show::Held, format!("Held ({held})")),
tab(Show::Returned, "Returned".into()),
tab(Show::All, "All".into()),
];
Ok(page(
&st,
&user,
"originals.html",
"Originals",
"originals",
StatusCode::OK,
context! { rows, tabs, show => show.slug() },
))
}
async fn found(st: &AppState, code: &str) -> Res {
match originals::by_code(&st.db, code).await? {
Some(o) => Ok(Redirect::to(&format!("/originals/{}", o.o.code)).into_response()),
None => Ok(message(
st,
StatusCode::NOT_FOUND,
"No original with this code",
&format!(
"No original has the code {}. The code is on its label, such as OR-2026-0001.",
originals::clean_code(code)
),
("/originals", "Back to the originals"),
)),
}
}
// ------------------------------------------------------------- intake
#[derive(Debug, Default, Deserialize)]
pub struct NewQuery {
#[serde(default)]
client: Option<i64>,
#[serde(default)]
person: Option<i64>,
}
/// The owner from the form or the address: `client:3`, `person:7`.
fn owner_of(client: Option<i64>, person: Option<i64>) -> Option<Owner> {
match (client, person) {
(Some(c), None) => Some(Owner::Client(c)),
(None, Some(p)) => Some(Owner::Person(p)),
_ => None,
}
}
fn parse_owner(s: &str) -> Option<Owner> {
let (k, id) = s.split_once(':')?;
let id: i64 = id.parse().ok()?;
match k {
"client" => Some(Owner::Client(id)),
"person" => Some(Owner::Person(id)),
_ => None,
}
}
/// The owner's name and page, and for a client their contracts (code,
/// title) to tie an original to; None when there is no such owner.
async fn owner_facts(
st: &AppState,
owner: Owner,
) -> anyhow::Result<Option<(String, String, Vec<(i64, String)>)>> {
Ok(match owner {
Owner::Client(id) => {
let name: Option<String> = sqlx::query_scalar("SELECT name FROM clients WHERE id = $1")
.bind(id)
.fetch_optional(&st.db)
.await?;
match name {
Some(n) => {
let contracts: Vec<(i64, String)> = sqlx::query_as(
"SELECT id, code || ' ' || title FROM contracts WHERE client_id = $1 \
ORDER BY id DESC",
)
.bind(id)
.fetch_all(&st.db)
.await?;
Some((n, format!("/clients/{id}"), contracts))
}
None => None,
}
}
Owner::Person(id) => {
let name: Option<String> = sqlx::query_scalar(
"SELECT upper(surname) || ', ' || trim(first_name || ' ' || middle_name) \
FROM people WHERE id = $1",
)
.bind(id)
.fetch_optional(&st.db)
.await?;
name.map(|n| (n, format!("/people/{id}"), Vec::new()))
}
})
}
fn owner_slug(owner: Owner) -> String {
match owner {
Owner::Client(id) => format!("client:{id}"),
Owner::Person(id) => format!("person:{id}"),
}
}
async fn intake_form(
st: &AppState,
user: &User,
owner: Owner,
form: &New,
errors: &Errors,
status: StatusCode,
) -> Res {
let Some((owner_name, owner_href, contracts)) = owner_facts(st, owner).await? else {
return Ok(not_found_page(st));
};
let contracts: Vec<(String, String)> = contracts
.into_iter()
.map(|(id, t)| (id.to_string(), t))
.collect();
let locations = originals::locations(&st.db).await?;
Ok(page(
st,
user,
"original_form.html",
"Take in an original",
"originals",
status,
context! {
form,
errors,
owner => owner_slug(owner),
owner_name, owner_href, contracts, locations,
due_on => form.due_on.map(|d| d.to_string()).unwrap_or_default(),
contract => form.contract_id.map(|c| c.to_string()).unwrap_or_default(),
kinds => originals::KINDS,
},
))
}
pub async fn new(
State(st): State<Arc<AppState>>,
Extension(user): Extension<User>,
Query(q): Query<NewQuery>,
) -> Res {
let Some(owner) = owner_of(q.client, q.person) else {
return Ok(message(
&st,
StatusCode::BAD_REQUEST,
"Whose original is it?",
"Take an original in from the client's or the person's page: it belongs to them.",
("/originals", "Back to the originals"),
));
};
// the person themselves usually hands it over
let from = match owner_facts(&st, owner).await? {
Some((name, ..)) if matches!(owner, Owner::Person(_)) => name,
_ => String::new(),
};
let form = New {
received_from: from,
..New::default()
};
intake_form(&st, &user, owner, &form, &Errors::new(), StatusCode::OK).await
}
pub async fn create(
State(st): State<Arc<AppState>>,
Extension(user): Extension<User>,
Form(f): Form<Fields>,
) -> Res {
let g = |k: &str| forms::get(&f, k).trim().to_string();
let Some(owner) = parse_owner(&g("owner")) else {
return Ok(not_found_page(&st));
};
let Some((_, _, contracts)) = owner_facts(&st, owner).await? else {
return Ok(not_found_page(&st));
};
let mut errors = Errors::new();
let due_on = match g("due_on").as_str() {
"" => None,
s => match dates::parse_form_date(s) {
Ok(d) => Some(d),
Err(e) => {
err(&mut errors, "due_on", e);
None
}
},
};
let contract_id = match g("contract").as_str() {
"" => None,
s => match s.parse::<i64>() {
Ok(id) if contracts.iter().any(|(c, _)| *c == id) => Some(id),
_ => {
err(
&mut errors,
"contract",
"Choose one of this client's contracts, or none.",
);
None
}
},
};
let form = New {
kind: g("kind"),
what: g("what"),
received_from: g("received_from"),
location: g("location"),
due_on,
contract_id,
};
if crate::records::label(originals::KINDS, &form.kind).is_none() {
err(&mut errors, "kind", "Choose what kind of original it is.");
}
for (k, v, msg) in [
(
"what",
&form.what,
"Say what it is, such as: Passport C01X00T47, Germany.",
),
(
"received_from",
&form.received_from,
"Say who handed it over.",
),
(
"location",
&form.location,
"Say where it lies now, such as: Office, safe, tray 2.",
),
] {
if v.is_empty() {
err(&mut errors, k, msg);
} else if v.len() > 300 {
err(&mut errors, k, "At most 300 characters.");
}
}
if !errors.is_empty() {
return intake_form(
&st,
&user,
owner,
&form,
&errors,
StatusCode::UNPROCESSABLE_ENTITY,
)
.await;
}
let mut tx = st.db.begin().await?;
let o = originals::receive(&mut tx, owner, &form, &user.login).await?;
let listed = Listed {
o: o.clone(),
owner: String::new(),
contract_code: None,
};
audit::record(&mut *tx, &audit_entry(&user, Action::Create, &listed, &[])).await?;
tx.commit().await?;
Ok(Redirect::to(&format!("/originals/{}", o.code)).into_response())
}
// ------------------------------------------------------- the item's page
async fn item_view(
st: &AppState,
user: &User,
l: &Listed,
form: &Move,
errors: &Errors,
status: StatusCode,
) -> Res {
let history = super::legal::journal_views(originals::history(&st.db, &l.o.code).await?);
let locations = originals::locations(&st.db).await?;
if l.o.person_id.is_some() {
audit::record(&st.db, &audit_entry(user, Action::View, l, &[])).await?;
}
let r = row(l, dates::today());
let received = dates::fmt_datetime(l.o.received_at);
Ok(page(
st,
user,
"original.html",
&format!("{} {}", l.o.code, r.kind),
"originals",
status,
context! {
r, o => &l.o, history, locations, received, form, errors,
due_on => form.due_on.map(|d| d.to_string()).unwrap_or_default(),
states => originals::STATES,
holders => originals::HOLDERS,
},
))
}
/// The move form as the original is now: its own values to change.
fn move_of(o: &originals::Original) -> Move {
Move {
state: o.state.clone(),
location: o.location.clone(),
holder: o.holder.clone(),
due_on: o.due_on,
note: String::new(),
}
}
/// `/originals/OR-2026-0001`, the address in the label's QR code.
pub async fn show(
State(st): State<Arc<AppState>>,
Extension(user): Extension<User>,
Path(code): Path<String>,
) -> Res {
let Some(l) = originals::by_code(&st.db, &code).await? else {
return found(&st, &code).await;
};
// a scanner's lower case or a stray space: the clean address
if code != l.o.code {
return Ok(Redirect::to(&format!("/originals/{}", l.o.code)).into_response());
}
item_view(
&st,
&user,
&l,
&move_of(&l.o),
&Errors::new(),
StatusCode::OK,
)
.await
}
pub async fn move_original(
State(st): State<Arc<AppState>>,
Extension(user): Extension<User>,
Path(id): Path<i64>,
Form(f): Form<Fields>,
) -> Res {
let Some(l) = originals::get(&st.db, id).await? else {
return Ok(not_found_page(&st));
};
let g = |k: &str| forms::get(&f, k).trim().to_string();
let mut errors = Errors::new();
let due_on = match g("due_on").as_str() {
"" => None,
s => match dates::parse_form_date(s) {
Ok(d) => Some(d),
Err(e) => {
err(&mut errors, "due_on", e);
None
}
},
};
let state = g("state");
// the form asks "With whom" while out and "Returned to" once returned
let holder = if state == "returned" {
g("returned_to")
} else {
g("holder")
};
let m = Move {
state,
location: g("location"),
holder,
due_on,
note: g("note"),
};
for (k, msg) in m.problems() {
err(&mut errors, k, msg);
}
if !errors.is_empty() {
return item_view(
&st,
&user,
&l,
&m,
&errors,
StatusCode::UNPROCESSABLE_ENTITY,
)
.await;
}
let mut tx = st.db.begin().await?;
if originals::move_to(&mut tx, &l.o, &m, &user.login).await? {
let fields = ["state".to_string()];
audit::record(&mut *tx, &audit_entry(&user, Action::Update, &l, &fields)).await?;
}
tx.commit().await?;
Ok(Redirect::to(&format!("/originals/{}#history", l.o.code)).into_response())
}
/// The label for the original's envelope or folder: the code large, a QR
/// code to its page, whose it is and where it belongs.
pub async fn label(
State(st): State<Arc<AppState>>,
Extension(user): Extension<User>,
Path(id): Path<i64>,
) -> Res {
let Some(l) = originals::get(&st.db, id).await? else {
return Ok(not_found_page(&st));
};
if l.o.person_id.is_some() {
audit::record(&st.db, &audit_entry(&user, Action::View, &l, &[])).await?;
}
let url = format!("{}/originals/{}", st.cfg.public_url, l.o.code);
let qr = super::links::qr_svg(&url);
let received = dates::fmt_date(
l.o.received_at
.with_timezone(&dates::bangkok())
.date_naive(),
);
Ok(page(
&st,
&user,
"original_label.html",
&format!("Label {}", l.o.code),
"originals",
StatusCode::OK,
context! {
o => &l.o, owner => &l.owner, qr, url, received,
kind => kind_note(&l.o),
},
))
}