Skip to content

Commit 7f5fb09

Browse files
committed
app/: staff pages for sign-ups and emails (sc-8900): the latest 100 sign-ups with how they heard about VisualCI, every email rendered with sample data, failed emails retried or dismissed; a 404 for anyone who isn't staff
1 parent f0714b1 commit 7f5fb09

3 files changed

Lines changed: 181 additions & 0 deletions

File tree

‎app/src/auth/mod.rs‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ pub mod invitations;
1313
pub mod me;
1414
pub mod memberships;
1515
pub mod sign_in;
16+
pub mod staff;
1617
pub mod tokens;
1718

1819
use axum::extract::FromRequestParts;
@@ -249,6 +250,7 @@ pub fn routes(route: &mut laravel::prelude::Router) {
249250
invitations::routes(route);
250251
me::routes(route);
251252
device::routes(route);
253+
staff::routes(route);
252254
route.get("/auth/{forge}", sign_in::start);
253255
route.post("/auth/{forge}/link", sign_in::link);
254256
route.get("/auth/{forge}/callback", sign_in::callback);

‎app/src/auth/staff.rs‎

Lines changed: 130 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,130 @@
1+
//! Staff pages on the auth and emails side (sc-8900), ported from today's server: the latest sign-ups, every email
2+
//! VisualCI sends rendered with sample data, and failed emails to retry or dismiss. Anyone who isn't staff gets a 404.
3+
4+
use laravel::auth::Authenticated;
5+
use laravel::db;
6+
use laravel::prelude::*;
7+
use serde_json::{Value, json};
8+
9+
use super::me::summary;
10+
use crate::models::User;
11+
use crate::notify::outbox::AppUrl;
12+
use crate::notify::{About, DeliverEmails, render, render::samples};
13+
14+
pub fn routes(route: &mut Router) {
15+
route.get("/api/ui/staff/signups", signups);
16+
route.get("/api/ui/staff/emails", emails);
17+
route.post("/api/ui/staff/emails/{id}/resolve", resolve);
18+
}
19+
20+
fn staff_only(user: &User) -> laravel::Result<()> {
21+
if user.staff { Ok(()) } else { Err(laravel::abort(404)) }
22+
}
23+
24+
const TIME: &str = "YYYY-MM-DD\"T\"HH24:MI:SS\"Z\"";
25+
26+
/// `GET /api/ui/staff/signups`: the latest 100 people, newest first, with how they heard about VisualCI.
27+
pub async fn signups(Authenticated(user): Authenticated<User>) -> laravel::Result<Json<Value>> {
28+
staff_only(&user)?;
29+
let rows = db::query!(
30+
"SELECT name, email, heard_about_source, heard_about_detail, \
31+
to_char(created_at AT TIME ZONE 'UTC', {TIME}) AS created_at, \
32+
(SELECT login FROM identities WHERE user_id = users.id ORDER BY id LIMIT 1) AS login \
33+
FROM users ORDER BY id DESC LIMIT 100"
34+
)
35+
.select()
36+
.await?;
37+
let mut list = Vec::new();
38+
for r in rows {
39+
let (source, detail): (Option<String>, Option<String>) =
40+
(r.try_get("heard_about_source")?, r.try_get("heard_about_detail")?);
41+
list.push(json!({
42+
"name": r.try_get::<String>("name")?, "email": r.try_get::<String>("email")?,
43+
"login": r.try_get::<Option<String>>("login")?, "created_at": r.try_get::<String>("created_at")?,
44+
"heard_about": summary(source.as_deref(), detail.as_deref()),
45+
}));
46+
}
47+
Ok(Json(json!({ "signups": list })))
48+
}
49+
50+
/// `GET /api/ui/staff/emails`: every email rendered with sample data (for Acme), and the failed ones nobody has
51+
/// retried or dismissed yet, newest first.
52+
pub async fn emails(
53+
Authenticated(user): Authenticated<User>,
54+
app: laravel::config::Section<AppUrl>,
55+
) -> laravel::Result<Json<Value>> {
56+
staff_only(&user)?;
57+
let about = About { org_name: "Acme", org_slug: "acme", app_url: app.url.trim_end_matches('/') };
58+
let list: Vec<Value> = samples()
59+
.into_iter()
60+
.map(|(label, kind)| {
61+
let r = render(&kind, &about);
62+
json!({
63+
"label": label, "kind": kind.name(), "subject": r.subject, "text": r.text, "html": r.html,
64+
"can_turn_off": kind.preference().is_some(),
65+
})
66+
})
67+
.collect();
68+
let rows = db::query!(
69+
"SELECT e.id, e.kind, e.recipient, e.attempts, e.last_error, o.slug AS org, \
70+
to_char(e.created_at AT TIME ZONE 'UTC', {TIME}) AS created_at, \
71+
to_char(e.updated_at AT TIME ZONE 'UTC', {TIME}) AS failed_at \
72+
FROM emails e LEFT JOIN organizations o ON o.id = e.organization_id \
73+
WHERE e.state = 'failed' AND e.dismissed_at IS NULL ORDER BY e.id DESC LIMIT 100"
74+
)
75+
.select()
76+
.await?;
77+
let mut failed = Vec::new();
78+
for r in rows {
79+
failed.push(json!({
80+
"id": r.try_get::<i64>("id")?, "kind": r.try_get::<String>("kind")?,
81+
"recipient": r.try_get::<String>("recipient")?, "org": r.try_get::<Option<String>>("org")?,
82+
"attempts": r.try_get::<i32>("attempts")?, "last_error": r.try_get::<Option<String>>("last_error")?,
83+
"created_at": r.try_get::<String>("created_at")?, "failed_at": r.try_get::<String>("failed_at")?,
84+
}));
85+
}
86+
Ok(Json(json!({ "emails": list, "failed": failed })))
87+
}
88+
89+
#[laravel::input]
90+
#[validate(authenticated)]
91+
pub struct ResolveInput {
92+
/// `retry` or `dismiss`.
93+
#[validate(required)]
94+
action: String,
95+
}
96+
97+
/// `POST /api/ui/staff/emails/{id}/resolve`: retry a failed email (sent again from scratch) or dismiss it. Either way
98+
/// it stops counting in `/status`'s `emails_failed_unresolved`. 404 when there's no such failed, undismissed email.
99+
pub async fn resolve(
100+
Authenticated(user): Authenticated<User>,
101+
Params(id): Params<i64>,
102+
Valid(p): Valid<ResolveInput>,
103+
) -> laravel::Result<Json<Value>> {
104+
staff_only(&user)?;
105+
let done: Option<i64> = match p.action.as_str() {
106+
"retry" => {
107+
db::query!(
108+
"UPDATE emails SET state = 'pending', attempts = 0, claimed_at = NULL, updated_at = now() \
109+
WHERE id = {id} AND state = 'failed' AND dismissed_at IS NULL RETURNING id"
110+
)
111+
.scalar()
112+
.await?
113+
}
114+
"dismiss" => {
115+
db::query!(
116+
"UPDATE emails SET dismissed_at = now(), updated_at = now() \
117+
WHERE id = {id} AND state = 'failed' AND dismissed_at IS NULL RETURNING id"
118+
)
119+
.scalar()
120+
.await?
121+
}
122+
_ => return Err(laravel::abort_with(422, "action is retry or dismiss")),
123+
};
124+
done.ok_or_else(|| laravel::abort(404))?;
125+
tracing::info!(email_id = id, action = %p.action, staff = user.id, "staff resolved a failed email");
126+
if p.action == "retry" {
127+
DeliverEmails.dispatch().await?;
128+
}
129+
Ok(Json(json!({ "id": id })))
130+
}

‎app/tests/staff.rs‎

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
//! Staff pages: the latest sign-ups, every email rendered, failed emails retried or dismissed; a 404 for anyone else.
2+
3+
use app::models::User;
4+
use laravel::db;
5+
use laravel::model::create;
6+
use laravel::testing::prelude::*;
7+
8+
#[laravel::test]
9+
async fn staff_see_sign_ups_and_emails_and_resolve_failures(app: Application) -> laravel::Result<()> {
10+
let grace =
11+
create!(User { pid: laravel::str::uuid7(), name: "Grace", email: "grace@example.com", staff: true }).await?;
12+
let ada = create!(User { pid: laravel::str::uuid7(), name: "Ada", email: "ada@example.com", staff: false }).await?;
13+
let ada_id = ada.id;
14+
db::query!(
15+
"UPDATE users SET heard_about_source = 'ai_assistant', heard_about_detail = 'Claude' WHERE id = {ada_id}"
16+
)
17+
.update()
18+
.await?;
19+
for path in ["/api/ui/staff/signups", "/api/ui/staff/emails"] {
20+
app.get(path).acting_as(&ada).await.assert_status(404);
21+
}
22+
app.get("/api/ui/staff/signups")
23+
.acting_as(&grace)
24+
.await
25+
.assert_ok()
26+
.assert_json_path("signups.0.name", "Ada")
27+
.assert_json_path("signups.0.heard_about", "AI assistant: Claude");
28+
29+
let failed: i64 = db::query!(
30+
"INSERT INTO emails (kind, dedupe_key, recipient, data, state, attempts, last_error) \
31+
VALUES ('welcome', 'w:1', 'ada@example.com', '[]', 'failed', 5, 'Postmark: HTTP 422') RETURNING id"
32+
)
33+
.scalar()
34+
.await?
35+
.unwrap();
36+
let page = app.get("/api/ui/staff/emails").acting_as(&grace).await;
37+
page.assert_ok().assert_json_path("failed.0.id", failed).assert_json_path("emails.0.kind", "credits_low");
38+
let resolve = |who: &User, action: &str| {
39+
app.post(format!("/api/ui/staff/emails/{failed}/resolve"))
40+
.acting_as(who)
41+
.header("sec-fetch-site", "same-origin")
42+
.json(json!({ "action": action }))
43+
};
44+
resolve(&ada, "dismiss").await.assert_status(404);
45+
resolve(&grace, "dismiss").await.assert_ok();
46+
resolve(&grace, "dismiss").await.assert_status(404);
47+
app.get("/api/ui/staff/emails").acting_as(&grace).await.assert_json_path("failed", json!([]));
48+
Ok(())
49+
}

0 commit comments

Comments
 (0)