feat(metering): this month's usage on the targets page (t72) (#931)
CI / Check (push) Skipped
CI / Agent integration (push) Skipped
CI / Detect Changes (push) Successful in 5s
CI / Deploy Docs (push) Skipped
CI / Deploy MCP (push) Skipped
CI / Deploy Dashboard (push) Successful in 6m24s
CI / Deploy Agent (push) Successful in 8m43s

This commit was merged in pull request #931.
This commit is contained in:
sharang committed 2026-11-07 02:50:56 +00:00
1 parent 168cbe98f8
commit 3bdaf28737
12 files changed
+359 -1

No files matched your search

@@ -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<u32>,
/// The monthly quota; `None` is unlimited.
monthly_pruefungen: Option<u32>,
/// The customer's Prüftag cap; `None` is no cap.
prueftag_cap: Option<u32>,
}
/// 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<Json<serde_json::Value>, 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 })))
}
+1
View File
@@ -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;
+1
View File
@@ -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.
+45
View File
@@ -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<Utc>) -> Result<MonthSummary, AgentError> {
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::*;
+7 -1
View File
@@ -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();
}
+15
View File
@@ -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;
@@ -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;
@@ -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<String> {
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"]);
}
}
+94
View File
@@ -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<u32>, 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<u32>, 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");
}
}
}
@@ -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<u32>,
/// The monthly quota; `None` is unlimited.
#[serde(default)]
pub monthly_pruefungen: Option<u32>,
/// The customer's Prüftag cap; `None` is no cap.
#[serde(default)]
pub prueftag_cap: Option<u32>,
}
/// 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<UsageResponse, ServerFnError> {
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
}
@@ -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;
@@ -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 {