Lanna Desk's larger work is contracts, general ones and artists', for clients who are Thai or foreign, people or organizations, with several lawyers in the team. The back office gets a Legal section (phase 9 in docs/PLAN.md): - Lawyers: license number, contact, the login of one who uses the app (then "My contracts"), in the team or left. - Clients, as record cards: person or organization, names in English and Thai, stage name or brand, a Thai ID number (checked), a passport or a registration number, the lawyer in charge. - Contracts: code LD-<year>-<n>, the general kinds and the artist kinds (recording, management, publishing, performance, license, merchandise), other party, status, lawyer, dates and value; a contract in force shows its notice day and its end ahead. Filters: general or artists, a lawyer, mine, those over. - Versions: a text kept here, a file (PDF or scan, encrypted as the client's document) or both. They never change: the database refuses UPDATE and DELETE, a version's file cannot be deleted and no document's checksum can change. Any version reads against the one before as a line diff. - Paper copies: the id <code>-P<n> to write on the paper or print as a 90 x 50 mm label with a QR code; where it lies, its state and holder, each move journaled; found again by its id. - The journal: every change in words, in the change's transaction, each entry chained to the one before by SHA-256. The database refuses to change, delete or truncate it; /journal checks the chain and every version's text and fingerprints against its entry, shows the last hash and exports CSV. The sidebar groups its sections: Legal, Visas and stays, Office. Demo data (seed-demo) adds three lawyers, six clients and seven contracts with versions, papers and moves. Documents take a third owner, the client (migration 0009). Checks: fmt, clippy, 115 unit and 62 integration tests (new: versions and the journal, the database refusing changes, a change around the app breaking the chain, paper ids and moves, the demo checking whole); screenshots of the new pages in light, dark and on a phone.
246 lines
8.4 KiB
Rust
246 lines
8.4 KiB
Rust
//! `visa [serve|migrate|seed-demo|files-check|files-migrate|files-mirror|version|help]`:
|
|
//! the server and its admin commands.
|
|
|
|
use std::path::PathBuf;
|
|
use std::process::ExitCode;
|
|
|
|
use anyhow::{Context, Result, bail, ensure};
|
|
use tracing::{info, warn};
|
|
|
|
use visa::config::Config;
|
|
use visa::files::{self, Store};
|
|
use visa::{dates, db, documents, seed, web};
|
|
|
|
const USAGE: &str = "\
|
|
visa: immigration records, deadlines and extension packs (Lanna Desk, lannadesk.com)
|
|
|
|
Usage: visa [COMMAND]
|
|
|
|
Commands:
|
|
serve run the web server (default); applies pending migrations first
|
|
migrate apply pending database migrations and exit
|
|
seed-demo add invented demo people and documents (local development only)
|
|
files-check read every document's file back and compare it with its upload;
|
|
list files without a document (exit status 1 on any problem)
|
|
files-migrate --from DIR
|
|
copy the documents' files from a files directory (the store
|
|
before the bucket, or a backup's mirror) into the store, each
|
|
checked against its upload; again is harmless
|
|
files-mirror --to DIR
|
|
make DIR hold exactly the store's files, still encrypted, for
|
|
the backups
|
|
version print the version and the commit it is built from (also --version)
|
|
help show this text
|
|
|
|
Settings come from the environment; see src/config.rs or README.md.";
|
|
|
|
#[tokio::main]
|
|
async fn main() -> ExitCode {
|
|
tracing_subscriber::fmt()
|
|
.with_max_level(tracing::Level::INFO)
|
|
.with_target(false)
|
|
.init();
|
|
let cmd = std::env::args().nth(1).unwrap_or_else(|| "serve".into());
|
|
match run(&cmd).await {
|
|
Ok(()) => ExitCode::SUCCESS,
|
|
Err(e) => {
|
|
eprintln!("visa: {e:#}");
|
|
ExitCode::FAILURE
|
|
}
|
|
}
|
|
}
|
|
|
|
/// The directory after `flag` on the command line.
|
|
fn dir_arg(flag: &str) -> Result<PathBuf> {
|
|
let args: Vec<String> = std::env::args().skip(2).collect();
|
|
match args.as_slice() {
|
|
[f, dir] if f == flag && !dir.is_empty() => Ok(PathBuf::from(dir)),
|
|
_ => bail!("give the directory as {flag} DIR; `visa help` lists the commands"),
|
|
}
|
|
}
|
|
|
|
/// The store the settings name; an error when documents are off.
|
|
fn store(cfg: &Config) -> Result<Store> {
|
|
let f = cfg
|
|
.files
|
|
.as_ref()
|
|
.context("documents are off here: no VISA_S3_BUCKET (or VISA_FILES_DIR) and file key")?;
|
|
Store::open(f)
|
|
}
|
|
|
|
async fn run(cmd: &str) -> Result<()> {
|
|
match cmd {
|
|
"serve" => serve().await,
|
|
// CI checks it, and cnx01 runs it before it installs a release
|
|
"version" | "--version" => {
|
|
println!(
|
|
"visa {} ({})",
|
|
env!("CARGO_PKG_VERSION"),
|
|
visa::embedded::COMMIT
|
|
);
|
|
Ok(())
|
|
}
|
|
"migrate" => {
|
|
let cfg = Config::from_env()?;
|
|
let pool = db::connect(&cfg).await?;
|
|
db::migrate(&pool).await?;
|
|
println!("migrations applied");
|
|
Ok(())
|
|
}
|
|
"seed-demo" => {
|
|
let cfg = Config::from_env()?;
|
|
ensure!(
|
|
!cfg.login_enabled(),
|
|
"seed-demo writes invented people and runs only in local development \
|
|
(VISA_INSECURE_NO_LOGIN=1, no VISA_OIDC_ISSUER)"
|
|
);
|
|
let pool = db::connect(&cfg).await?;
|
|
db::migrate(&pool).await?;
|
|
if seed::demo(&pool, dates::today()).await? {
|
|
println!("demo people added");
|
|
} else {
|
|
println!("demo people are there already");
|
|
}
|
|
match &cfg.files {
|
|
Some(_) => {
|
|
let store = store(&cfg)?;
|
|
let n = seed::demo_documents(&pool, &store, dates::today()).await?;
|
|
println!("demo documents added: {n}");
|
|
}
|
|
None => println!("no demo documents: documents are off (no place for them)"),
|
|
}
|
|
let store = cfg.files.as_ref().map(|_| store(&cfg)).transpose()?;
|
|
if seed::legal::demo(&pool, store.as_ref(), dates::today()).await? {
|
|
println!("demo clients and contracts added");
|
|
} else {
|
|
println!("demo clients and contracts are there already");
|
|
}
|
|
Ok(())
|
|
}
|
|
"files-check" => {
|
|
let cfg = Config::from_env()?;
|
|
let store = store(&cfg)?;
|
|
let pool = db::connect(&cfg).await?;
|
|
let check = documents::check(&pool, &store).await?;
|
|
for p in &check.problems {
|
|
println!("problem: {p}");
|
|
}
|
|
println!(
|
|
"{} documents checked in {} (file key {}): {} problems",
|
|
check.documents,
|
|
store.describe(),
|
|
store.key_id(),
|
|
check.problems.len()
|
|
);
|
|
ensure!(check.problems.is_empty(), "the files need attention");
|
|
Ok(())
|
|
}
|
|
"files-migrate" => {
|
|
let from = dir_arg("--from")?;
|
|
let cfg = Config::from_env()?;
|
|
let store = store(&cfg)?;
|
|
let pool = db::connect(&cfg).await?;
|
|
let moved = documents::migrate(&pool, &from, &store).await?;
|
|
for name in &moved.strays {
|
|
println!(
|
|
"left in {}: {name}, which is no document's file",
|
|
from.display()
|
|
);
|
|
}
|
|
for id in &moved.missing {
|
|
println!(
|
|
"problem: document {id} has no file in {} and none in the store",
|
|
from.display()
|
|
);
|
|
}
|
|
println!(
|
|
"{} files copied into {}, {} there already (file key {})",
|
|
moved.copied,
|
|
store.describe(),
|
|
moved.there,
|
|
store.key_id()
|
|
);
|
|
Ok(())
|
|
}
|
|
"files-mirror" => {
|
|
let to = dir_arg("--to")?;
|
|
let cfg = Config::from_env()?;
|
|
let store = store(&cfg)?;
|
|
let m = files::mirror(&store, &to).await?;
|
|
println!(
|
|
"{} mirrored into {}: {} copied, {} kept, {} removed",
|
|
store.describe(),
|
|
to.display(),
|
|
m.copied,
|
|
m.kept,
|
|
m.removed
|
|
);
|
|
Ok(())
|
|
}
|
|
"help" | "--help" | "-h" => {
|
|
println!("{USAGE}");
|
|
Ok(())
|
|
}
|
|
other => bail!("unknown command {other:?}; `visa help` lists the commands"),
|
|
}
|
|
}
|
|
|
|
async fn serve() -> Result<()> {
|
|
let cfg = Config::from_env()?;
|
|
let pool = db::connect(&cfg).await?;
|
|
db::migrate(&pool).await?;
|
|
let listen = cfg.listen;
|
|
let login = cfg.login_enabled();
|
|
let st = web::AppState::new(cfg, pool)?;
|
|
match &st.files {
|
|
Some(s) => {
|
|
info!("documents in {} (file key {})", s.describe(), s.key_id());
|
|
// A store that is not there yet (Garage starting) costs the
|
|
// documents, not the records: the check only warns, and the
|
|
// server listens meanwhile.
|
|
let s = s.clone();
|
|
tokio::spawn(async move {
|
|
match s.check().await {
|
|
Ok(()) => info!("documents: {} answers", s.describe()),
|
|
Err(e) => warn!("documents: {} does not answer yet: {e:#}", s.describe()),
|
|
}
|
|
});
|
|
}
|
|
None => info!("documents are off: no place for them (local development)"),
|
|
}
|
|
web::spawn_background(st.clone());
|
|
let app = web::router(st);
|
|
let listener = tokio::net::TcpListener::bind(listen)
|
|
.await
|
|
.with_context(|| format!("cannot listen on {listen}"))?;
|
|
if !login {
|
|
info!("no login: VISA_INSECURE_NO_LOGIN is set (loopback only)");
|
|
}
|
|
info!("listening on http://{listen}");
|
|
axum::serve(listener, app)
|
|
.with_graceful_shutdown(shutdown())
|
|
.await
|
|
.context("serving")?;
|
|
Ok(())
|
|
}
|
|
|
|
async fn shutdown() {
|
|
let ctrl_c = async {
|
|
let _ = tokio::signal::ctrl_c().await;
|
|
};
|
|
#[cfg(unix)]
|
|
let term = async {
|
|
if let Ok(mut s) = tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate())
|
|
{
|
|
s.recv().await;
|
|
}
|
|
};
|
|
#[cfg(not(unix))]
|
|
let term = std::future::pending::<()>();
|
|
tokio::select! {
|
|
_ = ctrl_c => {},
|
|
_ = term => {},
|
|
}
|
|
info!("shutting down");
|
|
}
|