Skip to main content

brep_app/
report_followup.rs

1//! Remembering the problem reports this user submitted, and telling them when
2//! one is resolved — with no account.
3//!
4//! `POST /api/report` answers with the new report's id. The app keeps each id
5//! it submitted, with when and the first line of the user's description, on
6//! this machine: `submitted-reports.json` in the app's config directory on the
7//! desktop, `localStorage` in the browser. A few seconds after start and every
8//! few hours after, it asks `GET /api/public/reports/status?ids=…`, which says
9//! what the public bug list already shows: each report's status. When a report
10//! reaches `fixed`, `wontfix` or `closed`, the user gets one notice; a report
11//! the server no longer has is forgotten.
12//!
13//! Inert until the app's entry point starts it, so a test or a harness neither
14//! records nor asks.
15
16use std::sync::mpsc::Receiver;
17
18use brep_render::engine_state::{EngineState, NoticeSeverity};
19use eframe::egui;
20use serde::{Deserialize, Serialize};
21
22/// The status lookup on the public reports server.
23const STATUS_URL: &str = "https://next.brep.io/api/public/reports/status";
24
25/// The feature name [`crate::offsite`]'s refusal sentence starts with.
26const FEATURE: &str = "Problem report status";
27
28/// The first check after start, and the period after it (seconds).
29const FIRST_CHECK_SECS: f64 = 5.0;
30const CHECK_EVERY_SECS: f64 = 3.0 * 60.0 * 60.0;
31
32/// The most reports remembered (the server answers at most 100 per lookup).
33const MAX_KEPT: usize = 50;
34
35/// One report this user submitted.
36#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
37pub struct Submitted {
38    pub id: String,
39    /// RFC 3339, when this app submitted it.
40    pub submitted_at: String,
41    /// The first line of the user's own description.
42    pub summary: String,
43    /// The status last read from the server.
44    #[serde(default)]
45    pub status: String,
46    /// The resolved status the user was last told about.
47    #[serde(default)]
48    pub notified: Option<String>,
49}
50
51/// The sentence for a report that reached a resolved status, or `None`.
52fn resolution_notice(report: &Submitted, status: &str) -> Option<String> {
53    let outcome = match status {
54        "fixed" => "was marked fixed. Thank you for reporting it!",
55        "wontfix" => "was closed as won't fix.",
56        "closed" => "was closed.",
57        _ => return None,
58    };
59    let date = report.submitted_at.get(..10).unwrap_or(&report.submitted_at);
60    let summary = if report.summary.is_empty() { "no description".to_string() } else { report.summary.clone() };
61    Some(format!("Your problem report from {date} (\u{201c}{summary}\u{201d}) {outcome}"))
62}
63
64/// Fold a status answer into `reports`: statuses updated, missing reports
65/// dropped. Returns the notices to show; `reports` then records them as told.
66pub fn apply(reports: &mut Vec<Submitted>, body: &str) -> Result<Vec<String>, String> {
67    #[derive(Deserialize)]
68    struct Row {
69        id: String,
70        status: String,
71    }
72    #[derive(Deserialize)]
73    struct Answer {
74        #[serde(default)]
75        reports: Vec<Row>,
76        #[serde(default)]
77        missing: Vec<String>,
78    }
79    let answer: Answer = serde_json::from_str(body).map_err(|e| format!("report status: {e}"))?;
80    reports.retain(|r| !answer.missing.contains(&r.id));
81    let mut notices = Vec::new();
82    for row in answer.reports {
83        let Some(report) = reports.iter_mut().find(|r| r.id == row.id) else { continue };
84        report.status = row.status.clone();
85        if report.notified.as_deref() == Some(row.status.as_str()) {
86            continue;
87        }
88        if let Some(notice) = resolution_notice(report, &row.status) {
89            notices.push(notice);
90            report.notified = Some(row.status);
91        }
92    }
93    Ok(notices)
94}
95
96/// The first line of a description, trimmed to a notice's length.
97pub fn summary_of(description: &str) -> String {
98    let line = description.lines().map(str::trim).find(|l| !l.is_empty()).unwrap_or("");
99    let mut out: String = line.chars().take(80).collect();
100    if line.chars().count() > 80 {
101        out.push('\u{2026}');
102    }
103    out
104}
105
106/// The report id out of `POST /api/report`'s `201` body.
107pub fn id_of_reply(body: &[u8]) -> Option<String> {
108    let v: serde_json::Value = serde_json::from_slice(body).ok()?;
109    let id = v.get("id")?.as_str()?;
110    let ok = !id.is_empty() && id.chars().all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_');
111    ok.then(|| id.to_string())
112}
113
114/// `2026-11-04T05:06:07Z` for Unix seconds (the app has no date crate; days
115/// to a civil date by Howard Hinnant's `civil_from_days`).
116fn rfc3339(secs: i64) -> String {
117    let (days, rem) = (secs.div_euclid(86_400), secs.rem_euclid(86_400));
118    let z = days + 719_468;
119    let era = z.div_euclid(146_097);
120    let doe = z - era * 146_097;
121    let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
122    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
123    let mp = (5 * doy + 2) / 153;
124    let day = doy - (153 * mp + 2) / 5 + 1;
125    let month = if mp < 10 { mp + 3 } else { mp - 9 };
126    let year = yoe + era * 400 + i64::from(month <= 2);
127    format!("{year:04}-{month:02}-{day:02}T{:02}:{:02}:{:02}Z", rem / 3600, rem % 3600 / 60, rem % 60)
128}
129
130fn status_url(reports: &[Submitted]) -> String {
131    let ids: Vec<String> = reports.iter().map(|r| crate::http::query_component(&r.id)).collect();
132    format!("{STATUS_URL}?ids={}", ids.join(","))
133}
134
135// ---------------------------------------------------------------- where the list lives
136
137#[cfg(not(target_arch = "wasm32"))]
138mod saved {
139    use super::Submitted;
140
141    fn path() -> std::path::PathBuf {
142        crate::plm::config::app_config_dir().join("submitted-reports.json")
143    }
144
145    pub fn load() -> Vec<Submitted> {
146        super::parse_saved(&std::fs::read_to_string(path()).unwrap_or_default())
147    }
148
149    pub fn save(reports: &[Submitted]) {
150        let path = path();
151        let write = || -> std::io::Result<()> {
152            if let Some(dir) = path.parent() {
153                std::fs::create_dir_all(dir)?;
154            }
155            std::fs::write(&path, serde_json::to_vec_pretty(reports).unwrap_or_default())
156        };
157        if let Err(e) = write() {
158            log::warn!("could not save {}: {e}", path.display());
159        }
160    }
161}
162
163#[cfg(target_arch = "wasm32")]
164mod saved {
165    use super::Submitted;
166
167    const KEY: &str = "brep-submitted-reports";
168
169    fn storage() -> Option<web_sys::Storage> {
170        web_sys::window()?.local_storage().ok().flatten()
171    }
172
173    pub fn load() -> Vec<Submitted> {
174        let text = storage().and_then(|s| s.get_item(KEY).ok().flatten()).unwrap_or_default();
175        super::parse_saved(&text)
176    }
177
178    pub fn save(reports: &[Submitted]) {
179        if let (Some(storage), Ok(text)) = (storage(), serde_json::to_string(reports)) {
180            let _ = storage.set_item(KEY, &text);
181        }
182    }
183}
184
185fn parse_saved(text: &str) -> Vec<Submitted> {
186    serde_json::from_str(text).unwrap_or_default()
187}
188
189// ---------------------------------------------------------------- the frame's half
190
191/// The remembered reports and the periodic status check.
192pub struct ReportFollowup {
193    started: bool,
194    reports: Vec<Submitted>,
195    rx: Option<Receiver<Result<String, String>>>,
196    /// egui time of the next check.
197    next_check: f64,
198}
199
200impl Default for ReportFollowup {
201    fn default() -> Self {
202        Self::new()
203    }
204}
205
206impl ReportFollowup {
207    /// Inert: records nothing and asks nothing until [`Self::start`].
208    pub fn new() -> Self {
209        ReportFollowup { started: false, reports: Vec::new(), rx: None, next_check: 0.0 }
210    }
211
212    /// Load the remembered reports; the first check follows shortly.
213    pub fn start(&mut self, ctx: &egui::Context) {
214        self.started = true;
215        self.reports = saved::load();
216        self.next_check = ctx.input(|i| i.time) + FIRST_CHECK_SECS;
217        if !self.reports.is_empty() {
218            ctx.request_repaint_after(std::time::Duration::from_secs_f64(FIRST_CHECK_SECS));
219        }
220    }
221
222    /// Remember a report this app just submitted.
223    pub fn record(&mut self, id: String, summary: String) {
224        if !self.started || self.reports.iter().any(|r| r.id == id) {
225            return;
226        }
227        let submitted_at = rfc3339(crate::recovery::wall_clock() as i64);
228        self.reports.push(Submitted { id, submitted_at, summary, status: "new".into(), notified: None });
229        if self.reports.len() > MAX_KEPT {
230            let extra = self.reports.len() - MAX_KEPT;
231            self.reports.drain(..extra);
232        }
233        saved::save(&self.reports);
234    }
235
236    /// The reports remembered, oldest first.
237    pub fn reports(&self) -> &[Submitted] {
238        &self.reports
239    }
240
241    /// Once a frame: start a due check, and turn an answer into notices.
242    pub fn tick(&mut self, ctx: &egui::Context, state: &mut EngineState) {
243        if !self.started {
244            return;
245        }
246        if let Some(rx) = &self.rx {
247            match rx.try_recv() {
248                Ok(Ok(body)) => {
249                    self.rx = None;
250                    match apply(&mut self.reports, &body) {
251                        Ok(notices) => {
252                            for notice in notices {
253                                state.push_notice_as(NoticeSeverity::Info, notice);
254                            }
255                            saved::save(&self.reports);
256                        }
257                        Err(e) => log::info!("{e}"),
258                    }
259                }
260                Ok(Err(e)) => {
261                    self.rx = None;
262                    log::info!("report status: {e}");
263                }
264                Err(std::sync::mpsc::TryRecvError::Empty) => return,
265                Err(std::sync::mpsc::TryRecvError::Disconnected) => self.rx = None,
266            }
267        }
268        let now = ctx.input(|i| i.time);
269        if now < self.next_check {
270            return;
271        }
272        self.next_check = now + CHECK_EVERY_SECS;
273        ctx.request_repaint_after(std::time::Duration::from_secs_f64(CHECK_EVERY_SECS));
274        // A PLM-hosted page that may not reach the report site skips quietly.
275        if self.reports.is_empty() || crate::offsite::refusal(FEATURE, STATUS_URL).is_some() {
276            return;
277        }
278        let (tx, rx) = std::sync::mpsc::channel();
279        let ctx = ctx.clone();
280        ehttp::fetch(ehttp::Request::get(status_url(&self.reports)), move |result| {
281            let out = match result {
282                Ok(resp) if resp.ok => Ok(String::from_utf8_lossy(&resp.bytes).into_owned()),
283                Ok(resp) => Err(format!("HTTP {} {}", resp.status, resp.status_text)),
284                Err(e) => Err(e),
285            };
286            let _ = tx.send(out);
287            ctx.request_repaint();
288        });
289        self.rx = Some(rx);
290    }
291}
292