Skip to main content

max / makenotwork

17.5 KB · 446 lines History Blame Raw
1 //! The library's Contacts tab, described.
2 //!
3 //! The second authenticated screen through the description layer, and the first
4 //! of S4's batches. Chosen by measurement rather than by the plan's original
5 //! pick: it is one of six tab partials in the tree that hold a table and no
6 //! client-side JavaScript at all, and of those it is the one whose route a
7 //! reader can actually reach from a nav.
8 //!
9 //! Compare `routes::pages::public::landing::library_tab_contacts`, which answers
10 //! the same address from Askama when the screen is switched off.
11 //!
12 //! # What it exercises
13 //!
14 //! Every table member the vocabulary has grown, and nothing that is still
15 //! unnamed. Two tables; a value that is a link, in two columns and two flavours
16 //! (a route this server answers, and a `mailto:` that leaves); a destructive
17 //! per-row `DELETE`; and three states, since either table can be empty on its
18 //! own and both empty is a third screen again.
19 //!
20 //! # It renders the same page, unlike S3's
21 //!
22 //! The SSH-keys tab could not be diffed against its Askama original because the
23 //! Askama version lazy-loads two lists and the described version renders them
24 //! inline. This one has no `hx-trigger="load"` anywhere: the Askama handler
25 //! already runs both queries and renders both tables in the response, so the two
26 //! renderings are comparable and the parity harness applies. That was the open
27 //! question hanging over S4's safety argument, and picking a screen that renders
28 //! its own data is the answer for this batch.
29
30 use makeover_layout as layout;
31 use quasi_router::screen::{Act, Cell, Cells, Column};
32 use quasi_router::{Action, Method, Node, RegionKind, Request, Response, RouteError, Slot};
33 use quasi_webview::Webview;
34
35 use super::Viewer;
36 use crate::db;
37
38 /// This screen's name. Was the `QUASI_SCREENS` switch name until `64b33b26`
39 /// deleted the flag; it survives as the marker the tab strips read.
40 pub const SCREEN: &str = "library_contacts";
41
42 /// The address this screen answers, and the one the Askama route gives up.
43 pub const PATH: &str = "/library/tabs/contacts";
44
45 /// The region the answer replaces: the pane the library's tab nav targets.
46 pub const REGION: &str = "library-contacts";
47
48 /// The address a revoke calls, relative to this screen's own nest.
49 const REVOKE: &str = "/revoke/{seller_id}";
50
51 /// The writes this screen serves. Registered under its nest by `super::mount`.
52 pub const WRITES: &[(Method, &str, super::Screen)] = &[(Method::Delete, REVOKE, revoke)];
53
54 /// One buyer who chose to share their email, as the screen needs it.
55 pub struct BuyerView {
56 username: String,
57 email: String,
58 purchases: String,
59 spent: String,
60 last_purchase: String,
61 }
62
63 /// One creator this reader has shared their own email with.
64 pub struct SharedView {
65 seller_id: String,
66 username: String,
67 name: String,
68 }
69
70 /// The tab.
71 pub fn screen(viewer: &Viewer, _request: Request) -> Result<Response, RouteError> {
72 let user_id = viewer.user.id;
73
74 let shared = viewer
75 .block_on(db::transactions::get_shared_creators(
76 &viewer.app.db,
77 user_id,
78 ))
79 .map_err(|_| RouteError::internal("your contacts could not be read"))?;
80
81 // A reader who cannot create projects has no buyers, so the second query is
82 // skipped rather than answered with an empty set. The Askama handler makes
83 // the same choice and it matters more here: every one of these round trips
84 // holds a blocking-pool thread. See the module header on `super`.
85 let profile = viewer
86 .block_on(db::users::get_user_by_id(&viewer.app.db, user_id))
87 .map_err(|_| RouteError::internal("your account could not be read"))?
88 .ok_or_else(|| RouteError::not_found("that account is gone"))?;
89 let buyers = if profile.can_create_projects {
90 viewer
91 .block_on(db::transactions::get_seller_contacts(
92 &viewer.app.db,
93 user_id,
94 ))
95 .map_err(|_| RouteError::internal("your buyers could not be read"))?
96 } else {
97 Vec::new()
98 };
99
100 let buyers: Vec<BuyerView> = buyers
101 .into_iter()
102 .map(|c| BuyerView {
103 username: c.username,
104 email: c.email,
105 purchases: c.total_purchases.to_string(),
106 spent: crate::formatting::format_revenue(
107 c.total_spent_cents,
108 viewer.user.settlement_currency,
109 ),
110 last_purchase: c.last_purchase_at.format("%b %d, %Y").to_string(),
111 })
112 .collect();
113 let shared: Vec<SharedView> = shared
114 .into_iter()
115 .map(|creator| SharedView {
116 seller_id: creator.seller_id.to_string(),
117 name: creator
118 .display_name
119 .clone()
120 .unwrap_or_else(|| creator.username.clone()),
121 username: creator.username,
122 })
123 .collect();
124
125 Ok(Response::fragment(REGION, pane(&buyers, &shared)))
126 }
127
128 /// Revoke sharing with one creator, and answer with the tab as it now stands.
129 ///
130 /// The screen's own route rather than `DELETE /api/contacts/{id}`, which the
131 /// Askama version calls and which answers 204. htmx never swaps a 204, so the
132 /// described control appeared to do nothing: the revoke landed and the row
133 /// stayed until the reader left the tab and came back. Answering the whole pane
134 /// is what a described write is for, and it is one query more than the API route
135 /// runs, on an action a reader takes once.
136 pub fn revoke(viewer: &Viewer, request: Request) -> Result<Response, RouteError> {
137 // Taken by value because the handler signature is quasi's.
138 let captures = request.captures;
139 let seller: crate::db::UserId = captures
140 .get("seller_id")
141 .and_then(|id| id.parse().ok())
142 .ok_or_else(|| RouteError::not_found("no such creator"))?;
143
144 viewer
145 .block_on(db::transactions::revoke_contact_sharing(
146 &viewer.app.db,
147 viewer.user.id,
148 seller,
149 ))
150 .map_err(|_| RouteError::internal("that sharing could not be revoked"))?;
151
152 screen(viewer, Request::get(PATH))
153 }
154
155 /// Everything inside the tab pane.
156 ///
157 /// Split from the handler so a test can build it without a database, the same
158 /// split `ssh_keys` uses and the reason a described screen is testable at all.
159 fn pane(buyers: &[BuyerView], shared: &[SharedView]) -> Node {
160 let mut slot = Slot::new(REGION, RegionKind::Pane);
161
162 // Both empty is its own screen and not two empty tables. The Askama version
163 // says this in a third `{% if %}` over the same two conditions.
164 if buyers.is_empty() && shared.is_empty() {
165 return Node::Region(slot.with(Node::empty("No contacts yet.")));
166 }
167
168 if !buyers.is_empty() {
169 slot = slot
170 .with(Node::section(format!("Your Buyers ({})", buyers.len())))
171 .with(Node::text(
172 "Buyers who opted to share their email with you at purchase time.",
173 ))
174 .with(buyers_table(buyers));
175 }
176
177 if !shared.is_empty() {
178 slot = slot
179 .with(Node::section("Shared With"))
180 .with(Node::text(
181 "You've shared your email with these creators. You can revoke sharing at any time.",
182 ))
183 .with(shared_table(shared));
184 }
185
186 Node::Region(slot)
187 }
188
189 /// The buyers who shared an email.
190 fn buyers_table(buyers: &[BuyerView]) -> Node {
191 Node::Table {
192 columns: vec![
193 Column::new("Username")
194 .width(layout::Width::Content)
195 .priority(layout::Priority::Essential),
196 Column::new("Email")
197 .width(layout::Width::Fill)
198 .priority(layout::Priority::Essential),
199 Column::new("Purchases").width(layout::Width::Content),
200 Column::new("Total Spent").width(layout::Width::Content),
201 Column::new("Last Purchase")
202 .width(layout::Width::Content)
203 .priority(layout::Priority::Optional),
204 ],
205 rows: buyers
206 .iter()
207 .map(|buyer| {
208 Cells::new([
209 // The two flavours of a linked value in one row. A profile
210 // is a route this server answers, so it stays inside the
211 // app; an address is not, so it leaves.
212 //
213 // Navigating (`00ee7af5`): a profile is a whole document,
214 // not a region, so the anchor is the whole of it and the
215 // swap is dropped. Without it htmx would morph a
216 // `<!doctype html>` page over the cell it was clicked in.
217 Cell::new(buyer.username.clone())
218 .activate(Action::get(format!("/u/{}", buyer.username)).navigating()),
219 Cell::new(buyer.email.clone())
220 .activate(Action::external(format!("mailto:{}", buyer.email))),
221 Cell::new(buyer.purchases.clone()),
222 Cell::new(buyer.spent.clone()),
223 Cell::new(buyer.last_purchase.clone()),
224 ])
225 })
226 .collect(),
227 // No paging described here: every one of these tables is a
228 // whole set the handler already counted.
229 more: None,
230 }
231 }
232
233 /// The creators this reader has shared an email with.
234 fn shared_table(shared: &[SharedView]) -> Node {
235 Node::Table {
236 columns: vec![
237 Column::new("Creator")
238 .width(layout::Width::Fill)
239 .priority(layout::Priority::Essential),
240 Column::new("")
241 .width(layout::Width::Content)
242 .priority(layout::Priority::Essential),
243 ],
244 rows: shared
245 .iter()
246 .map(|creator| {
247 Cells::new([
248 // The display name is what the row reads as and the username
249 // is where it goes, which is the pairing the template made
250 // with a nested `{% if let %}` inside the anchor.
251 Cell::new(creator.name.clone())
252 .activate(Action::get(format!("/u/{}", creator.username)).navigating()),
253 Cell::acts([Act::new(
254 "Revoke",
255 // This screen's own route, under its own nest. The API's
256 // answers 204, which htmx never swaps, so the row stayed
257 // after a successful revoke. See `revoke`.
258 Action::delete(format!("{PATH}/revoke/{}", creator.seller_id)).awaiting(),
259 )
260 // The template asked with hx-confirm. Said here, a
261 // terminal host asks in its own way and no host can
262 // forget to ask.
263 .confirm(format!("Revoke contact sharing with {}?", creator.username))
264 .tone(layout::Tone::Danger)]),
265 ])
266 })
267 .collect(),
268 // No paging described here: every one of these tables is a
269 // whole set the handler already counted.
270 more: None,
271 }
272 }
273
274 /// The renderer this screen is drawn with.
275 pub fn renderer(viewer: &Viewer) -> Webview {
276 Webview::new().with_shell(viewer.shell())
277 }
278
279 #[cfg(test)]
280 mod tests {
281 use super::*;
282 use quasi_axum::Serves;
283
284 fn buyer(username: &str) -> BuyerView {
285 BuyerView {
286 username: username.into(),
287 email: format!("{username}@example.com"),
288 purchases: "3".into(),
289 spent: "$42.00".into(),
290 last_purchase: "Aug 10, 2026".into(),
291 }
292 }
293
294 fn creator(id: &str, username: &str, name: &str) -> SharedView {
295 SharedView {
296 seller_id: id.into(),
297 username: username.into(),
298 name: name.into(),
299 }
300 }
301
302 fn render(node: &Node) -> String {
303 Webview::new().fragment(node)
304 }
305
306 #[test]
307 fn the_region_matches_the_panel_the_library_strip_gives_this_tab() {
308 // The router says what it changed, through HX-Retarget. If this and the
309 // strip's panel id ever disagree the tab swaps into nothing, and that
310 // failure is invisible to every other test.
311 //
312 // Read off the strip rather than off `library.html`, which stopped
313 // holding the nav when the strip was described (`6b24f2df`). Both halves
314 // are Rust now, so the id is shared rather than transcribed -- and this
315 // still earns its keep, because `library_tabs` names the panel and this
316 // module names the region and nothing but this asserts they agree.
317 let strip = crate::quasi::library_tabs::html("", true, true);
318 assert!(
319 strip.contains(&format!("id=\"{REGION}\"")),
320 "the library strip has no panel called {REGION}:\n{strip}"
321 );
322 assert!(strip.contains(&format!("hx-get=\"{PATH}\"")), "{strip}");
323 }
324
325 #[test]
326 fn a_reader_with_no_contacts_gets_one_sentence_and_no_tables() {
327 let html = render(&pane(&[], &[]));
328 assert!(html.contains("No contacts yet."));
329 assert!(!html.contains("role=\"table\""), "{html}");
330 }
331
332 #[test]
333 fn each_table_appears_only_when_it_has_rows() {
334 // Three screens, not one with two empty tables. A buyer with no shared
335 // creators is the common case for a creator account, and the reverse is
336 // the common case for everyone else.
337 let buyers_only = render(&pane(&[buyer("ada")], &[]));
338 assert!(buyers_only.contains("Your Buyers (1)"));
339 assert!(!buyers_only.contains("Shared With"));
340
341 let shared_only = render(&pane(&[], &[creator("s1", "grace", "Grace H")]));
342 assert!(!shared_only.contains("Your Buyers"));
343 assert!(shared_only.contains("Shared With"));
344 }
345
346 #[test]
347 fn a_buyers_name_goes_to_their_profile_and_their_address_leaves() {
348 let html = render(&buyers_table(&[buyer("ada")]));
349
350 // A read of a route this server answers: an anchor with a real href, so
351 // middle-click and copy-link work and it stays in the app. Navigating,
352 // so the anchor is all of it: a verb here would swap a whole document
353 // into the cell.
354 assert!(html.contains("href=\"/u/ada\""), "{html}");
355 assert!(
356 !html.contains("hx-get=\"/u/ada\""),
357 "a navigation carries no verb: {html}"
358 );
359 assert!(
360 !html.contains("hx-get=\"mailto"),
361 "no htmx on a mailto: {html}"
362 );
363 assert!(
364 html.contains("href=\"mailto:ada@example.com\""),
365 "the address is a link: {html}"
366 );
367 assert!(html.contains("target=\"_blank\""), "{html}");
368 }
369
370 #[test]
371 fn revoking_asks_first_and_every_row_asks_about_itself() {
372 let html = render(&shared_table(&[
373 creator("s1", "grace", "Grace H"),
374 creator("s2", "alan", "Alan T"),
375 ]));
376
377 assert_eq!(html.matches("hx-confirm").count(), 2, "both ask: {html}");
378 assert!(
379 html.contains("Revoke contact sharing with grace?"),
380 "{html}"
381 );
382 // `b279b9eb`: asking first and being destructive are marked separately,
383 // so a row that asks is not thereby dangerous and this act has to say
384 // both. The tone is what a terminal host colours by; without it the
385 // renderer would be back to reading the prompt string for a hint.
386 assert_eq!(
387 html.matches(r#"data-tone="danger""#).count(),
388 2,
389 "revoking is destructive and says so: {html}"
390 );
391 // Per row rather than one shared endpoint, which is the mistake a loop
392 // over rows makes when the id is read outside it.
393 assert!(
394 html.contains(&format!("hx-delete=\"{PATH}/revoke/s1\"")),
395 "{html}"
396 );
397 assert!(
398 html.contains(&format!("hx-delete=\"{PATH}/revoke/s2\"")),
399 "{html}"
400 );
401 }
402
403 #[test]
404 fn the_row_addresses_are_the_ones_the_api_actually_answers() {
405 // The conversion's real risk, and the one that already shipped once: a
406 // described control addressing a route registered nowhere renders fine
407 // and answers 404 when pressed. S3 shipped exactly that.
408 // The revoke is this screen's own route now, so the check is that the
409 // control and the registration agree rather than that an API path
410 // exists. They are three lines apart and still drifted once.
411 assert!(
412 WRITES
413 .iter()
414 .any(|(method, path, _)| *method == Method::Delete && *path == REVOKE),
415 "the revoke route is registered"
416 );
417 let control = render(&shared_table(&[creator("s1", "grace", "Grace H")]));
418 assert!(
419 control.contains(&format!("hx-delete=\"{PATH}/revoke/s1\"")),
420 "{control}"
421 );
422
423 // The linked value is the same risk with no button to press: a title
424 // that navigates nowhere is a dead link rather than a 404 on a write,
425 // and nothing else in the suite would notice.
426 let pages = include_str!("../routes/pages/public/mod.rs");
427 assert!(
428 pages.contains("\"/u/{username}\""),
429 "a buyer's name goes to a registered route"
430 );
431 }
432
433 #[test]
434 fn a_name_a_reader_chose_cannot_smuggle_markup() {
435 // A display name comes from a profile form, and it is the value of a
436 // cell that is also a link, which is the newest of the paths a string
437 // takes to the page.
438 let html = render(&shared_table(&[creator(
439 "s1",
440 "grace",
441 "<script>x()</script>",
442 )]));
443 assert!(!html.contains("<script>x()"), "{html}");
444 }
445 }
446