diff --git a/compliance-dashboard/assets/main.css b/compliance-dashboard/assets/main.css index 1707634..e1d4dd4 100644 --- a/compliance-dashboard/assets/main.css +++ b/compliance-dashboard/assets/main.css @@ -6052,3 +6052,429 @@ input[type="file"] { .license-policy-forbid { border-left: 3px solid var(--danger); } + + +/* ── Heute: the inbox of open decisions (#950) ── */ + +/* The page takes the keyboard (j/k/f/a/s); no ring around the whole page. */ +.inbox-page:focus { + outline: none; +} + +.nav-count { + margin-left: auto; + min-width: 18px; + padding: 0 5px; + border-radius: 9px; + background: var(--danger); + color: #fff; + font-family: var(--font-mono); + font-size: 10.5px; + font-weight: 600; + line-height: 18px; + text-align: center; +} + +.sidebar.collapsed .nav-count { + position: absolute; + top: 1px; + right: 1px; + min-width: 15px; + line-height: 15px; + font-size: 9px; +} + +.inbox-progress { + background: var(--bg-card); + border: 1px solid var(--border); + border-radius: var(--radius-lg); + padding: 12px 14px; + margin-bottom: 12px; +} + +.inbox-progress-head { + display: flex; + align-items: baseline; + gap: 10px; + margin-bottom: 8px; + font-size: 12.5px; +} + +.inbox-progress-label { + font-weight: 600; + color: var(--text-primary); +} + +.inbox-progress-value { + color: var(--text-tertiary); +} + +.inbox-progress-percent { + margin-left: auto; + font-family: var(--font-mono); + color: var(--text-secondary); +} + +.inbox-progress-track { + height: 6px; + border-radius: 3px; + background: var(--bg-elevated); + overflow: hidden; +} + +.inbox-progress-fill { + height: 100%; + background: var(--success); + border-radius: 3px; + transition: width 0.4s var(--ease-out); +} + +.inbox-targets { + display: flex; + flex-wrap: wrap; + gap: 6px; + margin-bottom: 12px; +} + +.inbox-target { + display: inline-flex; + align-items: center; + gap: 6px; + padding: 4px 10px; + border: 1px solid var(--border-bright); + border-radius: 999px; + background: var(--bg-card); + color: var(--text-secondary); + font-family: var(--font-body); + font-size: 12px; + cursor: pointer; +} + +.inbox-target:hover { + border-color: var(--border-strong); + color: var(--text-primary); +} + +.inbox-target.is-active { + border-color: var(--border-accent); + background: var(--accent-muted); + color: var(--accent); + font-weight: 600; +} + +.inbox-target-count { + font-family: var(--font-mono); + font-size: 10.5px; + color: var(--text-faint); +} + +.inbox-buckets { + display: grid; + grid-template-columns: repeat(4, minmax(0, 1fr)); + gap: 8px; + margin-bottom: 14px; +} + +.inbox-bucket { + --tone: var(--text-tertiary); + display: flex; + flex-direction: column; + align-items: flex-start; + gap: 2px; + padding: 11px 13px 12px; + border: 1px solid var(--border); + border-top: 3px solid var(--tone); + border-radius: var(--radius-lg); + background: var(--bg-card); + color: var(--text-primary); + font-family: var(--font-body); + text-align: left; + cursor: pointer; + transition: background 0.1s, border-color 0.1s; +} + +.inbox-bucket:hover { + background: var(--bg-card-hover); +} + +.inbox-bucket.is-active { + border-color: var(--tone); + background: color-mix(in oklch, var(--tone) 7%, var(--bg-card)); +} + +.inbox-bucket.tone-danger { --tone: var(--danger); } +.inbox-bucket.tone-warning { --tone: var(--orange); } +.inbox-bucket.tone-neutral { --tone: var(--info); } +.inbox-bucket.tone-accent { --tone: var(--accent); } + +.inbox-bucket-count { + font-family: var(--font-mono); + font-size: 24px; + font-weight: 600; + line-height: 1.1; + color: var(--tone); +} + +.inbox-bucket-label { + font-size: 13px; + font-weight: 600; +} + +.inbox-bucket-hint { + font-size: 11.5px; + color: var(--text-tertiary); +} + +.inbox-cards { + display: flex; + flex-direction: column; + gap: 8px; +} + +.inbox-card { + background: var(--bg-card); + border: 1px solid var(--border); + border-left: 3px solid transparent; + border-radius: var(--radius-lg); + padding: 12px 14px; + cursor: default; +} + +.inbox-card.is-selected { + border-color: var(--border-accent); + border-left-color: var(--accent); + box-shadow: var(--shadow-pop); +} + +.inbox-card-head { + display: flex; + align-items: center; + gap: 9px; +} + +.inbox-card-title { + font-family: var(--font-display); + font-size: 14px; + font-weight: 600; + color: var(--text-primary); + letter-spacing: -0.01em; + overflow-wrap: anywhere; +} + +.inbox-card-sub { + display: flex; + flex-wrap: wrap; + align-items: baseline; + gap: 4px 10px; + margin-top: 4px; + font-size: 12px; + color: var(--text-tertiary); +} + +.inbox-card-target { + font-weight: 500; + color: var(--text-secondary); +} + +.inbox-card-place { + font-family: var(--font-mono); + font-size: 11.5px; + overflow-wrap: anywhere; +} + +.inbox-chips { + display: flex; + flex-wrap: wrap; + gap: 5px; + margin-top: 8px; +} + +.inbox-chip { + --tone: var(--text-tertiary); + padding: 1px 8px; + border-radius: 999px; + border: 1px solid color-mix(in oklch, var(--tone) 32%, transparent); + background: color-mix(in oklch, var(--tone) 10%, transparent); + color: var(--tone); + font-size: 11px; + font-weight: 500; + white-space: nowrap; +} + +.inbox-chip.tone-danger { --tone: var(--danger); } +.inbox-chip.tone-warning { --tone: var(--orange); } +.inbox-chip.tone-success { --tone: var(--success); } +.inbox-chip.tone-info { --tone: var(--info); } +.inbox-chip.tone-accent { --tone: var(--accent); } + +.inbox-card-note { + margin-top: 8px; + font-size: 12px; + color: var(--text-secondary); +} + +.inbox-card-note-label { + font-weight: 600; + margin-right: 6px; +} + +.inbox-actions, +.inbox-input { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 6px; + margin-top: 10px; +} + +.inbox-later { + position: relative; +} + +.inbox-later > summary { + list-style: none; +} + +.inbox-later > summary::-webkit-details-marker { + display: none; +} + +.inbox-later-menu { + position: absolute; + z-index: 20; + top: calc(100% + 4px); + left: 0; + display: flex; + flex-direction: column; + gap: 6px; + min-width: 210px; + padding: 8px; + border: 1px solid var(--border-bright); + border-radius: var(--radius-lg); + background: var(--bg-card-solid); + box-shadow: var(--shadow-pop); +} + +.inbox-later-option { + padding: 5px 8px; + border: none; + border-radius: var(--radius-sm); + background: transparent; + color: var(--text-primary); + font-family: var(--font-body); + font-size: 12.5px; + text-align: left; + cursor: pointer; +} + +.inbox-later-option:hover { + background: var(--bg-elevated); +} + +.inbox-later-date { + display: flex; + flex-direction: column; + gap: 3px; + padding: 4px 8px 0; + font-size: 11.5px; + color: var(--text-tertiary); +} + +.inbox-later-date input, +.inbox-input-text, +.inbox-input-select { + padding: 5px 8px; + border: 1px solid var(--border-bright); + border-radius: var(--radius); + background: var(--bg-secondary); + color: var(--text-primary); + font-family: var(--font-body); + font-size: 12.5px; +} + +.inbox-input-text { + flex: 1 1 240px; + min-width: 0; +} + +.inbox-details { + margin-left: auto; + font-size: 12.5px; + color: var(--accent); + text-decoration: none; +} + +.inbox-details:hover { + text-decoration: underline; +} + +.inbox-empty { + text-align: center; + color: var(--text-tertiary); + padding: 28px 16px; +} + +.inbox-empty .btn { + margin-top: 10px; +} + +.inbox-shortcuts { + margin-top: 12px; + font-family: var(--font-mono); + font-size: 11px; + color: var(--text-faint); +} + +.inbox-undo { + position: fixed; + left: 50%; + bottom: 22px; + z-index: 210; + transform: translateX(-50%); + display: flex; + align-items: center; + gap: 14px; + max-width: calc(100vw - 32px); + padding: 9px 10px 9px 16px; + border-radius: var(--radius-lg); + background: var(--text-primary); + color: var(--bg-primary); + font-size: 13px; + box-shadow: var(--shadow-pop); +} + +.inbox-undo > span { + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.inbox-undo-btn { + background: transparent; + border-color: color-mix(in oklch, var(--bg-primary) 40%, transparent); + color: var(--bg-primary); + font-weight: 600; +} + +.inbox-undo-btn:hover { + background: color-mix(in oklch, var(--bg-primary) 14%, transparent); + color: var(--bg-primary); + border-color: var(--bg-primary); +} + +@media (max-width: 900px) { + .inbox-buckets { + grid-template-columns: repeat(2, minmax(0, 1fr)); + } +} + +@media (max-width: 480px) { + .inbox-details { + margin-left: 0; + } + + .inbox-later-menu { + position: static; + margin-top: 4px; + } +} diff --git a/compliance-dashboard/src/app.rs b/compliance-dashboard/src/app.rs index 4add56e..6325d4b 100644 --- a/compliance-dashboard/src/app.rs +++ b/compliance-dashboard/src/app.rs @@ -8,7 +8,10 @@ use crate::pages::*; #[allow(clippy::enum_variant_names)] pub enum Route { #[layout(AppShell)] + // The landing page: the open decisions (#950). #[route("/")] + HeutePage {}, + #[route("/overview")] OverviewPage {}, #[route("/targets")] TargetsPage {}, @@ -81,6 +84,16 @@ mod tests { use super::Route; use std::str::FromStr; + #[test] + fn heute_is_the_landing_page_and_the_overview_stays_reachable() { + assert!(matches!(Route::from_str("/"), Ok(Route::HeutePage {}))); + assert!(matches!( + Route::from_str("/overview"), + Ok(Route::OverviewPage {}) + )); + assert_eq!(Route::OverviewPage {}.to_string(), "/overview"); + } + #[test] fn the_sbom_page_carries_its_target_in_the_query() { let filtered = Route::SbomPage { diff --git a/compliance-dashboard/src/components/sidebar.rs b/compliance-dashboard/src/components/sidebar.rs index d61e224..3dcd02d 100644 --- a/compliance-dashboard/src/components/sidebar.rs +++ b/compliance-dashboard/src/components/sidebar.rs @@ -158,6 +158,11 @@ pub fn Sidebar() -> Element { } } div { class: "sidebar-nav", + TodayNavItem { + collapsed: collapsed(), + active: current_route == (Route::HeutePage {}), + on_navigate: move |_| mobile_open.set(false), + } for item in nav_items.into_iter().filter(|i| can_write || !i.write_only) { { let is_active = match (¤t_route, &item.route) { @@ -281,6 +286,41 @@ pub fn Sidebar() -> Element { } } +/// The sidebar's "Heute" entry with the workspace's "Heute handeln" count +/// (#950): fetched once, then kept current by the page. +#[component] +fn TodayNavItem(collapsed: bool, active: bool, on_navigate: EventHandler<()>) -> Element { + use crate::infrastructure::inbox::fetch_inbox; + use crate::pages::inbox::TODAY_COUNT; + use compliance_core::models::inbox::Bucket; + + let lang = use_lang()(); + let _count = use_resource(|| async { + if TODAY_COUNT.peek().is_none() { + if let Ok(view) = fetch_inbox(String::new(), Bucket::Today, Some(0)).await { + *TODAY_COUNT.write() = Some(view.counts.today); + } + } + }); + let label = crate::i18n::texts::inbox::NAV.get(lang); + let today = TODAY_COUNT().filter(|n| *n > 0); + rsx! { + Link { + to: Route::HeutePage {}, + class: if active { "nav-item active" } else { "nav-item" }, + title: "{label}", + onclick: move |_| on_navigate.call(()), + Icon { icon: BsInbox, width: 18, height: 18 } + if !collapsed { + span { "{label}" } + } + if let Some(today) = today { + span { class: "nav-count", "{today}" } + } + } + } +} + /// The BreakPilot wordmark, as on breakpilot.com and the portal: the chevron, /// and unless `with_name` is off, "BreakPilot" with "Prüfwerk" beneath. #[component] diff --git a/compliance-dashboard/src/i18n/texts.rs b/compliance-dashboard/src/i18n/texts.rs index 95cc78b..821f0f7 100644 --- a/compliance-dashboard/src/i18n/texts.rs +++ b/compliance-dashboard/src/i18n/texts.rs @@ -4951,3 +4951,310 @@ pub mod graph { } } } + +/// The "Heute" inbox (#950): open decisions in four urgency buckets. +pub mod inbox { + use super::super::Lang; + use super::Text; + + pub const NAV: Text = Text { + de: "Heute", + en: "Today", + }; + pub const TITLE: Text = Text { + de: "Heute", + en: "Today", + }; + pub const SUBTITLE: Text = Text { + de: "Offene Entscheidungen, nach Dringlichkeit sortiert. Eine Karte, eine Entscheidung.", + en: "Open decisions, sorted by urgency. One card, one decision.", + }; + pub const PROGRESS: Text = Text { + de: "Erstbewertung", + en: "First assessment", + }; + pub const PROGRESS_HINT: Text = Text { + de: "Befunde und Schwachstellen, über die schon entschieden ist (Fehlalarm, \ + Risiko akzeptiert, VEX-Aussage), von allen, die nicht behoben sind.", + en: "Findings and vulnerabilities already decided (false alarm, risk accepted, VEX \ + statement), of all that are not resolved.", + }; + pub const ALL_TARGETS: Text = Text { + de: "Alle Prüfobjekte", + en: "All targets", + }; + pub const TODAY: Text = Text { + de: "Heute handeln", + en: "Act today", + }; + pub const THIS_WEEK: Text = Text { + de: "Diese Woche", + en: "This week", + }; + pub const LATER: Text = Text { + de: "Später", + en: "Later", + }; + pub const AI: Text = Text { + de: "KI: wohl Fehlalarm", + en: "AI: likely false alarm", + }; + pub const TODAY_HINT: Text = Text { + de: "Ausgenutzt, CRA-Frist läuft, Secret im Code", + en: "Exploited, CRA deadline running, secret in code", + }; + pub const THIS_WEEK_HINT: Text = Text { + de: "Hoch und kritisch, oder ein Fix ist da", + en: "High and critical, or a fix is available", + }; + pub const LATER_HINT: Text = Text { + de: "Mittel und niedrig, fällige Wiedervorlagen", + en: "Medium and low, resubmissions due", + }; + pub const AI_HINT: Text = Text { + de: "Von der KI verworfen, bitte bestätigen", + en: "Dismissed by the AI, please confirm", + }; + pub const EMPTY_TODAY: Text = Text { + de: "Heute ist nichts dringend.", + en: "Nothing is urgent today.", + }; + pub const EMPTY_THIS_WEEK: Text = Text { + de: "Für diese Woche ist nichts offen.", + en: "Nothing is open for this week.", + }; + pub const EMPTY_LATER: Text = Text { + de: "Für später ist nichts offen.", + en: "Nothing is open for later.", + }; + pub const EMPTY_AI: Text = Text { + de: "Die KI hat nichts verworfen, das auf Sie wartet.", + en: "The AI dismissed nothing that waits for you.", + }; + pub const LOAD_FAILED: Text = Text { + de: "Die Entscheidungen konnten nicht geladen werden.", + en: "The decisions could not be loaded.", + }; + pub const KEV: Text = Text { + de: "Aktiv ausgenutzt (CISA KEV)", + en: "Exploited (CISA KEV)", + }; + pub const SECRET_IN_CODE: Text = Text { + de: "Secret im Code", + en: "Secret in code", + }; + pub const AI_DISMISSED: Text = Text { + de: "Von der KI verworfen", + en: "Dismissed by the AI", + }; + pub const CRA_DUTY: Text = Text { + de: "CRA-Meldepflicht", + en: "CRA notification due", + }; + pub const FALSE_POSITIVE: Text = Text { + de: "Fehlalarm", + en: "False alarm", + }; + pub const CONFIRM_FALSE_POSITIVE: Text = Text { + de: "Fehlalarm bestätigen", + en: "Confirm false alarm", + }; + pub const CONFIRM: Text = Text { + de: "Doch echt", + en: "It is real", + }; + pub const ACCEPT_RISK: Text = Text { + de: "Risiko akzeptieren", + en: "Accept the risk", + }; + pub const NOT_AFFECTED: Text = Text { + de: "Nicht betroffen", + en: "Not affected", + }; + pub const AFFECTED: Text = Text { + de: "Betroffen, Update geplant", + en: "Affected, update planned", + }; + pub const LATER_MENU: Text = Text { + de: "Später", + en: "Later", + }; + pub const ONE_WEEK: Text = Text { + de: "In 1 Woche", + en: "In 1 week", + }; + pub const ONE_MONTH: Text = Text { + de: "In 1 Monat", + en: "In 1 month", + }; + pub const ON_DATE: Text = Text { + de: "Am Datum", + en: "On a date", + }; + pub const SET_DATE: Text = Text { + de: "Wiedervorlage setzen", + en: "Set the resubmission", + }; + pub const DETAILS: Text = Text { + de: "Details →", + en: "Details →", + }; + pub const REASON: Text = Text { + de: "Warum wird das Risiko akzeptiert?", + en: "Why is the risk accepted?", + }; + pub const DECIDE: Text = Text { + de: "Entscheiden", + en: "Decide", + }; + pub const CANCEL: Text = Text { + de: "Abbrechen", + en: "Cancel", + }; + pub const DECIDED: Text = Text { + de: "Entschieden", + en: "Decided", + }; + pub const UNDO: Text = Text { + de: "Rückgängig", + en: "Undo", + }; + pub const UNDONE: Text = Text { + de: "Rückgängig gemacht", + en: "Undone", + }; + pub const FAILED: Text = Text { + de: "Das hat nicht geklappt", + en: "That did not work", + }; + pub const SHORTCUTS: Text = Text { + de: "Tasten: j / k wählen · f Fehlalarm · a Risiko akzeptiert · s später (1 Woche)", + en: "Keys: j / k move · f false alarm · a risk accepted · s later (1 week)", + }; + pub const AI_NOTE: Text = Text { + de: "Begründung der KI", + en: "The AI's reasoning", + }; + + /// "42 von 180 entschieden", "42 of 180 decided". + pub fn progress_line(decided: u64, total: u64, lang: Lang) -> String { + match lang { + Lang::De => format!("{decided} von {total} entschieden"), + Lang::En => format!("{decided} of {total} decided"), + } + } + + /// The EPSS chip: "EPSS 97. Perzentil", "EPSS 97th percentile". + pub fn epss(percentile: f64, lang: Lang) -> String { + // Whole percentiles; the fraction runs from 0 to 1. + let whole = (percentile * 100.0).floor(); + match lang { + Lang::De => format!("EPSS {whole}. Perzentil"), + Lang::En => format!("EPSS {whole}th percentile"), + } + } + + /// A CRA Article 14 stage, by its name in the agent's answer. + pub fn stage(stage: &str, lang: Lang) -> &'static str { + let text = match stage { + "early_warning" => Text { + de: "Frühwarnung", + en: "early warning", + }, + "vulnerability_notification" => Text { + de: "Schwachstellenmeldung", + en: "vulnerability notification", + }, + _ => Text { + de: "Abschlussbericht", + en: "final report", + }, + }; + text.get(lang) + } + + /// The CRA deadline chip: "CRA-Frühwarnung in 14 h", "… überfällig". + pub fn enisa(stage_name: &str, overdue: bool, hours_left: Option, lang: Lang) -> String { + let stage = stage(stage_name, lang); + match (lang, overdue, hours_left) { + (Lang::De, true, _) => format!("CRA-{stage} überfällig"), + (Lang::En, true, _) => format!("CRA {stage} overdue"), + (Lang::De, false, Some(h)) => format!("CRA-{stage} in {h} h"), + (Lang::En, false, Some(h)) => format!("CRA {stage} in {h} h"), + (Lang::De, false, None) => format!("CRA-{stage} fällig"), + (Lang::En, false, None) => format!("CRA {stage} due"), + } + } + + /// The fix chip: "Fix: 2.17.1". + pub fn fix(version: &str) -> String { + format!("Fix: {version}") + } + + /// The resubmission chip: "Wiedervorlage seit 01.12.2026". + pub fn resubmission(date: &str, lang: Lang) -> String { + match lang { + Lang::De => format!("Wiedervorlage seit {date}"), + Lang::En => format!("Resubmission since {date}"), + } + } + + /// The undo toast after a snooze: "Wiedervorlage am 01.12.2026". + pub fn snoozed(date: &str, lang: Lang) -> String { + match lang { + Lang::De => format!("Wiedervorlage am {date}"), + Lang::En => format!("Back on {date}"), + } + } + + /// A CVE card's size: "1 CVE", "3 CVEs". + pub fn cves(count: usize) -> String { + match count { + 1 => "1 CVE".to_string(), + n => format!("{n} CVEs"), + } + } + + /// A finding's places when it has several: "3 Stellen", "3 places". + pub fn places(count: usize, lang: Lang) -> String { + match lang { + Lang::De => format!("{count} Stellen"), + Lang::En => format!("{count} places"), + } + } + + /// The action statement an update is prefilled with. + pub fn update_to(version: &str, lang: Lang) -> String { + match lang { + Lang::De => format!("Auf Version {version} aktualisieren."), + Lang::En => format!("Update to version {version}."), + } + } + + #[cfg(test)] + mod tests { + use super::*; + + #[test] + fn chips_read_in_both_languages() { + assert_eq!(progress_line(42, 180, Lang::De), "42 von 180 entschieden"); + assert_eq!(progress_line(42, 180, Lang::En), "42 of 180 decided"); + assert_eq!(epss(0.973, Lang::De), "EPSS 97. Perzentil"); + assert_eq!( + enisa("early_warning", false, Some(14), Lang::De), + "CRA-Frühwarnung in 14 h" + ); + assert_eq!( + enisa("vulnerability_notification", true, Some(-3), Lang::En), + "CRA vulnerability notification overdue" + ); + assert_eq!(cves(1), "1 CVE"); + assert_eq!(cves(4), "4 CVEs"); + assert_eq!( + update_to("2.17.1", Lang::De), + "Auf Version 2.17.1 aktualisieren." + ); + assert_eq!(places(3, Lang::En), "3 places"); + } + } +} diff --git a/compliance-dashboard/src/infrastructure/inbox.rs b/compliance-dashboard/src/infrastructure/inbox.rs new file mode 100644 index 0000000..8d0dda2 --- /dev/null +++ b/compliance-dashboard/src/infrastructure/inbox.rs @@ -0,0 +1,94 @@ +//! The "Heute" inbox (#950): the cards of a bucket, decisions on a card, +//! undo, and resubmission dates. The agent does the work; these only carry +//! the session's token there and back. + +use dioxus::prelude::*; + +use compliance_core::models::inbox::{ + Bucket, DecideRequest, DecideResponse, InboxView, SnoozeRequest, SnoozeResponse, UndoRequest, +}; + +/// The agent's `{ data }` reply (read on the server only). +#[cfg(feature = "server")] +#[derive(Debug, serde::Deserialize)] +struct ViewResponse { + data: InboxView, +} + +/// The counts, the Erstbewertung, the targets and the cards of `bucket`, for +/// the whole workspace or, with a non-empty `target`, one target; at most +/// `limit` cards (the agent's default without one). +#[server] +pub async fn fetch_inbox( + target: String, + bucket: Bucket, + limit: Option, +) -> Result { + let mut request = super::agent_client::agent_get("/api/v1/inbox") + .await? + .query(&[("bucket", bucket.as_str())]); + if !target.is_empty() { + request = request.query(&[("target", target.as_str())]); + } + if let Some(limit) = limit { + request = request.query(&[("limit", limit)]); + } + let resp = request + .send() + .await + .map_err(|e| ServerFnError::new(e.to_string()))?; + let body: ViewResponse = super::agent_client::json_or_error(resp).await?; + Ok(body.data) +} + +/// Apply a decision to every item of a card; what they were before, for +/// [`undo_decision`]. The agent's refusal (a missing reason, a card already +/// decided, a read-only role) is the error. +#[server] +pub async fn decide_card(request: DecideRequest) -> Result { + let resp = super::agent_client::agent_request(reqwest::Method::POST, "/api/v1/inbox/decide") + .await? + .json(&request) + .send() + .await + .map_err(|e| ServerFnError::new(e.to_string()))?; + super::agent_client::json_or_error(resp).await +} + +/// Put the items of a decision back. +#[server] +pub async fn undo_decision(request: UndoRequest) -> Result<(), ServerFnError> { + let resp = super::agent_client::agent_request(reqwest::Method::POST, "/api/v1/inbox/undo") + .await? + .json(&request) + .send() + .await + .map_err(|e| ServerFnError::new(e.to_string()))?; + super::agent_client::ok_or_error(resp).await +} + +/// Put a card off; when it comes back. +#[server] +pub async fn snooze_card(request: SnoozeRequest) -> Result { + let resp = super::agent_client::agent_request(reqwest::Method::POST, "/api/v1/inbox/snooze") + .await? + .json(&request) + .send() + .await + .map_err(|e| ServerFnError::new(e.to_string()))?; + super::agent_client::json_or_error(resp).await +} + +/// Take a card's resubmission back (the undo of [`snooze_card`]). +#[server] +pub async fn unsnooze_card(key: String) -> Result<(), ServerFnError> { + let resp = super::agent_client::agent_request( + reqwest::Method::DELETE, + &format!("/api/v1/inbox/snooze/{key}"), + ) + .await? + .send() + .await + .map_err(|e| ServerFnError::new(e.to_string()))?; + super::agent_client::ok_or_error(resp).await +} diff --git a/compliance-dashboard/src/infrastructure/mod.rs b/compliance-dashboard/src/infrastructure/mod.rs index 60a7950..0fc030d 100644 --- a/compliance-dashboard/src/infrastructure/mod.rs +++ b/compliance-dashboard/src/infrastructure/mod.rs @@ -8,6 +8,7 @@ pub mod evidence; pub mod findings; pub mod graph; pub mod help_chat; +pub mod inbox; pub mod issues; pub mod manual_findings; pub mod mcp; diff --git a/compliance-dashboard/src/pages/inbox.rs b/compliance-dashboard/src/pages/inbox.rs new file mode 100644 index 0000000..4262f0f --- /dev/null +++ b/compliance-dashboard/src/pages/inbox.rs @@ -0,0 +1,920 @@ +//! "Heute" (#950), the landing page: the workspace's open decisions in four +//! urgency buckets, one card per decision, with the decision, "Später" with +//! a resubmission date, and undo, all from here. +//! +//! Keyboard (on this page only, never while typing): `j`/`k` move between +//! cards, `f` false alarm (VEX `not_affected` on a CVE card), `a` risk +//! accepted (VEX `affected` on a CVE card), `s` later (one week), `Esc` +//! closes an open input. + +use std::collections::HashSet; +use std::rc::Rc; + +use chrono::{DateTime, NaiveDate, Utc}; +use dioxus::prelude::*; + +use compliance_core::models::inbox::{ + Bucket, CardKind, DecideRequest, InboxAction, InboxCard, InboxView, Reason, SnoozeFor, + SnoozeRequest, UndoRequest, +}; +use compliance_core::models::VexJustification; + +use crate::app::Route; +use crate::components::no_access::use_can_write; +use crate::components::page_header::PageHeader; +use crate::components::severity_badge::SeverityBadge; +use crate::components::toast::{ToastType, Toasts}; +use crate::i18n::texts::{common, inbox as tx, vex as vex_tx}; +use crate::i18n::{use_lang, Lang, Text}; +use crate::infrastructure::inbox::{ + decide_card, fetch_inbox, snooze_card, undo_decision, unsnooze_card, +}; + +/// The workspace's "Heute handeln" cards, for the sidebar: fetched once, +/// then kept current by this page. +pub static TODAY_COUNT: GlobalSignal> = Signal::global(|| None); + +/// How long the undo strip stays after a decision. +#[cfg(feature = "web")] +const UNDO_MS: u32 = 8_000; + +/// The VEX justifications in the "Nicht betroffen" choice, with their labels. +const JUSTIFICATIONS: [(VexJustification, Text); 5] = [ + ( + VexJustification::ComponentNotPresent, + vex_tx::COMPONENT_NOT_PRESENT, + ), + ( + VexJustification::VulnerableCodeNotPresent, + vex_tx::CODE_NOT_PRESENT, + ), + ( + VexJustification::VulnerableCodeNotInExecutePath, + vex_tx::CODE_NOT_IN_EXECUTE_PATH, + ), + ( + VexJustification::VulnerableCodeCannotBeControlledByAdversary, + vex_tx::CODE_NOT_CONTROLLABLE, + ), + ( + VexJustification::InlineMitigationsAlreadyExist, + vex_tx::MITIGATIONS_EXIST, + ), +]; + +/// A decision that needs a word first: the reason of an accepted risk, the +/// justification of a `not_affected`, the action of an `affected`. +#[derive(Debug, Clone, PartialEq)] +struct Pending { + key: String, + action: InboxAction, + text: String, + justification: Option, +} + +impl Pending { + /// Whether it carries what the agent asks for. + fn ready(&self) -> bool { + let has_text = !self.text.trim().is_empty(); + match self.action { + InboxAction::NotAffected => self.justification.is_some() || has_text, + InboxAction::AcceptedRisk | InboxAction::Affected => has_text, + InboxAction::FalsePositive | InboxAction::Confirm => true, + } + } + + /// The request deciding card `key` with it. + fn request(&self) -> DecideRequest { + let text = Some(self.text.trim().to_string()).filter(|t| !t.is_empty()); + let (reason, statement) = match self.action { + InboxAction::AcceptedRisk => (text, None), + InboxAction::NotAffected | InboxAction::Affected => (None, text), + InboxAction::FalsePositive | InboxAction::Confirm => (None, None), + }; + DecideRequest { + key: self.key.clone(), + action: self.action, + reason, + justification: self + .justification + .filter(|_| self.action == InboxAction::NotAffected), + statement, + } + } +} + +/// What the undo strip takes back. +#[derive(Debug, Clone, PartialEq)] +enum UndoKind { + Decision(UndoRequest), + Snooze(String), +} + +/// The undo strip's offer; `id` tells a newer offer from the one a timer +/// was started for. +#[derive(Debug, Clone, PartialEq)] +struct UndoOffer { + id: u64, + kind: UndoKind, + message: String, +} + +/// The labels of a bucket: name, what goes in it, and what an empty one says. +const fn bucket_texts(bucket: Bucket) -> (Text, Text, Text) { + match bucket { + Bucket::Today => (tx::TODAY, tx::TODAY_HINT, tx::EMPTY_TODAY), + Bucket::ThisWeek => (tx::THIS_WEEK, tx::THIS_WEEK_HINT, tx::EMPTY_THIS_WEEK), + Bucket::Later => (tx::LATER, tx::LATER_HINT, tx::EMPTY_LATER), + Bucket::LikelyFalsePositive => (tx::AI, tx::AI_HINT, tx::EMPTY_AI), + } +} + +/// The CSS tone of a bucket's tile. +const fn bucket_tone(bucket: Bucket) -> &'static str { + match bucket { + Bucket::Today => "tone-danger", + Bucket::ThisWeek => "tone-warning", + Bucket::Later => "tone-neutral", + Bucket::LikelyFalsePositive => "tone-accent", + } +} + +/// An action's button label; the AI bucket's false alarm confirms the AI. +fn action_label(action: InboxAction, bucket: Bucket) -> Text { + match action { + InboxAction::FalsePositive if bucket == Bucket::LikelyFalsePositive => { + tx::CONFIRM_FALSE_POSITIVE + } + InboxAction::FalsePositive => tx::FALSE_POSITIVE, + InboxAction::AcceptedRisk => tx::ACCEPT_RISK, + InboxAction::Confirm => tx::CONFIRM, + InboxAction::NotAffected => tx::NOT_AFFECTED, + InboxAction::Affected => tx::AFFECTED, + } +} + +/// The action key `f` or `a` stands for on `card`, if the card offers it: +/// false alarm and accepted risk, on a CVE card their VEX counterparts. +fn shortcut_action(key: &str, card: &InboxCard) -> Option { + let wanted = match (key, card.kind) { + ("f", CardKind::Finding) => InboxAction::FalsePositive, + ("f", CardKind::CvePackage) => InboxAction::NotAffected, + ("a", CardKind::Finding) => InboxAction::AcceptedRisk, + ("a", CardKind::CvePackage) => InboxAction::Affected, + _ => return None, + }; + card.actions.contains(&wanted).then_some(wanted) +} + +/// A day in the reader's convention: `01.12.2026`, `2026-12-01`. +fn format_day(time: &DateTime, lang: Lang) -> String { + match lang { + Lang::De => time.format("%d.%m.%Y").to_string(), + Lang::En => time.format("%Y-%m-%d").to_string(), + } +} + +/// A reason as a chip: its text and tone. +fn chip(reason: &Reason, lang: Lang) -> (String, &'static str) { + match reason { + Reason::AiDismissed => (tx::AI_DISMISSED.get(lang).to_string(), "tone-accent"), + Reason::Kev => (tx::KEV.get(lang).to_string(), "tone-danger"), + Reason::Epss { percentile } => (tx::epss(*percentile, lang), "tone-warning"), + Reason::EnisaDeadline { + stage: Some(stage), + overdue, + hours_left, + .. + } => (tx::enisa(stage, *overdue, *hours_left, lang), "tone-danger"), + Reason::EnisaDeadline { stage: None, .. } => { + (tx::CRA_DUTY.get(lang).to_string(), "tone-danger") + } + Reason::SecretInCode => (tx::SECRET_IN_CODE.get(lang).to_string(), "tone-danger"), + Reason::FixAvailable { version } => (tx::fix(version), "tone-success"), + Reason::Resubmission { since } => ( + tx::resubmission(&format_day(since, lang), lang), + "tone-info", + ), + } +} + +/// The page's state and what it does with it; every field is a copyable +/// handle, so event handlers take the whole of it. +#[derive(Clone, Copy)] +struct Inbox { + view: Resource>, + hidden: Signal>, + pending: Signal>, + undo: Signal>, + offers: Signal, + busy: Signal, + page: Signal>>, + toasts: Toasts, + lang: Lang, +} + +impl Inbox { + /// Start `action` on `card`: at once, or by asking for its input first. + fn begin(mut self, card: &InboxCard, action: InboxAction) { + if !action.needs_input() { + self.decide( + card.title.clone(), + Pending { + key: card.key.clone(), + action, + text: String::new(), + justification: None, + }, + ); + return; + } + let text = match (action, &card.fix_version) { + (InboxAction::Affected, Some(version)) => tx::update_to(version, self.lang), + _ => String::new(), + }; + self.pending.set(Some(Pending { + key: card.key.clone(), + action, + text, + justification: None, + })); + } + + /// Apply `decision` to the card titled `title`, then offer to undo it. + fn decide(mut self, title: String, decision: Pending) { + if *self.busy.peek() || !decision.ready() { + return; + } + self.busy.set(true); + spawn(async move { + match decide_card(decision.request()).await { + Ok(answer) => { + self.hidden.write().insert(answer.key.clone()); + self.pending.set(None); + let message = format!("{}: {title}", tx::DECIDED.get(self.lang)); + self.offer( + UndoKind::Decision(UndoRequest { + key: answer.key, + previous: answer.previous, + }), + message, + ); + self.view.restart(); + } + Err(e) => self.failed(&e), + } + self.busy.set(false); + self.refocus().await; + }); + } + + /// Put `card` off as `choice` says, then offer to undo it. + fn snooze(mut self, card: &InboxCard, choice: SnoozeFor) { + if *self.busy.peek() { + return; + } + self.busy.set(true); + let request = SnoozeRequest { + key: card.key.clone(), + snooze_for: choice, + }; + spawn(async move { + match snooze_card(request).await { + Ok(answer) => { + self.hidden.write().insert(answer.key.clone()); + self.pending.set(None); + let message = tx::snoozed(&format_day(&answer.until, self.lang), self.lang); + self.offer(UndoKind::Snooze(answer.key), message); + self.view.restart(); + } + Err(e) => self.failed(&e), + } + self.busy.set(false); + self.refocus().await; + }); + } + + /// Take the offered decision or snooze back. + fn undo(mut self) { + let Some(offer) = self.undo.write().take() else { + return; + }; + spawn(async move { + let (key, result) = match offer.kind { + UndoKind::Decision(request) => (request.key.clone(), undo_decision(request).await), + UndoKind::Snooze(key) => (key.clone(), unsnooze_card(key).await), + }; + match result { + Ok(()) => { + self.hidden.write().remove(&key); + self.toasts.push(ToastType::Info, tx::UNDONE.get(self.lang)); + self.view.restart(); + } + Err(e) => self.failed(&e), + } + self.refocus().await; + }); + } + + /// Show the undo strip with `message` for a while. + fn offer(mut self, kind: UndoKind, message: String) { + let id = *self.offers.peek() + 1; + self.offers.set(id); + self.undo.set(Some(UndoOffer { id, kind, message })); + #[cfg(feature = "web")] + { + let mut undo = self.undo; + spawn(async move { + gloo_timers::future::TimeoutFuture::new(UNDO_MS).await; + if undo.peek().as_ref().is_some_and(|o| o.id == id) { + undo.set(None); + } + }); + } + } + + fn failed(mut self, error: &ServerFnError) { + self.toasts.push( + ToastType::Error, + format!("{}: {error}", tx::FAILED.get(self.lang)), + ); + } + + /// Give the keyboard back to the page (a removed card took the focus + /// with it). + async fn refocus(self) { + let page = self.page.peek().clone(); + if let Some(page) = page { + // Focusing can only fail when the page has gone; nothing to do then. + let _focused = page.set_focus(true).await; + } + } +} + +#[component] +pub fn HeutePage() -> Element { + let lang = use_lang()(); + let can_write = use_can_write(); + let target = use_signal(String::new); + let bucket = use_signal(|| Bucket::Today); + let mut selected = use_signal(|| 0_usize); + let view = use_resource(move || async move { fetch_inbox(target(), bucket(), None).await }); + let inbox = Inbox { + view, + hidden: use_signal(HashSet::new), + pending: use_signal(|| None), + undo: use_signal(|| None), + offers: use_signal(|| 0), + busy: use_signal(|| false), + page: use_signal(|| None), + toasts: use_context::(), + lang, + }; + + // The sidebar shows the workspace's count, not one target's. + use_effect(move || { + if let Some(Ok(view)) = &*view.read() { + if target.peek().is_empty() && *bucket.peek() == view.bucket { + *TODAY_COUNT.write() = Some(view.counts.today); + } + } + }); + // Keep the chosen card in sight. + use_effect(move || { + let _ = selected(); + let _scrolled = document::eval( + "document.querySelector('.inbox-card.is-selected')?.scrollIntoView({block: 'nearest'})", + ); + }); + + let current = view.read().clone(); + let cards: Vec = match ¤t { + Some(Ok(v)) => { + let hidden = inbox.hidden.read(); + v.cards + .iter() + .filter(|c| !hidden.contains(&c.key)) + .cloned() + .collect() + } + _ => Vec::new(), + }; + let chosen = selected().min(cards.len().saturating_sub(1)); + let key_cards = cards.clone(); + let mut pending = inbox.pending; + let onkeydown = move |e: KeyboardEvent| { + let modifiers = e.modifiers(); + if modifiers.ctrl() || modifiers.meta() || modifiers.alt() { + return; + } + let key = match e.key() { + Key::Character(c) => c, + Key::Escape => { + pending.set(None); + return; + } + _ => return, + }; + let card = key_cards.get(chosen); + match (key.as_str(), card) { + ("j", Some(_)) => selected.set((chosen + 1).min(key_cards.len() - 1)), + ("k", Some(_)) => selected.set(chosen.saturating_sub(1)), + ("f" | "a", Some(card)) if can_write => { + if let Some(action) = shortcut_action(&key, card) { + e.prevent_default(); + inbox.begin(card, action); + } + } + ("s", Some(card)) if can_write => { + e.prevent_default(); + inbox.snooze(card, SnoozeFor::Week); + } + _ => {} + } + }; + + rsx! { + div { + class: "inbox-page", + tabindex: "0", + onkeydown, + onmounted: move |e| { + let page = e.data(); + let mut handle = inbox.page; + handle.set(Some(page.clone())); + spawn(async move { + let _focused = page.set_focus(true).await; + }); + }, + PageHeader { + title: tx::TITLE.get(lang).to_string(), + description: tx::SUBTITLE.get(lang).to_string(), + } + match current { + None => rsx! { div { class: "loading", {common::LOADING.get(lang)} } }, + Some(Err(_)) => rsx! { + div { class: "card inbox-empty", + p { {tx::LOAD_FAILED.get(lang)} } + button { + class: "btn btn-secondary btn-sm", + onclick: move |_| { let mut view = view; view.restart(); }, + {common::RETRY.get(lang)} + } + } + }, + Some(Ok(v)) => rsx! { + InboxHeader { view: v.clone(), target, bucket, selected, pending } + if cards.is_empty() { + div { class: "card inbox-empty", + p { {bucket_texts(v.bucket).2.get(lang)} } + } + } else { + div { class: "inbox-cards", + for (i, card) in cards.into_iter().enumerate() { + CardView { + key: "{card.key}", + target_name: v + .targets + .iter() + .find(|t| t.id == card.target_id) + .map_or_else(|| card.target_id.clone(), |t| t.name.clone()), + selected: i == chosen, + can_write, + pending: inbox + .pending + .read() + .clone() + .filter(|p| p.key == card.key), + on_select: move |_| selected.set(i), + on_action: { + let card = card.clone(); + move |action| inbox.begin(&card, action) + }, + on_snooze: { + let card = card.clone(); + move |choice| inbox.snooze(&card, choice) + }, + on_edit: move |next| pending.set(Some(next)), + on_submit: { + let title = card.title.clone(); + move |decision| inbox.decide(title.clone(), decision) + }, + on_cancel: move |_| pending.set(None), + card, + } + } + } + if can_write { + p { class: "inbox-shortcuts", {tx::SHORTCUTS.get(lang)} } + } + } + }, + } + if let Some(offer) = (inbox.undo)() { + div { class: "inbox-undo", role: "status", + span { "{offer.message}" } + button { + class: "btn btn-sm inbox-undo-btn", + onclick: move |_| inbox.undo(), + {tx::UNDO.get(lang)} + } + } + } + } + } +} + +/// The Erstbewertung, the target chips and the bucket tiles. +#[component] +fn InboxHeader( + view: InboxView, + target: Signal, + bucket: Signal, + selected: Signal, + pending: Signal>, +) -> Element { + let lang = use_lang()(); + let progress = view.progress; + let percent = progress.percent(); + let mut choose_bucket = move |b: Bucket| { + bucket.set(b); + selected.set(0); + pending.set(None); + }; + let mut choose_target = move |id: String| { + target.set(id); + selected.set(0); + pending.set(None); + }; + rsx! { + section { class: "inbox-progress", title: tx::PROGRESS_HINT.get(lang), + div { class: "inbox-progress-head", + span { class: "inbox-progress-label", {tx::PROGRESS.get(lang)} } + span { class: "inbox-progress-value", + {tx::progress_line(progress.decided, progress.total, lang)} + } + span { class: "inbox-progress-percent", "{percent} %" } + } + div { + class: "inbox-progress-track", + role: "progressbar", + "aria-valuemin": "0", + "aria-valuemax": "100", + "aria-valuenow": "{percent}", + div { class: "inbox-progress-fill", style: "width: {percent}%" } + } + } + if !view.targets.is_empty() { + div { class: "inbox-targets", + button { + class: if target().is_empty() { "inbox-target is-active" } else { "inbox-target" }, + onclick: move |_| choose_target(String::new()), + {tx::ALL_TARGETS.get(lang)} + } + for t in view.targets.iter().cloned() { + button { + key: "{t.id}", + class: if target() == t.id { "inbox-target is-active" } else { "inbox-target" }, + onclick: move |_| choose_target(t.id.clone()), + "{t.name}" + span { class: "inbox-target-count", "{t.cards}" } + } + } + } + } + div { class: "inbox-buckets", role: "tablist", + for b in Bucket::ALL { + { + let (label, hint, _) = bucket_texts(b); + let active = view.bucket == b; + let tone = bucket_tone(b); + let count = view.counts.get(b); + rsx! { + button { + key: "{b.as_str()}", + class: if active { "inbox-bucket {tone} is-active" } else { "inbox-bucket {tone}" }, + role: "tab", + "aria-selected": if active { "true" } else { "false" }, + onclick: move |_| choose_bucket(b), + span { class: "inbox-bucket-count", "{count}" } + span { class: "inbox-bucket-label", {label.get(lang)} } + span { class: "inbox-bucket-hint", {hint.get(lang)} } + } + } + } + } + } + } +} + +/// One card: what it is, why it is here, and its decisions. +#[component] +fn CardView( + card: InboxCard, + target_name: String, + selected: bool, + can_write: bool, + pending: Option, + on_select: EventHandler<()>, + on_action: EventHandler, + on_snooze: EventHandler, + on_edit: EventHandler, + on_submit: EventHandler, + on_cancel: EventHandler<()>, +) -> Element { + let lang = use_lang()(); + let mut date = use_signal(String::new); + let details = match card.kind { + CardKind::Finding => Route::FindingDetailPage { + id: card.item_ids.first().cloned().unwrap_or_default(), + }, + CardKind::CvePackage => Route::TargetPage { + id: card.target_id.clone(), + }, + }; + let size = match card.kind { + CardKind::CvePackage => Some(tx::cves(card.count)), + CardKind::Finding if card.count > 1 => Some(tx::places(card.count, lang)), + CardKind::Finding => None, + }; + let chips: Vec<(String, &'static str)> = card.reasons.iter().map(|r| chip(r, lang)).collect(); + let bucket = card.bucket; + rsx! { + article { + class: if selected { "inbox-card is-selected" } else { "inbox-card" }, + onclick: move |_| on_select.call(()), + div { class: "inbox-card-head", + SeverityBadge { severity: card.severity.to_string() } + h3 { class: "inbox-card-title", "{card.title}" } + } + p { class: "inbox-card-sub", + span { class: "inbox-card-target", "{target_name}" } + if !card.subtitle.is_empty() { + code { class: "inbox-card-place", "{card.subtitle}" } + } + if let Some(size) = size { + span { class: "inbox-card-size", "{size}" } + } + } + if !chips.is_empty() { + div { class: "inbox-chips", + for (label, tone) in chips { + span { class: "inbox-chip {tone}", "{label}" } + } + } + } + if let Some(note) = card.note.clone() { + p { class: "inbox-card-note", + span { class: "inbox-card-note-label", {tx::AI_NOTE.get(lang)} } + "{note}" + } + } + if let Some(decision) = pending { + DecisionInput { decision, on_edit, on_submit, on_cancel } + } else { + div { class: "inbox-actions", + if can_write { + for (i, action) in card.actions.iter().copied().enumerate() { + button { + key: "{i}", + class: if i == 0 { "btn btn-primary btn-sm" } else { "btn btn-secondary btn-sm" }, + onclick: move |e| { + e.stop_propagation(); + on_action.call(action); + }, + {action_label(action, bucket).get(lang)} + } + } + details { + class: "inbox-later", + onclick: move |e| e.stop_propagation(), + summary { class: "btn btn-ghost btn-sm", {tx::LATER_MENU.get(lang)} " ▾" } + div { class: "inbox-later-menu", + button { + class: "inbox-later-option", + onclick: move |_| on_snooze.call(SnoozeFor::Week), + {tx::ONE_WEEK.get(lang)} + } + button { + class: "inbox-later-option", + onclick: move |_| on_snooze.call(SnoozeFor::Month), + {tx::ONE_MONTH.get(lang)} + } + label { class: "inbox-later-date", + span { {tx::ON_DATE.get(lang)} } + input { + r#type: "date", + value: "{date}", + oninput: move |e| date.set(e.value()), + onkeydown: move |e| e.stop_propagation(), + } + } + button { + class: "btn btn-secondary btn-sm", + disabled: NaiveDate::parse_from_str(&date(), "%Y-%m-%d").is_err(), + onclick: move |_| { + if let Ok(day) = NaiveDate::parse_from_str(&date(), "%Y-%m-%d") { + on_snooze.call(SnoozeFor::Date { date: day }); + } + }, + {tx::SET_DATE.get(lang)} + } + } + } + } + Link { + class: "inbox-details", + to: details, + onclick: move |e: MouseEvent| e.stop_propagation(), + {tx::DETAILS.get(lang)} + } + } + } + } + } +} + +/// The input a decision needs before it can be made. +#[component] +fn DecisionInput( + decision: Pending, + on_edit: EventHandler, + on_submit: EventHandler, + on_cancel: EventHandler<()>, +) -> Element { + let lang = use_lang()(); + let placeholder = match decision.action { + InboxAction::NotAffected => vex_tx::IMPACT_STATEMENT, + InboxAction::Affected => vex_tx::ACTION_STATEMENT, + InboxAction::AcceptedRisk | InboxAction::FalsePositive | InboxAction::Confirm => tx::REASON, + }; + let ready = decision.ready(); + let typed = decision.clone(); + let chosen = decision.clone(); + let submitted = decision.clone(); + let on_key = decision.clone(); + let justification = decision + .justification + .map(VexJustification::as_str) + .unwrap_or_default(); + rsx! { + div { + class: "inbox-input", + onclick: move |e| e.stop_propagation(), + if decision.action == InboxAction::NotAffected { + select { + class: "inbox-input-select", + value: "{justification}", + "aria-label": vex_tx::JUSTIFICATION.get(lang), + onkeydown: move |e| e.stop_propagation(), + onchange: move |e| { + let mut next = chosen.clone(); + next.justification = JUSTIFICATIONS + .iter() + .map(|(j, _)| *j) + .find(|j| j.as_str() == e.value()); + on_edit.call(next); + }, + option { value: "", {vex_tx::NO_JUSTIFICATION.get(lang)} } + for (j, label) in JUSTIFICATIONS { + option { key: "{j.as_str()}", value: j.as_str(), {label.get(lang)} } + } + } + } + input { + class: "inbox-input-text", + r#type: "text", + value: "{decision.text}", + placeholder: placeholder.get(lang), + "aria-label": placeholder.get(lang), + onmounted: move |e| async move { + // Focusing can only fail when the input has gone. + let _focused = e.data().set_focus(true).await; + }, + oninput: move |e| { + let mut next = typed.clone(); + next.text = e.value(); + on_edit.call(next); + }, + onkeydown: move |e| { + e.stop_propagation(); + match e.key() { + Key::Enter if on_key.ready() => on_submit.call(on_key.clone()), + Key::Escape => on_cancel.call(()), + _ => {} + } + }, + } + button { + class: "btn btn-primary btn-sm", + disabled: !ready, + onclick: move |_| on_submit.call(submitted.clone()), + {tx::DECIDE.get(lang)} + } + button { + class: "btn btn-ghost btn-sm", + onclick: move |_| on_cancel.call(()), + {tx::CANCEL.get(lang)} + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use compliance_core::models::Severity; + + fn card(kind: CardKind, actions: Vec) -> InboxCard { + InboxCard { + key: "f-1".into(), + kind, + bucket: Bucket::Today, + target_id: "t1".into(), + title: "t".into(), + subtitle: String::new(), + severity: Severity::High, + count: 1, + reasons: Vec::new(), + item_ids: vec!["1".into()], + actions, + fix_version: None, + note: None, + } + } + + #[test] + fn shortcuts_pick_the_card_s_matching_action() { + use InboxAction::*; + let finding = card(CardKind::Finding, vec![FalsePositive, AcceptedRisk]); + assert_eq!(shortcut_action("f", &finding), Some(FalsePositive)); + assert_eq!(shortcut_action("a", &finding), Some(AcceptedRisk)); + assert_eq!(shortcut_action("x", &finding), None); + let ai = card(CardKind::Finding, vec![FalsePositive, Confirm]); + assert_eq!(shortcut_action("a", &ai), None, "not offered"); + let cve = card(CardKind::CvePackage, vec![Affected, NotAffected]); + assert_eq!(shortcut_action("f", &cve), Some(NotAffected)); + assert_eq!(shortcut_action("a", &cve), Some(Affected)); + } + + #[test] + fn a_decision_needs_its_input_and_sends_it_in_the_right_field() { + let mut risk = Pending { + key: "f-1".into(), + action: InboxAction::AcceptedRisk, + text: " ".into(), + justification: None, + }; + assert!(!risk.ready()); + risk.text = " isolated ".into(); + assert!(risk.ready()); + assert_eq!(risk.request().reason.as_deref(), Some("isolated")); + assert_eq!(risk.request().statement, None); + let mut not_affected = Pending { + key: "c-1-2".into(), + action: InboxAction::NotAffected, + text: String::new(), + justification: None, + }; + assert!(!not_affected.ready()); + not_affected.justification = Some(VexJustification::VulnerableCodeNotPresent); + assert!(not_affected.ready()); + assert_eq!( + not_affected.request().justification, + Some(VexJustification::VulnerableCodeNotPresent) + ); + let affected = Pending { + key: "c-1-2".into(), + action: InboxAction::Affected, + text: "Update to version 2.17.1.".into(), + justification: Some(VexJustification::ComponentNotPresent), + }; + assert_eq!( + affected.request().statement.as_deref(), + Some("Update to version 2.17.1.") + ); + assert_eq!(affected.request().justification, None); + } + + #[test] + fn chips_name_their_reason() { + let (label, tone) = chip(&Reason::Kev, Lang::De); + assert_eq!(label, "Aktiv ausgenutzt (CISA KEV)"); + assert_eq!(tone, "tone-danger"); + let (label, _) = chip( + &Reason::FixAvailable { + version: "2.17.1".into(), + }, + Lang::En, + ); + assert_eq!(label, "Fix: 2.17.1"); + assert_eq!( + action_label(InboxAction::FalsePositive, Bucket::LikelyFalsePositive), + tx::CONFIRM_FALSE_POSITIVE + ); + assert_eq!( + action_label(InboxAction::FalsePositive, Bucket::Today), + tx::FALSE_POSITIVE + ); + } +} diff --git a/compliance-dashboard/src/pages/mod.rs b/compliance-dashboard/src/pages/mod.rs index f893a84..bf98dd7 100644 --- a/compliance-dashboard/src/pages/mod.rs +++ b/compliance-dashboard/src/pages/mod.rs @@ -10,6 +10,7 @@ pub mod findings; pub mod graph_explorer; pub(crate) mod graph_view; pub mod impact_analysis; +pub mod inbox; pub mod issues; pub mod mcp_servers; pub mod mcp_tokens; @@ -32,6 +33,7 @@ pub use finding_detail::FindingDetailPage; pub use findings::FindingsPage; pub use graph_explorer::GraphExplorerPage; pub use impact_analysis::ImpactAnalysisPage; +pub use inbox::HeutePage; pub use issues::IssuesPage; pub use mcp_servers::McpServersPage; pub use mcp_tokens::McpTokensPage;