Skip to main content

adk_website/ui/
review.rs

1//! The weekly review page and the summary sent to the owner's channel (spec 3.5 §7.21).
2//!
3//! The review holds KPIs against baselines and targets with trends, what each agent did,
4//! cost, revenue and profit and loss, experiments, incidents, leads handed off, promotion
5//! offers and demotions, alarms that waited, and a short list of questions. Reviews come from
6//! the weekly-review job ([`WebsiteDesk::record_review`]) or are composed here; sending one
7//! puts its one-line summary on the owner's channel and records `website.review.sent`.
8
9use adk_core::Result;
10use adk_kernel::charter::{KpiPhase, ladder_rank};
11use awp_types::Role;
12use chrono::{DateTime, Datelike, Duration, NaiveDate, Utc};
13use schemars::JsonSchema;
14use serde::{Deserialize, Serialize};
15
16use super::site::KpiCard;
17use super::words::{self, major};
18use super::{Line, Pill, Tone, WebsiteDesk, invalid, not_found, unavailable};
19use crate::review::{ReviewInputs, Trend, WeeklyReview};
20
21/// Where and when a review's summary went.
22type Sent = (String, DateTime<Utc>);
23
24#[derive(Default)]
25pub(crate) struct State {
26    reviews: Vec<(WeeklyReview, Option<Sent>)>,
27}
28
29/// One review in the list.
30#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
31#[serde(rename_all = "camelCase")]
32pub struct ReviewLine {
33    /// The Monday its week starts.
34    pub week: NaiveDate,
35    /// Its title.
36    pub title: String,
37    /// Where and when its summary went.
38    #[serde(default, skip_serializing_if = "Option::is_none")]
39    pub sent: Option<String>,
40}
41
42/// What each agent did.
43#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
44#[serde(rename_all = "camelCase")]
45pub struct WorkLine {
46    /// The agent.
47    pub agent: String,
48    /// What it did.
49    pub items: Vec<String>,
50}
51
52/// Cost, revenue and profit and loss (spec 3.5 §7.14).
53#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
54#[serde(rename_all = "camelCase")]
55pub struct MoneyView {
56    /// Spent this week.
57    pub spend: String,
58    /// Spent this month, against the budget.
59    pub month: String,
60    /// Whether the month is inside the budget.
61    pub within: Pill,
62    /// Each category this week.
63    pub categories: Vec<Line>,
64    /// Revenue, profit, cost per lead and per sale, where the site sells.
65    pub results: Vec<Line>,
66}
67
68/// A promotion the jobs earned, for the owner to decide (A-I13).
69#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
70#[serde(rename_all = "camelCase")]
71pub struct OfferLine {
72    /// The job.
73    pub job: String,
74    /// What it is.
75    pub title: String,
76    /// Its level now.
77    pub from: String,
78    /// The level a promotion gives it.
79    pub to: String,
80    /// The record behind the offer.
81    pub record: String,
82}
83
84/// One week's review (spec 3.5 §7.21).
85#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
86#[serde(rename_all = "camelCase")]
87pub struct ReviewView {
88    /// The Monday its week starts.
89    pub week: NaiveDate,
90    /// "Week of 19 October".
91    pub title: String,
92    /// The charter version in force.
93    #[serde(default, skip_serializing_if = "Option::is_none")]
94    pub charter_version: Option<u32>,
95    /// The week at a glance.
96    pub headline: Vec<Line>,
97    /// KPIs against baselines and targets, with trends.
98    pub kpis: Vec<KpiCard>,
99    /// What each agent did.
100    pub work: Vec<WorkLine>,
101    /// Money.
102    #[serde(default, skip_serializing_if = "Option::is_none")]
103    pub money: Option<MoneyView>,
104    /// Experiments and their evidence.
105    pub experiments: Vec<String>,
106    /// Incidents.
107    pub incidents: Vec<String>,
108    /// Leads captured and handed off.
109    pub leads: Vec<String>,
110    /// Promotions the jobs earned.
111    pub promotions: Vec<OfferLine>,
112    /// Demotions, with why.
113    pub demotions: Vec<Line>,
114    /// Alarms that waited for the review.
115    pub alarms: Vec<String>,
116    /// Questions for the owner.
117    pub questions: Vec<String>,
118    /// What the constant-update engine did: updates, deliveries, what it held and its cost;
119    /// empty when the site runs no engine (spec 3.5 §7.8.3).
120    pub updates: Vec<Line>,
121    /// The line sent to the owner's channel.
122    pub summary: String,
123    /// The review as a document, in Markdown.
124    pub markdown: String,
125    /// Where and when its summary went.
126    #[serde(default, skip_serializing_if = "Option::is_none")]
127    pub sent: Option<String>,
128}
129
130/// The weekly review page.
131#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
132#[serde(rename_all = "camelCase")]
133pub struct ReviewPage {
134    /// Every review, newest first.
135    pub reviews: Vec<ReviewLine>,
136    /// The review shown.
137    #[serde(default, skip_serializing_if = "Option::is_none")]
138    pub current: Option<ReviewView>,
139    /// Whether the viewer can compose one now.
140    pub can_compose: bool,
141    /// The owner's channel the summary goes to.
142    #[serde(default, skip_serializing_if = "Option::is_none")]
143    pub channel: Option<String>,
144    /// When the next one is due.
145    pub next_due: NaiveDate,
146}
147
148/// A review action.
149#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
150#[serde(tag = "type", rename_all = "camelCase", rename_all_fields = "camelCase")]
151pub enum ReviewCommand {
152    /// Composes the review of the week starting `week`, last week's when absent.
153    Compose {
154        /// The Monday.
155        #[serde(default)]
156        week: Option<NaiveDate>,
157    },
158    /// Sends the review's summary to the owner's channel.
159    Send {
160        /// The Monday of the review.
161        week: NaiveDate,
162    },
163}
164
165fn monday(day: NaiveDate) -> NaiveDate {
166    day - Duration::days(i64::from(day.weekday().num_days_from_monday()))
167}
168
169fn sent_words(sent: Option<&Sent>) -> Option<String> {
170    sent.map(|(channel, at)| {
171        let channel = match channel.as_str() {
172            "whatsapp" => "WhatsApp",
173            "telegram" => "Telegram",
174            "sms" => "text message",
175            "slack" => "Slack",
176            "discord" => "Discord",
177            "matrix" => "Matrix",
178            other => other,
179        };
180        format!("Sent to {channel} on {} UTC", at.format("%-d %b at %H:%M"))
181    })
182}
183
184pub(crate) fn review_view(
185    review: &WeeklyReview,
186    sent: Option<&Sent>,
187    currency: &str,
188) -> ReviewView {
189    let up = review.kpis.iter().filter(|k| k.trend == Trend::Up).count();
190    let mut headline = vec![Line::new("Measures better", format!("{up} of {}", review.kpis.len()))];
191    if let Some(money) = &review.money {
192        headline.push(Line::new("Spent this week", major(money.spend, currency)));
193    }
194    if let Some(leads) = review.leads {
195        headline.push(Line::new("Leads", leads.to_string()));
196    }
197    headline.push(Line::new("Incidents", review.incidents.len().to_string()));
198    headline.push(Line::new("Questions for you", review.questions.len().to_string()));
199    let kpis = review
200        .kpis
201        .iter()
202        .map(|line| {
203            let k = &line.review;
204            KpiCard {
205                id: k.kpi.clone(),
206                name: k.name.clone(),
207                this_week: k.week.map(words::number),
208                last_week: k.previous_week.map(words::number),
209                baseline: k.baseline.map(words::number),
210                target: k.target.map(words::number),
211                trend: match line.trend {
212                    Trend::Up => Pill::new("Better", Tone::Good),
213                    Trend::Down => Pill::new("Worse", Tone::Bad),
214                    Trend::Flat => Pill::new("Same", Tone::Neutral),
215                    Trend::Unknown => Pill::new("New", Tone::Neutral),
216                },
217                phase: match &k.phase {
218                    KpiPhase::MeasureOnly { until } => {
219                        format!("Finding its baseline until {}", until.format("%-d %b"))
220                    }
221                    _ => "Tracking".into(),
222                },
223            }
224        })
225        .collect();
226    let work = review
227        .work
228        .iter()
229        .map(|(agent, items)| WorkLine { agent: words::agent(*agent).into(), items: items.clone() })
230        .collect();
231    let money = review.money.as_ref().map(|money| {
232        let mut results = Vec::new();
233        if let Some(revenue) = money.revenue {
234            results.push(Line::new("Revenue", major(revenue, currency)));
235        }
236        if let Some(profit) = money.profit {
237            results.push(Line::new("Profit", major(profit, currency)));
238        }
239        if let Some(per_lead) = money.cost_per_lead {
240            results.push(Line::new("Cost per lead", major(per_lead, currency)));
241        }
242        if let Some(per_sale) = money.cost_per_sale {
243            results.push(Line::new("Cost per sale", major(per_sale, currency)));
244        }
245        MoneyView {
246            spend: major(money.spend, currency),
247            month: format!(
248                "{} of {}",
249                major(money.month_to_date, currency),
250                major(money.monthly_budget, currency)
251            ),
252            within: if money.within_budget {
253                Pill::new("Within budget", Tone::Good)
254            } else {
255                Pill::new("Over budget", Tone::Bad)
256            },
257            categories: money
258                .by_category
259                .iter()
260                .map(|(category, spent)| {
261                    let mut name = category.clone();
262                    if let Some(first) = name.get_mut(..1) {
263                        first.make_ascii_uppercase();
264                    }
265                    Line::new(name, major(*spent, currency))
266                })
267                .collect(),
268            results,
269        }
270    });
271    let mut leads = Vec::new();
272    if let Some(count) = review.leads {
273        leads.push(format!("{count} captured this week"));
274    }
275    leads.extend(review.handed_off.iter().map(|lead| format!("Handed to you: {lead}")));
276    ReviewView {
277        week: review.week_start,
278        title: format!("Week of {}", review.week_start.format("%-d %B")),
279        charter_version: review.charter_version,
280        headline,
281        kpis,
282        work,
283        money,
284        experiments: review.experiments.clone(),
285        incidents: review
286            .incidents
287            .iter()
288            .map(|incident| {
289                format!(
290                    "{} file{} changed on the host; {} to release {}",
291                    incident.drift.len(),
292                    if incident.drift.len() == 1 { "" } else { "s" },
293                    if incident.closed.is_some() { "rolled back" } else { "rolling back" },
294                    incident.rollback.to_release
295                )
296            })
297            .collect(),
298        leads,
299        promotions: review
300            .promotions
301            .iter()
302            .filter(|offer| offer.eligible)
303            .map(|offer| OfferLine {
304                job: offer.job.clone(),
305                title: crate::jobs::job(&offer.job)
306                    .map_or_else(|| offer.job.clone(), |s| s.title.to_string()),
307                from: words::level(offer.level).into(),
308                to: words::level(offer.next.unwrap_or(offer.level)).into(),
309                record: format!("{} proposals in a row approved unchanged", offer.streak),
310            })
311            .collect(),
312        demotions: review
313            .demotions
314            .iter()
315            .filter(|change| {
316                change.from.is_some_and(|from| ladder_rank(change.to) < ladder_rank(from))
317            })
318            .map(|change| {
319                Line::new(
320                    crate::jobs::job(&change.job)
321                        .map_or_else(|| change.job.clone(), |s| s.title.to_string()),
322                    format!(
323                        "Lowered to \u{201c}{}\u{201d}: {}",
324                        words::level(change.to),
325                        change.reason.describe()
326                    ),
327                )
328            })
329            .collect(),
330        alarms: review.alarms.iter().map(|alarm| alarm.summary.clone()).collect(),
331        questions: review.questions.clone(),
332        updates: review
333            .updates
334            .as_ref()
335            .map(|u| {
336                vec![
337                    Line::new(
338                        "Updates",
339                        format!(
340                            "{} ({} live, {} in releases)",
341                            u.updates, u.live_updates, u.release_updates
342                        ),
343                    ),
344                    Line::new("Releases", u.releases.to_string()),
345                    Line::new("Written with a model", u.updates_with_model.to_string()),
346                    Line::new(
347                        "Feed deliveries",
348                        format!("{}, {} held whole", u.deliveries, u.held_deliveries),
349                    ),
350                    Line::new("Items held alone", u.held_items.to_string()),
351                    Line::new(
352                        "Cost per thousand updates",
353                        major(u.cost_per_thousand_updates_micros / 1_000_000.0, currency),
354                    ),
355                ]
356            })
357            .unwrap_or_default(),
358        summary: review.summary(),
359        markdown: review.to_markdown(),
360        sent: sent_words(sent),
361    }
362}
363
364impl WebsiteDesk {
365    /// Keeps a review the weekly-review job composed, so the web home shows it (spec 3.5
366    /// §7.21). A review of the same week replaces the earlier one.
367    pub async fn record_review(&self, review: WeeklyReview) {
368        let mut state = self.inner.reviews.lock().await;
369        state.reviews.retain(|(held, _)| held.week_start != review.week_start);
370        state.reviews.push((review, None));
371        state.reviews.sort_by_key(|(held, _)| held.week_start);
372    }
373
374    /// The weekly review page for `person`, showing the week starting `week`, or the latest.
375    ///
376    /// # Errors
377    ///
378    /// `Forbidden` for a person with no role.
379    pub async fn review_page(&self, person: &str, week: Option<NaiveDate>) -> Result<ReviewPage> {
380        let roles = self.roles(person).await?;
381        if roles.is_empty() {
382            return Err(super::forbidden(
383                "website.ui.not_allowed",
384                format!("{person} holds no role in this site's charter"),
385            ));
386        }
387        let state = self.inner.reviews.lock().await;
388        let current = match week {
389            Some(week) => state.reviews.iter().find(|(r, _)| r.week_start == week),
390            None => state.reviews.last(),
391        };
392        let today = self.now().date_naive();
393        Ok(ReviewPage {
394            reviews: state
395                .reviews
396                .iter()
397                .rev()
398                .map(|(review, sent)| ReviewLine {
399                    week: review.week_start,
400                    title: format!("Week of {}", review.week_start.format("%-d %B")),
401                    sent: sent_words(sent.as_ref()),
402                })
403                .collect(),
404            current: current
405                .map(|(review, sent)| review_view(review, sent.as_ref(), &self.inner.currency)),
406            can_compose: roles.contains(&Role::Owner) && self.inner.composer.is_some(),
407            channel: self.inner.channel.as_ref().map(|(sink, _)| sink.channel().to_string()),
408            next_due: monday(today) + Duration::days(7),
409        })
410    }
411
412    /// Carries out a review `command` for `person` (spec 3.5 §7.21).
413    ///
414    /// # Errors
415    ///
416    /// `Forbidden` for a person who is not an owner; `NotFound` for a week with no review;
417    /// the composer's and the channel's errors.
418    pub async fn review_command(&self, person: &str, command: ReviewCommand) -> Result<ReviewPage> {
419        self.require(person, &[Role::Owner], "The weekly review").await?;
420        let composer = self
421            .inner
422            .composer
423            .as_ref()
424            .ok_or_else(|| unavailable("The weekly review's composer"))?;
425        match command {
426            ReviewCommand::Compose { week } => {
427                let week =
428                    monday(week.unwrap_or_else(|| self.now().date_naive() - Duration::days(7)));
429                let inputs = match &self.inner.notes {
430                    Some(notes) => notes.notes(week).await?,
431                    None => ReviewInputs::default(),
432                };
433                let review = composer.compose(week, inputs).await?;
434                self.record_review(review).await;
435                self.review_page(person, Some(week)).await
436            }
437            ReviewCommand::Send { week } => {
438                let (sink, thread) =
439                    self.inner.channel.clone().ok_or_else(|| unavailable("The owner's channel"))?;
440                let review = {
441                    let state = self.inner.reviews.lock().await;
442                    state
443                        .reviews
444                        .iter()
445                        .find(|(r, _)| r.week_start == week)
446                        .map(|(r, _)| r.clone())
447                        .ok_or_else(|| {
448                            not_found(
449                                "website.review.week",
450                                format!("no review of the week of {week}"),
451                            )
452                        })?
453                };
454                if review.week_start > self.now().date_naive() {
455                    return Err(invalid("website.review.future", "that week has not happened yet"));
456                }
457                composer.send(&review, sink.as_ref(), &thread).await?;
458                let mut state = self.inner.reviews.lock().await;
459                if let Some((_, sent)) =
460                    state.reviews.iter_mut().find(|(r, _)| r.week_start == week)
461                {
462                    *sent = Some((sink.channel().to_string(), self.now()));
463                }
464                drop(state);
465                self.review_page(person, Some(week)).await
466            }
467        }
468    }
469}
470
471#[cfg(test)]
472mod tests {
473    use super::*;
474
475    #[test]
476    fn the_week_starts_on_monday() {
477        let sunday = NaiveDate::from_ymd_opt(2026, 10, 25).unwrap();
478        assert_eq!(monday(sunday), NaiveDate::from_ymd_opt(2026, 10, 19).unwrap());
479    }
480
481    #[test]
482    fn a_review_reads_in_plain_words() {
483        let review = WeeklyReview {
484            site: uuid::Uuid::nil(),
485            week_start: NaiveDate::from_ymd_opt(2026, 10, 19).unwrap(),
486            charter_version: Some(1),
487            kpis: Vec::new(),
488            work: Default::default(),
489            money: None,
490            experiments: Vec::new(),
491            incidents: Vec::new(),
492            leads: Some(4),
493            handed_off: vec!["A catering enquiry for 40 people".into()],
494            promotions: Vec::new(),
495            demotions: Vec::new(),
496            alarms: Vec::new(),
497            questions: vec!["Should the site answer in Swahili too?".into()],
498            updates: None,
499        };
500        let view = review_view(&review, Some(&("whatsapp".into(), Utc::now())), "KES");
501        assert_eq!(view.title, "Week of 19 October");
502        assert_eq!(
503            view.leads,
504            ["4 captured this week", "Handed to you: A catering enquiry for 40 people"]
505        );
506        assert!(view.sent.unwrap().starts_with("Sent to WhatsApp"));
507        assert_eq!(view.summary, review.summary());
508    }
509}