diff --git a/compliance-dashboard/assets/main.css b/compliance-dashboard/assets/main.css index 88dba23..93a3f9a 100644 --- a/compliance-dashboard/assets/main.css +++ b/compliance-dashboard/assets/main.css @@ -9331,3 +9331,182 @@ span.repo-crumb-name { .rel-sieve { grid-template-columns: minmax(0, 1fr); } .rel-sieve-mesh { height: 4px; background: repeating-linear-gradient(to right, var(--accent) 0 6px, transparent 6px 11px); } } + +/* ============ Supplier offers (#1028): the customer's side ============ */ +.offer-others { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 8px; +} +.offer-others-title { font-size: 13px; color: var(--text-tertiary); margin-right: 4px; } +.offer-pick { + padding: 6px 12px; + font: inherit; + font-size: 13px; + color: var(--text-secondary); + background: var(--bg-card); + border: 1px solid var(--border-bright); + border-radius: 999px; + cursor: pointer; +} +.offer-pick.active { color: var(--accent); border-color: var(--accent); background: var(--accent-muted); } +.rel-canvas.plain { background-image: none; } +.offer-frame { + position: absolute; + box-sizing: border-box; + background: var(--bg-primary); + border: 1px solid var(--border); + border-radius: 20px; +} +.offer-machine { + position: absolute; + display: flex; + align-items: center; + gap: 6px; + font-size: 13px; + font-weight: 600; + color: var(--text-secondary); +} +.offer-machine select, +.offer-rest { + max-width: 200px; + padding: 4px 8px; + font: inherit; + font-weight: 600; + color: var(--text-primary); + background: var(--bg-card); + border: 1px solid var(--border-bright); + border-radius: 8px; +} +.offer-option { + position: absolute; + box-sizing: border-box; + padding: 10px 14px; + display: flex; + align-items: center; + gap: 12px; + font: inherit; + text-align: left; + color: var(--text-primary); + background: var(--bg-card); + border: 1px solid var(--border-bright); + border-radius: 14px; + cursor: pointer; +} +div.offer-option { flex-direction: column; align-items: flex-start; justify-content: center; gap: 4px; cursor: default; } +.offer-option.chosen { + background: color-mix(in srgb, var(--accent) 7%, var(--bg-card)); + border: 2px solid var(--accent); + box-shadow: 0 0 0 5px var(--accent-muted); +} +.offer-option:disabled { cursor: default; } +.offer-radio { + flex: none; + width: 20px; + height: 20px; + box-sizing: border-box; + border-radius: 10px; + border: 2px solid var(--border-strong); +} +.offer-option.chosen .offer-radio { + border: 0; + background: var(--accent) url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24'%3E%3Cpath d='M7 12.5l3.2 3.2L17 9' fill='none' stroke='white' stroke-width='2.6' stroke-linecap='round' stroke-linejoin='round'/%3E%3C/svg%3E") center / 16px no-repeat; +} +.offer-option-text { display: flex; flex-direction: column; gap: 2px; min-width: 0; } +.offer-option-text b { + font-size: 15px; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} +.offer-option-sub { font-size: 12px; color: var(--text-secondary); } +.offer-parts { + position: absolute; + display: flex; + gap: 8px; + align-items: center; +} +.offer-part { + flex: 1 1 0; + min-width: 0; + height: 34px; + box-sizing: border-box; + padding: 0 10px; + display: flex; + align-items: center; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + font-size: 12px; + color: var(--text-tertiary); + background: var(--bg-card); + border: 1px solid var(--border); + border-radius: 10px; +} +.offer-part.more { flex: none; border-style: dashed; } +.rel-chip.parcel { color: var(--accent-ink); background: var(--accent); } +.offer-meaning { display: flex; flex-wrap: wrap; gap: 14px; align-items: stretch; } +.offer-tile { + flex: 1 1 200px; + display: flex; + gap: 12px; + align-items: flex-start; + padding: 16px; + font-size: 14px; + line-height: 1.45; + color: var(--accent); + background: var(--bg-card); + border: 1px solid var(--border); + border-radius: 14px; +} +.offer-tile svg { flex: none; } +.offer-tile > span { color: var(--text-primary); } +.offer-tile-sub { color: var(--text-tertiary); } +.offer-tile-warn { color: var(--warning); } +.offer-answer { + flex: 1 1 260px; + display: flex; + flex-direction: column; + justify-content: center; + gap: 10px; +} +.offer-answer .btn { min-height: 44px; justify-content: center; } +.offer-answer-note { margin: 0; font-size: 13px; line-height: 1.5; color: var(--text-secondary); } +.btn.offer-decline-confirm { color: var(--bg-card); background: var(--danger); border: 0; } +.offer-chain-title { position: absolute; left: 32px; top: 22px; margin: 0; font-size: 16px; font-weight: 600; } +.offer-chain-link { position: absolute; right: 40px; top: 24px; font-size: 13px; } +.offer-chain-supplier { + position: absolute; + box-sizing: border-box; + padding: 10px 14px; + display: flex; + align-items: center; + color: var(--bg-card); + background: var(--text-primary); + border-radius: 14px; +} +.offer-chain-supplier.ended { + color: var(--text-tertiary); + background: var(--bg-primary); + border: 1px dashed var(--border-strong); +} +.offer-chain-component { text-decoration: none; } +.offer-chain-component:hover { border-color: var(--border-accent); } +.offer-waiting { + margin-bottom: 16px; + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 10px; + padding: 12px 16px; + font-size: 14px; + font-weight: 500; + text-decoration: none; + color: var(--text-primary); + background: var(--accent-muted); + border: 1px solid var(--border-accent); + border-radius: 12px; +} +.offer-waiting-dot { width: 8px; height: 8px; border-radius: 4px; background: var(--accent); } +.offer-waiting-go { margin-left: auto; font-weight: 600; color: var(--accent); } diff --git a/compliance-dashboard/src/app.rs b/compliance-dashboard/src/app.rs index f3b31aa..cc17d3c 100644 --- a/compliance-dashboard/src/app.rs +++ b/compliance-dashboard/src/app.rs @@ -22,6 +22,9 @@ pub enum Route { SupplyChainPage {}, #[route("/targets")] TargetsPage {}, + // What connected suppliers offer the workspace (#1028). + #[route("/supplier-offers")] + SupplierOffersPage {}, #[route("/targets/:id")] TargetPage { id: String }, // The target's views (#957), one tab each (`findings`, `cves`, diff --git a/compliance-dashboard/src/components/sidebar.rs b/compliance-dashboard/src/components/sidebar.rs index a3b5280..835f1da 100644 --- a/compliance-dashboard/src/components/sidebar.rs +++ b/compliance-dashboard/src/components/sidebar.rs @@ -41,6 +41,8 @@ pub fn Sidebar() -> Element { let lang = use_lang()(); let can_write = use_can_write(); + // Open supplier offers, counted on "Prüfobjekte" (#1028). + let open_offers = crate::pages::offers::use_open_offers(); let nav_items = [ NavItem { label: nav::OVERVIEW, @@ -186,6 +188,7 @@ pub fn Sidebar() -> Element { (Route::SbomEcosystemPage { .. }, Route::SbomPage { .. }) => true, (Route::CompliancePage { .. }, Route::TargetsPage {}) => true, (Route::TargetReleasesPage { .. }, Route::TargetsPage {}) => true, + (Route::SupplierOffersPage {}, Route::TargetsPage {}) => true, (Route::DastTargetsPage {}, Route::DastOverviewPage {}) => true, (Route::DastFindingsPage {}, Route::DastOverviewPage {}) => true, (Route::DastFindingDetailPage { .. }, Route::DastOverviewPage {}) => true, @@ -230,6 +233,9 @@ pub fn Sidebar() -> Element { if !collapsed() { span { "{label}" } } + if let Some(n) = (item.route == Route::TargetsPage {}).then_some(open_offers).flatten().filter(|n| *n > 0) { + span { class: "nav-count", title: crate::i18n::texts::offers::waiting(n, lang), "{n}" } + } } } } diff --git a/compliance-dashboard/src/i18n/mod.rs b/compliance-dashboard/src/i18n/mod.rs index 164fe37..1f14767 100644 --- a/compliance-dashboard/src/i18n/mod.rs +++ b/compliance-dashboard/src/i18n/mod.rs @@ -70,6 +70,15 @@ impl Text { } } +/// The agent's refusal code in a server function's error message: the +/// first word of `error` that is one of `codes`, as in +/// `error running server function: label_taken (409) (details: None)`. +pub fn agent_code<'a>(error: &str, codes: &[&'a str]) -> Option<&'a str> { + error + .split(|c: char| !(c.is_ascii_lowercase() || c == '_')) + .find_map(|word| codes.iter().copied().find(|code| *code == word)) +} + /// A byte count for people: `12,3 MB` in German, `12.3 MB` in English. pub fn format_bytes(bytes: u64, lang: Lang) -> String { const UNITS: [&str; 4] = ["KB", "MB", "GB", "TB"]; diff --git a/compliance-dashboard/src/i18n/texts.rs b/compliance-dashboard/src/i18n/texts.rs index 40c8147..8d1d009 100644 --- a/compliance-dashboard/src/i18n/texts.rs +++ b/compliance-dashboard/src/i18n/texts.rs @@ -8416,8 +8416,6 @@ pub mod releases { } /// The agent's refusal `error` in words; anything else as it came. pub fn refusal(error: &str, lang: Lang) -> String { - // The agent's code is one word of the message, as in - // `error running server function: label_taken (409) (details: None)`. const CODES: [&str; 7] = [ "label_taken", "label", @@ -8427,10 +8425,7 @@ pub mod releases { "peer_not_entitled", "released", ]; - let code = error - .split(|c: char| !(c.is_ascii_lowercase() || c == '_')) - .find(|word| CODES.contains(word)); - let text = match code { + let text = match crate::i18n::agent_code(error, &CODES) { Some("label_taken") => Text { de: "Diese Versionsangabe gibt es schon. Wählen Sie eine neue.", en: "This label exists already. Choose a new one.", @@ -8458,3 +8453,279 @@ pub mod releases { text.get(lang).to_string() } } + +/// The customer's offer screen (#1028): what connected suppliers offer. +pub mod offers { + use super::Text; + use crate::i18n::Lang; + + pub const CRUMB: Text = Text { + de: "Freigaben von Zulieferern", + en: "Releases from suppliers", + }; + pub fn title(supplier: &str, product: &str, lang: Lang) -> String { + match lang { + Lang::De => format!("{supplier} möchte Ihnen die SBOM von {product} liefern"), + Lang::En => format!("{supplier} would like to deliver the SBOM of {product}"), + } + } + pub const INTRO: Text = Text { + de: "Wählen Sie, wo sie in Ihrer Maschine ankommt. Danach erhalten Sie jede neue \ + Version, ohne dass jemand eine Datei schickt.", + en: "Choose where it arrives in your machine. After that every new version reaches \ + you without anyone sending a file.", + }; + pub const NONE_OPEN: Text = Text { + de: "Gerade wartet kein Angebot auf Ihre Antwort. Gibt Ihnen ein verbundener \ + Zulieferer eine SBOM frei, erscheint sie hier.", + en: "No offer is waiting for your answer. When a connected supplier releases an SBOM \ + to you, it appears here.", + }; + pub const LOADING: Text = Text { + de: "Angebote werden geladen …", + en: "Loading the offers …", + }; + pub const LOAD_FAILED: Text = Text { + de: "Die Angebote lassen sich gerade nicht laden.", + en: "The offers cannot be loaded right now.", + }; + pub const OTHERS: Text = Text { + de: "Offene Angebote", + en: "Open offers", + }; + pub fn from(product: &str, supplier: &str, lang: Lang) -> String { + match lang { + Lang::De => format!("{product} von {supplier}"), + Lang::En => format!("{product} from {supplier}"), + } + } + pub const ROUTE: Text = Text { + de: "Wohin die SBOM geht", + en: "Where the SBOM goes", + }; + pub const SUPPLIER: Text = Text { + de: "verbundener Zulieferer", + en: "connected supplier", + }; + pub fn parcel(label: &str, components: Option, lang: Lang) -> String { + match (components, lang) { + (Some(n), Lang::De) => format!("{label}, {n} Komp."), + (Some(n), Lang::En) => format!("{label}, {n} comp."), + (None, _) => label.to_string(), + } + } + pub const NO_VERSION: Text = Text { + de: "noch keine Version", + en: "no version yet", + }; + pub const MACHINE: Text = Text { + de: "Ihre Maschine", + en: "Your machine", + }; + pub const NO_MACHINE: Text = Text { + de: "keinem Produkt zuordnen", + en: "no product", + }; + pub const AS_NEW: Text = Text { + de: "Als neue Komponente", + en: "As a new component", + }; + pub fn created(product: &str, lang: Lang) -> String { + match lang { + Lang::De => format!("„{product}“ wird angelegt"), + Lang::En => format!("“{product}” is created"), + } + } + pub fn into(component: &str, lang: Lang) -> String { + match lang { + Lang::De => format!("In {component}"), + Lang::En => format!("Into {component}"), + } + } + pub const REPLACES: Text = Text { + de: "ersetzt die hochgeladene SBOM", + en: "replaces the uploaded SBOM", + }; + pub const REPLACES_LATER: Text = Text { + de: "ersetzt die SBOM mit der ersten Version", + en: "replaces the SBOM with the first version", + }; + pub const OTHER_COMPONENT: Text = Text { + de: "Andere Komponente …", + en: "Another component …", + }; + pub fn more_parts(n: usize, lang: Lang) -> String { + match lang { + Lang::De => format!("+{n} weitere"), + Lang::En => format!("+{n} more"), + } + } + pub const MEANING: Text = Text { + de: "Was die Annahme bedeutet", + en: "What accepting means", + }; + pub const ONE_MORE: Text = Text { + de: "Ein Prüfobjekt mehr", + en: "One more target", + }; + pub const COUNTS_LIKE_ANY: Text = Text { + de: "zählt wie jedes andere", + en: "counts like any other", + }; + pub const BILLED_EXTRA: Text = Text { + de: "über Ihrem Tarif, wird zusätzlich berechnet", + en: "beyond your plan, billed on top", + }; + pub const NO_NEW_TARGET: Text = Text { + de: "Kein neues Prüfobjekt", + en: "No new target", + }; + pub const EVERY_VERSION: Text = Text { + de: "Jede neue Version kommt von selbst", + en: "Every new version arrives by itself", + }; + pub const AND_IS_SCANNED: Text = Text { + de: "und wird gleich geprüft", + en: "and is scanned at once", + }; + pub const ONLY_BOM: Text = Text { + de: "Nur die Stückliste", + en: "Only the bill of materials", + }; + pub const NO_FINDINGS: Text = Text { + de: "nichts von den Befunden des Zulieferers", + en: "nothing of the supplier's findings", + }; + pub const ACCEPT_NEW: Text = Text { + de: "Als neue Komponente annehmen", + en: "Accept as a new component", + }; + pub fn accept_into(component: &str, lang: Lang) -> String { + match lang { + Lang::De => format!("In {component} annehmen"), + Lang::En => format!("Accept into {component}"), + } + } + pub fn confirm_replace(component: &str, lang: Lang) -> String { + match lang { + Lang::De => format!("SBOM von {component} ersetzen und annehmen"), + Lang::En => format!("Replace the SBOM of {component} and accept"), + } + } + pub const DECLINE: Text = Text { + de: "Ablehnen", + en: "Decline", + }; + pub const DECLINE_CONFIRM: Text = Text { + de: "Endgültig ablehnen", + en: "Decline for good", + }; + pub const DECLINE_HINT: Text = Text { + de: "Der Zulieferer sieht die Ablehnung. Für eine neue Freigabe muss er erneut \ + freigeben.", + en: "The supplier sees that you declined. A new release needs them to release again.", + }; + pub const CANCEL: Text = Text { + de: "Abbrechen", + en: "Cancel", + }; + pub fn accepted(product: &str, lang: Lang) -> String { + match lang { + Lang::De => format!("{product} angenommen"), + Lang::En => format!("{product} accepted"), + } + } + pub fn declined(product: &str, lang: Lang) -> String { + match lang { + Lang::De => format!("{product} abgelehnt"), + Lang::En => format!("{product} declined"), + } + } + + // The supply lines. + pub const CHAIN: Text = Text { + de: "Ihre Lieferkette", + en: "Your supply chain", + }; + pub const CHAIN_LINK: Text = Text { + de: "Zur ganzen Lieferkette", + en: "Open the whole supply chain", + }; + pub fn in_products(names: &str, lang: Lang) -> String { + match lang { + Lang::De => format!("in {names}"), + Lang::En => format!("in {names}"), + } + } + pub const IN_NO_PRODUCT: Text = Text { + de: "keinem Produkt zugeordnet", + en: "in no product", + }; + pub const COMPONENT_GONE: Text = Text { + de: "Komponente entfernt", + en: "component removed", + }; + pub const ACCEPTED_CHIP: Text = Text { + de: "angenommen", + en: "accepted", + }; + pub fn ended(label: Option<&str>, lang: Lang) -> String { + match (label, lang) { + (Some(label), Lang::De) => format!("beendet, {label} bleibt"), + (Some(label), Lang::En) => format!("ended, {label} stays"), + (None, Lang::De) => "beendet".to_string(), + (None, Lang::En) => "ended".to_string(), + } + } + pub fn line(supplier: &str, component: &str, state: &str, lang: Lang) -> String { + match lang { + Lang::De => format!("Von {supplier} zu {component}: {state}"), + Lang::En => format!("From {supplier} to {component}: {state}"), + } + } + + // On the targets page and in the sidebar. + pub fn waiting(n: usize, lang: Lang) -> String { + match (n, lang) { + (1, Lang::De) => "Ein Zulieferer möchte Ihnen eine SBOM liefern".to_string(), + (n, Lang::De) => format!("{n} Angebote von Zulieferern warten auf Ihre Antwort"), + (1, Lang::En) => "A supplier would like to deliver an SBOM to you".to_string(), + (n, Lang::En) => format!("{n} offers from suppliers are waiting for your answer"), + } + } + pub const OPEN_THEM: Text = Text { + de: "Ansehen", + en: "View", + }; + + /// The agent's refusal `error` in words; anything else as it came. + pub fn refusal(error: &str, lang: Lang) -> String { + const CODES: [&str; 4] = [ + "answered", + "ended", + "target_taken", + "not_supplier_component", + ]; + let text = match crate::i18n::agent_code(error, &CODES) { + Some("answered") => Text { + de: "Dieses Angebot ist schon beantwortet.", + en: "This offer has been answered already.", + }, + Some("ended") => Text { + de: "Der Zulieferer hat die Freigabe beendet, oder die Verbindung besteht \ + nicht mehr.", + en: "The supplier ended the release, or the connection no longer exists.", + }, + Some("target_taken") => Text { + de: "Diese Komponente erhält schon die SBOM eines anderen Zulieferers.", + en: "This component already receives another supplier's SBOM.", + }, + Some("not_supplier_component") => Text { + de: "Nur eine zugekaufte Komponente kann eine SBOM eines Zulieferers erhalten.", + en: "Only a bought-in component can receive a supplier's SBOM.", + }, + _ => return error.to_string(), + }; + text.get(lang).to_string() + } +} diff --git a/compliance-dashboard/src/infrastructure/mod.rs b/compliance-dashboard/src/infrastructure/mod.rs index 747c28e..6e7bfcc 100644 --- a/compliance-dashboard/src/infrastructure/mod.rs +++ b/compliance-dashboard/src/infrastructure/mod.rs @@ -20,6 +20,7 @@ pub mod mcp; pub mod mcp_tokens; pub mod metering; pub mod notifications; +pub mod offers; pub mod onboarding; pub mod pentest; pub mod platform; diff --git a/compliance-dashboard/src/infrastructure/offers.rs b/compliance-dashboard/src/infrastructure/offers.rs new file mode 100644 index 0000000..4838fe2 --- /dev/null +++ b/compliance-dashboard/src/infrastructure/offers.rs @@ -0,0 +1,122 @@ +//! SBOM releases connected suppliers offer the workspace (#1028), the +//! customer's side: the agent's `/api/v1/sbom-offers`. + +use chrono::{DateTime, Utc}; +use compliance_core::models::TargetType; +use dioxus::prelude::*; +use serde::{Deserialize, Serialize}; + +/// Where an offer stands. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum OfferState { + /// Waiting for the workspace's answer. + Offered, + /// Accepted: each version arrives in its component. + Accepted, + Declined, + /// The supplier ended the release, the connection ended, or the + /// component was deleted. + Ended, +} + +/// One supplier's offer. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct OfferDto { + pub id: String, + /// The supplier workspace's display name. + pub supplier_name: String, + pub product_name: String, + pub product_type: TargetType, + pub state: OfferState, + /// The component it was accepted into. + #[serde(default)] + pub target_id: Option, + pub offered_at: DateTime, + #[serde(default)] + pub ended_at: Option>, + /// The version last delivered, and when. + #[serde(default)] + pub delivered_label: Option, + #[serde(default)] + pub delivered_at: Option>, + /// While open: the version accepting delivers at once. + #[serde(default)] + pub offered_label: Option, + #[serde(default)] + pub offered_components: Option, +} + +/// Where an accepted offer goes: an existing supplier component, or a new +/// one with its name and projects. Unset fields are left out (and read back +/// as unset: it also crosses to the server function this way). +#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)] +pub struct Destination { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub target_id: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub name: Option, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub project_ids: Vec, +} + +/// The workspace's offers, open ones first. +#[server] +pub async fn fetch_offers() -> Result, ServerFnError> { + super::agent_client::data(super::agent_client::agent_get("/api/v1/sbom-offers").await?).await +} + +/// Accept offer `id` into `to`. +#[server] +pub async fn accept_offer(id: String, to: Destination) -> Result { + let req = super::agent_client::agent_request( + reqwest::Method::POST, + &format!("/api/v1/sbom-offers/{id}/accept"), + ) + .await? + .json(&to); + super::agent_client::data(req).await +} + +/// Decline offer `id`. +#[server] +pub async fn decline_offer(id: String) -> Result { + let req = super::agent_client::agent_request( + reqwest::Method::POST, + &format!("/api/v1/sbom-offers/{id}/decline"), + ) + .await? + .json(&serde_json::json!({})); + super::agent_client::data(req).await +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_agents_offers_read() { + let offers: Vec = serde_json::from_value(serde_json::json!([{ + "id": "o1", "supplier_name": "Test Antriebstechnik", "product_name": "DR-4 Firmware", + "product_type": "firmware_rtos", "state": "offered", "target_id": null, + "offered_at": "2026-11-19T09:00:00Z", "decided_at": null, "ended_at": null, + "delivered_label": null, "delivered_at": null, + "offered_label": "1.4.0", "offered_components": 214 + }])) + .expect("readable"); + assert_eq!(offers[0].state, OfferState::Offered); + assert_eq!(offers[0].offered_components, Some(214)); + } + + #[test] + fn a_destination_names_only_what_is_set() { + let existing = Destination { + target_id: Some("t1".into()), + ..Default::default() + }; + let sent = serde_json::to_value(&existing).expect("serialisable"); + assert_eq!(sent, serde_json::json!({ "target_id": "t1" })); + let read: Destination = serde_json::from_value(sent).expect("reads back"); + assert_eq!(read, existing); + } +} diff --git a/compliance-dashboard/src/pages/mod.rs b/compliance-dashboard/src/pages/mod.rs index 1af362b..f97ea87 100644 --- a/compliance-dashboard/src/pages/mod.rs +++ b/compliance-dashboard/src/pages/mod.rs @@ -15,6 +15,7 @@ pub mod issues; pub mod machine; pub mod mcp_servers; pub mod mcp_tokens; +pub mod offers; pub mod onboarding; pub mod overview; pub mod pentest_dashboard; @@ -42,6 +43,7 @@ pub use issues::IssuesPage; pub use machine::MachinePage; pub use mcp_servers::McpServersPage; pub use mcp_tokens::McpTokensPage; +pub use offers::SupplierOffersPage; pub use onboarding::OnboardingPage; pub use overview::OverviewPage; pub use pentest_dashboard::PentestDashboardPage; diff --git a/compliance-dashboard/src/pages/offers.rs b/compliance-dashboard/src/pages/offers.rs new file mode 100644 index 0000000..97bc74c --- /dev/null +++ b/compliance-dashboard/src/pages/offers.rs @@ -0,0 +1,917 @@ +//! What connected suppliers offer (#1028), the customer's side of releases: +//! for each open offer, where its SBOM would arrive (a new component in a +//! machine, or a bought-in component that has none from a supplier yet), +//! what accepting means, and the supply lines already running. + +use dioxus::prelude::*; + +use compliance_core::models::Project; + +use crate::app::Route; +use crate::components::no_access::use_can_write; +use crate::components::toast::{ToastType, Toasts}; +use crate::i18n::texts::{offers as tx, repo_views as rv}; +use crate::i18n::{format_ago, use_lang}; +use crate::infrastructure::metering::fetch_usage; +use crate::infrastructure::offers::{ + accept_offer, decline_offer, fetch_offers, Destination, OfferDto, OfferState, +}; +use crate::infrastructure::onboarding::{fetch_targets, SupplierDto}; +use crate::infrastructure::projects::{fetch_projects, project_ids_of}; +use crate::pages::targets::target_id; + +/// Open offers, for the sidebar and the targets page; `None` until read. +pub static OPEN_OFFERS: GlobalSignal> = Signal::global(|| None); + +/// The schematic's width; it scrolls in its box on a narrow screen. +const WIDTH: i32 = 920; +/// The supplier's box. +const SUPPLIER_X: i32 = 40; +const SUPPLIER_W: i32 = 220; +const SUPPLIER_H: i32 = 88; +/// Where the line splits towards the choices. +const JUNCTION_X: i32 = 440; +/// The machine's frame, and the choices in it. +const FRAME_X: i32 = 560; +const FRAME_W: i32 = 340; +const OPTION_X: i32 = 580; +const OPTION_W: i32 = 300; +const OPTION_H: i32 = 76; +/// Space between choices, and the row of the machine's other parts. +const OPTION_GAP: i32 = 14; +const PARTS_H: i32 = 34; +/// The frame's title row. +const FRAME_TOP: i32 = 24; +const FIRST_OPTION: i32 = 64; +/// Bought-in components offered as choices; the rest in a list. +const SHOWN_COMPONENTS: usize = 2; +/// The machine's parts named in its frame. +const SHOWN_PARTS: usize = 2; +/// A line of the supply chain. +const CHAIN_PITCH: i32 = 96; +const CHAIN_TOP: i32 = 70; + +/// A bought-in component that can receive the offer. +#[derive(Debug, Clone, PartialEq)] +struct Candidate { + id: String, + name: String, +} + +/// The bought-in components no accepted offer delivers into, those named +/// after `supplier` first, then by name. +fn candidates( + targets: &[serde_json::Value], + offers: &[OfferDto], + supplier: &str, +) -> Vec { + let taken: Vec<&str> = offers + .iter() + .filter(|o| o.state == OfferState::Accepted) + .filter_map(|o| o.target_id.as_deref()) + .collect(); + let mut found: Vec<(bool, Candidate)> = targets + .iter() + .filter_map(|t| { + let bought = SupplierDto::of(t)?; + let id = target_id(t); + if id.is_empty() || taken.contains(&id.as_str()) { + return None; + } + let name = t["name"].as_str().unwrap_or_default().to_string(); + Some(( + !bought.name.eq_ignore_ascii_case(supplier), + Candidate { id, name }, + )) + }) + .collect(); + found.sort_by(|a, b| (a.0, &a.1.name).cmp(&(b.0, &b.1.name))); + found.into_iter().map(|(_, c)| c).collect() +} + +/// Where the offer goes. +#[derive(Debug, Clone, PartialEq)] +enum Choice { + /// A new component, named after the product, in `project` if any. + New, + /// An existing bought-in component. + Existing(Candidate), +} + +/// Where the choices sit in the schematic. +#[derive(Debug, Clone, PartialEq, Eq)] +struct DecisionGeometry { + height: i32, + frame_h: i32, + /// The top of the row naming the machine's parts, if it has any. + parts_y: Option, + /// The top of each choice: the new component first. + option_y: Vec, + trunk_y: i32, +} + +impl DecisionGeometry { + fn new(choices: usize, parts: bool) -> Self { + let mut y = FIRST_OPTION; + let mut option_y = vec![y]; + y += OPTION_H + OPTION_GAP; + let parts_y = parts.then_some(y); + if parts { + y += PARTS_H + OPTION_GAP; + } + for _ in 1..choices.max(1) { + option_y.push(y); + y += OPTION_H + OPTION_GAP; + } + let frame_h = y - OPTION_GAP + 20 - FRAME_TOP; + let height = (FRAME_TOP + frame_h + FRAME_TOP).max(SUPPLIER_H + 2 * FRAME_TOP); + let first = option_y[0] + OPTION_H / 2; + let last = option_y[option_y.len() - 1] + OPTION_H / 2; + Self { + height, + frame_h, + parts_y, + option_y, + trunk_y: (first + last) / 2, + } + } +} + +/// Whether one more target goes beyond the plan's included ones. +fn beyond_plan(included: Option, active: usize) -> bool { + included.is_some_and(|n| active >= usize::try_from(n).unwrap_or(usize::MAX)) +} + +/// One running or ended supply line. +#[derive(Debug, Clone, PartialEq)] +struct ChainRow { + supplier: String, + /// The component's id and name; `None` when it was removed. + component: Option<(String, String)>, + products: Vec, + state: OfferState, + delivered_label: Option, + delivered_at: Option>, +} + +/// The accepted offers, then those that ended after delivering, each group +/// newest first, each with its component and the products it is in. +fn chain_rows( + offers: &[OfferDto], + targets: &[serde_json::Value], + projects: &[Project], +) -> Vec { + let mut rows: Vec = offers + .iter() + .filter(|o| { + o.state == OfferState::Accepted + || (o.state == OfferState::Ended && o.delivered_label.is_some()) + }) + .map(|o| { + let target = o + .target_id + .as_deref() + .and_then(|id| targets.iter().find(|t| target_id(t) == id)); + let products = target + .map(|t| { + project_ids_of(t) + .iter() + .filter_map(|id| projects.iter().find(|p| &p.id == id)) + .map(|p| p.name.clone()) + .collect() + }) + .unwrap_or_default(); + ChainRow { + supplier: o.supplier_name.clone(), + component: target.map(|t| { + ( + target_id(t), + t["name"].as_str().unwrap_or_default().to_string(), + ) + }), + products, + state: o.state, + delivered_label: o.delivered_label.clone(), + delivered_at: o.delivered_at, + } + }) + .collect(); + // Running lines first; the stable sort keeps each group's order. + rows.sort_by_key(|r| r.state != OfferState::Accepted); + rows +} + +/// The offers suppliers make the workspace. +#[component] +pub fn SupplierOffersPage() -> Element { + let lang = use_lang()(); + let can_write = use_can_write(); + let mut offers = use_resource(fetch_offers); + let mut targets = use_resource(fetch_targets); + let projects = use_resource(fetch_projects); + let usage = use_resource(fetch_usage); + let mut selected = use_signal(|| 0usize); + + let listed = match &*offers.read() { + Some(Ok(listed)) => listed.clone(), + Some(Err(_)) => { + return rsx! { + OfferCrumbs {} + div { class: "card", p { {tx::LOAD_FAILED.get(lang)} } } + } + } + None => return rsx! { div { class: "loading", {tx::LOADING.get(lang)} } }, + }; + let open: Vec = listed + .iter() + .filter(|o| o.state == OfferState::Offered) + .cloned() + .collect(); + if OPEN_OFFERS.peek().as_ref() != Some(&open.len()) { + *OPEN_OFFERS.write() = Some(open.len()); + } + // Targets and projects are read for the choices; until then the offer + // waits rather than showing choices that may be wrong. + let all_targets = match &*targets.read() { + Some(Ok(found)) => Some(found.data.clone()), + Some(Err(_)) => Some(Vec::new()), + None => None, + }; + let all_projects = match &*projects.read() { + Some(Ok(found)) => found.clone(), + _ => Vec::new(), + }; + let included = usage + .read() + .as_ref() + .and_then(|u| u.as_ref().ok()) + .and_then(|u| u.data.included_targets); + let current = open + .get(selected().min(open.len().saturating_sub(1))) + .cloned(); + let on_answered = move |_| { + selected.set(0); + offers.restart(); + targets.restart(); + }; + let chain = chain_rows( + &listed, + all_targets.as_deref().unwrap_or_default(), + &all_projects, + ); + + rsx! { + div { class: "rel-page", + OfferCrumbs {} + match ¤t { + Some(offer) => rsx! { + header { class: "chain-head", + h1 { {tx::title(&offer.supplier_name, &offer.product_name, lang)} } + p { {tx::INTRO.get(lang)} } + } + }, + None => rsx! { + header { class: "chain-head", + h1 { {tx::CRUMB.get(lang)} } + p { {tx::NONE_OPEN.get(lang)} } + } + }, + } + if open.len() > 1 { + nav { class: "offer-others", "aria-label": tx::OTHERS.get(lang), + span { class: "offer-others-title", {tx::OTHERS.get(lang)} } + for (i, o) in open.iter().enumerate() { + button { + key: "{o.id}", + class: if i == selected().min(open.len() - 1) { "offer-pick active" } else { "offer-pick" }, + r#type: "button", + "aria-pressed": "{i == selected()}", + onclick: move |_| selected.set(i), + {tx::from(&o.product_name, &o.supplier_name, lang)} + } + } + } + } + if let (Some(offer), Some(found)) = (current.clone(), all_targets.clone()) { + OfferDecision { + key: "{offer.id}", + candidates: candidates(&found, &listed, &offer.supplier_name), + targets: found.clone(), + beyond_plan: beyond_plan(included, found.len()), + projects: all_projects.clone(), + offer, + can_write, + on_answered, + } + } else if current.is_some() { + div { class: "loading", {tx::LOADING.get(lang)} } + } + if !chain.is_empty() { + SupplyLines { rows: chain } + } + } + } +} + +/// Prüfobjekte › Freigaben von Zulieferern. +#[component] +fn OfferCrumbs() -> Element { + let lang = use_lang()(); + rsx! { + nav { class: "repo-crumbs", "aria-label": rv::BREADCRUMB.get(lang), + Link { to: Route::TargetsPage {}, {crate::i18n::texts::nav::TARGETS.get(lang)} } + span { class: "repo-crumb-sep", "aria-hidden": "true", "›" } + span { "aria-current": "page", {tx::CRUMB.get(lang)} } + } + } +} + +/// One open offer: the supplier, the version on the way, where it can +/// arrive, what accepting means, and the answer. +#[component] +fn OfferDecision( + offer: OfferDto, + candidates: Vec, + targets: Vec, + projects: Vec, + beyond_plan: bool, + can_write: bool, + on_answered: EventHandler<()>, +) -> Element { + let lang = use_lang()(); + let mut toasts = use_context::(); + let mut choice = use_signal(|| Choice::New); + let mut project = use_signal(String::new); + let mut asking = use_signal(|| false); + let mut declining = use_signal(|| false); + let mut busy = use_signal(|| false); + + // Products and assemblies, the places a component can go. + let machines: Vec<&Project> = projects + .iter() + .filter(|p| p.kind == compliance_core::models::ProjectKind::Product) + .collect(); + let parts: Vec = if project().is_empty() { + Vec::new() + } else { + targets + .iter() + .filter(|t| project_ids_of(t).contains(&project())) + .map(|t| t["name"].as_str().unwrap_or_default().to_string()) + .collect() + }; + let shown: Vec = candidates.iter().take(SHOWN_COMPONENTS).cloned().collect(); + let rest: Vec = candidates.iter().skip(SHOWN_COMPONENTS).cloned().collect(); + // A component picked from the list takes the list's row. + let picked_rest = match choice() { + Choice::Existing(c) if rest.contains(&c) => Some(c), + _ => None, + }; + let choices = 1 + shown.len() + usize::from(!rest.is_empty()); + let geometry = DecisionGeometry::new(choices, !parts.is_empty()); + let (height, trunk_y) = (geometry.height, geometry.trunk_y); + let supplier_top = trunk_y - SUPPLIER_H / 2; + let selected_row = match choice() { + Choice::New => 0, + Choice::Existing(c) => shown + .iter() + .position(|s| s == &c) + .map_or(choices - 1, |i| i + 1), + }; + let has_version = offer.offered_label.is_some(); + let parcel = offer + .offered_label + .as_deref() + .map(|l| tx::parcel(l, offer.offered_components, lang)); + let accept_label = match choice() { + Choice::New => tx::ACCEPT_NEW.get(lang).to_string(), + Choice::Existing(c) if asking() => tx::confirm_replace(&c.name, lang), + Choice::Existing(c) => tx::accept_into(&c.name, lang), + }; + let offer_id = offer.id.clone(); + let product = offer.product_name.clone(); + let decline_id = offer.id.clone(); + let declined_product = offer.product_name.clone(); + + rsx! { + section { class: "rel-route", "aria-label": tx::ROUTE.get(lang), + div { class: "rel-canvas", style: "width: {WIDTH}px; height: {height}px;", + div { + class: "offer-frame", + "aria-hidden": "true", + style: "left: {FRAME_X}px; top: {FRAME_TOP}px; width: {FRAME_W}px; height: {geometry.frame_h}px;", + } + label { class: "offer-machine", r#for: "offer-machine", style: "left: {FRAME_X + 20}px; top: {FRAME_TOP + 10}px;", + span { "{tx::MACHINE.get(lang)}: " } + select { + id: "offer-machine", + disabled: choice() != Choice::New || !can_write, + onchange: move |e| project.set(e.value()), + option { value: "", selected: project().is_empty(), {tx::NO_MACHINE.get(lang)} } + for m in machines.iter() { + option { key: "{m.id}", value: "{m.id}", selected: project() == m.id, "{m.name}" } + } + } + } + svg { class: "rel-lines", width: "{WIDTH}", height: "{height}", "aria-hidden": "true", + defs { + marker { id: "offer-arrow", "markerWidth": "8", "markerHeight": "8", "refX": "6", "refY": "4", orient: "auto", + path { d: "M0 0 L8 4 L0 8 Z", class: "rel-arrow-head" } + } + } + path { + class: if has_version { "rel-line live" } else { "rel-line wait" }, + d: "M {SUPPLIER_X + SUPPLIER_W} {trunk_y} H {JUNCTION_X}", + } + for (i, top) in geometry.option_y.iter().enumerate() { + { + let y = top + OPTION_H / 2; + let chosen = i == selected_row; + let end = if chosen { OPTION_X - 8 } else { OPTION_X }; + rsx! { + path { + class: if chosen { "rel-line live" } else { "rel-line off" }, + d: "M {JUNCTION_X} {trunk_y} V {y} H {end}", + "marker-end": if chosen { "url(#offer-arrow)" }, + } + } + } + } + circle { class: "rel-dot live", cx: "{JUNCTION_X}", cy: "{trunk_y}", r: "5" } + } + div { + class: "rel-target", + style: "left: {SUPPLIER_X}px; top: {supplier_top}px; width: {SUPPLIER_W}px; height: {SUPPLIER_H}px;", + span { class: "rel-target-kind", {tx::SUPPLIER.get(lang)} } + span { class: "rel-target-name", title: "{offer.supplier_name}", "{offer.supplier_name}" } + } + span { + class: if has_version { "rel-chip parcel" } else { "rel-chip off" }, + style: "left: {(SUPPLIER_X + SUPPLIER_W + JUNCTION_X) / 2}px; top: {trunk_y}px;", + {parcel.clone().unwrap_or_else(|| tx::NO_VERSION.get(lang).to_string())} + } + OptionButton { + top: geometry.option_y[0], + chosen: choice() == Choice::New, + enabled: can_write, + title: tx::AS_NEW.get(lang).to_string(), + sub: tx::created(&offer.product_name, lang), + on_pick: move |_| { choice.set(Choice::New); asking.set(false); }, + } + if let Some(y) = geometry.parts_y { + div { class: "offer-parts", style: "left: {OPTION_X}px; top: {y}px; width: {OPTION_W}px; height: {PARTS_H}px;", + for part in parts.iter().take(SHOWN_PARTS) { + span { class: "offer-part", title: "{part}", "{part}" } + } + if parts.len() > SHOWN_PARTS { + span { class: "offer-part more", {tx::more_parts(parts.len() - SHOWN_PARTS, lang)} } + } + } + } + for (i, c) in shown.iter().enumerate() { + { + let picked = c.clone(); + rsx! { + OptionButton { + key: "{c.id}", + top: geometry.option_y[i + 1], + chosen: choice() == Choice::Existing(c.clone()), + enabled: can_write, + title: tx::into(&c.name, lang), + sub: if has_version { tx::REPLACES.get(lang).to_string() } else { tx::REPLACES_LATER.get(lang).to_string() }, + on_pick: move |_| { choice.set(Choice::Existing(picked.clone())); asking.set(false); }, + } + } + } + } + if !rest.is_empty() { + { + let top = geometry.option_y[choices - 1]; + let chosen = picked_rest.is_some(); + let list = rest.clone(); + rsx! { + div { + class: if chosen { "offer-option chosen" } else { "offer-option" }, + style: "left: {OPTION_X}px; top: {top}px; width: {OPTION_W}px; height: {OPTION_H}px;", + select { + class: "offer-rest", + "aria-label": tx::OTHER_COMPONENT.get(lang), + disabled: !can_write, + onchange: move |e| { + let id = e.value(); + asking.set(false); + match list.iter().find(|c| c.id == id) { + Some(c) => choice.set(Choice::Existing(c.clone())), + None => choice.set(Choice::New), + } + }, + option { value: "", selected: !chosen, {tx::OTHER_COMPONENT.get(lang)} } + for c in rest.iter() { + option { key: "{c.id}", value: "{c.id}", selected: picked_rest.as_ref() == Some(c), "{c.name}" } + } + } + span { class: "offer-option-sub", if has_version { {tx::REPLACES.get(lang)} } else { {tx::REPLACES_LATER.get(lang)} } } + } + } + } + } + } + } + section { class: "offer-meaning", "aria-label": tx::MEANING.get(lang), + div { class: "offer-tile", + svg { width: "28", height: "28", view_box: "0 0 24 24", "aria-hidden": "true", + rect { x: "4", y: "4", width: "16", height: "16", rx: "4", fill: "none", stroke: "currentColor", stroke_width: "1.8" } + path { d: "M12 8.5v7M8.5 12h7", fill: "none", stroke: "currentColor", stroke_width: "1.8", stroke_linecap: "round" } + } + span { + match choice() { + Choice::New => rsx! { + b { {tx::ONE_MORE.get(lang)} } + br {} + span { class: if beyond_plan { "offer-tile-warn" } else { "offer-tile-sub" }, + if beyond_plan { {tx::BILLED_EXTRA.get(lang)} } else { {tx::COUNTS_LIKE_ANY.get(lang)} } + } + }, + Choice::Existing(_) => rsx! { + b { {tx::NO_NEW_TARGET.get(lang)} } + br {} + span { class: "offer-tile-sub", + if has_version { {tx::REPLACES.get(lang)} } else { {tx::REPLACES_LATER.get(lang)} } + } + }, + } + } + } + div { class: "offer-tile", + svg { width: "28", height: "28", view_box: "0 0 24 24", "aria-hidden": "true", + path { d: "M4 12a8 8 0 0 1 13.7-5.6L20 8.5M20 4v4.5h-4.5M20 12a8 8 0 0 1-13.7 5.6L4 15.5M4 20v-4.5h4.5", fill: "none", stroke: "currentColor", stroke_width: "1.8", stroke_linecap: "round", stroke_linejoin: "round" } + } + span { + b { {tx::EVERY_VERSION.get(lang)} } + br {} + span { class: "offer-tile-sub", {tx::AND_IS_SCANNED.get(lang)} } + } + } + div { class: "offer-tile", + svg { width: "28", height: "28", view_box: "0 0 24 24", "aria-hidden": "true", + path { d: "M2.5 12s3.5-6.5 9.5-6.5S21.5 12 21.5 12 18 18.5 12 18.5 2.5 12 2.5 12z", fill: "none", stroke: "currentColor", stroke_width: "1.8", stroke_linejoin: "round" } + circle { cx: "12", cy: "12", r: "3", fill: "none", stroke: "currentColor", stroke_width: "1.8" } + } + span { + b { {tx::ONLY_BOM.get(lang)} } + br {} + span { class: "offer-tile-sub", {tx::NO_FINDINGS.get(lang)} } + } + } + if can_write { + div { class: "offer-answer", + if declining() { + p { class: "offer-answer-note", {tx::DECLINE_HINT.get(lang)} } + button { + class: "btn offer-decline-confirm", + r#type: "button", + disabled: busy(), + onclick: move |_| { + let (id, product) = (decline_id.clone(), declined_product.clone()); + busy.set(true); + spawn(async move { + match decline_offer(id).await { + Ok(_) => toasts.push(ToastType::Success, tx::declined(&product, lang)), + Err(e) => toasts.push(ToastType::Error, tx::refusal(&e.to_string(), lang)), + } + busy.set(false); + on_answered.call(()); + }); + }, + {tx::DECLINE_CONFIRM.get(lang)} + } + button { class: "btn btn-ghost", r#type: "button", onclick: move |_| declining.set(false), {tx::CANCEL.get(lang)} } + } else { + button { + class: "btn btn-primary offer-accept", + r#type: "button", + disabled: busy(), + onclick: move |_| { + let to = match choice() { + Choice::Existing(_) if !asking() => { + // Replacing an uploaded SBOM is asked once more. + asking.set(true); + return; + } + Choice::Existing(c) => Destination { target_id: Some(c.id), ..Default::default() }, + Choice::New => Destination { + name: Some(product.clone()), + project_ids: if project().is_empty() { Vec::new() } else { vec![project()] }, + ..Default::default() + }, + }; + let (id, product) = (offer_id.clone(), product.clone()); + busy.set(true); + spawn(async move { + match accept_offer(id, to).await { + Ok(_) => toasts.push(ToastType::Success, tx::accepted(&product, lang)), + Err(e) => toasts.push(ToastType::Error, tx::refusal(&e.to_string(), lang)), + } + busy.set(false); + asking.set(false); + on_answered.call(()); + }); + }, + "{accept_label}" + } + if asking() { + button { class: "btn btn-ghost", r#type: "button", onclick: move |_| asking.set(false), {tx::CANCEL.get(lang)} } + } else { + button { class: "btn btn-secondary", r#type: "button", disabled: busy(), onclick: move |_| declining.set(true), {tx::DECLINE.get(lang)} } + } + } + } + } + } + } +} + +/// One choice in the machine's frame. +#[component] +fn OptionButton( + top: i32, + chosen: bool, + enabled: bool, + title: String, + sub: String, + on_pick: EventHandler<()>, +) -> Element { + rsx! { + button { + class: if chosen { "offer-option chosen" } else { "offer-option" }, + style: "left: {OPTION_X}px; top: {top}px; width: {OPTION_W}px; height: {OPTION_H}px;", + r#type: "button", + "aria-pressed": "{chosen}", + disabled: !enabled, + onclick: move |_| on_pick.call(()), + span { class: "offer-radio", "aria-hidden": "true" } + span { class: "offer-option-text", + b { title: "{title}", "{title}" } + span { class: "offer-option-sub", "{sub}" } + } + } + } +} + +/// The supply lines already running: supplier, the version that arrived, +/// the component it arrived in. +#[component] +fn SupplyLines(rows: Vec) -> Element { + let lang = use_lang()(); + let now = chrono::Utc::now(); + let rows_i = i32::try_from(rows.len()).unwrap_or(i32::MAX / CHAIN_PITCH); + let height = CHAIN_TOP + rows_i * CHAIN_PITCH; + const LEFT_W: i32 = 200; + const RIGHT_X: i32 = 620; + const RIGHT_W: i32 = 260; + const BOX_H: i32 = 64; + + rsx! { + section { class: "rel-train", "aria-labelledby": "offer-chain-h", + div { class: "rel-canvas plain", style: "width: {WIDTH}px; height: {height}px;", + h2 { id: "offer-chain-h", class: "offer-chain-title", {tx::CHAIN.get(lang)} } + Link { class: "offer-chain-link", to: Route::SupplyChainPage {}, {tx::CHAIN_LINK.get(lang)} } + for (i, row) in rows.iter().enumerate() { + { + let y = CHAIN_TOP + i32::try_from(i).unwrap_or(0) * CHAIN_PITCH; + let mid = y + BOX_H / 2; + let live = row.state == OfferState::Accepted && row.component.is_some(); + let end = if live { RIGHT_X - 8 } else { RIGHT_X }; + let chip = match (row.state, &row.delivered_label, &row.delivered_at) { + (OfferState::Accepted, Some(label), Some(at)) => format!("{label} {}", format_ago(at, &now, lang)), + (OfferState::Accepted, _, _) => tx::ACCEPTED_CHIP.get(lang).to_string(), + (_, label, _) => tx::ended(label.as_deref(), lang), + }; + let component_name = row.component.as_ref().map_or_else( + || tx::COMPONENT_GONE.get(lang).to_string(), + |(_, name)| name.clone(), + ); + let aria = tx::line(&row.supplier, &component_name, &chip, lang); + let products = if row.products.is_empty() { + tx::IN_NO_PRODUCT.get(lang).to_string() + } else { + tx::in_products(&row.products.join(", "), lang) + }; + rsx! { + svg { class: "rel-lines", width: "{WIDTH}", height: "{height}", role: "img", "aria-label": "{aria}", + path { + class: if live { "rel-line live" } else { "rel-line off" }, + d: "M {40 + LEFT_W} {mid} H {end}", + "marker-end": if live { "url(#offer-chain-arrow)" }, + } + if i == 0 { + defs { + marker { id: "offer-chain-arrow", "markerWidth": "8", "markerHeight": "8", "refX": "6", "refY": "4", orient: "auto", + path { d: "M0 0 L8 4 L0 8 Z", class: "rel-arrow-head" } + } + } + } + } + div { + class: if live { "offer-chain-supplier" } else { "offer-chain-supplier ended" }, + style: "left: 40px; top: {y}px; width: {LEFT_W}px; height: {BOX_H}px;", + span { class: "rel-peer-name", title: "{row.supplier}", "{row.supplier}" } + } + span { + class: if live { "rel-chip live" } else { "rel-chip off" }, + style: "left: {(40 + LEFT_W + RIGHT_X) / 2}px; top: {mid}px;", + "{chip}" + } + match &row.component { + Some((id, name)) => rsx! { + Link { + class: "rel-peer offer-chain-component", + style: "left: {RIGHT_X}px; top: {y}px; width: {RIGHT_W}px; height: {BOX_H}px;", + to: Route::target(id.clone()), + span { class: "rel-peer-name", title: "{name}", "{name}" } + span { class: "rel-peer-status", "{products}" } + } + }, + None => rsx! { + div { + class: "rel-peer off", + style: "left: {RIGHT_X}px; top: {y}px; width: {RIGHT_W}px; height: {BOX_H}px;", + span { class: "rel-peer-status", {tx::COMPONENT_GONE.get(lang)} } + } + }, + } + } + } + } + } + } + } +} + +/// The open-offer count in the sidebar, read once, then kept by the page. +pub fn use_open_offers() -> Option { + let _read = use_resource(|| async { + if OPEN_OFFERS.peek().is_none() { + if let Ok(listed) = fetch_offers().await { + *OPEN_OFFERS.write() = Some( + listed + .iter() + .filter(|o| o.state == OfferState::Offered) + .count(), + ); + } + } + }); + OPEN_OFFERS() +} + +/// The targets page's note about waiting offers. +#[component] +pub fn OffersWaiting() -> Element { + let lang = use_lang()(); + let waiting = use_open_offers().filter(|n| *n > 0); + rsx! { + if let Some(n) = waiting { + Link { class: "offer-waiting", to: Route::SupplierOffersPage {}, + span { class: "offer-waiting-dot", "aria-hidden": "true" } + span { {tx::waiting(n, lang)} } + span { class: "offer-waiting-go", {tx::OPEN_THEM.get(lang)} } + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::i18n::Lang; + use chrono::{TimeZone, Utc}; + use compliance_core::models::{ProjectKind, ProjectLevel, TargetType}; + + fn offer(id: &str, state: OfferState, target: Option<&str>) -> OfferDto { + OfferDto { + id: id.into(), + supplier_name: "Beispiel Display".into(), + product_name: "HMI".into(), + product_type: TargetType::FirmwareRtos, + state, + target_id: target.map(String::from), + offered_at: Utc.with_ymd_and_hms(2026, 11, 10, 9, 0, 0).unwrap(), + ended_at: None, + delivered_label: None, + delivered_at: None, + offered_label: None, + offered_components: None, + } + } + + fn target( + id: &str, + name: &str, + supplier: Option<&str>, + projects: &[&str], + ) -> serde_json::Value { + serde_json::json!({ + "_id": { "$oid": id }, + "name": name, + "supplier": supplier.map(|s| serde_json::json!({ "name": s })), + "project_ids": projects, + }) + } + + #[test] + fn only_free_bought_in_components_are_choices_the_suppliers_own_first() { + let targets = [ + target("t1", "Steuerung", None, &[]), + target("t2", "Antrieb", Some("Muster Antriebe"), &[]), + target("t3", "Display", Some("Beispiel Display"), &[]), + target("t4", "Funkmodul", Some("Muster Funk"), &[]), + ]; + let offers = [offer("o1", OfferState::Accepted, Some("t4"))]; + + let found = candidates(&targets, &offers, "beispiel display"); + + let names: Vec<&str> = found.iter().map(|c| c.name.as_str()).collect(); + assert_eq!( + names, + ["Display", "Antrieb"], + "own targets and taken ones are not choices" + ); + } + + #[test] + fn the_frame_holds_every_choice() { + for (choices, parts) in [(1, false), (1, true), (3, true), (4, false)] { + let g = DecisionGeometry::new(choices, parts); + assert_eq!(g.option_y.len(), choices); + let last = g.option_y[choices - 1] + OPTION_H; + assert!( + last <= FRAME_TOP + g.frame_h, + "{choices}/{parts}: inside the frame" + ); + assert!(FRAME_TOP + g.frame_h <= g.height); + if let Some(y) = g.parts_y { + assert!( + y >= g.option_y[0] + OPTION_H, + "parts under the new component" + ); + } + assert!(g.trunk_y - SUPPLIER_H / 2 >= 0); + } + } + + #[test] + fn one_more_target_is_beyond_a_full_plan() { + assert!(!beyond_plan(Some(5), 4)); + assert!(beyond_plan(Some(5), 5)); + assert!(!beyond_plan(None, 500), "unlimited"); + } + + #[test] + fn the_supply_lines_are_the_running_and_the_ended_deliveries() { + let mut ended = offer("o2", OfferState::Ended, Some("gone")); + ended.delivered_label = Some("2.0.4".into()); + let offers = [ + offer("o1", OfferState::Accepted, Some("t3")), + ended, + offer("o3", OfferState::Declined, None), + offer("o4", OfferState::Ended, None), + ]; + let targets = [target("t3", "Display", Some("Beispiel Display"), &["p1"])]; + let projects = [Project { + id: "p1".into(), + name: "Pumpstation PS-200".into(), + kind: ProjectKind::Product, + description: String::new(), + level: Some(ProjectLevel::Product), + parent_id: None, + }]; + + let rows = chain_rows(&offers, &targets, &projects); + + assert_eq!( + rows.len(), + 2, + "declined and never-delivered ended offers are not lines" + ); + assert_eq!(rows[0].component, Some(("t3".into(), "Display".into()))); + assert_eq!(rows[0].products, ["Pumpstation PS-200"]); + assert_eq!(rows[1].component, None, "its component was removed"); + assert_eq!( + tx::ended(rows[1].delivered_label.as_deref(), Lang::De), + "beendet, 2.0.4 bleibt" + ); + } + + #[test] + fn an_offer_refusal_reads_in_words() { + assert_eq!( + tx::refusal( + "error running server function: target_taken (409) (details: None)", + Lang::De + ), + "Diese Komponente erhält schon die SBOM eines anderen Zulieferers." + ); + assert_eq!(tx::refusal("x (500)", Lang::De), "x (500)"); + } +} diff --git a/compliance-dashboard/src/pages/targets.rs b/compliance-dashboard/src/pages/targets.rs index bb73ce7..e960820 100644 --- a/compliance-dashboard/src/pages/targets.rs +++ b/compliance-dashboard/src/pages/targets.rs @@ -66,7 +66,8 @@ fn str_at<'a>(v: &'a serde_json::Value, key: &str) -> &'a str { v.get(key).and_then(|x| x.as_str()).unwrap_or("") } -fn target_id(t: &serde_json::Value) -> String { +/// A listed target's id: the agent writes it as `{"$oid": "..."}`. +pub(crate) fn target_id(t: &serde_json::Value) -> String { t.get("_id") .and_then(|o| o.get("$oid")) .and_then(|s| s.as_str()) @@ -134,6 +135,7 @@ pub fn TargetsPage() -> Element { description: tx::SUBTITLE.get(lang), } UsageSummary {} + crate::pages::offers::OffersWaiting {} div { class: "page-actions", if can_write {