From 1376efa24912e57252cea92868c0d866b695d8dd Mon Sep 17 00:00:00 2001 From: Sharang Parnerkar Date: Thu, 19 Nov 2026 10:35:22 +0000 Subject: [PATCH] feat(supply-chain): a product's description and documents on its box (#1054) (#1059) --- .../src/api/handlers/supply_chain.rs | 158 ++++++++++++++++++ compliance-agent/src/api/routes.rs | 1 + compliance-agent/src/registry.rs | 55 ++++++ .../tests/integration/api/supply_chain.rs | 10 ++ compliance-dashboard/assets/main.css | 36 ++++ compliance-dashboard/src/i18n/texts.rs | 24 +++ .../src/infrastructure/supply_chain.rs | 39 +++++ .../src/pages/supply_chain.rs | 102 ++++++++++- docs/guide/lieferkette.md | 10 ++ 9 files changed, 432 insertions(+), 3 deletions(-) diff --git a/compliance-agent/src/api/handlers/supply_chain.rs b/compliance-agent/src/api/handlers/supply_chain.rs index 3bb6a84..a5bb30b 100644 --- a/compliance-agent/src/api/handlers/supply_chain.rs +++ b/compliance-agent/src/api/handlers/supply_chain.rs @@ -274,6 +274,127 @@ pub fn supply_chain( SupplyChain { nodes, edges } } +/// A document of a product's box: one of the store's documents of the +/// product, opened in the portal. +#[derive(Debug, Clone, PartialEq, Serialize)] +pub struct BoxDocument { + /// The store's id of the document. + pub id: String, + pub title: String, + pub filename: String, + pub content_type: Option, + pub size_bytes: Option, + /// Internal to the workspace rather than published with the product. + pub internal: bool, + pub created_at: Option>, + /// Where the portal shows it, below the portal's address. + pub path: String, +} + +/// What a product's box shows besides its graph (#1054): the project's +/// description and its documents in the portal's Dokumentenablage. +#[derive(Debug, Clone, PartialEq, Serialize)] +pub struct ProjectDocuments { + /// The project's description, as the portal keeps it. + pub description: String, + /// Its documents, newest first. + pub documents: Vec, + /// Where the portal's store is, below the portal's address, for adding + /// one; empty without a registry. + pub store_path: String, +} + +/// The documents of `store` that belong to product project `project`, newest +/// first, with where the portal of workspace `slug` shows each. Legal web +/// documents and BreakPilot's deliveries belong to no product. +fn box_documents( + store: Vec, + project: &str, + slug: &str, +) -> Vec { + let slug = urlencoding::encode(slug); + let mut documents: Vec = store + .into_iter() + .filter(|d| d.project_ids.iter().any(|p| p == project)) + .filter_map(|d| { + let internal = match d.area.as_deref() { + Some("product_public") => false, + Some("internal") => true, + _ => return None, + }; + Some(BoxDocument { + path: format!("/{slug}/dokumente/{}/original", urlencoding::encode(&d.id)), + id: d.id, + title: d.title, + filename: d.filename, + content_type: d.content_type, + size_bytes: d.size_bytes, + internal, + created_at: d.created_at, + }) + }) + .collect(); + documents.sort_by_key(|d| std::cmp::Reverse(d.created_at)); + documents +} + +/// A product's description and documents, for its box on the Lieferkette. +/// +/// The description is the project's, and the documents are those of the +/// portal's Dokumentenablage that belong to the project (published with the +/// product or internal), newest first. Each names where the portal shows it. +/// Prüfwerk keeps no copy. Without a registry (development) there is +/// nothing to show. +#[utoipa::path( + get, + path = "/api/v1/supply-chain/projects/{id}/documents", + tag = "Targets", + params(("id" = String, Path, description = "The product project's id")), + responses( + (status = 200, description = "Its description and documents (`data`)"), + (status = 404, description = "No product project of the workspace"), + (status = 503, description = "The registry cannot be asked"), + (status = 401, description = "No valid bearer token"), + ) +)] +#[tracing::instrument(skip_all, fields(project_id = %id))] +pub async fn project_documents( + Extension(agent): AgentExt, + tenant: TenantCtx, + axum::extract::Path(id): axum::extract::Path, +) -> Result>, StatusCode> { + let Some(registry) = agent.registry.as_ref() else { + return Ok(Json(ApiResponse { + data: ProjectDocuments { + description: String::new(), + documents: Vec::new(), + store_path: String::new(), + }, + total: None, + page: None, + })); + }; + let ctx = &tenant.0; + let project = tenant_projects(&agent, &ctx.tenant_id) + .await? + .into_iter() + .find(|p| p.id == id && p.kind == ProjectKind::Product) + .ok_or(StatusCode::NOT_FOUND)?; + let store = registry.list_store(&ctx.tenant_id).await.map_err(|e| { + tracing::error!(tenant_id = %ctx.tenant_id, "store list unavailable: {e}"); + StatusCode::SERVICE_UNAVAILABLE + })?; + Ok(Json(ApiResponse { + data: ProjectDocuments { + description: project.description, + documents: box_documents(store, &id, &ctx.tenant_slug), + store_path: format!("/{}/dokumente", urlencoding::encode(&ctx.tenant_slug)), + }, + total: None, + page: None, + })) +} + /// Without a registry (development), every project a target names, as a /// product named by its id, as the machine page names it. fn unregistered_projects(targets: &[OnboardedTarget]) -> Vec { @@ -563,6 +684,43 @@ mod tests { assert_eq!(b.open, Some(counts(0, 1, 0))); } + #[test] + fn a_box_shows_the_documents_of_its_product_newest_first() { + use crate::registry::StoreDocument; + let doc = |id: &str, area: Option<&str>, projects: &[&str], day: u32| StoreDocument { + id: id.into(), + title: format!("Doc {id}"), + filename: format!("{id}.pdf"), + content_type: Some("application/pdf".into()), + size_bytes: Some(1024), + area: area.map(String::from), + project_ids: projects.iter().map(|p| p.to_string()).collect(), + created_at: chrono::NaiveDate::from_ymd_opt(2026, 11, day) + .and_then(|d| d.and_hms_opt(9, 0, 0)) + .map(|d| d.and_utc()), + }; + let store = vec![ + doc("manual", Some("product_public"), &["p1"], 10), + doc("notes", Some("internal"), &["p1", "p2"], 12), + doc("other", Some("product_public"), &["p2"], 11), + doc("imprint", Some("legal_web"), &["p1"], 13), + doc("delivery", None, &["p1"], 14), + ]; + + let shown = box_documents(store, "p1", "beispiel maschinenbau"); + + let ids: Vec<(&str, bool)> = shown.iter().map(|d| (d.id.as_str(), d.internal)).collect(); + assert_eq!( + ids, + [("notes", true), ("manual", false)], + "newest first, its own only" + ); + assert_eq!( + shown[1].path, + "/beispiel%20maschinenbau/dokumente/manual/original" + ); + } + #[test] fn without_a_registry_projects_are_named_by_their_id() { let targets = vec![ diff --git a/compliance-agent/src/api/routes.rs b/compliance-agent/src/api/routes.rs index 17dbf9b..efcae38 100644 --- a/compliance-agent/src/api/routes.rs +++ b/compliance-agent/src/api/routes.rs @@ -51,6 +51,7 @@ fn described_routes() -> OpenApiRouter { .routes(routes!(handlers::machine::machine_cves)) .routes(routes!(handlers::machine::machine_scan_changes)) .routes(routes!(handlers::supply_chain::get_supply_chain)) + .routes(routes!(handlers::supply_chain::project_documents)) // The customer's arrangement of the supply chain (#1052). .routes(routes!( handlers::supply_chain_layout::get_layout, diff --git a/compliance-agent/src/registry.rs b/compliance-agent/src/registry.rs index 56ccede..710679b 100644 --- a/compliance-agent/src/registry.rs +++ b/compliance-agent/src/registry.rs @@ -39,6 +39,29 @@ const TOKEN_MARGIN: Duration = Duration::from_secs(30); /// client's 30 s. const REQUEST_TIMEOUT: Duration = Duration::from_secs(5); +/// A document of the tenant's store (Dokumentenablage), as the registry +/// lists it (`GET /v1/tenants/{id}/store`). +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +pub struct StoreDocument { + pub id: String, + pub title: String, + #[serde(default)] + pub filename: String, + #[serde(default)] + pub content_type: Option, + #[serde(default)] + pub size_bytes: Option, + /// `legal_web`, `product_public` or `internal`; none for BreakPilot's + /// deliveries. + #[serde(default)] + pub area: Option, + /// The product projects it belongs to. + #[serde(default)] + pub project_ids: Vec, + #[serde(default)] + pub created_at: Option>, +} + /// The registry's `reason` for a member blocked in the tenant. pub const MEMBER_BLOCKED: &str = "member_blocked"; @@ -531,6 +554,38 @@ impl RegistryClient { Ok(page.items) } + /// The tenant's document store (Dokumentenablage): its published + /// documents, by area. Not cached: it is read when a product's box is + /// opened on the Lieferkette (#1054). + /// + /// # Errors + /// + /// The registry could not be asked, or answered with an error. + pub async fn list_store(&self, tenant_id: &str) -> Result, String> { + #[derive(Deserialize)] + struct Page { + #[serde(default)] + items: Vec, + } + let resp = self + .request( + reqwest::Method::GET, + &format!("/v1/tenants/{}/store", urlencoding::encode(tenant_id)), + ) + .await? + .send() + .await + .map_err(|e| format!("store list failed: {e}"))?; + if !resp.status().is_success() { + return Err(format!("store list returned {}", resp.status())); + } + let page: Page = resp + .json() + .await + .map_err(|e| format!("store list invalid: {e}"))?; + Ok(page.items) + } + /// Verify a portal-issued API key (`bp_…`), valid or not, reusing a /// verdict younger than [`API_KEY_TTL`]. /// diff --git a/compliance-agent/tests/integration/api/supply_chain.rs b/compliance-agent/tests/integration/api/supply_chain.rs index 0ecbabb..1c626a8 100644 --- a/compliance-agent/tests/integration/api/supply_chain.rs +++ b/compliance-agent/tests/integration/api/supply_chain.rs @@ -101,6 +101,16 @@ async fn the_supply_chain_links_suppliers_components_and_products() { let part_of = edges.iter().filter(|e| e["kind"] == "part_of").count(); assert_eq!(part_of, 3, "drive to m1, PLC to m1 and m2"); + // Without a registry a product's box has no documents to show. + let body: serde_json::Value = server + .get("/api/v1/supply-chain/projects/m1/documents") + .await + .json() + .await + .unwrap(); + assert_eq!(body["data"]["documents"], json!([])); + assert_eq!(body["data"]["store_path"], ""); + server.cleanup().await; } diff --git a/compliance-dashboard/assets/main.css b/compliance-dashboard/assets/main.css index 2c5f081..731a0f2 100644 --- a/compliance-dashboard/assets/main.css +++ b/compliance-dashboard/assets/main.css @@ -8907,3 +8907,39 @@ span.repo-crumb-name { font-weight: 500; line-height: 1; } +.chain-panel-muted { margin: 0; font-size: 13px; color: var(--text-tertiary); } +.chain-panel-desc { + margin: 0; + font-size: 14px; + line-height: 1.5; + color: var(--text-secondary); + white-space: pre-line; +} +.chain-docs { display: flex; flex-direction: column; gap: 8px; } +.chain-docs h3 { margin: 4px 0 0; font-size: 13px; font-weight: 600; } +.chain-docs ul { + margin: 0; + padding: 0; + list-style: none; + display: flex; + flex-direction: column; + gap: 6px; +} +.chain-docs li { + display: flex; + flex-direction: column; + gap: 2px; + padding: 8px 10px; + border: 1px solid var(--border); + border-radius: 10px; +} +.chain-doc-title { font-size: 14px; font-weight: 500; } +.chain-doc-meta { font-size: 12px; color: var(--text-tertiary); } +.chain-doc-add { + padding: 8px 10px; + border: 1.5px dashed var(--border-bright); + border-radius: 10px; + font-size: 13px; + color: var(--accent); + text-decoration: none; +} diff --git a/compliance-dashboard/src/i18n/texts.rs b/compliance-dashboard/src/i18n/texts.rs index 3450c3d..50a0bcd 100644 --- a/compliance-dashboard/src/i18n/texts.rs +++ b/compliance-dashboard/src/i18n/texts.rs @@ -7799,6 +7799,30 @@ pub mod supply_chain { de: "Upload-Link aktiv", en: "Upload link active", }; + pub const DOCUMENTS: Text = Text { + de: "Unterlagen", + en: "Documents", + }; + pub const NO_DOCUMENTS: Text = Text { + de: "Noch keine Unterlagen in der Dokumentenablage.", + en: "No documents in the document store yet.", + }; + pub const ADD_DOCUMENT: Text = Text { + de: "In der Dokumentenablage hinzufügen", + en: "Add in the document store", + }; + pub const DOCS_LOADING: Text = Text { + de: "Unterlagen werden geladen …", + en: "Loading the documents …", + }; + pub const DOCS_FAILED: Text = Text { + de: "Die Unterlagen lassen sich gerade nicht laden.", + en: "The documents cannot be loaded right now.", + }; + pub const INTERNAL: Text = Text { + de: "intern", + en: "internal", + }; pub const GHOST_BOUGHT: Text = Text { de: "Zugekaufte Komponente", en: "Bought-in component", diff --git a/compliance-dashboard/src/infrastructure/supply_chain.rs b/compliance-dashboard/src/infrastructure/supply_chain.rs index c25588d..e611cf0 100644 --- a/compliance-dashboard/src/infrastructure/supply_chain.rs +++ b/compliance-dashboard/src/infrastructure/supply_chain.rs @@ -118,6 +118,35 @@ pub struct LayoutDto { pub updated_at: Option>, } +/// A document of a product's box, shown in the portal. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct BoxDocumentDto { + pub id: String, + pub title: String, + #[serde(default)] + pub filename: String, + #[serde(default)] + pub size_bytes: Option, + /// Internal to the workspace rather than published with the product. + #[serde(default)] + pub internal: bool, + /// Where the portal shows it, below the portal's address. + pub path: String, +} + +/// A product's description and documents +/// (`GET /api/v1/supply-chain/projects/{id}/documents`). +#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)] +pub struct ProjectDocumentsDto { + #[serde(default)] + pub description: String, + #[serde(default)] + pub documents: Vec, + /// The portal's store, below its address; empty without a registry. + #[serde(default)] + pub store_path: String, +} + /// The `data` of an agent answer to `req`. #[cfg(feature = "server")] async fn data( @@ -147,6 +176,16 @@ pub async fn fetch_supply_chain_layout() -> Result { data(super::agent_client::agent_get("/api/v1/supply-chain/layout").await?).await } +/// Product project `id`'s description and documents. +#[server] +pub async fn fetch_project_documents(id: String) -> Result { + data( + super::agent_client::agent_get(&format!("/api/v1/supply-chain/projects/{id}/documents")) + .await?, + ) + .await +} + /// Save the arrangement: every placed box. #[server] pub async fn save_supply_chain_layout(positions: Vec) -> Result<(), ServerFnError> { diff --git a/compliance-dashboard/src/pages/supply_chain.rs b/compliance-dashboard/src/pages/supply_chain.rs index c902767..fe910b0 100644 --- a/compliance-dashboard/src/pages/supply_chain.rs +++ b/compliance-dashboard/src/pages/supply_chain.rs @@ -21,9 +21,9 @@ use crate::components::toast::{ToastType, Toasts}; use crate::i18n::texts::{kinds, supply_chain as tx}; use crate::i18n::{format_ago, use_lang, Lang}; use crate::infrastructure::supply_chain::{ - fetch_supply_chain, fetch_supply_chain_layout, reset_supply_chain_layout, - save_supply_chain_layout, DeliveryKind, EdgeDto, EdgeKind, LayoutDto, NodeDto, NodeKind, - PositionDto, SupplyChainDto, + fetch_project_documents, fetch_supply_chain, fetch_supply_chain_layout, + reset_supply_chain_layout, save_supply_chain_layout, DeliveryKind, EdgeDto, EdgeKind, + LayoutDto, NodeDto, NodeKind, PositionDto, SupplyChainDto, }; /// The top of the first box in each column, below the column titles. @@ -720,6 +720,12 @@ fn ChainView(chain: SupplyChainDto, layout: LayoutDto) -> Element { Link { class: "chain-panel-link", to: Route::TargetPage { id: id.to_string() }, {tx::OPEN_TARGET.get(lang)} } } if let Some(id) = n.project_id() { + ProjectDocs { + key: "{id}", + id: id.to_string(), + portal_url: portal_url.trim_end_matches('/').to_string(), + can_write, + } Link { class: "chain-panel-link", to: Route::MachinePage { id: id.to_string(), tab: String::new() }, {tx::OPEN_PRODUCT.get(lang)} } } } @@ -728,6 +734,88 @@ fn ChainView(chain: SupplyChainDto, layout: LayoutDto) -> Element { } } +/// A file size as people read it: "340 KB", "1,2 MB". +fn size_text(bytes: u64, lang: Lang) -> String { + const KB: f64 = 1024.0; + let b = bytes as f64; + let text = if b < KB * KB { + format!("{:.0} KB", (b / KB).max(1.0)) + } else { + format!("{:.1} MB", b / (KB * KB)) + }; + match lang { + Lang::De => text.replace('.', ","), + Lang::En => text, + } +} + +/// A product's description and its documents from the portal's +/// Dokumentenablage (#1054), each opened in the portal; the way to add one +/// for those who may. +#[component] +fn ProjectDocs(id: String, portal_url: String, can_write: bool) -> Element { + let lang = use_lang()(); + let docs = use_resource(move || { + let id = id.clone(); + async move { fetch_project_documents(id).await } + }); + let read = docs.read(); + let Some(answer) = read.as_ref() else { + return rsx! { p { class: "chain-panel-muted", {tx::DOCS_LOADING.get(lang)} } }; + }; + let Ok(d) = answer else { + return rsx! { p { class: "chain-panel-muted", {tx::DOCS_FAILED.get(lang)} } }; + }; + rsx! { + if !d.description.is_empty() { + p { class: "chain-panel-desc", "{d.description}" } + } + div { class: "chain-docs", + h3 { {tx::DOCUMENTS.get(lang)} } + if d.documents.is_empty() { + p { class: "chain-panel-muted", {tx::NO_DOCUMENTS.get(lang)} } + } + ul { + for doc in d.documents.iter() { + li { key: "{doc.id}", + if portal_url.is_empty() { + span { class: "chain-doc-title", "{doc.title}" } + } else { + a { + class: "chain-doc-title", + href: "{portal_url}{doc.path}", + target: "_blank", + rel: "noopener", + "{doc.title}" + } + } + span { class: "chain-doc-meta", + { + let size = doc.size_bytes.map(|b| size_text(b, lang)); + match (doc.internal, size) { + (true, Some(s)) => format!("{}, {s}", tx::INTERNAL.get(lang)), + (true, None) => tx::INTERNAL.get(lang).to_string(), + (false, Some(s)) => s, + (false, None) => doc.filename.clone(), + } + } + } + } + } + } + if can_write && !portal_url.is_empty() && !d.store_path.is_empty() { + a { + class: "chain-doc-add", + href: "{portal_url}{d.store_path}", + target: "_blank", + rel: "noopener", + {tx::ADD_DOCUMENT.get(lang)} + } + } + } + } +} + #[cfg(test)] mod tests { use super::*; @@ -918,6 +1006,14 @@ mod tests { ); } + #[test] + fn a_file_size_reads_in_the_language() { + assert_eq!(size_text(1_258_291, Lang::De), "1,2 MB"); + assert_eq!(size_text(1_258_291, Lang::En), "1.2 MB"); + assert_eq!(size_text(348_160, Lang::De), "340 KB"); + assert_eq!(size_text(10, Lang::En), "1 KB"); + } + #[test] fn a_cve_state_names_the_worst() { let counts = |critical, high| SeverityCounts { diff --git a/docs/guide/lieferkette.md b/docs/guide/lieferkette.md index aec50b2..1af2a6d 100644 --- a/docs/guide/lieferkette.md +++ b/docs/guide/lieferkette.md @@ -44,6 +44,16 @@ seinen berechneten Platz ein. **Anordnung zurücksetzen** stellt die Spalten wieder her. Rollen, die nur lesen dürfen, sehen die Anordnung, verschieben aber nichts. +## Beschreibung und Unterlagen eines Produkts + +Bei einem Produkt oder einer Baugruppe stehen rechts seine Beschreibung und +seine Unterlagen aus der Dokumentenablage im Portal, etwa die +Betriebsanleitung, neueste zuerst. Ein Klick öffnet die Unterlage im Portal. +Interne Unterlagen sind als „intern“ gekennzeichnet. Hinzufügen und die +Beschreibung ändern Sie in der Dokumentenablage beziehungsweise unter +**Projekte** im Portal. Prüfwerk hält keine Kopie der Dateien. Ein Bild des +Produkts folgt, sobald die Dokumentenablage Bilder aufnehmen kann. + Ein Klick auf einen Kasten hebt alles hervor, was davor und danach liegt: bei einem Produkt seine Baugruppen, Komponenten und Zulieferer. Rechts stehen die Angaben zum Kasten und der Weg zum Prüfobjekt oder Produkt.