//! The audit log (PDPA): who viewed or changed which record. It holds the //! names of changed fields, never their values, and the table refuses //! updates and deletes (migrations/0001_init.sql). use anyhow::Result; use chrono::{DateTime, Utc}; use serde::Serialize; use sqlx::{Executor, PgPool, Postgres}; use crate::dates; #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Action { View, Create, Update, Delete, Archive, Restore, SignIn, SignOut, /// A document's file saved to the browser's disk (opening it is a view). Download, /// The client sent what they filled in through their link. Send, /// Staff closed a client's link. Close, } impl Action { pub fn as_str(self) -> &'static str { match self { Action::View => "view", Action::Create => "create", Action::Update => "update", Action::Delete => "delete", Action::Archive => "archive", Action::Restore => "restore", Action::SignIn => "sign-in", Action::SignOut => "sign-out", Action::Download => "download", Action::Send => "send", Action::Close => "close", } } } #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Entity { Person, Passport, Address, Session, Company, Visa, Arrival, Extension, ReentryPermit, Report, WorkPermit, Document, /// A filled-in form, opened or downloaded; `fields` names the forms. Form, /// A client link (`links.rs`). Link, /// An agreement's text, published (`agreements`). Agreement, /// A client's signature of an agreement. Signature, } impl Entity { pub fn as_str(self) -> &'static str { match self { Entity::Person => "person", Entity::Passport => "passport", Entity::Address => "address", Entity::Session => "session", Entity::Company => "company", Entity::Visa => "visa", Entity::Arrival => "arrival", Entity::Extension => "extension", Entity::ReentryPermit => "reentry-permit", Entity::Report => "report", Entity::WorkPermit => "work-permit", Entity::Document => "document", Entity::Form => "form", Entity::Link => "link", Entity::Agreement => "agreement", Entity::Signature => "signature", } } } pub struct Entry<'a> { pub actor: &'a str, pub action: Action, pub entity: Entity, pub entity_id: Option, pub person_id: Option, /// The company a company's record or document belongs to. pub company_id: Option, pub fields: &'a [String], } /// Writes one entry; pass the transaction (`&mut *tx`) when the change it /// records is in one, so both commit or roll back together. pub async fn record<'e, E>(ex: E, e: &Entry<'_>) -> Result<()> where E: Executor<'e, Database = Postgres>, { sqlx::query( "INSERT INTO audit_log (actor, action, entity, entity_id, person_id, company_id, fields) \ VALUES ($1, $2, $3, $4, $5, $6, $7)", ) .bind(e.actor) .bind(e.action.as_str()) .bind(e.entity.as_str()) .bind(e.entity_id) .bind(e.person_id) .bind(e.company_id) .bind(e.fields) .execute(ex) .await?; Ok(()) } /// A view of a person's record. pub async fn viewed(db: &PgPool, actor: &str, entity: Entity, id: i64, person: i64) -> Result<()> { record( db, &Entry { actor, action: Action::View, entity, entity_id: Some(id), person_id: Some(person), company_id: None, fields: &[], }, ) .await } #[derive(Debug, sqlx::FromRow)] struct Row { id: i64, at: DateTime, actor: String, action: String, entity: String, entity_id: Option, person_id: Option, company_id: Option, fields: Vec, person_name: Option, company_name: Option, } #[derive(Debug, Serialize)] pub struct Item { pub id: i64, pub at: String, pub actor: String, pub action: String, pub what: String, pub person_id: Option, pub person_name: Option, pub company_id: Option, pub company_name: Option, pub fields: String, } /// The record's kind as people say it. fn noun(entity: &str) -> &str { match entity { "reentry-permit" => "re-entry permit", "work-permit" => "work permit", "report" => "90-day report", "link" => "client link", other => other, } } /// The newest entries first, for one person or for everyone. pub async fn recent(db: &PgPool, person: Option, limit: i64) -> Result> { let rows: Vec = sqlx::query_as( "SELECT a.id, a.at, a.actor, a.action, a.entity, a.entity_id, a.person_id, \ COALESCE(a.company_id, CASE WHEN a.entity = 'company' THEN a.entity_id END) \ AS company_id, a.fields, \ CASE WHEN p.id IS NULL THEN NULL \ ELSE upper(p.surname) || ', ' || trim(p.first_name || ' ' || p.middle_name) \ END AS person_name, c.name AS company_name \ FROM audit_log a LEFT JOIN people p ON p.id = a.person_id \ LEFT JOIN companies c \ ON c.id = COALESCE(a.company_id, CASE WHEN a.entity = 'company' THEN a.entity_id END) \ WHERE ($1::bigint IS NULL OR a.person_id = $1) \ ORDER BY a.id DESC LIMIT $2", ) .bind(person) .bind(limit) .fetch_all(db) .await?; Ok(rows .into_iter() .map(|r| { let what = match (r.entity.as_str(), r.entity_id) { ("session", _) => String::new(), ("company", _) => String::new(), (e, Some(id)) => format!("{} {id}", noun(e)), (e, None) => noun(e).to_string(), }; let company_id = r.company_id; Item { id: r.id, at: dates::fmt_datetime(r.at), actor: r.actor, action: r.action, what, person_id: r.person_id, person_name: r.person_name, company_id, company_name: r.company_name, fields: r.fields.join(", ").replace('_', " "), } }) .collect()) }