diff --git a/app/database/migrations/2026_12_03_000300_create_emails_table.rs b/app/database/migrations/2026_12_03_000300_create_emails_table.rs new file mode 100644 index 00000000..240e0138 --- /dev/null +++ b/app/database/migrations/2026_12_03_000300_create_emails_table.rs @@ -0,0 +1,37 @@ +use laravel::db::AnyTransaction; + +/// The emails outbox (ported as today's), and each person's email choices and sign-up notice. +pub async fn migrate(tx: &mut AnyTransaction<'_>) -> laravel::Result<()> { + tx.query( + "CREATE TABLE emails ( + id BIGSERIAL PRIMARY KEY, + kind TEXT NOT NULL, + dedupe_key TEXT NOT NULL UNIQUE, + organization_id BIGINT REFERENCES organizations(id) ON DELETE CASCADE, + user_id BIGINT REFERENCES users(id) ON DELETE CASCADE, + recipient TEXT NOT NULL, + data JSONB NOT NULL, + subject TEXT, + text_body TEXT, + html_body TEXT, + state TEXT NOT NULL DEFAULT 'pending' CHECK (state IN ('pending', 'sent', 'failed')), + attempts INTEGER NOT NULL DEFAULT 0, + last_error TEXT, + claimed_at TIMESTAMPTZ, + sent_at TIMESTAMPTZ, + dismissed_at TIMESTAMPTZ, + created_at TIMESTAMPTZ NOT NULL DEFAULT now(), + updated_at TIMESTAMPTZ NOT NULL DEFAULT now() + ); + CREATE INDEX emails_pending ON emails (created_at) WHERE state = 'pending'; + CREATE INDEX emails_organization ON emails (organization_id, created_at); + CREATE INDEX emails_failed ON emails (id) WHERE state = 'failed' AND dismissed_at IS NULL; + ALTER TABLE users + ADD COLUMN email_low_credits BOOLEAN NOT NULL DEFAULT true, + ADD COLUMN email_receipts BOOLEAN NOT NULL DEFAULT true, + ADD COLUMN signup_notified_at TIMESTAMPTZ;", + ) + .unprepared() + .await?; + Ok(()) +} diff --git a/app/src/auth/memberships.rs b/app/src/auth/memberships.rs index 38ac485e..4ea95108 100644 --- a/app/src/auth/memberships.rs +++ b/app/src/auth/memberships.rs @@ -21,6 +21,16 @@ pub struct MembershipChanged { pub organization_id: i64, pub user_id: i64, pub role: Option, + /// When the membership changed (milliseconds), fixed at dispatch: the notice's dedupe key, so a retried listener + /// doesn't send it twice. + pub changed_at: i64, +} + +impl MembershipChanged { + #[must_use] + pub fn now(organization_id: i64, user_id: i64, role: Option) -> Self { + Self { organization_id, user_id, role, changed_at: laravel::now().timestamp().as_millisecond() } + } } #[derive(Debug)] @@ -151,7 +161,7 @@ pub async fn apply( }) .await?; for (org, role) in ¬ices { - MembershipChanged { organization_id: *org, user_id, role: *role }.dispatch().await?; + MembershipChanged::now(*org, user_id, *role).dispatch().await?; } Ok(notices.len()) } diff --git a/app/src/billing/mod.rs b/app/src/billing/mod.rs new file mode 100644 index 00000000..d6f69286 --- /dev/null +++ b/app/src/billing/mod.rs @@ -0,0 +1,14 @@ +//! Billing (sc-8900, the billing side; ported from today's server as it moves over). For now, the credit pack the +//! emails quote. + +/// A pack of credits bought on top of a plan. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct CreditPack { + pub credits: i64, + pub price_cents: i64, + /// Automatic packs buy one when the balance falls below this. + pub reload_below: i64, +} + +/// One pack: 500,000 credits for $15, as today. +pub const CREDIT_PACK: CreditPack = CreditPack { credits: 500_000, price_cents: 1_500, reload_below: 100_000 }; diff --git a/app/src/heartbeat.rs b/app/src/heartbeat.rs new file mode 100644 index 00000000..abc91f2a --- /dev/null +++ b/app/src/heartbeat.rs @@ -0,0 +1,24 @@ +//! Scheduled work pushes its result to a Gatus external endpoint when one is configured (`_URL` and +//! `_TOKEN`, such as `VISUALCI_EMAILS_HEARTBEAT_URL`), so a run that failed, or no run at all, alerts. Ported +//! from today's server. + +use laravel::http::client; + +/// Push a run's result. A failed push only logs: Gatus alerts on the missing heartbeat instead. +pub async fn push(prefix: &str, result: Result<(), String>) { + let Ok(url) = std::env::var(format!("{prefix}_URL")) else { return }; + if url.is_empty() { + return; + } + let token = std::env::var(format!("{prefix}_TOKEN")).unwrap_or_default(); + let (success, error) = match result { + Ok(()) => ("true", String::new()), + Err(e) => ("false", e), + }; + let sent = client::post(url).token(token).query([("success", success), ("error", error.as_str())]).await; + match sent { + Ok(response) if response.successful() => {} + Ok(response) => tracing::warn!(prefix, status = %response.status(), "heartbeat refused"), + Err(e) => tracing::warn!(prefix, error = %e, "heartbeat failed"), + } +} diff --git a/app/src/lib.rs b/app/src/lib.rs index 8afdb3a9..698a7a31 100644 --- a/app/src/lib.rs +++ b/app/src/lib.rs @@ -1,12 +1,15 @@ //! VisualCI's server on Laravel Rust. Who owns which module, and the seams between them, are in sc-8900. pub mod auth; +pub mod billing; pub mod config; pub mod domain; pub mod forge; +pub mod heartbeat; pub mod http; pub mod listeners; pub mod models; +pub mod notify; #[path = "../database/seeders/mod.rs"] pub mod seeders; pub mod storage; diff --git a/app/src/notify/mod.rs b/app/src/notify/mod.rs new file mode 100644 index 00000000..2f29169e --- /dev/null +++ b/app/src/notify/mod.rs @@ -0,0 +1,30 @@ +//! Transactional emails (sc-8900, the emails side), ported from today's server. Each email is rendered from a +//! [`Kind`], recorded in the `emails` outbox under a `dedupe_key` that names the event and its period (so a threshold +//! emails once a month, an invoice once), and sent through Postmark by [`DeliverEmails`]: queued right after an email +//! is, and scheduled every five minutes for anything left over. A failed send stays pending and is retried; after five +//! attempts it's marked failed for staff to retry or dismiss. Billing emails go to an organization's billing email, or +//! else its admins; security emails go to the person concerned. People can turn off low-credit warnings and +//! receipt-style emails; security, billing problems and running out can't be. + +pub mod outbox; +pub mod postmark; +pub mod render; + +pub use outbox::{DeliverEmails, To, queue}; +pub use render::{About, Kind, Paused, Preference, Rendered, render}; + +use laravel::event::{Event, listener}; + +use crate::auth::memberships::MembershipChanged; + +/// Someone joined an organization or left it: tell them. +#[listener] +pub async fn membership_changed(event: Event) -> laravel::Result<()> { + let kind = match event.role { + Some(role) => Kind::AddedToOrg { role: role.as_str().to_string() }, + None => Kind::RemovedFromOrg, + }; + let key = format!("{}:{}:{}:{}", kind.name(), event.organization_id, event.user_id, event.changed_at); + queue(&kind, To::User(event.user_id), Some(event.organization_id), &key).await?; + Ok(()) +} diff --git a/app/src/notify/outbox.rs b/app/src/notify/outbox.rs new file mode 100644 index 00000000..888ed663 --- /dev/null +++ b/app/src/notify/outbox.rs @@ -0,0 +1,261 @@ +//! The `emails` outbox: queueing (once per dedupe key and recipient), delivery, and what staff and `/status` read. + +use laravel::db; +use laravel::queue::{Queueable, job}; +use laravel::schedule::{self, Schedule}; + +use super::postmark::{self, Postmark}; +use super::render::{About, Kind, Preference, render}; + +/// Who gets an email. +#[derive(Clone, Copy, Debug)] +pub enum To { + /// The organization's billing email, or else its admins (each one's preferences apply). + Billing(i64), + /// One person, by user ID. + User(i64), + /// The organization's admins (each one's preferences apply). + Admins(i64), +} + +/// The organization's admins who haven't turned this email off, with their user IDs. +async fn admins(org_id: i64, preference: Option) -> laravel::Result)>> { + let rows = match preference { + Some(Preference::LowCredits) => { + db::query!( + "SELECT u.id, u.email FROM memberships m JOIN users u ON u.id = m.user_id \ + WHERE m.organization_id = {org_id} AND m.role = 'admin' AND u.email_low_credits ORDER BY u.id" + ) + .select() + .await? + } + Some(Preference::Receipts) => { + db::query!( + "SELECT u.id, u.email FROM memberships m JOIN users u ON u.id = m.user_id \ + WHERE m.organization_id = {org_id} AND m.role = 'admin' AND u.email_receipts ORDER BY u.id" + ) + .select() + .await? + } + None => { + db::query!( + "SELECT u.id, u.email FROM memberships m JOIN users u ON u.id = m.user_id \ + WHERE m.organization_id = {org_id} AND m.role = 'admin' ORDER BY u.id" + ) + .select() + .await? + } + }; + rows.iter().map(|r| Ok((r.try_get::("email")?, Some(r.try_get::("id")?)))).collect() +} + +/// Record an email in the outbox, once per `dedupe_key` and recipient, and queue its delivery. It's rendered when it's +/// sent. Returns how many were queued: 0 when it was already queued, or everyone it would go to turned it off. +/// +/// # Errors +/// On a database error. +pub async fn queue(kind: &Kind, to: To, org_id: Option, dedupe_key: &str) -> laravel::Result { + let org_id = match to { + To::Billing(o) | To::Admins(o) => Some(o), + To::User(_) => org_id, + }; + let recipients: Vec<(String, Option)> = match to { + To::User(id) => db::query!("SELECT email FROM users WHERE id = {id}") + .scalar::() + .await? + .map(|e| vec![(e, Some(id))]) + .unwrap_or_default(), + To::Billing(o) => { + let billing: Option = db::query!("SELECT billing_email FROM organizations WHERE id = {o}") + .scalar::>() + .await? + .flatten() + .filter(|e| !e.trim().is_empty()); + match billing { + Some(e) => vec![(e.trim().to_string(), None)], + None => admins(o, kind.preference()).await?, + } + } + To::Admins(o) => admins(o, kind.preference()).await?, + }; + let data = serde_json::to_value(kind).map_err(|e| laravel::Error::msg(e.to_string()))?; + let name = kind.name(); + let mut queued = 0; + for (address, user_id) in recipients { + let key = format!("{dedupe_key}:{address}"); + let inserted: Option = db::query!( + "INSERT INTO emails (kind, dedupe_key, organization_id, user_id, recipient, data) \ + VALUES ({name}, {key}, {org_id}, {user_id}, {address}, {data}) \ + ON CONFLICT (dedupe_key) DO NOTHING RETURNING id" + ) + .scalar() + .await?; + queued += usize::from(inserted.is_some()); + } + if queued > 0 { + DeliverEmails.dispatch().await?; + } + Ok(queued) +} + +/// Send pending emails, up to 50 a run. Each is claimed just before it's sent, so two runs never send one twice; a +/// failure leaves it pending for the next run, and after five attempts it's marked failed. Without a Postmark token nothing is sent. +#[derive(Queueable, Clone, Debug, serde::Serialize, serde::Deserialize)] +pub struct DeliverEmails; + +#[job] +impl DeliverEmails { + async fn handle( + self, + postmark: laravel::config::Section, + app: laravel::config::Section, + ) -> laravel::Result<()> { + let delivered = deliver(&postmark, &app.url).await; + // The heartbeat checks the work, not just the run: an email waiting more than half an hour fails it + let health = match &delivered { + Err(e) => Err(e.to_string()), + Ok(_) => match oldest_unsent_seconds().await { + Ok(waited) if waited > STALE_SECONDS => Err(format!("the oldest unsent email has waited {waited}s")), + Ok(_) => Ok(()), + Err(e) => Err(e.to_string()), + }, + }; + crate::heartbeat::push("VISUALCI_EMAILS_HEARTBEAT", health).await; + delivered?; + Ok(()) + } +} + +/// How long an email may wait unsent before the heartbeat fails. +pub const STALE_SECONDS: i64 = 30 * 60; + +/// The web app's URL, for the links in emails. +#[derive(Clone, laravel::config::Section)] +pub struct AppUrl { + #[env("VISUALCI_APP_URL", default = "http://localhost")] + pub url: String, +} + +/// Anything left over (a failed send, a worker that stopped) goes out within five minutes. +#[schedule::tasks] +fn schedule(schedule: &mut Schedule) { + schedule.job(DeliverEmails).every_five_minutes().without_overlapping(); +} + +/// How long a claimed email waits before another run may take it: far longer than one send can take. +pub const RECLAIM_MINUTES: i64 = 30; +/// How long a failed send waits before it's tried again. +pub const RETRY_MINUTES: i64 = 5; + +/// Send what's pending. Returns how many were sent. +/// +/// # Errors +/// On a database error. +pub async fn deliver(config: &Postmark, app_url: &str) -> laravel::Result { + let Some(token) = config.token.as_deref().filter(|t| !t.is_empty()) else { return Ok(0) }; + // Anything a crashed run left claimed after its fifth attempt has had its tries. + let window = RECLAIM_MINUTES; + db::query!( + "UPDATE emails SET state = 'failed', claimed_at = NULL, \ + last_error = COALESCE(last_error, 'no result after five attempts'), updated_at = now() \ + WHERE state = 'pending' AND attempts >= 5 AND claimed_at < now() - make_interval(mins => {window}::int)" + ) + .update() + .await?; + let mut sent = 0; + // One at a time, each claimed just before it's sent: a claim only lapses after RECLAIM_MINUTES, far longer than one + // send can take, so a slow run's later emails are never taken by the next run while it's still sending. + for _ in 0..50 { + let Some(r) = db::query!( + "UPDATE emails SET claimed_at = now(), attempts = attempts + 1 WHERE id = ( \ + SELECT id FROM emails WHERE state = 'pending' AND attempts < 5 \ + AND (claimed_at IS NULL OR claimed_at < now() - make_interval(mins => {window}::int)) \ + ORDER BY id LIMIT 1 FOR UPDATE SKIP LOCKED) \ + RETURNING id, recipient, data, organization_id, attempts" + ) + .select_one() + .await? + else { + break; + }; + let id: i64 = r.try_get("id")?; + let to: String = r.try_get("recipient")?; + let attempts: i32 = r.try_get("attempts")?; + let org_id: Option = r.try_get("organization_id")?; + let data: serde_json::Value = r.try_get("data")?; + let Ok(kind) = serde_json::from_value::(data) else { + db::query!( + "UPDATE emails SET state = 'failed', last_error = 'unreadable data', updated_at = now() WHERE id = {id}" + ) + .update() + .await?; + continue; + }; + let (org_name, org_slug) = match org_id { + Some(o) => db::query!("SELECT name, slug FROM organizations WHERE id = {o}") + .select_one() + .await? + .map(|row| { + ( + row.try_get::("name").unwrap_or_default(), + row.try_get::("slug").unwrap_or_default(), + ) + }) + .unwrap_or_default(), + None => (String::new(), String::new()), + }; + let rendered = + render(&kind, &About { org_name: &org_name, org_slug: &org_slug, app_url: app_url.trim_end_matches('/') }); + match postmark::send(config, token, &to, &rendered.subject, &rendered.text, &rendered.html).await { + Ok(()) => { + let (subject, text, html) = (rendered.subject, rendered.text, rendered.html); + db::query!( + "UPDATE emails SET state = 'sent', sent_at = now(), claimed_at = NULL, last_error = NULL, \ + subject = {subject}, text_body = {text}, html_body = {html}, updated_at = now() WHERE id = {id}" + ) + .update() + .await?; + sent += 1; + } + Err(e) => { + let state = if attempts >= 5 { "failed" } else { "pending" }; + let error = e.to_string(); + // Its claim lapses in RETRY_MINUTES, so the next run tries again, never this one. + let hold = RECLAIM_MINUTES - RETRY_MINUTES; + db::query!( + "UPDATE emails SET state = {state}, last_error = {error}, updated_at = now(), \ + claimed_at = CASE WHEN {state} = 'failed' THEN NULL \ + ELSE now() - make_interval(mins => {hold}::int) END WHERE id = {id}" + ) + .update() + .await?; + tracing::warn!(email_id = id, error = %e, "an email wasn't sent"); + } + } + } + Ok(sent) +} + +/// How long the oldest unsent email has waited, for `/status`. +/// +/// # Errors +/// On a database error. +pub async fn oldest_unsent_seconds() -> laravel::Result { + Ok(db::query!( + "SELECT COALESCE(EXTRACT(EPOCH FROM now() - MIN(created_at)), 0)::BIGINT FROM emails WHERE state = 'pending'" + ) + .scalar::() + .await? + .unwrap_or(0)) +} + +/// Failed emails nobody has retried or dismissed yet, for `/status` (`emails_failed_unresolved`). +/// +/// # Errors +/// On a database error. +pub async fn failed_unresolved_count() -> laravel::Result { + Ok(db::query!("SELECT count(*) FROM emails WHERE state = 'failed' AND dismissed_at IS NULL") + .scalar::() + .await? + .unwrap_or(0)) +} diff --git a/app/src/notify/postmark.rs b/app/src/notify/postmark.rs new file mode 100644 index 00000000..78c4216b --- /dev/null +++ b/app/src/notify/postmark.rs @@ -0,0 +1,49 @@ +//! Sending one email through Postmark's API (`POSTMARK_SERVER_TOKEN`, `MAIL_FROM`, `MAIL_REPLY_TO`). Without a token, +//! nothing is sent and the outbox keeps the emails pending. + +use laravel::http::client; +use serde_json::json; + +#[derive(Clone, laravel::config::Section)] +pub struct Postmark { + #[env("POSTMARK_SERVER_TOKEN")] + pub token: Option, + #[env("MAIL_FROM", default = "VisualCI ")] + pub from: String, + #[env("MAIL_REPLY_TO", default = "support@visualci.com")] + pub reply_to: String, +} + +/// Send one email with its text and HTML bodies. +/// +/// # Errors +/// When Postmark can't be reached or refuses the message. +pub async fn send( + config: &Postmark, + token: &str, + to: &str, + subject: &str, + text: &str, + html: &str, +) -> laravel::Result<()> { + let body = json!({ + "From": config.from, + "To": to, + "ReplyTo": config.reply_to, + "Subject": subject, + "TextBody": text, + "HtmlBody": html, + "MessageStream": "outbound", + }); + let response = client::post("https://api.postmarkapp.com/email") + .header("X-Postmark-Server-Token", token) + .accept_json() + .timeout(std::time::Duration::from_secs(10)) + .json(&body) + .await?; + if !response.successful() { + let detail: serde_json::Value = response.json().unwrap_or_default(); + return Err(laravel::Error::msg(format!("Postmark: HTTP {}: {}", response.status(), detail["Message"]))); + } + Ok(()) +} diff --git a/app/src/notify/render.rs b/app/src/notify/render.rs new file mode 100644 index 00000000..6de6ad20 --- /dev/null +++ b/app/src/notify/render.rs @@ -0,0 +1,442 @@ +//! What each email VisualCI sends says (ported as is from today's server, sc-8900): every [`Kind`], rendered to a +//! subject, plain text and HTML ([`render`]). The outbox and delivery are in `notify::outbox`. + +use crate::billing::CREDIT_PACK; + +/// Why automatic packs stopped. +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +pub enum Paused { + Declined(String), + LimitReached(i32), +} + +/// Every email VisualCI sends to customers, with what it says. +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +pub enum Kind { + /// 80% or 95% of the plan's credits (or of the open source pool) used this month. + CreditsLow { + pool: bool, + percent: u8, + left: i64, + total: i64, + renews: String, + next: String, + }, + /// The plan's credits and packs are used up: builds fail with "out of credits". + OutOfCredits { + plan: String, + renews: String, + packs: bool, + }, + /// Automatic packs bought one. + PackBought { + packs_this_month: i64, + limit: i32, + invoice_url: Option, + }, + AutoBuyPaused(Paused), + PlanChanged { + from: String, + to: String, + }, + OpenSourceLost { + project: String, + reason: String, + }, + /// A public project's repository went private (or it was unlinked), so VisualCI made the project private. + MadePrivate { + project: String, + }, + /// A maintainer of the repository moved its link to their own organization: one organization per repository. + RepositoryMoved { + project: String, + repository: String, + to_org: String, + by: String, + }, + Welcome { + name: String, + }, + Invited { + inviter: String, + role: String, + }, + AddedToOrg { + role: String, + }, + RemovedFromOrg, + /// `client` is how the CLI names itself: `visualci CLI on ada-laptop`. + DeviceSignIn { + client: String, + at: String, + }, + TokenCreated { + name: String, + project: Option, + }, +} + +impl Kind { + /// The name the outbox, the admin MCP and the staff page use. + #[must_use] + pub const fn name(&self) -> &'static str { + match self { + Self::CreditsLow { .. } => "credits_low", + Self::OutOfCredits { .. } => "out_of_credits", + Self::PackBought { .. } => "pack_bought", + Self::AutoBuyPaused(_) => "auto_buy_paused", + Self::PlanChanged { .. } => "plan_changed", + Self::OpenSourceLost { .. } => "open_source_lost", + Self::MadePrivate { .. } => "made_private", + Self::RepositoryMoved { .. } => "repository_moved", + Self::Welcome { .. } => "welcome", + Self::Invited { .. } => "invited", + Self::AddedToOrg { .. } => "added_to_org", + Self::RemovedFromOrg => "removed_from_org", + Self::DeviceSignIn { .. } => "device_sign_in", + Self::TokenCreated { .. } => "token_created", + } + } + + /// Which preference can turn it off, if any. + #[must_use] + pub const fn preference(&self) -> Option { + match self { + Self::CreditsLow { .. } => Some(Preference::LowCredits), + Self::PackBought { .. } | Self::PlanChanged { .. } => Some(Preference::Receipts), + _ => None, + } + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Preference { + LowCredits, + Receipts, +} + +/// An email ready to send. +#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)] +pub struct Rendered { + pub subject: String, + pub text: String, + pub html: String, +} + +/// What an email is about: the organization (by name and slug) when it has one. +#[derive(Debug, Clone)] +pub struct About<'a> { + pub org_name: &'a str, + pub org_slug: &'a str, + pub app_url: &'a str, +} + +fn n(v: i64) -> String { + let s = v.abs().to_string(); + let mut out = String::new(); + for (i, c) in s.chars().enumerate() { + if i > 0 && (s.len() - i).is_multiple_of(3) { + out.push(','); + } + out.push(c); + } + if v < 0 { format!("-{out}") } else { out } +} + +fn money(cents: i64) -> String { + if cents % 100 == 0 { format!("${}", cents / 100) } else { format!("${}.{:02}", cents / 100, cents % 100) } +} + +fn escape(s: &str) -> String { + s.replace('&', "&").replace('<', "<").replace('>', ">").replace('"', """) +} + +/// A paragraph that starts with this is a line to copy: monospace in a box in the HTML, on its own line in the text. +const COPY: &str = "copy:"; + +/// The one-line setup prompt for a coding agent, as the app shows it. +pub const AGENT_PROMPT: &str = "Fetch https://visualci.com/install.md and follow it"; + +/// The email's HTML: its paragraphs and one button, in a plain single column. +fn html(paragraphs: &[String], button: (&str, &str)) -> String { + let body: String = paragraphs + .iter() + .map(|p| match p.strip_prefix(COPY) { + Some(line) => format!( + "
{}
", + escape(line) + ), + None => { + format!("

{}

", escape(p)) + } + }) + .collect(); + format!( + "\ +
\ +

VisualCI

{body}\ +

\ + {label}

\ +

\ + Questions? Reply to this email.

", + url = escape(button.1), + label = escape(button.0), + ) +} + +fn text(paragraphs: &[String], button: (&str, &str)) -> String { + let lines: Vec<&str> = paragraphs.iter().map(|p| p.strip_prefix(COPY).unwrap_or(p)).collect(); + let mut out = lines.join("\n\n"); + out.push_str(&format!("\n\n{}: {}\n\nQuestions? Reply to this email.\n", button.0, button.1)); + out +} + +/// Render an email. +#[must_use] +pub fn render(kind: &Kind, about: &About<'_>) -> Rendered { + let org = about.org_name; + let billing = format!("{}/{}/billing", about.app_url, about.org_slug); + let (subject, paragraphs, button): (String, Vec, (String, String)) = match kind { + Kind::CreditsLow { pool, percent, left, total, renews, next } => { + let what = if *pool { "open source credits" } else { "credits" }; + ( + format!("{org} has used {percent}% of this month's VisualCI {what}"), + vec![ + format!("{org} has {} of its {} {what} left this month. They renew on {renews}.", n(*left), n(*total)), + next.clone(), + ], + ("Open billing".into(), billing), + ) + } + Kind::OutOfCredits { plan, renews, packs } => ( + format!("{org} is out of VisualCI credits"), + vec![ + format!( + "{org} has used this month's credits on the {plan} plan and has no pack credits left. New builds \ + fail with an \"out of credits\" error instead of being compared, until the credits renew on {renews}." + ), + if *packs { + "Buy a credit pack, or turn on automatic packs, on the billing page.".to_string() + } else { + "Team includes 1,000,000 credits a month. Upgrade on the billing page.".to_string() + }, + ], + ("Open billing".into(), billing), + ), + Kind::PackBought { packs_this_month, limit, invoice_url } => ( + format!("VisualCI bought a credit pack for {org}"), + vec![ + format!( + "Credits were running low, so VisualCI bought a pack of {} credits for {} with {org}'s default card.", + n(CREDIT_PACK.credits), + money(CREDIT_PACK.price_cents) + ), + format!("That's {packs_this_month} of the {limit} automatic packs allowed this month."), + ], + match invoice_url { + Some(url) => ("View the invoice".into(), url.clone()), + None => ("Open billing".into(), billing), + }, + ), + Kind::AutoBuyPaused(Paused::Declined(reason)) => ( + format!("A VisualCI credit pack for {org} was declined"), + vec![ + format!("The card was declined ({reason}), so automatic credit packs are paused."), + "Update the card on the Payment methods tab, then save the automatic pack limit on the Plan tab to \ + turn them back on." + .to_string(), + ], + ("Payment methods".into(), format!("{billing}/payment-methods")), + ), + Kind::AutoBuyPaused(Paused::LimitReached(limit)) => ( + format!("{org} reached its limit of automatic credit packs"), + vec![ + format!("VisualCI has bought {limit} credit packs this month, the limit you set, so it won't buy more."), + "When the credits run out, builds stop being compared. Raise the limit or buy a pack on the billing page." + .to_string(), + ], + ("Open billing".into(), billing), + ), + Kind::PlanChanged { from, to } => ( + format!("{org} is now on the {to} plan"), + vec![format!("{org} moved from the {from} plan to the {to} plan. The change applies now.")], + ("Open billing".into(), billing), + ), + Kind::OpenSourceLost { project, reason } => ( + format!("{project} no longer uses VisualCI's open source credits"), + vec![ + format!("{project} isn't an open source project any more: {}.", sentence_part(reason)), + format!( + "Its builds use {org}'s plan credits from now on. If that's a mistake, fix the repository on \ + GitHub: VisualCI checks again when GitHub says it changed, and once a day." + ), + ], + ("Project settings".into(), format!("{}/{}/{project}?tab=settings", about.app_url, about.org_slug)), + ), + Kind::MadePrivate { project } => ( + format!("{project} is private now"), + vec![ + format!( + "The repository for {project} isn't public any more, so VisualCI made the project private too: \ + its builds, diffs and pull requests are no longer public." + ), + "If the repository is public again, an admin can make the project public in its settings.".to_string(), + ], + ("Project settings".into(), format!("{}/{}/{project}?tab=settings", about.app_url, about.org_slug)), + ), + Kind::RepositoryMoved { project, repository, to_org, by } => ( + format!("{repository} moved to another organization"), + vec![ + format!( + "{by}, a maintainer of {repository}, linked it to their organization {to_org} on VisualCI. A \ + repository belongs to one organization, so {project} isn't linked to it any more: its builds \ + no longer post checks or comments there." + ), + format!( + "If that's wrong, a maintainer of {repository} can link it to {project} again from the project's \ + settings, which moves it back." + ), + ], + ("Project settings".into(), format!("{}/{}/{project}?tab=settings", about.app_url, about.org_slug)), + ), + Kind::Welcome { name } => ( + "Welcome to VisualCI".to_string(), + vec![ + format!("Hi {name}, you're signed in to VisualCI."), + "To set it up, paste this into your coding agent:".to_string(), + format!("{COPY}{AGENT_PROMPT}"), + "It connects VisualCI's MCP server and adds a VisualCI step to your CI.".to_string(), + ], + ("Open VisualCI".into(), format!("{}/{}", about.app_url, about.org_slug).trim_end_matches('/').to_string()), + ), + Kind::Invited { inviter, role } => ( + format!("{inviter} invited you to {org} on VisualCI"), + vec![format!( + "{inviter} invited you to join {org} on VisualCI as {}. Sign in with this email address, or with GitHub, \ + and accept it there.", + article(role) + )], + ("See the invitation".into(), about.app_url.to_string()), + ), + Kind::AddedToOrg { role } => ( + format!("You joined {org} on VisualCI"), + vec![format!("You're now {} of {org} on VisualCI.", article(role))], + (format!("Open {org}"), format!("{}/{}", about.app_url, about.org_slug)), + ), + Kind::RemovedFromOrg => ( + format!("You were removed from {org} on VisualCI"), + vec![format!("You're no longer a member of {org} on VisualCI. Its admins can add you again.")], + ("Open VisualCI".into(), about.app_url.to_string()), + ), + Kind::DeviceSignIn { client, at } => ( + "The VisualCI CLI signed in as you".to_string(), + vec![ + format!("{client} signed in to your VisualCI account at {at}."), + "If that wasn't you, revoke it on your account page.".to_string(), + ], + ("Account".into(), format!("{}/account", about.app_url)), + ), + Kind::TokenCreated { name, project } => ( + format!("A new VisualCI token: {name}"), + vec![ + match project { + Some(p) => format!("A project token named \"{name}\" was created for {}/{p}.", about.org_slug), + None => format!("A personal token named \"{name}\" was created for your VisualCI account."), + }, + "If you didn't create it, delete it now.".to_string(), + ], + match project { + Some(p) => ("Project tokens".into(), format!("{}/{}/{p}?tab=tokens", about.app_url, about.org_slug)), + None => ("Account".into(), format!("{}/account", about.app_url)), + }, + ), + }; + let button = (button.0.as_str(), button.1.as_str()); + Rendered { text: text(¶graphs, button), html: html(¶graphs, button), subject } +} + +/// "Its repository is private." as part of a sentence: "its repository is private". +fn sentence_part(s: &str) -> String { + let s = s.trim().trim_end_matches('.'); + let mut c = s.chars(); + c.next().map_or_else(String::new, |f| f.to_lowercase().chain(c).collect()) +} + +fn article(role: &str) -> String { + let role = role.to_lowercase(); + if role.starts_with(['a', 'e', 'i', 'o', 'u']) { format!("an {role}") } else { format!("a {role}") } +} + +/// Every template with sample data, for the staff preview page and the snapshot tests. +#[must_use] +pub fn samples() -> Vec<(&'static str, Kind)> { + let renews = "1 January 2027".to_string(); + vec![ + ("Credits low (80%)", Kind::CreditsLow { + pool: false, + percent: 80, + left: 200_000, + total: 1_000_000, + renews: renews.clone(), + next: "When they run out, VisualCI buys a pack of 500,000 credits for $15 with the default card, up to 4 \ + packs this month." + .into(), + }), + ("Credits low (95%, Free)", Kind::CreditsLow { + pool: false, + percent: 95, + left: 1_250, + total: 25_000, + renews: renews.clone(), + next: "When they run out, builds aren't compared until the credits renew. Team includes 1,000,000 credits a month." + .into(), + }), + ("Open source credits low (80%)", Kind::CreditsLow { + pool: true, + percent: 80, + left: 200_000, + total: 1_000_000, + renews: renews.clone(), + next: "When they run out, open source projects use the plan's credits.".into(), + }), + ("Out of credits (Free)", Kind::OutOfCredits { plan: "Free".into(), renews: renews.clone(), packs: false }), + ("Out of credits (Team)", Kind::OutOfCredits { plan: "Team".into(), renews, packs: true }), + ("Pack bought", Kind::PackBought { + packs_this_month: 1, + limit: 4, + invoice_url: Some("https://invoice.stripe.com/i/acct_test/sample".into()), + }), + ("Automatic packs paused (declined)", Kind::AutoBuyPaused(Paused::Declined("your card has insufficient funds".into()))), + ("Automatic packs paused (limit)", Kind::AutoBuyPaused(Paused::LimitReached(4))), + ("Plan changed", Kind::PlanChanged { from: "Free".into(), to: "Team".into() }), + ("Open source status lost", Kind::OpenSourceLost { + project: "widgets".into(), + reason: "Its licence (BUSL-1.1) isn't OSI-approved.".into(), + }), + ("Project made private", Kind::MadePrivate { project: "widgets".into() }), + ( + "Repository moved", + Kind::RepositoryMoved { + project: "widgets".into(), + repository: "acme/widgets".into(), + to_org: "Acme".into(), + by: "Grace Hopper".into(), + }, + ), + ("Welcome", Kind::Welcome { name: "Ada".into() }), + ("Invitation", Kind::Invited { inviter: "Grace Hopper".into(), role: "member".into() }), + ("Added to an organization", Kind::AddedToOrg { role: "admin".into() }), + ("Removed from an organization", Kind::RemovedFromOrg), + ("CLI signed in", Kind::DeviceSignIn { + client: "visualci CLI on ada-laptop".into(), + at: "1 December 2026, 09:41 UTC".into(), + }), + ("Personal token created", Kind::TokenCreated { name: "Claude Code".into(), project: None }), + ("Project token created", Kind::TokenCreated { name: "GitHub Actions".into(), project: Some("web".into()) }), + ] +} diff --git a/app/tests/emails.rs b/app/tests/emails.rs new file mode 100644 index 00000000..e791dc18 --- /dev/null +++ b/app/tests/emails.rs @@ -0,0 +1,117 @@ +//! Emails: every kind renders; the outbox queues once per dedupe key and recipient, respects people's choices, and +//! sends through Postmark (faked), keeping a failed send pending for the next run. + +use app::models::User; +use app::notify::{self, Kind, To, outbox}; +use laravel::db; +use laravel::http::client; +use laravel::model::create; +use laravel::testing::prelude::*; + +#[test] +fn every_email_renders() { + let about = notify::About { org_name: "Acme", org_slug: "acme", app_url: "https://app.visualci.test" }; + for (label, kind) in notify::render::samples() { + let r = notify::render(&kind, &about); + assert!(!r.subject.is_empty() && !r.text.is_empty() && r.html.contains("<"), "{label}"); + } +} + +async fn org_with_admins() -> laravel::Result<(i64, User, User)> { + let org: i64 = db::query!( + "INSERT INTO organizations (pid, slug, name, created_at, updated_at) \ + VALUES (gen_random_uuid(), 'acme', 'Acme', now(), now()) RETURNING id" + ) + .scalar() + .await? + .expect("an id"); + let ada = create!(User { pid: laravel::str::uuid7(), name: "Ada", email: "ada@example.com", staff: false }).await?; + let bea = create!(User { pid: laravel::str::uuid7(), name: "Bea", email: "bea@example.com", staff: false }).await?; + for u in [ada.id, bea.id] { + db::query!( + "INSERT INTO memberships (organization_id, user_id, role, source, created_at, updated_at) \ + VALUES ({org}, {u}, 'admin', 'created', now(), now())" + ) + .insert() + .await?; + } + Ok((org, ada, bea)) +} + +fn postmark() -> Application { + app::testing::configure().with_env("POSTMARK_SERVER_TOKEN", "test-token").create() +} + +#[laravel::test(app = postmark)] +async fn the_outbox_queues_once_respects_choices_and_sends(_app: Application) -> laravel::Result<()> { + let (org, _ada, bea) = org_with_admins().await?; + let bea_id = bea.id; + db::query!("UPDATE users SET email_low_credits = false WHERE id = {bea_id}").update().await?; + let low = Kind::CreditsLow { + pool: false, + percent: 80, + left: 200_000, + total: 1_000_000, + renews: "1 January 2027".into(), + next: "1 January 2027".into(), + }; + let postmark = client::fake().with("api.postmarkapp.com/*", json!({ "MessageID": "x" })); + // Only Ada: Bea turned low-credit warnings off. The delivery job runs at once in tests (sync queue). + assert_eq!(notify::queue(&low, To::Billing(org), None, "credits_low:80:2026-12").await?, 1); + assert_eq!(notify::queue(&low, To::Billing(org), None, "credits_low:80:2026-12").await?, 0, "once per period"); + postmark.assert_sent_count(1); + let sent: Option = + db::query!("SELECT state FROM emails WHERE recipient = 'ada@example.com'").scalar().await?; + assert_eq!(sent.as_deref(), Some("sent")); + Ok(()) +} + +#[laravel::test(app = postmark)] +async fn a_failed_send_stays_pending_for_the_next_run(_app: Application) -> laravel::Result<()> { + let (org, _ada, _bea) = org_with_admins().await?; + let _postmark = + client::fake().with("api.postmarkapp.com/*", client::response().status(500).json(json!({ "Message": "down" }))); + notify::queue(&Kind::RemovedFromOrg, To::Admins(org), None, "removed:1").await?; + let rows = db::query!("SELECT state, attempts, last_error FROM emails ORDER BY id").select().await?; + assert_eq!(rows.len(), 2); + for r in rows { + assert_eq!(r.try_get::("state")?, "pending"); + assert_eq!(r.try_get::("attempts")?, 1); + assert!(r.try_get::("last_error")?.contains("down")); + } + assert!(outbox::oldest_unsent_seconds().await? >= 0); + assert_eq!(outbox::failed_unresolved_count().await?, 0, "pending, not failed, after one attempt"); + Ok(()) +} + +#[laravel::test(app = postmark)] +async fn claims_are_per_email_and_attempts_end_at_five(_app: Application) -> laravel::Result<()> { + let postmark = client::fake().with("api.postmarkapp.com/*", json!({ "MessageID": "x" })); + // A run that crashed during its fifth attempt, half an hour ago: failed, not sent a sixth time. + db::query!( + "INSERT INTO emails (kind, dedupe_key, recipient, data, attempts, claimed_at) \ + VALUES ('removed_from_org', 'crashed', 'ada@example.com', '\"RemovedFromOrg\"', 5, now() - interval '31 minutes')" + ) + .insert() + .await?; + // Another run is sending this one right now: left alone. + db::query!( + "INSERT INTO emails (kind, dedupe_key, recipient, data, attempts, claimed_at) \ + VALUES ('removed_from_org', 'in-flight', 'bea@example.com', '\"RemovedFromOrg\"', 1, now() - interval '6 minutes')" + ) + .insert() + .await?; + let config = app::notify::postmark::Postmark { + token: Some("test-token".into()), + from: "VisualCI ".into(), + reply_to: "support@visualci.com".into(), + }; + assert_eq!(outbox::deliver(&config, "https://app.visualci.com").await?, 0); + postmark.assert_nothing_sent(); + let state = |key: &'static str| async move { + db::query!("SELECT state FROM emails WHERE dedupe_key = {key}").scalar::().await + }; + assert_eq!(state("crashed").await?.as_deref(), Some("failed")); + assert_eq!(state("in-flight").await?.as_deref(), Some("pending")); + Ok(()) +}