From 686b8b086364245d230f03d6ae0046258b1ed2bc Mon Sep 17 00:00:00 2001 From: Sharang Parnerkar <30073382+mighty840@users.noreply.github.com> Date: Fri, 6 Nov 2026 16:28:16 +0100 Subject: [PATCH] feat(metering): this month's usage on the targets page (t72) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - GET /api/v1/metering/usage: the tenant's counted Prüfungen and Prüftage this month (Europe/Berlin), the extra targets now and the month's peak, with the plan's limits and whether the plan could be read. - The targets page shows it in one row: "37 von 100 Prüfungen", Prüftage with the cap, and the extra targets. Enterprise reads "unbegrenzt"; an unknown plan shows only the count, never a limit it cannot know. The hover text says what counts. Co-Authored-By: Claude Opus 5.5 --- compliance-agent/src/api/handlers/metering.rs | 54 +++++++++++ compliance-agent/src/api/handlers/mod.rs | 1 + compliance-agent/src/api/routes.rs | 1 + compliance-agent/src/metering.rs | 45 +++++++++ compliance-agent/tests/metering_counters.rs | 8 +- compliance-dashboard/assets/main.css | 15 +++ compliance-dashboard/src/components/mod.rs | 1 + .../src/components/usage_summary.rs | 87 +++++++++++++++++ compliance-dashboard/src/i18n/texts.rs | 94 +++++++++++++++++++ .../src/infrastructure/metering.rs | 51 ++++++++++ .../src/infrastructure/mod.rs | 1 + compliance-dashboard/src/pages/targets.rs | 2 + 12 files changed, 359 insertions(+), 1 deletion(-) create mode 100644 compliance-agent/src/api/handlers/metering.rs create mode 100644 compliance-dashboard/src/components/usage_summary.rs create mode 100644 compliance-dashboard/src/infrastructure/metering.rs diff --git a/compliance-agent/src/api/handlers/metering.rs b/compliance-agent/src/api/handlers/metering.rs new file mode 100644 index 0000000..ea196a8 --- /dev/null +++ b/compliance-agent/src/api/handlers/metering.rs @@ -0,0 +1,54 @@ +//! The tenant's metering this month, for the dashboard's usage view (t72). + +use axum::extract::Extension; +use axum::http::StatusCode; +use axum::Json; +use serde::Serialize; + +use compliance_core::tenant_ctx::TenantCtx; + +use super::dto::{tenant_db, AgentExt}; +use crate::metering::{month_summary, MonthSummary}; + +/// The usage view: what was used this month, and what the plan allows. +#[derive(Debug, Serialize)] +struct UsageView { + /// What was used. + #[serde(flatten)] + used: MonthSummary, + /// Whether the plan could be read; without it the limits are unknown, + /// not unlimited. + plan_known: bool, + /// The plan's included targets; `None` is unlimited. + included_targets: Option, + /// The monthly quota; `None` is unlimited. + monthly_pruefungen: Option, + /// The customer's Prüftag cap; `None` is no cap. + prueftag_cap: Option, +} + +/// GET /api/v1/metering/usage — the tenant's Prüfungen, Prüftage and extra +/// targets this month (Europe/Berlin), with the plan's limits. +/// +/// # Errors +/// +/// `500` when the counters cannot be read. +pub async fn get_usage( + Extension(agent): AgentExt, + tenant: TenantCtx, +) -> Result, StatusCode> { + let db = tenant_db(&agent, &tenant).await?; + let used = month_summary(&db, chrono::Utc::now()).await.map_err(|e| { + tracing::error!(tenant_id = %tenant.0.tenant_id, "usage not read: {e}"); + StatusCode::INTERNAL_SERVER_ERROR + })?; + let plan = agent.plan(&tenant.0.tenant_id).await; + let view = UsageView { + used, + plan_known: plan.is_some(), + included_targets: plan.and_then(|p| p.included_targets), + monthly_pruefungen: plan.and_then(|p| p.limits.monthly_pruefungen), + prueftag_cap: plan.and_then(|p| p.limits.prueftag_cap), + }; + Ok(Json(serde_json::json!({ "data": view }))) +} diff --git a/compliance-agent/src/api/handlers/mod.rs b/compliance-agent/src/api/handlers/mod.rs index e3ce2e8..344bdc5 100644 --- a/compliance-agent/src/api/handlers/mod.rs +++ b/compliance-agent/src/api/handlers/mod.rs @@ -14,6 +14,7 @@ pub mod licenses; pub mod manual_findings; pub mod mcp_servers; pub mod mcp_tokens; +pub mod metering; pub mod notifications; pub mod onboarding; pub mod oscal; diff --git a/compliance-agent/src/api/routes.rs b/compliance-agent/src/api/routes.rs index c793cdb..8e66b0e 100644 --- a/compliance-agent/src/api/routes.rs +++ b/compliance-agent/src/api/routes.rs @@ -15,6 +15,7 @@ pub fn build_router() -> Router { .route("/api/v1/stats/overview", get(handlers::stats_overview)) // The tenant's projects (owned by the registry), for assigning targets. .route("/api/v1/projects", get(handlers::projects::list_projects)) + .route("/api/v1/metering/usage", get(handlers::metering::get_usage)) // Whether the caller may use Prüfwerk at all: answered by the // authentication and entitlement layers in front of it (a blocked // member gets 403 MEMBER_BLOCKED), for the dashboard's sign-in check. diff --git a/compliance-agent/src/metering.rs b/compliance-agent/src/metering.rs index f740c93..298b84c 100644 --- a/compliance-agent/src/metering.rs +++ b/compliance-agent/src/metering.rs @@ -316,6 +316,51 @@ pub async fn record_extra_peak( Ok(Some(peak)) } +/// The tenant's metering this month, for the dashboard (t72). +#[derive(Debug, Clone, Default, PartialEq, Eq, serde::Serialize)] +pub struct MonthSummary { + /// The calendar month in Europe/Berlin, `YYYY-MM`. + pub month: String, + /// Counted Prüfungen charged to the quota. + pub pruefungen: u32, + /// Prüftage booked. + pub prueftage: u32, + /// Active targets that are extra now. + pub extra_targets: u32, + /// The highest number of extra targets at once this month, which the + /// extra-target line bills. + pub extra_peak: u32, +} + +/// What the tenant used in the month of `at`. +/// +/// # Errors +/// +/// Returns an error if the counters or the targets cannot be read. +pub async fn month_summary(db: &Database, at: DateTime) -> Result { + let (month, _) = berlin_period(at); + let stored = db + .raw_collection(MONTHS) + .find_one(doc! { "_id": &month }) + .await?; + let extra = mongodb::bson::to_bson(&TargetBilling::Extra) + .map_err(|e| AgentError::Other(e.to_string()))?; + let extra_targets = db + .onboarded_targets() + .count_documents(doc! { "archived_at": null, "billing": extra }) + .await?; + let extra_targets = u32::try_from(extra_targets).unwrap_or(u32::MAX); + Ok(MonthSummary { + month, + pruefungen: count(stored.as_ref(), "pruefungen"), + prueftage: count(stored.as_ref(), "prueftage"), + extra_targets, + // The peak is recorded when the billing is refreshed; until then + // it is at least what is extra now. + extra_peak: count(stored.as_ref(), "extra_peak").max(extra_targets), + }) +} + #[cfg(test)] mod tests { use super::*; diff --git a/compliance-agent/tests/metering_counters.rs b/compliance-agent/tests/metering_counters.rs index 5723579..fd332ed 100644 --- a/compliance-agent/tests/metering_counters.rs +++ b/compliance-agent/tests/metering_counters.rs @@ -7,7 +7,7 @@ use chrono::{TimeZone, Utc}; use compliance_agent::database::DatabasePool; -use compliance_agent::metering::{charge, usage}; +use compliance_agent::metering::{charge, month_summary, usage}; use compliance_core::models::{ admit, Admission, PlanLimits, Refusal, RunCharge, PRUEFUNGEN_PER_PRUEFTAG, }; @@ -79,5 +79,11 @@ async fn the_quota_then_a_prueftag_of_six_then_nothing() { assert_eq!(month.prueftage, 1); assert_eq!(month.pruefungen, 2); + // The usage view reads the same month. + let summary = month_summary(&db, at).await.unwrap(); + assert_eq!(summary.month, "2026-11"); + assert_eq!((summary.pruefungen, summary.prueftage), (2, 1)); + assert_eq!((summary.extra_targets, summary.extra_peak), (0, 0)); + pool.drop_tenant(TENANT).await.ok(); } diff --git a/compliance-dashboard/assets/main.css b/compliance-dashboard/assets/main.css index e017846..a19a4d7 100644 --- a/compliance-dashboard/assets/main.css +++ b/compliance-dashboard/assets/main.css @@ -4782,6 +4782,21 @@ tbody tr:last-child td { color: var(--accent); } +.usage-summary { + display: flex; + flex-wrap: wrap; + align-items: baseline; + gap: 6px 16px; + margin: 0 0 16px; + font-size: 13px; + color: var(--text-secondary); +} + +.usage-summary-title { + font-weight: 600; + color: var(--text-primary); +} + .targets-type, .targets-ago { display: block; diff --git a/compliance-dashboard/src/components/mod.rs b/compliance-dashboard/src/components/mod.rs index 39d1333..7fb8491 100644 --- a/compliance-dashboard/src/components/mod.rs +++ b/compliance-dashboard/src/components/mod.rs @@ -28,5 +28,6 @@ pub mod sidebar; pub mod support; pub mod theme_toggle; pub mod toast; +pub mod usage_summary; pub mod vex_panel; pub mod webhook_deliveries; diff --git a/compliance-dashboard/src/components/usage_summary.rs b/compliance-dashboard/src/components/usage_summary.rs new file mode 100644 index 0000000..c19c48e --- /dev/null +++ b/compliance-dashboard/src/components/usage_summary.rs @@ -0,0 +1,87 @@ +//! The usage view on the targets page (t72): this month's Prüfungen against +//! the quota, Prüftage against the cap, and the extra targets. + +use dioxus::prelude::*; + +use crate::i18n::texts::metering as tx; +use crate::i18n::use_lang; +use crate::infrastructure::metering::{fetch_usage, Usage}; + +/// The lines of the usage view: only the count when the plan is not known, +/// Prüftage only where there is a quota, extra targets only where the plan +/// limits the included ones. +fn lines(u: &Usage, lang: crate::i18n::Lang) -> Vec { + if !u.plan_known { + return vec![tx::counted(u.pruefungen, lang)]; + } + let mut lines = vec![tx::pruefungen(u.pruefungen, u.monthly_pruefungen, lang)]; + if u.monthly_pruefungen.is_some() { + lines.push(tx::prueftage(u.prueftage, u.prueftag_cap, lang)); + } + if u.included_targets.is_some() { + lines.push(tx::extra_targets(u.extra_targets, lang)); + } + lines +} + +/// This month's usage in one row. Shows nothing while it loads or when it +/// cannot be read. +#[component] +pub fn UsageSummary() -> Element { + let lang = use_lang()(); + let usage = use_resource(move || async move { fetch_usage().await }); + let Some(Ok(resp)) = usage.read().clone() else { + return rsx! {}; + }; + rsx! { + div { class: "usage-summary", title: tx::HINT.get(lang), + span { class: "usage-summary-title", {tx::TITLE.get(lang)} } + for line in lines(&resp.data, lang) { + span { class: "usage-summary-item", "{line}" } + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::i18n::Lang; + + #[test] + fn a_standard_plan_shows_quota_prueftage_and_extra_targets() { + let u = Usage { + pruefungen: 37, + prueftage: 1, + extra_targets: 2, + plan_known: true, + included_targets: Some(5), + monthly_pruefungen: Some(100), + prueftag_cap: None, + ..Usage::default() + }; + assert_eq!( + lines(&u, Lang::De), + [ + "37 von 100 Prüfungen", + "1 Prüftag", + "2 zusätzliche Prüfobjekte" + ] + ); + } + + #[test] + fn enterprise_and_an_unknown_plan_show_only_the_count() { + let enterprise = Usage { + pruefungen: 12, + plan_known: true, + ..Usage::default() + }; + assert_eq!(lines(&enterprise, Lang::En), ["12 scans, unlimited"]); + let unknown = Usage { + pruefungen: 12, + ..Usage::default() + }; + assert_eq!(lines(&unknown, Lang::En), ["12 counted scans"]); + } +} diff --git a/compliance-dashboard/src/i18n/texts.rs b/compliance-dashboard/src/i18n/texts.rs index 25c2af6..8608fcb 100644 --- a/compliance-dashboard/src/i18n/texts.rs +++ b/compliance-dashboard/src/i18n/texts.rs @@ -4433,3 +4433,97 @@ pub mod license_review { } } } + +/// The usage view on the targets page (t72): Prüfungen against the quota, +/// Prüftage against the cap, extra targets. +pub mod metering { + use super::Text; + use crate::i18n::Lang; + + pub const TITLE: Text = Text { + de: "Nutzung in diesem Monat", + en: "Usage this month", + }; + pub const HINT: Text = Text { + de: "Gezählt werden Prüfungen, die Sie starten, und jede Prüfung eines zusätzlichen \ + Prüfobjekts. Prüfungen nach einer Änderung an enthaltenen Prüfobjekten zählen \ + nicht.", + en: "Counted are the scans you start, and every scan of an extra target. Scans after \ + a change to an included target are not counted.", + }; + + /// "37 von 100 Prüfungen", or "37 Prüfungen, unbegrenzt" without a quota. + pub fn pruefungen(used: u32, quota: Option, lang: Lang) -> String { + match (lang, quota) { + (Lang::De, Some(q)) => format!("{used} von {q} Prüfungen"), + (Lang::De, None) => format!("{used} Prüfungen, unbegrenzt"), + (Lang::En, Some(q)) => format!("{used} of {q} scans"), + (Lang::En, None) => format!("{used} scans, unlimited"), + } + } + + /// "37 gezählte Prüfungen", when the plan's limits are not known. + pub fn counted(used: u32, lang: Lang) -> String { + match lang { + Lang::De => format!("{used} gezählte Prüfungen"), + Lang::En => format!("{used} counted scans"), + } + } + + /// "2 Prüftage (Limit 5)", "1 Prüftag", or that none are allowed. + pub fn prueftage(booked: u32, cap: Option, lang: Lang) -> String { + let days = match (lang, booked) { + (Lang::De, 1) => "1 Prüftag".to_string(), + (Lang::De, n) => format!("{n} Prüftage"), + (Lang::En, 1) => "1 Prüftag".to_string(), + (Lang::En, n) => format!("{n} Prüftage"), + }; + match (lang, cap) { + (Lang::De, Some(0)) => "Keine Prüftage erlaubt".to_string(), + (Lang::En, Some(0)) => "No Prüftage allowed".to_string(), + (_, Some(c)) => format!("{days} (Limit {c})"), + (_, None) => days, + } + } + + /// "1 zusätzliches Prüfobjekt", or that every target is included. + pub fn extra_targets(extra: u32, lang: Lang) -> String { + match (lang, extra) { + (Lang::De, 0) => "Alle Prüfobjekte im Tarif enthalten".to_string(), + (Lang::De, 1) => "1 zusätzliches Prüfobjekt".to_string(), + (Lang::De, n) => format!("{n} zusätzliche Prüfobjekte"), + (Lang::En, 0) => "All targets included in your plan".to_string(), + (Lang::En, 1) => "1 extra target".to_string(), + (Lang::En, n) => format!("{n} extra targets"), + } + } + + #[cfg(test)] + mod tests { + use super::*; + + #[test] + fn the_quota_line_says_what_is_left_or_that_there_is_no_limit() { + assert_eq!(pruefungen(37, Some(100), Lang::De), "37 von 100 Prüfungen"); + assert_eq!(pruefungen(37, None, Lang::En), "37 scans, unlimited"); + assert_eq!(counted(37, Lang::De), "37 gezählte Prüfungen"); + } + + #[test] + fn the_prueftag_line_names_the_cap() { + assert_eq!(prueftage(2, Some(5), Lang::De), "2 Prüftage (Limit 5)"); + assert_eq!(prueftage(1, None, Lang::De), "1 Prüftag"); + assert_eq!(prueftage(0, Some(0), Lang::De), "Keine Prüftage erlaubt"); + } + + #[test] + fn extra_targets_read_naturally() { + assert_eq!( + extra_targets(0, Lang::De), + "Alle Prüfobjekte im Tarif enthalten" + ); + assert_eq!(extra_targets(1, Lang::De), "1 zusätzliches Prüfobjekt"); + assert_eq!(extra_targets(3, Lang::En), "3 extra targets"); + } + } +} diff --git a/compliance-dashboard/src/infrastructure/metering.rs b/compliance-dashboard/src/infrastructure/metering.rs new file mode 100644 index 0000000..d16e3d9 --- /dev/null +++ b/compliance-dashboard/src/infrastructure/metering.rs @@ -0,0 +1,51 @@ +//! Server function for the usage view (t72): proxies the agent's +//! `/api/v1/metering/usage`. + +use dioxus::prelude::*; +use serde::{Deserialize, Serialize}; + +/// The tenant's metering this month, as the agent reports it. +#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)] +pub struct Usage { + /// The calendar month in Europe/Berlin, `YYYY-MM`. + #[serde(default)] + pub month: String, + /// Counted Prüfungen charged to the quota. + #[serde(default)] + pub pruefungen: u32, + /// Prüftage booked. + #[serde(default)] + pub prueftage: u32, + /// Active targets that are extra now. + #[serde(default)] + pub extra_targets: u32, + /// Whether the plan could be read; without it the limits are unknown. + #[serde(default)] + pub plan_known: bool, + /// The plan's included targets; `None` is unlimited. + #[serde(default)] + pub included_targets: Option, + /// The monthly quota; `None` is unlimited. + #[serde(default)] + pub monthly_pruefungen: Option, + /// The customer's Prüftag cap; `None` is no cap. + #[serde(default)] + pub prueftag_cap: Option, +} + +/// The agent's answer. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct UsageResponse { + pub data: Usage, +} + +/// The tenant's Prüfungen, Prüftage and extra targets this month. +#[server] +pub async fn fetch_usage() -> Result { + let resp = super::agent_client::agent_get("/api/v1/metering/usage") + .await? + .send() + .await + .map_err(|e| ServerFnError::new(e.to_string()))?; + super::agent_client::json_or_error(resp).await +} diff --git a/compliance-dashboard/src/infrastructure/mod.rs b/compliance-dashboard/src/infrastructure/mod.rs index 6a913ea..60a7950 100644 --- a/compliance-dashboard/src/infrastructure/mod.rs +++ b/compliance-dashboard/src/infrastructure/mod.rs @@ -12,6 +12,7 @@ pub mod issues; pub mod manual_findings; pub mod mcp; pub mod mcp_tokens; +pub mod metering; pub mod notifications; pub mod onboarding; pub mod pentest; diff --git a/compliance-dashboard/src/pages/targets.rs b/compliance-dashboard/src/pages/targets.rs index 2902557..638ff80 100644 --- a/compliance-dashboard/src/pages/targets.rs +++ b/compliance-dashboard/src/pages/targets.rs @@ -15,6 +15,7 @@ use crate::components::pagination::Pagination; use crate::components::projects::ProjectChips; use crate::components::scan_runs::status_badge; use crate::components::toast::{ToastType, Toasts}; +use crate::components::usage_summary::UsageSummary; use crate::i18n::texts::{common, kinds, scans as scan_texts, targets as tx}; use crate::i18n::{format_ago, use_lang, Lang}; use crate::infrastructure::auth_check::{go_to_login, is_session_expired}; @@ -132,6 +133,7 @@ pub fn TargetsPage() -> Element { title: tx::TITLE.get(lang), description: tx::SUBTITLE.get(lang), } + UsageSummary {} div { class: "page-actions", if can_write {