feat(supply-chain): a product's description and documents on its box (#1054)
CI / Check (push) Skipped
CI / Detect Changes (pull_request) Skipped
CI / Deploy Agent (pull_request) Skipped
CI / Deploy Dashboard (pull_request) Skipped
CI / Deploy Docs (pull_request) Skipped
CI / Deploy MCP (pull_request) Skipped
CI / Agent integration (pull_request) Successful in 5m38s
CI / Check (pull_request) Successful in 22m37s

A product's or assembly's box on the Lieferkette shows its description and
its documents from the portal's Dokumentenablage, where the user decided the
files live (2026-11-19):

- `GET /api/v1/supply-chain/projects/{id}/documents`: the project's
  description and the store's documents that belong to it (published with
  the product or internal), newest first, each with where the portal shows
  it (`/{slug}/dokumente/{doc}/original`) and the store's path for adding
  one; legal web documents and BreakPilot's deliveries belong to no product.
  Prüfwerk keeps no copy. 404 for anything but a product project of the
  workspace; nothing to show without a registry (dev).
- registry client: `list_store` reads `GET /v1/tenants/{id}/store`.
- the panel: the description, the documents (internal ones marked, with
  their size), each opening in the portal, and "In der Dokumentenablage
  hinzufügen" for those who may add.

The picture waits on the store taking images (tenant-registry#140).
Components and suppliers get no slots: the store files documents per product.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Q9inRcu428A2iNjDHPEAT9
This commit is contained in:
Sharang ParnerkarandClaude Opus 5.5 committed 2026-11-19 11:12:17 +01:00
1 parent 40fb69072e
commit 69b476fd5f
9 files changed
+432 -3

No files matched your search

@@ -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<String>,
pub size_bytes: Option<u64>,
/// Internal to the workspace rather than published with the product.
pub internal: bool,
pub created_at: Option<DateTime<Utc>>,
/// 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<BoxDocument>,
/// 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<crate::registry::StoreDocument>,
project: &str,
slug: &str,
) -> Vec<BoxDocument> {
let slug = urlencoding::encode(slug);
let mut documents: Vec<BoxDocument> = 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<String>,
) -> Result<Json<ApiResponse<ProjectDocuments>>, 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<Project> {
@@ -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![
+1
View File
@@ -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,
+55
View File
@@ -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<String>,
#[serde(default)]
pub size_bytes: Option<u64>,
/// `legal_web`, `product_public` or `internal`; none for BreakPilot's
/// deliveries.
#[serde(default)]
pub area: Option<String>,
/// The product projects it belongs to.
#[serde(default)]
pub project_ids: Vec<String>,
#[serde(default)]
pub created_at: Option<chrono::DateTime<chrono::Utc>>,
}
/// 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<Vec<StoreDocument>, String> {
#[derive(Deserialize)]
struct Page {
#[serde(default)]
items: Vec<StoreDocument>,
}
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`].
///
@@ -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;
}
+36
View File
@@ -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;
}
+24
View File
@@ -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",
@@ -118,6 +118,35 @@ pub struct LayoutDto {
pub updated_at: Option<DateTime<Utc>>,
}
/// 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<u64>,
/// 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<BoxDocumentDto>,
/// 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<T: serde::de::DeserializeOwned>(
@@ -147,6 +176,16 @@ pub async fn fetch_supply_chain_layout() -> Result<LayoutDto, ServerFnError> {
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<ProjectDocumentsDto, ServerFnError> {
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<PositionDto>) -> Result<(), ServerFnError> {
+99 -3
View File
@@ -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 {
+10
View File
@@ -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.