diff --git a/app/database/migrations/2026_12_03_000500_add_heard_about_to_users.rs b/app/database/migrations/2026_12_03_000500_add_heard_about_to_users.rs new file mode 100644 index 00000000..a46492d1 --- /dev/null +++ b/app/database/migrations/2026_12_03_000500_add_heard_about_to_users.rs @@ -0,0 +1,15 @@ +use laravel::db::AnyTransaction; + +/// "How did you hear about VisualCI?" (asked once after sign-up), ported as today's. +pub async fn migrate(tx: &mut AnyTransaction<'_>) -> laravel::Result<()> { + tx.query( + "ALTER TABLE users + ADD COLUMN heard_about_pending BOOLEAN NOT NULL DEFAULT false, + ADD COLUMN heard_about_source TEXT, + ADD COLUMN heard_about_detail TEXT; + CREATE INDEX users_signup_unnotified ON users (id) WHERE signup_notified_at IS NULL;", + ) + .unprepared() + .await?; + Ok(()) +} diff --git a/app/src/auth/me.rs b/app/src/auth/me.rs new file mode 100644 index 00000000..30dd4c56 --- /dev/null +++ b/app/src/auth/me.rs @@ -0,0 +1,459 @@ +//! The signed-in person's own page (sc-8900, the auth side), ported from today's server: `GET /api/ui/me` (who they +//! are, their organizations, their pending invitations, their email choices), turning low-credit and receipt emails +//! on or off, an organization's billing email, and "How did you hear about VisualCI?". Also the team's email about +//! each new sign-up, which waits for that answer. + +use laravel::auth::Authenticated; +use laravel::db; +use laravel::prelude::*; +use laravel::queue::{Queueable, job}; +use laravel::schedule::{self, Schedule}; +use serde_json::{Value, json}; + +use super::Role; +use super::invitations::{self, Invitee}; +use crate::models::User; +use crate::notify::outbox::AppUrl; +use crate::notify::{self, Kind, To}; + +pub fn routes(route: &mut Router) { + route.get("/api/ui/me", me); + route.patch("/api/ui/me/notifications", update_notifications); + route.post("/api/ui/me/heard-about", heard_about); + route.put("/api/ui/orgs/{org}/billing-email", update_billing_email); +} + +/// An answer to "How did you hear about VisualCI?". The keys are stored, so a label can change but a key can't. +#[derive(Clone, Copy, Debug, serde::Serialize)] +pub struct Choice { + pub key: &'static str, + /// On the card. + pub label: &'static str, + /// On /staff and in the admin tools: "AI assistant: Claude". + pub short_label: &'static str, + /// The text box's label, for the answers that have one. + pub detail_label: Option<&'static str>, +} + +pub const DETAIL_MAX: usize = 255; + +pub const OPTIONS: &[Choice] = &[ + Choice { + key: "search", + label: "Search engine", + short_label: "Search", + detail_label: Some("What did you search for?"), + }, + Choice { + key: "ai_assistant", + label: "AI Assistant (ChatGPT, Claude, etc.)", + short_label: "AI assistant", + detail_label: Some("Which one?"), + }, + Choice { key: "colleague", label: "Colleague or friend", short_label: "Colleague or friend", detail_label: None }, + Choice { + key: "article", + label: "Blog post or article", + short_label: "Blog post or article", + detail_label: Some("Which one?"), + }, + Choice { + key: "social", + label: "Social media (X, LinkedIn, Reddit, etc.)", + short_label: "Social media", + detail_label: Some("Which one?"), + }, + Choice { + key: "directory", + label: "Directory (MCP, software, etc.)", + short_label: "Directory", + detail_label: Some("Which one?"), + }, + Choice { key: "github", label: "GitHub", short_label: "GitHub", detail_label: None }, + Choice { key: "other", label: "Other", short_label: "Other", detail_label: Some("Where did you hear about us?") }, +]; + +/// What's stored: a key we offer (else nothing) and its detail as one clean line of at most 255 characters. An answer +/// we don't offer is dropped, never refused. +#[must_use] +pub fn clean(source: Option<&str>, detail: Option<&str>) -> (Option, Option) { + let Some(option) = source.and_then(|s| OPTIONS.iter().find(|o| o.key == s)) else { return (None, None) }; + let detail = detail + .map(|d| d.chars().map(|c| if c.is_control() { ' ' } else { c }).collect::()) + .map(|d| d.split_whitespace().collect::>().join(" ")) + .map(|d| d.chars().take(DETAIL_MAX).collect::()) + .filter(|d| !d.is_empty() && option.detail_label.is_some()); + (Some(option.key.to_string()), detail) +} + +/// "AI assistant: Claude", or `None` when there's no answer. +#[must_use] +pub fn summary(source: Option<&str>, detail: Option<&str>) -> Option { + let source = source.filter(|s| !s.is_empty())?; + let label = OPTIONS.iter().find(|o| o.key == source).map_or(source, |o| o.short_label); + Some(match detail.filter(|d| !d.is_empty()) { + Some(d) => format!("{label}: {d}"), + None => label.to_string(), + }) +} + +/// `GET /api/ui/me`. +/// The forges a person can sign in with here: those whose OAuth application has its ID and secret. +#[derive(Clone, laravel::config::Section)] +pub struct SignInApps { + #[env("GITHUB_CLIENT_ID")] + pub github_id: Option, + #[env("GITHUB_CLIENT_SECRET")] + pub github_secret: Option, + #[env("GITLAB_CLIENT_ID")] + pub gitlab_id: Option, + #[env("GITLAB_CLIENT_SECRET")] + pub gitlab_secret: Option, +} + +impl SignInApps { + #[must_use] + pub fn forges(&self) -> Vec<&'static str> { + let set = |v: &Option| v.as_deref().is_some_and(|s| !s.trim().is_empty()); + let mut forges = Vec::new(); + if set(&self.github_id) && set(&self.github_secret) { + forges.push("github"); + } + if set(&self.gitlab_id) && set(&self.gitlab_secret) { + forges.push("gitlab"); + } + forges + } +} + +pub async fn me( + Authenticated(user): Authenticated, + apps: laravel::config::Section, +) -> laravel::Result> { + let user_id = user.id; + let row = db::query!( + "SELECT staff, heard_about_pending, email_low_credits, email_receipts, \ + COALESCE((SELECT json_agg(json_build_object('forge', forge, 'login', login) ORDER BY id) \ + FROM identities WHERE user_id = {user_id}), '[]'::json)::text AS identities, \ + COALESCE((SELECT json_agg(json_build_object('id', o.id, 'slug', o.slug, 'name', o.name, 'role', m.role) \ + ORDER BY o.name) FROM memberships m JOIN organizations o ON o.id = m.organization_id \ + WHERE m.user_id = {user_id}), '[]'::json)::text AS organizations \ + FROM users WHERE id = {user_id}" + ) + .select_one() + .await? + .ok_or_else(|| laravel::abort(401))?; + let identities: Value = serde_json::from_str(&row.try_get::("identities")?).unwrap_or_default(); + let mut organizations: Value = serde_json::from_str(&row.try_get::("organizations")?).unwrap_or_default(); + // Each organization's plan and credits this month, as the domain computes them (OrgsPage reads usage.plan.name) + if let Some(list) = organizations.as_array_mut() { + for org in list.iter_mut() { + let Some(id) = org.get("id").and_then(Value::as_i64) else { continue }; + let usage = match crate::models::Organization::find(id).await? { + Some(o) => crate::domain::credits::usage(&o).await?, + None => Value::Null, + }; + if let Some(o) = org.as_object_mut() { + o.remove("id"); + o.insert("usage".into(), usage); + } + } + } + Ok(Json(json!({ + "user": { + "name": user.name, "email": user.email, "avatar_url": user.avatar_url, + "login": identities.get(0).and_then(|i| i.get("login")).cloned(), "identities": identities, + }, + "forges": apps.forges(), + "organizations": organizations, + "invitations": invitations::pending_for(&user).await?, + "staff": row.try_get::("staff")?, + // Ask "How did you hear about VisualCI?" (once, after sign-up), with these choices. + "heard_about_pending": row.try_get::("heard_about_pending")?, + "heard_about_options": OPTIONS, + // Emails people can turn off; security emails, billing problems and running out of credits always go. + "notifications": { + "low_credits": row.try_get::("email_low_credits")?, + "receipts": row.try_get::("email_receipts")?, + }, + }))) +} + +#[laravel::input] +#[validate(authenticated)] +pub struct NotificationsInput { + low_credits: Option, + receipts: Option, +} + +/// `PATCH /api/ui/me/notifications`: turn low-credit warnings or receipt-style emails on or off for yourself. +pub async fn update_notifications( + Authenticated(user): Authenticated, + Valid(p): Valid, +) -> laravel::Result> { + let (user_id, low_credits, receipts) = (user.id, p.low_credits, p.receipts); + let row = db::query!( + "UPDATE users SET email_low_credits = COALESCE({low_credits}, email_low_credits), \ + email_receipts = COALESCE({receipts}, email_receipts), updated_at = now() \ + WHERE id = {user_id} RETURNING email_low_credits, email_receipts" + ) + .select_one() + .await? + .ok_or_else(|| laravel::abort(401))?; + Ok(Json(json!({ + "low_credits": row.try_get::("email_low_credits")?, + "receipts": row.try_get::("email_receipts")?, + }))) +} + +#[laravel::input] +#[validate(authenticated)] +pub struct HeardAboutInput { + skip: Option, + source: Option, + detail: Option, +} + +/// `POST /api/ui/me/heard-about`: an answer, or Skip. Either way it isn't asked again, and the team's email about +/// the sign-up, which waits for it, goes out. +pub async fn heard_about( + Authenticated(user): Authenticated, + Valid(p): Valid, +) -> laravel::Result> { + let (source, detail) = if p.skip.unwrap_or(false) { + (None, None) + } else { + clean(p.source.as_ref().and_then(Value::as_str), p.detail.as_ref().and_then(Value::as_str)) + }; + let user_id = user.id; + db::query!( + "UPDATE users SET heard_about_pending = false, \ + heard_about_source = COALESCE({source}, heard_about_source), \ + heard_about_detail = CASE WHEN {source}::text IS NULL THEN heard_about_detail ELSE {detail} END, \ + updated_at = now() WHERE id = {user_id}" + ) + .update() + .await?; + NotifySignups.dispatch().await?; + Ok(Json(json!({ "ok": true }))) +} + +#[laravel::input] +#[validate(authenticated)] +pub struct BillingEmailInput { + /// Empty sends billing emails to the admins again. + #[validate(max_length(320))] + billing_email: Option, +} + +/// `PUT /api/ui/orgs/{org}/billing-email` (admins): where billing emails go instead of the admins. +pub async fn update_billing_email( + Authenticated(user): Authenticated, + Params(org): Params, + Valid(p): Valid, +) -> laravel::Result> { + let user_id = user.id; + let row = db::query!( + "SELECT o.id, m.role FROM organizations o \ + LEFT JOIN memberships m ON m.organization_id = o.id AND m.user_id = {user_id} WHERE o.slug = {org}" + ) + .select_one() + .await? + .ok_or_else(|| laravel::abort(404))?; + let org_id: i64 = row.try_get("id")?; + match row.try_get::>("role")?.as_deref().and_then(Role::parse) { + Some(Role::Admin) => {} + Some(_) => return Err(laravel::abort_with(403, "only admins can change the billing email")), + None => return Err(laravel::abort(404)), + } + let email = p.billing_email.as_deref().unwrap_or("").trim(); + if !email.is_empty() && !matches!(Invitee::parse(email), Ok(Invitee::Email(_))) { + return Err(laravel::abort_with(422, format!("{email:?} isn't an email address"))); + } + let email = (!email.is_empty()).then(|| email.to_lowercase()); + db::query!("UPDATE organizations SET billing_email = {email}, updated_at = now() WHERE id = {org_id}") + .update() + .await?; + Ok(Json(json!({ "billing_email": email }))) +} + +/// The team's address for sign-up emails. +#[derive(Clone, laravel::config::Section)] +pub struct Team { + #[env("VISUALCI_TEAM_EMAIL", default = "support@visualci.com")] + pub email: String, +} + +/// How long after sign-up the team's email waits for "How did you hear". +pub const WAIT_MINUTES: i64 = 10; + +/// The team's email's text: who, how they signed up and heard about VisualCI, their organizations, and anything they +/// asked for. +#[must_use] +pub fn signup_text( + who: &str, + signup_via: Option<&str>, + heard: &str, + orgs: &[String], + requests: &[String], + app_url: &str, +) -> String { + let mut lines = vec![ + format!("New sign-up: {who}"), + format!("Signed up with: {}", signup_via.unwrap_or("unknown")), + format!("Heard about VisualCI from: {heard}"), + ]; + for org in orgs { + lines.push(format!("Organization: {app_url}/{org}")); + } + if requests.is_empty() { + lines.push("They haven't asked for anything yet.".to_string()); + } else { + lines.push(String::new()); + lines.push("What they need from VisualCI:".to_string()); + for r in requests { + lines.push(String::new()); + lines.push(r.clone()); + } + } + lines.push(String::new()); + lines.push(format!("All sign-ups: {app_url}/staff. Replying to this email reaches them.")); + lines.join("\n") +} + +/// Queue the team's email about every sign-up that's ready (answered or skipped, or past the wait), up to 20 a run. +/// The outbox sends it (with retries, and its own heartbeat); the dedupe key makes a second run's copy a no-op. +/// Returns how many were queued. +/// +/// # Errors +/// On a database error. +pub async fn queue_signups(team: &Team, app_url: &str) -> laravel::Result { + let wait = WAIT_MINUTES; + let ready = db::query!( + "SELECT id, name, email, signup_via, heard_about_pending, heard_about_source, heard_about_detail, \ + (SELECT login FROM identities WHERE user_id = users.id ORDER BY id LIMIT 1) AS login \ + FROM users WHERE signup_notified_at IS NULL \ + AND (NOT heard_about_pending OR created_at < now() - make_interval(mins => {wait}::int)) \ + ORDER BY id LIMIT 20" + ) + .select() + .await?; + let app_url = app_url.trim_end_matches('/'); + let mut queued = 0; + for u in ready { + let id: i64 = u.try_get("id")?; + let (name, email): (String, String) = (u.try_get("name")?, u.try_get("email")?); + let login: Option = u.try_get("login")?; + let source: Option = u.try_get("heard_about_source")?; + let detail: Option = u.try_get("heard_about_detail")?; + let heard = match summary(source.as_deref(), detail.as_deref()) { + Some(s) => s, + None if u.try_get::("heard_about_pending")? => "not answered yet".to_string(), + None => "skipped".to_string(), + }; + let orgs: Vec = db::query!( + "SELECT o.slug FROM memberships m JOIN organizations o ON o.id = m.organization_id \ + WHERE m.user_id = {id} ORDER BY o.id" + ) + .select() + .await? + .iter() + .map(|r| r.try_get("slug")) + .collect::>()?; + let requests: Vec = + db::query!("SELECT description FROM feedback WHERE user_id = {id} AND kind = 'request' ORDER BY id") + .select() + .await? + .iter() + .map(|r| r.try_get("description")) + .collect::>()?; + let who = match &login { + Some(l) => format!("{name} (@{l}) <{email}>"), + None => format!("{name} <{email}>"), + }; + let signup_via: Option = u.try_get("signup_via")?; + let text = signup_text(&who, signup_via.as_deref(), &heard, &orgs, &requests, app_url); + let subject = format!("New VisualCI sign-up: {}", login.as_deref().unwrap_or(&name)); + let kind = Kind::NewSignup { subject, text, reply_to: email }; + notify::queue(&kind, To::Address(team.email.clone()), None, &format!("new_signup:{id}")).await?; + db::query!("UPDATE users SET signup_notified_at = now() WHERE id = {id}").update().await?; + queued += 1; + } + Ok(queued) +} + +/// How long a ready sign-up may wait before the heartbeat fails: the schedule runs every minute. +pub const STALE_MINUTES: i64 = 30; + +/// Queue the team's sign-up emails; pushes `VISUALCI_SIGNUPS_HEARTBEAT`, failing when one ready sign-up has waited +/// more than half an hour (the job stopped running, or keeps failing). +#[derive(Queueable, Clone, Debug, serde::Serialize, serde::Deserialize)] +pub struct NotifySignups; + +#[job] +impl NotifySignups { + async fn handle( + self, + team: laravel::config::Section, + app: laravel::config::Section, + ) -> laravel::Result<()> { + let result = queue_signups(&team, &app.url).await; + let stale = WAIT_MINUTES + STALE_MINUTES; + let waiting = db::query!( + "SELECT count(*) FROM users WHERE signup_notified_at IS NULL \ + AND created_at < now() - make_interval(mins => {stale}::int)" + ) + .scalar::() + .await; + // A database that can't answer fails the heartbeat too. + let health = match (&result, waiting) { + (Err(e), _) => Err(e.to_string()), + (Ok(_), Err(e)) => Err(e.to_string()), + (Ok(_), Ok(Some(n))) if n > 0 => { + Err(format!("{n} sign-ups waited over {stale} minutes for the team's email")) + } + _ => Ok(()), + }; + crate::heartbeat::push("VISUALCI_SIGNUPS_HEARTBEAT", health).await; + result.map(|_| ()) + } +} + +#[schedule::tasks] +fn schedule(schedule: &mut Schedule) { + schedule.job(NotifySignups).every_minute().without_overlapping(); +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn answers_are_cleaned_and_summarised() { + assert_eq!( + clean(Some("ai_assistant"), Some(" Claude\n ")), + (Some("ai_assistant".into()), Some("Claude".into())) + ); + assert_eq!(clean(Some("colleague"), Some("Bob")), (Some("colleague".into()), None)); + assert_eq!(clean(Some("made-up"), Some("x")), (None, None)); + assert_eq!(summary(Some("ai_assistant"), Some("Claude")).as_deref(), Some("AI assistant: Claude")); + assert_eq!(summary(None, None), None); + } + + #[test] + fn the_team_email_says_who_how_and_what_they_asked_for() { + let text = signup_text( + "Ada (@ada) ", + Some("github, from an MCP client's sign-in"), + "AI assistant: Claude", + &["ada".into()], + &["Buildkite with Cypress".into()], + "https://app.visualci.com", + ); + assert!(text.contains("New sign-up: Ada (@ada) "), "{text}"); + assert!(text.contains("Signed up with: github, from an MCP client's sign-in")); + assert!(text.contains("Heard about VisualCI from: AI assistant: Claude")); + assert!(text.contains("Organization: https://app.visualci.com/ada")); + assert!(text.contains("Buildkite with Cypress")); + } +} diff --git a/app/src/auth/mod.rs b/app/src/auth/mod.rs index 79e3e7fb..5a04ea03 100644 --- a/app/src/auth/mod.rs +++ b/app/src/auth/mod.rs @@ -9,6 +9,7 @@ //! Nobody found: `401`. pub mod invitations; +pub mod me; pub mod memberships; pub mod oauth; pub mod orgs; @@ -267,6 +268,7 @@ pub fn routes(route: &mut laravel::prelude::Router) { tokens::routes(route); invitations::routes(route); orgs::routes(route); + me::routes(route); route.get("/auth/{forge}", sign_in::start); route.post("/auth/{forge}/link", sign_in::link); route.get("/auth/{forge}/callback", sign_in::callback); diff --git a/app/src/auth/sign_in.rs b/app/src/auth/sign_in.rs index 44edbfd1..5eed8d59 100644 --- a/app/src/auth/sign_in.rs +++ b/app/src/auth/sign_in.rs @@ -379,7 +379,7 @@ async fn new_user(id: &Identity) -> laravel::Result { .cloned() .unwrap_or_else(|| format!("{}+{}@users.noreply.{}.visualci.com", id.id, id.login, id.forge.as_str())); let verified = (!id.trusted_emails().is_empty()).then(laravel::now); - create!(User { + let user = create!(User { pid: laravel::str::uuid7(), name: id.name.clone().unwrap_or_else(|| id.login.clone()), email: email, @@ -387,7 +387,11 @@ async fn new_user(id: &Identity) -> laravel::Result { avatar_url: id.avatar_url.clone(), staff: false, }) - .await + .await?; + // "How did you hear about VisualCI?" is asked once, after sign-up; the team's email waits for it + let user_id = user.id; + db::query!("UPDATE users SET heard_about_pending = true WHERE id = {user_id}").update().await?; + Ok(user) } async fn record_waitlist(id: &Identity, source: &str) -> laravel::Result<()> { diff --git a/app/src/notify/outbox.rs b/app/src/notify/outbox.rs index 9f70d89b..a6638095 100644 --- a/app/src/notify/outbox.rs +++ b/app/src/notify/outbox.rs @@ -209,7 +209,9 @@ pub async fn deliver(config: &Postmark, app_url: &str) -> laravel::Result }; 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 { + match postmark::send(config, token, &to, &rendered.subject, &rendered.text, &rendered.html, kind.reply_to()) + .await + { Ok(()) => { let (subject, text, html) = (rendered.subject, rendered.text, rendered.html); db::query!( diff --git a/app/src/notify/postmark.rs b/app/src/notify/postmark.rs index 78c4216b..3dd43373 100644 --- a/app/src/notify/postmark.rs +++ b/app/src/notify/postmark.rs @@ -25,11 +25,12 @@ pub async fn send( subject: &str, text: &str, html: &str, + reply_to: Option<&str>, ) -> laravel::Result<()> { let body = json!({ "From": config.from, "To": to, - "ReplyTo": config.reply_to, + "ReplyTo": reply_to.unwrap_or(&config.reply_to), "Subject": subject, "TextBody": text, "HtmlBody": html, diff --git a/app/src/notify/render.rs b/app/src/notify/render.rs index 6de6ad20..b663f634 100644 --- a/app/src/notify/render.rs +++ b/app/src/notify/render.rs @@ -74,6 +74,12 @@ pub enum Kind { name: String, project: Option, }, + /// To the team (`VISUALCI_TEAM_EMAIL`): someone signed up. Plain text; replying reaches them. + NewSignup { + subject: String, + text: String, + reply_to: String, + }, } impl Kind { @@ -95,6 +101,16 @@ impl Kind { Self::RemovedFromOrg => "removed_from_org", Self::DeviceSignIn { .. } => "device_sign_in", Self::TokenCreated { .. } => "token_created", + Self::NewSignup { .. } => "new_signup", + } + } + + /// Where a reply goes when it isn't VisualCI's support address. + #[must_use] + pub fn reply_to(&self) -> Option<&str> { + match self { + Self::NewSignup { reply_to, .. } => Some(reply_to), + _ => None, } } @@ -199,6 +215,10 @@ fn text(paragraphs: &[String], button: (&str, &str)) -> String { /// Render an email. #[must_use] pub fn render(kind: &Kind, about: &About<'_>) -> Rendered { + if let Kind::NewSignup { subject, text, .. } = kind { + let html = format!("
{}
", escape(text)); + return Rendered { subject: subject.clone(), text: text.clone(), html }; + } 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 { @@ -341,6 +361,8 @@ pub fn render(kind: &Kind, about: &About<'_>) -> Rendered { ], ("Account".into(), format!("{}/account", about.app_url)), ), + // Rendered as plain text above. + Kind::NewSignup { subject, text, .. } => (subject.clone(), vec![text.clone()], (String::new(), String::new())), Kind::TokenCreated { name, project } => ( format!("A new VisualCI token: {name}"), vec![ diff --git a/app/tests/me.rs b/app/tests/me.rs new file mode 100644 index 00000000..9ca33462 --- /dev/null +++ b/app/tests/me.rs @@ -0,0 +1,117 @@ +//! The person's own page: who they are, their organizations and invitations, their email choices, the billing email +//! (admins), and "How did you hear", which the team's sign-up email waits for. + +use app::models::User; +use laravel::db; +use laravel::model::create; +use laravel::testing::prelude::*; + +async fn person(name: &str, email: &str) -> laravel::Result { + create!(User { pid: laravel::str::uuid7(), name: name, email: email, staff: false }).await +} + +async fn org_with(user: &User, slug: &str, role: &str) -> laravel::Result { + let org: i64 = db::query!( + "INSERT INTO organizations (pid, slug, name, created_at, updated_at) \ + VALUES (gen_random_uuid(), {slug}, 'Acme', now(), now()) RETURNING id" + ) + .scalar() + .await? + .unwrap(); + let id = user.id; + db::query!( + "INSERT INTO memberships (organization_id, user_id, role, source, created_at, updated_at) \ + VALUES ({org}, {id}, {role}, 'created', now(), now())" + ) + .insert() + .await?; + Ok(org) +} + +#[laravel::test] +async fn me_shows_their_organizations_and_email_choices(app: Application) -> laravel::Result<()> { + let ada = person("Ada", "ada@example.com").await?; + org_with(&ada, "acme", "admin").await?; + app.get("/api/ui/me") + .acting_as(&ada) + .await + .assert_ok() + .assert_json_path("user.name", "Ada") + .assert_json_path("organizations.0.slug", "acme") + .assert_json_path("organizations.0.role", "admin") + .assert_json_path("organizations.0.usage.plan.name", "Free") + .assert_json_path("notifications.low_credits", true) + .assert_json_path("heard_about_options.1.key", "ai_assistant") + .assert_json_path("forges", json!([])); + // Signed out, the React app (asking for JSON) gets a 401; a page would go to /login + app.get("/api/ui/me").header("accept", "application/json").await.assert_status(401); + + app.patch("/api/ui/me/notifications") + .acting_as(&ada) + .header("sec-fetch-site", "same-origin") + .json(json!({ "receipts": false })) + .await + .assert_ok() + .assert_json_path("receipts", false) + .assert_json_path("low_credits", true); + Ok(()) +} + +#[laravel::test] +async fn only_admins_set_the_billing_email(app: Application) -> laravel::Result<()> { + let ada = person("Ada", "ada@example.com").await?; + let bob = person("Bob", "bob@example.com").await?; + let org = org_with(&ada, "acme", "admin").await?; + let bob_id = bob.id; + db::query!( + "INSERT INTO memberships (organization_id, user_id, role, source, created_at, updated_at) \ + VALUES ({org}, {bob_id}, 'member', 'invite', now(), now())" + ) + .insert() + .await?; + let put = |who: &User, email: &str| { + app.put("/api/ui/orgs/acme/billing-email") + .acting_as(who) + .header("sec-fetch-site", "same-origin") + .json(json!({ "billing_email": email })) + }; + put(&bob, "ap@example.com").await.assert_status(403); + // Staff who aren't in it are nobody here. + let sam = create!(User { pid: laravel::str::uuid7(), name: "Sam", email: "sam@example.com", staff: true }).await?; + put(&sam, "ap@example.com").await.assert_status(404); + put(&ada, "not an address").await.assert_status(422); + put(&ada, " AP@Example.com ").await.assert_ok().assert_json_path("billing_email", "ap@example.com"); + put(&ada, "").await.assert_ok().assert_json_path("billing_email", json!(null)); + Ok(()) +} + +#[laravel::test] +async fn the_team_hears_about_a_sign_up_once_it_is_answered(app: Application) -> laravel::Result<()> { + let ada = person("Ada", "ada@example.com").await?; + let id = ada.id; + db::query!("UPDATE users SET heard_about_pending = true WHERE id = {id}").update().await?; + app::auth::me::NotifySignups.dispatch().await?; + let queued = || async { + db::query!("SELECT count(*) FROM emails WHERE kind = 'new_signup' AND recipient = 'support@visualci.com'") + .scalar::() + .await + }; + assert_eq!(queued().await?, Some(0), "it waits for the answer"); + + app.post("/api/ui/me/heard-about") + .acting_as(&ada) + .header("sec-fetch-site", "same-origin") + .json(json!({ "source": "ai_assistant", "detail": "Claude" })) + .await + .assert_ok(); + assert_eq!(queued().await?, Some(1)); + let data: Option = db::query!("SELECT data::text FROM emails WHERE kind = 'new_signup'").scalar().await?; + let data = data.unwrap(); + assert!(data.contains("AI assistant: Claude") && data.contains("ada@example.com"), "{data}"); + app.get("/api/ui/me").acting_as(&ada).await.assert_json_path("heard_about_pending", false); + + // Once only. + app::auth::me::NotifySignups.dispatch().await?; + assert_eq!(queued().await?, Some(1)); + Ok(()) +}