//! Mail rules as stored: the list, the create/edit/delete writes and the enable switch. The rules //! themselves are evaluated in `rules_engine.rs`. Every write is checked here: the trigger and audience //! words, the column only for `status`, and the column and project belonging to the board. use turso::Connection; use super::{col_bool, col_opt_text, col_text, db_err, fetch_all, fetch_opt, new_id}; use crate::error::{Error, Result}; use crate::limits::RULE_SUBJECT_MAX; use crate::rules::{Audience, is_trigger}; use crate::store::Store; use crate::time::now_stamp; /// The longest rule name, in characters. pub const RULE_NAME_MAX: usize = 120; /// One rule as stored. #[derive(Debug, Clone, PartialEq, Eq)] pub struct MailRule { /// Rule id (ULID). pub id: String, /// The board it belongs to. pub board_id: String, /// The admin's name for it. pub name: String, /// The trigger word. pub trigger: String, /// Only for `status`: the column that must be entered; `None` is any column. pub column_id: Option, /// The project it is limited to; `None` is any project. pub tag_id: Option, /// Who is mailed. pub audience: Audience, /// Whether the mail carries the details block. pub include_details: bool, /// Whether the rule is on. pub enabled: bool, /// The subject template, with `{key}`, `{title}`, `{column}`, `{actor}`, `{tag}`, `{deadline}`. pub subject_template: String, /// UTC stamp of creation. pub created_at: String, } /// The fields of a rule as the admin enters them. The store checks them all. #[derive(Debug, Clone, PartialEq, Eq)] pub struct RuleInput { /// Name, 1 to 120 characters. pub name: String, /// The trigger word. pub trigger: String, /// Column, only with the `status` trigger. pub column_id: Option, /// Project, or `None` for any. pub tag_id: Option, /// Audience word. pub audience: String, /// Whether to include the details block. pub include_details: bool, /// Whether the rule is on. pub enabled: bool, /// Subject template, 1 to 120 characters. pub subject_template: String, } const RULE_COLS: &str = "id, board_id, name, trigger, column_id, tag_id, audience, include_details, enabled, \ subject_template, created_at"; fn map_rule(row: &turso::Row) -> Result { let audience_text = col_text(row, 6)?; let audience = Audience::parse(&audience_text) .ok_or_else(|| Error::Database(format!("unknown stored audience: {audience_text}")))?; Ok(MailRule { id: col_text(row, 0)?, board_id: col_text(row, 1)?, name: col_text(row, 2)?, trigger: col_text(row, 3)?, column_id: col_opt_text(row, 4)?, tag_id: col_opt_text(row, 5)?, audience, include_details: col_bool(row, 7)?, enabled: col_bool(row, 8)?, subject_template: col_text(row, 9)?, created_at: col_text(row, 10)?, }) } /// Checks the input and returns the cleaned copy. Every refusal is a message for the admin. async fn checked(conn: &Connection, board_id: &str, input: &RuleInput) -> Result { let name = crate::text::single_line(&input.name); if name.is_empty() || name.chars().count() > RULE_NAME_MAX { return Err(Error::Invalid(format!( "the name must be 1 to {RULE_NAME_MAX} characters" ))); } let trigger = input.trigger.trim().to_owned(); if !is_trigger(&trigger) { return Err(Error::Invalid("that trigger does not exist".into())); } let column_id = match input .column_id .as_deref() .map(str::trim) .filter(|c| !c.is_empty()) { None => None, Some(column) if trigger == "status" => { let live = fetch_opt( conn, "SELECT id FROM columns WHERE id = ?1 AND board_id = ?2 AND deleted_at IS NULL", (column.to_owned(), board_id.to_owned()), |row| col_text(row, 0), ) .await?; if live.is_none() { return Err(Error::Invalid("that column does not exist".into())); } Some(column.to_owned()) } Some(_) => { return Err(Error::Invalid( "only a status rule can name a column".into(), )); } }; let tag_id = match input .tag_id .as_deref() .map(str::trim) .filter(|t| !t.is_empty()) { None => None, Some(tag) => { let known = fetch_opt( conn, "SELECT id FROM tags WHERE id = ?1 AND board_id = ?2", (tag.to_owned(), board_id.to_owned()), |row| col_text(row, 0), ) .await?; if known.is_none() { return Err(Error::Invalid("that project does not exist".into())); } Some(tag.to_owned()) } }; let audience = input.audience.trim().to_owned(); if Audience::parse(&audience).is_none() { return Err(Error::Invalid("that audience does not exist".into())); } let subject_template = input.subject_template.trim().to_owned(); if subject_template.is_empty() || subject_template.chars().count() > RULE_SUBJECT_MAX { return Err(Error::Invalid(format!( "the subject must be 1 to {RULE_SUBJECT_MAX} characters" ))); } Ok(RuleInput { name, trigger, column_id, tag_id, audience, include_details: input.include_details, enabled: input.enabled, subject_template, }) } impl Store { /// Every rule of the board, oldest first. pub async fn list_rules(&self, board_id: &str) -> Result> { let conn = self.read_conn().await; fetch_all( &conn, &format!( "SELECT {RULE_COLS} FROM mail_rules WHERE board_id = ?1 ORDER BY created_at, id" ), (board_id.to_owned(),), map_rule, ) .await } /// One rule of the board, or `NotFound`. pub async fn rule(&self, board_id: &str, rule_id: &str) -> Result { let conn = self.read_conn().await; fetch_opt( &conn, &format!("SELECT {RULE_COLS} FROM mail_rules WHERE id = ?1 AND board_id = ?2"), (rule_id.to_owned(), board_id.to_owned()), map_rule, ) .await? .ok_or(Error::NotFound) } /// Creates a rule after checking it. Returns the stored rule. pub async fn create_rule(&self, board_id: &str, input: &RuleInput) -> Result { let conn = self.inner.conn.lock().await; let input = checked(&conn, board_id, input).await?; let id = new_id(); conn.execute( "INSERT INTO mail_rules (id, board_id, name, trigger, column_id, tag_id, audience, include_details, \ enabled, subject_template, created_at) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11)", ( id.clone(), board_id.to_owned(), input.name, input.trigger, input.column_id, input.tag_id, input.audience, i64::from(input.include_details), i64::from(input.enabled), input.subject_template, now_stamp(), ), ) .await .map_err(db_err)?; drop(conn); self.rule(board_id, &id).await } /// Replaces the fields of a rule after checking them. The rule keeps its id and creation time. pub async fn update_rule( &self, board_id: &str, rule_id: &str, input: &RuleInput, ) -> Result { let conn = self.inner.conn.lock().await; let input = checked(&conn, board_id, input).await?; let changed = conn .execute( "UPDATE mail_rules SET name = ?3, trigger = ?4, column_id = ?5, tag_id = ?6, audience = ?7, \ include_details = ?8, enabled = ?9, subject_template = ?10 WHERE id = ?1 AND board_id = ?2", ( rule_id.to_owned(), board_id.to_owned(), input.name, input.trigger, input.column_id, input.tag_id, input.audience, i64::from(input.include_details), i64::from(input.enabled), input.subject_template, ), ) .await .map_err(db_err)?; drop(conn); if changed == 0 { return Err(Error::NotFound); } self.rule(board_id, rule_id).await } /// Switches a rule on or off. pub async fn set_rule_enabled( &self, board_id: &str, rule_id: &str, enabled: bool, ) -> Result<()> { let conn = self.inner.conn.lock().await; let changed = conn .execute( "UPDATE mail_rules SET enabled = ?3 WHERE id = ?1 AND board_id = ?2", (rule_id.to_owned(), board_id.to_owned(), i64::from(enabled)), ) .await .map_err(db_err)?; if changed == 0 { return Err(Error::NotFound); } Ok(()) } /// Deletes a rule. Its outbox rows stay (the link to the rule is cleared), and its decisions go with it. pub async fn delete_rule(&self, board_id: &str, rule_id: &str) -> Result<()> { let conn = self.inner.conn.lock().await; let changed = conn .execute( "DELETE FROM mail_rules WHERE id = ?1 AND board_id = ?2", (rule_id.to_owned(), board_id.to_owned()), ) .await .map_err(db_err)?; if changed == 0 { return Err(Error::NotFound); } Ok(()) } }