//! The Notifications page (phase 8): how the app reaches people, a test //! mail to see that it does, and the log of what went out. use std::sync::Arc; use axum::extract::{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, page}; use crate::anchor; use crate::config::MailSecurity; use crate::dates; use crate::forms::Fields; use crate::mail::{self, Entry, Outgoing}; use crate::session::User; #[derive(Debug, Default, Deserialize)] pub struct NotificationsQuery { /// The log line of a test just sent, to show how it went. #[serde(default)] sent: Option, /// What "Send the anchor now" did. #[serde(default)] anchor: Option, } #[derive(Debug, Serialize)] struct AnchorLine { day: String, seq: i64, hash: String, whole: bool, status: String, recipients: String, how: String, at: String, } /// What the anchor form shows again after a post. #[derive(Debug, Default)] struct AnchorForm { to: Option, error: String, done: String, } #[derive(Debug, Serialize)] struct Line { id: i64, channel: String, purpose: String, recipient: String, subject: String, status: String, detail: String, actor: String, at: String, } fn line(l: mail::Logged) -> Line { Line { id: l.id, at: dates::fmt_datetime(l.created_at), channel: l.channel, purpose: l.purpose, recipient: l.recipient, subject: l.subject, status: l.status, detail: l.detail, actor: l.actor, } } /// The mail settings as the page states them, without the password. #[derive(Debug, Serialize)] struct MailShown { from: String, server: String, security: &'static str, reply_to: Option, } async fn show( st: &AppState, user: &User, sent: Option, address: &str, error: &str, af: AnchorForm, ) -> Res { let mail = st.cfg.mail.as_ref().map(|m| MailShown { from: m.from.clone(), server: format!("{}:{}", m.host, m.port), security: match m.security { MailSecurity::Tls => "TLS", MailSecurity::StartTls => "STARTTLS", MailSecurity::None => "no TLS (a test server on this machine)", }, reply_to: m.reply_to.clone(), }); let result = match sent { Some(id) => mail::get(&st.db, id).await?.map(line), None => None, }; let address = if address.is_empty() { mail::last_test_address(&st.db, &user.login) .await? .unwrap_or_default() } else { address.to_string() }; let log: Vec = mail::recent(&st.db, 30) .await? .into_iter() .map(line) .collect(); let status = if error.is_empty() && af.error.is_empty() { StatusCode::OK } else { StatusCode::UNPROCESSABLE_ENTITY }; let anchor_to = match af.to { Some(t) => t, None => anchor::recipients(&st.db).await?.join(", "), }; let anchors: Vec = anchor::recent(&st.db, 7) .await? .into_iter() .map(|a| AnchorLine { day: dates::fmt_date(a.day), at: dates::fmt_datetime(a.at), seq: a.seq, hash: a.hash, whole: a.whole, status: a.status, recipients: a.recipients, how: a.how, }) .collect(); Ok(page( st, user, "notifications.html", "Notifications", "notifications", status, context! { mail, result, address, error, log, anchor_to, anchors, anchor_error => af.error, anchor_done => af.done, anchor_hour => anchor::HOUR, }, )) } pub async fn notifications( State(st): State>, Extension(user): Extension, Query(q): Query, ) -> Res { let done = match q.anchor.as_deref() { Some("sent") => "The anchor went out. The recipients' copies are in the log below.", Some("failed") => "The anchor did not reach every recipient: see the log below.", Some("nothing") => "Nothing was sent: the journal is still empty.", Some("saved") => "Saved. The change is in the journal.", _ => "", }; let af = AnchorForm { done: done.to_string(), ..AnchorForm::default() }; show(&st, &user, q.sent, "", "", af).await } /// Saves where the daily anchor goes. pub async fn anchor_to( State(st): State>, Extension(user): Extension, Form(f): Form, ) -> Res { let raw = crate::forms::get(&f, "anchor_to"); let to = anchor::split(&raw); let bad: Vec<&String> = to.iter().filter(|a| !mail::valid_address(a)).collect(); if !bad.is_empty() || to.len() > 10 { let error = if to.len() > 10 { "Ten addresses at most.".to_string() } else { format!( "Not an email address: {}.", bad.iter() .map(|s| s.as_str()) .collect::>() .join(", ") ) }; let af = AnchorForm { to: Some(raw.trim().to_string()), error, ..AnchorForm::default() }; return show(&st, &user, None, "", "", af).await; } anchor::set_recipients(&st.db, &to, &user.login).await?; Ok(Redirect::to("/notifications?anchor=saved#anchor").into_response()) } /// Sends the anchor at once, whatever the day's run did. pub async fn anchor_now(State(st): State>, Extension(user): Extension) -> Res { let out = anchor::send(&st.cfg, &st.db, false, &user.login, chrono::Utc::now()).await?; let said = match out { anchor::Outcome::Sent { failed: 0, .. } => "sent", anchor::Outcome::Sent { .. } => "failed", anchor::Outcome::Unchanged => "sent", anchor::Outcome::Nothing("the journal is empty") => "nothing", anchor::Outcome::Nothing(why) => { let af = AnchorForm { error: format!("Nothing was sent: {why}."), ..AnchorForm::default() }; return show(&st, &user, None, "", "", af).await; } }; Ok(Redirect::to(&format!("/notifications?anchor={said}#anchor")).into_response()) } /// Sends a test mail to the address given, logs how it went and shows it. pub async fn test_email( State(st): State>, Extension(user): Extension, Form(f): Form, ) -> Res { let to = crate::forms::get(&f, "to").trim().to_string(); let Some(cfg) = st.cfg.mail.as_ref() else { return show( &st, &user, None, &to, "Mail is not set up on this server.", AnchorForm::default(), ) .await; }; if !mail::valid_address(&to) { return show( &st, &user, None, &to, "Enter one email address, such as alex@buildfor.life.", AnchorForm::default(), ) .await; } let subject = "Test from Lanna Desk"; let text = format!( "This is a test of the notifications of Lanna Desk's back office ({url}).\n\n\ {who} sent it on {at}, Chiang Mai time. If it reached you, mail from the \ back office reaches this address.\n\n\ Lanna Desk\n", url = st.cfg.public_url, who = user.login, at = dates::fmt_datetime(chrono::Utc::now()), ); let hello = mail::hello_name(&st.cfg.public_url); let result = mail::send( cfg, &hello, &Outgoing { to: &to, subject, text: &text, }, ) .await; if let Err(e) = &result { tracing::warn!("test mail to {to} failed: {e:#}"); } let id = mail::log( &st.db, &Entry { channel: "email", purpose: "test", recipient: &to, subject, result: &result, actor: &user.login, }, ) .await?; Ok(Redirect::to(&format!("/notifications?sent={id}#result")).into_response()) }