diff --git a/compliance-agent/src/api/handlers/onboarding.rs b/compliance-agent/src/api/handlers/onboarding.rs index 87f4307..722b456 100644 --- a/compliance-agent/src/api/handlers/onboarding.rs +++ b/compliance-agent/src/api/handlers/onboarding.rs @@ -1023,6 +1023,76 @@ fn requested_trigger(staff: bool, reason: Option<&str>) -> compliance_core::mode } } +/// `POST /api/v1/targets/{id}/billing/swap`: the included target to swap +/// the extra target `{id}` with. +#[derive(Debug, Deserialize)] +pub struct SwapRequest { + /// The id of the included target that becomes extra. + pub with: String, +} + +/// The JSON `error` of a refused swap, for the dashboard to word. +fn swap_refusal_code(refusal: compliance_core::models::SwapRefusal) -> &'static str { + use compliance_core::models::SwapRefusal; + match refusal { + SwapRefusal::Unlimited => "swap_unlimited", + SwapRefusal::NotExtra => "swap_not_extra", + SwapRefusal::NotIncluded => "swap_not_included", + SwapRefusal::Locked => "swap_locked", + } +} + +/// POST /api/v1/targets/{id}/billing/swap — swap the extra target `{id}` +/// with the included target `with` (t72): `{id}` becomes included and stays +/// so until the end of the calendar month, `with` becomes extra at once. +/// The number of extra targets, and so the extra-target line, is the same. +/// +/// # Errors +/// +/// `404` for a target that is not an active one of the tenant, `409` with +/// the reason when the swap is not allowed, `503` when the plan cannot be +/// read. +pub async fn swap_target_billing( + Extension(agent): AgentExt, + tenant: TenantCtx, + Path(id): Path, + Json(req): Json, +) -> Result, (StatusCode, Json)> { + let refuse = + |status: StatusCode, error: &str| (status, Json(serde_json::json!({ "error": error }))); + let incoming = parse_oid(&id).map_err(|s| refuse(s, "invalid_id"))?; + let outgoing = parse_oid(&req.with).map_err(|s| refuse(s, "invalid_id"))?; + let db = tenant_db(&agent, &tenant) + .await + .map_err(|s| refuse(s, "database_unavailable"))?; + let tenant_id = tenant.0.tenant_id.as_str(); + let plan = agent + .plan(tenant_id) + .await + .ok_or_else(|| refuse(StatusCode::SERVICE_UNAVAILABLE, "plan_unavailable"))?; + let outcome = crate::metering::swap( + &db, + incoming, + outgoing, + plan.included_targets.is_some(), + chrono::Utc::now(), + ) + .await + .map_err(|e| { + tracing::error!(tenant_id, "swap failed: {e}"); + refuse(StatusCode::INTERNAL_SERVER_ERROR, "swap_failed") + })?; + match outcome { + None => Err(refuse(StatusCode::NOT_FOUND, "target_not_found")), + Some(Err(refusal)) => Err(refuse(StatusCode::CONFLICT, swap_refusal_code(refusal))), + Some(Ok(())) => { + agent.refresh_billing(tenant_id, &db).await; + tracing::info!(tenant_id, incoming = %id, outgoing = %req.with, "targets swapped"); + Ok(Json(serde_json::json!({ "data": { "swapped": true } }))) + } + } +} + /// POST /api/v1/targets/{id}/scan — trigger a scan for the target. /// /// Dispatches to the unified pipeline when `UNIFIED_PIPELINE` is set (else the diff --git a/compliance-agent/src/api/routes.rs b/compliance-agent/src/api/routes.rs index 8e66b0e..cd1a7dd 100644 --- a/compliance-agent/src/api/routes.rs +++ b/compliance-agent/src/api/routes.rs @@ -85,6 +85,10 @@ pub fn build_router() -> Router { "/api/v1/targets/{id}/scan", post(handlers::onboarding::trigger_target_scan), ) + .route( + "/api/v1/targets/{id}/billing/swap", + post(handlers::onboarding::swap_target_billing), + ) .route("/api/v1/findings", get(handlers::list_findings)) .route( "/api/v1/findings/variants", diff --git a/compliance-agent/src/metering.rs b/compliance-agent/src/metering.rs index 298b84c..2d1c0c2 100644 --- a/compliance-agent/src/metering.rs +++ b/compliance-agent/src/metering.rs @@ -20,7 +20,8 @@ use futures_util::TryStreamExt; use mongodb::bson::{doc, oid::ObjectId, Document}; use compliance_core::models::{ - split_included, BillableTarget, DayUsage, MonthUsage, PlanLimits, RunCharge, TargetBilling, + check_swap, split_included, BillableTarget, DayUsage, IncludedChoice, MonthUsage, PlanLimits, + RunCharge, SwapRefusal, TargetBilling, }; use crate::database::Database; @@ -45,12 +46,12 @@ pub async fn assign_billing( db: &Database, included: Option, ) -> Result, AgentError> { - // Only the three fields the split needs: a whole target holds its - // artifacts, and older documents may lack fields the model requires. + // Only the fields the split needs: a whole target holds its artifacts, + // and older documents may lack fields the model requires. let docs: Vec = db .raw_collection("onboarded_targets") .find(doc! { "archived_at": null }) - .projection(doc! { "_id": 1, "created_at": 1, "billing": 1 }) + .projection(doc! { "_id": 1, "created_at": 1, "billing": 1, "included_choice": 1 }) .await? .try_collect() .await?; @@ -90,9 +91,89 @@ fn billable(target: &Document) -> Option> { .get("billing") .and_then(|b| mongodb::bson::from_bson(b.clone()).ok()) .unwrap_or_default(), + choice: target + .get("included_choice") + .and_then(|c| mongodb::bson::from_bson(c.clone()).ok()), }) } +/// The first instant after the calendar month (Europe/Berlin) of `at`: until +/// then a target swapped in at `at` stays included. +pub fn end_of_berlin_month(at: DateTime) -> DateTime { + use chrono::{Datelike, TimeZone}; + let local = at.with_timezone(&chrono_tz::Europe::Berlin); + let (year, month) = if local.month() == 12 { + (local.year() + 1, 1) + } else { + (local.year(), local.month() + 1) + }; + // Midnight is never skipped or repeated in Berlin (DST changes at 2–3 h). + chrono_tz::Europe::Berlin + .with_ymd_and_hms(year, month, 1, 0, 0, 0) + .earliest() + .map_or(at, |next| next.with_timezone(&Utc)) +} + +/// Swap the extra target `incoming` with the included target `outgoing` +/// (t72): the one swapped in stays included until the end of the calendar +/// month, the other becomes extra. It records the customer's choice; the +/// next [`assign_billing`] (which the caller runs) moves the billing. +/// +/// # Arguments +/// +/// * `limited` - Whether the plan limits the included targets. +/// +/// # Returns +/// +/// `None` when either target is not an active one of the tenant; else +/// whether the swap was made, or why not. +/// +/// # Errors +/// +/// Returns an error if the targets cannot be read or updated. +pub async fn swap( + db: &Database, + incoming: ObjectId, + outgoing: ObjectId, + limited: bool, + at: DateTime, +) -> Result>, AgentError> { + let targets = db.onboarded_targets(); + let active = |id: ObjectId| doc! { "_id": id, "archived_at": null }; + let (Some(swapped_in), Some(swapped_out)) = ( + targets.find_one(active(incoming)).await?, + targets.find_one(active(outgoing)).await?, + ) else { + return Ok(None); + }; + let locked = swapped_out.included_until.is_some_and(|until| until > at); + if let Err(refusal) = check_swap(limited, swapped_in.billing, swapped_out.billing, locked) { + return Ok(Some(Err(refusal))); + } + let to_bson = |v: IncludedChoice| { + mongodb::bson::to_bson(&v).map_err(|e| AgentError::Other(e.to_string())) + }; + targets + .update_one( + doc! { "_id": incoming }, + doc! { "$set": { + "included_choice": to_bson(IncludedChoice::Included)?, + "included_until": mongodb::bson::DateTime::from_chrono(end_of_berlin_month(at)), + } }, + ) + .await?; + targets + .update_one( + doc! { "_id": outgoing }, + doc! { + "$set": { "included_choice": to_bson(IncludedChoice::Extra)? }, + "$unset": { "included_until": "" }, + }, + ) + .await?; + Ok(Some(Ok(()))) +} + /// The tenant's plan as metering reads it from the registry. #[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] pub struct Plan { @@ -366,6 +447,30 @@ mod tests { use super::*; use chrono::TimeZone; + #[test] + fn a_swap_holds_until_the_berlin_month_ends() { + let at = |y, m, d, h| { + Utc.with_ymd_and_hms(y, m, d, h, 0, 0) + .single() + .expect("valid") + }; + // 1 Dec 00:00 in Berlin (CET) is 30 Nov 23:00 UTC. + assert_eq!( + end_of_berlin_month(at(2026, 11, 6, 9)), + at(2026, 11, 30, 23) + ); + // December rolls into January of the next year. + assert_eq!( + end_of_berlin_month(at(2026, 12, 15, 9)), + at(2026, 12, 31, 23) + ); + // 1 Aug 00:00 in Berlin (CEST) is 31 Jul 22:00 UTC. + assert_eq!( + end_of_berlin_month(at(2026, 7, 31, 21)), + at(2026, 7, 31, 22) + ); + } + #[test] fn periods_are_calendar_ones_in_berlin() { let at = |y, m, d, h, min| { @@ -413,6 +518,7 @@ mod tests { id, created_at: at.to_chrono(), billing: TargetBilling::Extra, + choice: None, }) ); assert_eq!( @@ -421,6 +527,7 @@ mod tests { id, created_at: DateTime::::MIN_UTC, billing: TargetBilling::Included, + choice: None, }) ); assert_eq!(billable(&doc! { "name": "no id" }), None); diff --git a/compliance-agent/tests/target_billing.rs b/compliance-agent/tests/target_billing.rs index c073282..9ea11d8 100644 --- a/compliance-agent/tests/target_billing.rs +++ b/compliance-agent/tests/target_billing.rs @@ -80,3 +80,71 @@ async fn the_oldest_targets_are_included_and_an_extra_one_moves_up() { pool.drop_tenant(TENANT).await.ok(); } + +#[tokio::test] +async fn a_swap_moves_both_and_holds_the_one_swapped_in_until_month_end() { + use compliance_agent::metering::swap; + use compliance_core::models::SwapRefusal; + + let uri = std::env::var("TEST_MONGODB_URI") + .unwrap_or_else(|_| "mongodb://root:example@localhost:27017/?authSource=admin".into()); + let prefix = format!("swap_{}", &uuid::Uuid::new_v4().simple().to_string()[..10]); + let Ok(pool) = DatabasePool::connect(&uri, &prefix).await else { + eprintln!("SKIP target_billing swap: no MongoDB reachable at {uri}"); + return; + }; + let db = pool.for_tenant_id(TENANT).await.unwrap(); + // Arrange: three targets on a plan with two included: the newest is extra. + let mut ids = Vec::new(); + for days in [3, 2, 1] { + let mut target = OnboardedTarget::new(format!("t{days}"), TargetType::FirmwareRtos); + target.created_at = Utc::now() - Duration::days(days); + let res = db.onboarded_targets().insert_one(&target).await.unwrap(); + ids.push(res.inserted_id.as_object_id().unwrap()); + } + let (oldest, middle, newest) = (ids[0], ids[1], ids[2]); + assign_billing(&db, Some(2)).await.unwrap(); + let nov6 = chrono::TimeZone::with_ymd_and_hms(&Utc, 2026, 11, 6, 9, 0, 0) + .single() + .unwrap(); + + // Act: swap the newest in for the oldest. + let swapped = swap(&db, newest, oldest, true, nov6).await.unwrap(); + assign_billing(&db, Some(2)).await.unwrap(); + + // Assert: they changed places; the count of extra targets is the same. + assert_eq!(swapped, Some(Ok(()))); + assert_eq!(billing(&db, newest).await, TargetBilling::Included); + assert_eq!(billing(&db, oldest).await, TargetBilling::Extra); + assert_eq!(billing(&db, middle).await, TargetBilling::Included); + + // The one swapped in stays included this month; another may go out. + assert_eq!( + swap(&db, oldest, newest, true, nov6).await.unwrap(), + Some(Err(SwapRefusal::Locked)) + ); + assert_eq!( + swap(&db, oldest, middle, true, nov6).await.unwrap(), + Some(Ok(())) + ); + assign_billing(&db, Some(2)).await.unwrap(); + assert_eq!(billing(&db, middle).await, TargetBilling::Extra); + + // From December, the target swapped in on 6 Nov may go out again. + let dec1 = chrono::TimeZone::with_ymd_and_hms(&Utc, 2026, 12, 1, 9, 0, 0) + .single() + .unwrap(); + assert_eq!( + swap(&db, middle, newest, true, dec1).await.unwrap(), + Some(Ok(())) + ); + assert_eq!( + swap(&db, middle, ObjectId::new(), true, dec1) + .await + .unwrap(), + None, + "an unknown target" + ); + + pool.drop_tenant(TENANT).await.ok(); +} diff --git a/compliance-core/src/models/metering.rs b/compliance-core/src/models/metering.rs index 5799346..35cfc33 100644 --- a/compliance-core/src/models/metering.rs +++ b/compliance-core/src/models/metering.rs @@ -186,6 +186,79 @@ pub fn admit(limits: PlanLimits, month: MonthUsage, day: DayUsage) -> Admission } } +/// The customer's choice for a target's billing, from a swap (t72): the +/// target swapped in is wanted included, the one swapped out extra. +#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)] +#[serde(rename_all = "snake_case")] +pub enum IncludedChoice { + /// Swapped in: included before the oldest targets. + Included, + /// Swapped out: extra before the newest targets. + Extra, +} + +impl IncludedChoice { + /// Where a target with `choice` comes in the split: swapped in first, + /// swapped out last, every other target by age in between. + fn rank(choice: Option) -> u8 { + match choice { + Some(Self::Included) => 0, + None => 1, + Some(Self::Extra) => 2, + } + } +} + +/// Why a swap of an extra target with an included one is not made (t72). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum SwapRefusal { + /// The plan includes every target, so there is nothing to swap. + Unlimited, + /// The target to swap in is not extra. + NotExtra, + /// The target to swap out is not included. + NotIncluded, + /// The target to swap out was swapped in this month and stays included + /// until the month's end. + Locked, +} + +/// Whether an extra target may be swapped with an included one, by the +/// contract: at any time, except that a target swapped in stays included +/// until the end of its calendar month. +/// +/// # Arguments +/// +/// * `limited` - Whether the plan limits the included targets. +/// * `incoming` - How the target to swap in is billed now. +/// * `outgoing` - How the target to swap out is billed now. +/// * `outgoing_locked` - Whether the target to swap out is still within +/// the month it was swapped in. +/// +/// # Errors +/// +/// The [`SwapRefusal`] that stops the swap. +pub fn check_swap( + limited: bool, + incoming: TargetBilling, + outgoing: TargetBilling, + outgoing_locked: bool, +) -> Result<(), SwapRefusal> { + if !limited { + return Err(SwapRefusal::Unlimited); + } + if incoming != TargetBilling::Extra { + return Err(SwapRefusal::NotExtra); + } + if outgoing != TargetBilling::Included { + return Err(SwapRefusal::NotIncluded); + } + if outgoing_locked { + return Err(SwapRefusal::Locked); + } + Ok(()) +} + /// One active target as [`split_included`] sees it. #[derive(Debug, Clone, PartialEq, Eq)] pub struct BillableTarget { @@ -195,10 +268,14 @@ pub struct BillableTarget { pub created_at: DateTime, /// How it is billed now. pub billing: TargetBilling, + /// The customer's choice from a swap, if any. + pub choice: Option, } /// The targets whose billing has to change so that the `included` oldest -/// active targets are included and the rest are extra. +/// active targets are included and the rest are extra; a target the +/// customer swapped in comes before the oldest, one swapped out after the +/// newest. /// /// # Arguments /// @@ -215,7 +292,12 @@ pub fn split_included( included: Option, ) -> Vec<(Id, TargetBilling)> { let mut ordered: Vec<&BillableTarget> = targets.iter().collect(); - ordered.sort_unstable_by(|a, b| a.created_at.cmp(&b.created_at).then(a.id.cmp(&b.id))); + ordered.sort_unstable_by(|a, b| { + IncludedChoice::rank(a.choice) + .cmp(&IncludedChoice::rank(b.choice)) + .then(a.created_at.cmp(&b.created_at)) + .then(a.id.cmp(&b.id)) + }); // `usize::MAX` stands for "no limit"; a u32 always fits a usize here. let limit = included.map_or(usize::MAX, |n| n as usize); ordered @@ -245,9 +327,53 @@ mod tests { .single() .expect("valid date"), billing, + choice: None, } } + #[test] + fn a_swap_moves_one_in_and_one_out() { + // Arrange: two included (days 1, 2) and one extra (day 3); the + // customer swaps 3 in for 1. + let mut incoming = target(3, 3, TargetBilling::Extra); + incoming.choice = Some(IncludedChoice::Included); + let mut outgoing = target(1, 1, TargetBilling::Included); + outgoing.choice = Some(IncludedChoice::Extra); + let targets = [outgoing, target(2, 2, TargetBilling::Included), incoming]; + + // Act + let mut changes = split_included(&targets, Some(2)); + changes.sort_unstable_by_key(|(id, _)| *id); + + // Assert: the count of extra targets is the same. + assert_eq!( + changes, + vec![(1, TargetBilling::Extra), (3, TargetBilling::Included)] + ); + } + + #[test] + fn a_target_swapped_in_this_month_cannot_go_out() { + use TargetBilling::{Extra, Included}; + assert_eq!(check_swap(true, Extra, Included, false), Ok(())); + assert_eq!( + check_swap(true, Extra, Included, true), + Err(SwapRefusal::Locked) + ); + assert_eq!( + check_swap(true, Included, Included, false), + Err(SwapRefusal::NotExtra) + ); + assert_eq!( + check_swap(true, Extra, Extra, false), + Err(SwapRefusal::NotIncluded) + ); + assert_eq!( + check_swap(false, Extra, Included, false), + Err(SwapRefusal::Unlimited) + ); + } + #[test] fn the_oldest_targets_are_included_and_the_rest_extra() { // Arrange: three included targets, created on days 3, 1 and 2. diff --git a/compliance-core/src/models/mod.rs b/compliance-core/src/models/mod.rs index 7afc683..d80b6a4 100644 --- a/compliance-core/src/models/mod.rs +++ b/compliance-core/src/models/mod.rs @@ -59,8 +59,9 @@ pub use license_policy::{ pub use mcp::{McpServerConfig, McpServerStatus, McpTransport}; pub use mcp_token::{McpToken, McpTokenView}; pub use metering::{ - admit, split_included, Admission, BillableTarget, DayUsage, MonthUsage, PlanLimits, Refusal, - RunCharge, ScanAttribution, TargetBilling, PRUEFUNGEN_PER_PRUEFTAG, + admit, check_swap, split_included, Admission, BillableTarget, DayUsage, IncludedChoice, + MonthUsage, PlanLimits, Refusal, RunCharge, ScanAttribution, SwapRefusal, TargetBilling, + PRUEFUNGEN_PER_PRUEFTAG, }; pub use notification::{CveNotification, NotificationSeverity, NotificationStatus}; pub use onboarding::{ diff --git a/compliance-core/src/models/onboarding.rs b/compliance-core/src/models/onboarding.rs index 876a949..0792a2a 100644 --- a/compliance-core/src/models/onboarding.rs +++ b/compliance-core/src/models/onboarding.rs @@ -665,6 +665,18 @@ pub struct OnboardedTarget { /// unseen. #[serde(default)] pub billing: super::metering::TargetBilling, + /// The customer's choice from a swap of an extra target with an + /// included one (t72); `None` until one is made. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub included_choice: Option, + /// Until when a target swapped in stays included: the end of the + /// calendar month (Europe/Berlin) it was swapped in. + #[serde( + default, + skip_serializing_if = "Option::is_none", + with = "super::serde_helpers::opt_bson_datetime" + )] + pub included_until: Option>, /// Creation timestamp. #[serde( default = "chrono::Utc::now", @@ -706,6 +718,8 @@ impl OnboardedTarget { last_scan: None, layer_pins: None, billing: super::metering::TargetBilling::default(), + included_choice: None, + included_until: None, created_at: now, updated_at: now, } diff --git a/compliance-dashboard/assets/main.css b/compliance-dashboard/assets/main.css index a19a4d7..e868e79 100644 --- a/compliance-dashboard/assets/main.css +++ b/compliance-dashboard/assets/main.css @@ -4812,6 +4812,21 @@ tbody tr:last-child td { margin-top: 4px; } +.target-billing { + display: flex; + flex-direction: column; + align-items: flex-start; + gap: 8px; + margin-bottom: 16px; +} + +.billing-swap-row { + display: flex; + flex-wrap: wrap; + gap: 8px; + align-items: center; +} + .targets-cra { min-width: 220px; } diff --git a/compliance-dashboard/src/components/billing_swap.rs b/compliance-dashboard/src/components/billing_swap.rs new file mode 100644 index 0000000..757472a --- /dev/null +++ b/compliance-dashboard/src/components/billing_swap.rs @@ -0,0 +1,121 @@ +//! On an extra target's page: swap it with an included target (t72). The +//! target swapped in stays included until the end of the month; the one +//! swapped out becomes extra at once. + +use dioxus::prelude::*; + +use crate::components::toast::{ToastType, Toasts}; +use crate::i18n::texts::targets as tx; +use crate::i18n::use_lang; +use crate::infrastructure::onboarding::{fetch_targets_page, swap_target_billing}; + +/// The included targets one could swap out, as (id, name), from the +/// targets list: included, not archived, and not `target_id` itself. +fn swappable(targets: &[serde_json::Value], target_id: &str) -> Vec<(String, String)> { + targets + .iter() + .filter(|t| { + t.get("billing") + .and_then(|b| b.as_str()) + .unwrap_or("included") + == "included" + }) + .filter(|t| t.get("archived_at").is_none_or(serde_json::Value::is_null)) + .filter_map(|t| { + let id = t + .get("_id") + .and_then(|i| i.get("$oid").or(Some(i))) + .and_then(|i| i.as_str())? + .to_string(); + let name = t + .get("name") + .and_then(|n| n.as_str()) + .unwrap_or("") + .to_string(); + (id != target_id).then_some((id, name)) + }) + .collect() +} + +/// The swap control for the extra target `target_id`; `on_swapped` runs +/// once the swap is made. +#[component] +pub fn BillingSwap(target_id: String, on_swapped: EventHandler<()>) -> Element { + let lang = use_lang()(); + let mut toasts = use_context::(); + let targets = use_resource(move || async move { fetch_targets_page(None, 1, 100).await }); + let mut chosen = use_signal(String::new); + let mut busy = use_signal(|| false); + let options = match &*targets.read() { + Some(Ok(resp)) => swappable(&resp.data, &target_id), + _ => Vec::new(), + }; + if options.is_empty() { + return rsx! {}; + } + rsx! { + div { class: "billing-swap", + h4 { class: "target-subhead", {tx::SWAP_TITLE.get(lang)} } + p { class: "target-muted", {tx::SWAP_HINT.get(lang)} } + div { class: "billing-swap-row", + select { + onchange: move |e| chosen.set(e.value()), + option { value: "", {tx::SWAP_CHOOSE.get(lang)} } + for (id, name) in options { + option { value: "{id}", selected: chosen() == id, "{name}" } + } + } + button { + class: "btn btn-secondary", + disabled: chosen().is_empty() || busy(), + onclick: { + let target_id = target_id.clone(); + move |_| { + let (id, with) = (target_id.clone(), chosen()); + busy.set(true); + spawn(async move { + match swap_target_billing(id, with).await { + Ok(()) => { + toasts.push(ToastType::Success, tx::SWAPPED.get(lang)); + on_swapped.call(()); + } + Err(e) => toasts.push( + ToastType::Error, + tx::swap_refused(&e.to_string(), lang), + ), + } + busy.set(false); + }); + } + }, + {tx::SWAP.get(lang)} + } + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn only_other_included_active_targets_can_be_swapped_out() { + let targets = serde_json::json!([ + { "_id": { "$oid": "a" }, "name": "Pumpe", "billing": "included" }, + { "_id": { "$oid": "b" }, "name": "Ventil", "billing": "extra" }, + { "_id": { "$oid": "c" }, "name": "Alt" }, + { "_id": { "$oid": "d" }, "name": "Archiv", "billing": "included", + "archived_at": { "$date": { "$numberLong": "1" } } }, + { "_id": { "$oid": "e" }, "name": "Selbst", "billing": "included" }, + ]); + let list = targets.as_array().cloned().unwrap_or_default(); + assert_eq!( + swappable(&list, "e"), + [ + ("a".to_string(), "Pumpe".to_string()), + ("c".to_string(), "Alt".to_string()) + ] + ); + } +} diff --git a/compliance-dashboard/src/components/mod.rs b/compliance-dashboard/src/components/mod.rs index 7fb8491..a20aa3b 100644 --- a/compliance-dashboard/src/components/mod.rs +++ b/compliance-dashboard/src/components/mod.rs @@ -1,6 +1,7 @@ pub mod app_shell; pub mod artifact_upload; pub mod attack_chain; +pub mod billing_swap; pub mod code_inspector; pub mod code_snippet; pub mod copy_button; diff --git a/compliance-dashboard/src/i18n/texts.rs b/compliance-dashboard/src/i18n/texts.rs index 8608fcb..1766b4c 100644 --- a/compliance-dashboard/src/i18n/texts.rs +++ b/compliance-dashboard/src/i18n/texts.rs @@ -870,6 +870,56 @@ pub mod targets { de: "Zusätzliches Prüfobjekt", en: "Extra target", }; + pub const SWAP_TITLE: Text = Text { + de: "Gegen ein enthaltenes Prüfobjekt tauschen", + en: "Swap with an included target", + }; + pub const SWAP_HINT: Text = Text { + de: "Dieses Prüfobjekt wird enthalten und bleibt es bis Monatsende; das gewählte wird \ + sofort zusätzlich. Die Zahl der zusätzlichen Prüfobjekte bleibt gleich.", + en: "This target becomes included and stays so until the end of the month; the one \ + you choose becomes extra at once. The number of extra targets stays the same.", + }; + pub const SWAP_CHOOSE: Text = Text { + de: "Enthaltenes Prüfobjekt wählen", + en: "Choose an included target", + }; + pub const SWAP: Text = Text { + de: "Tauschen", + en: "Swap", + }; + pub const SWAPPED: Text = Text { + de: "Getauscht. Dieses Prüfobjekt ist jetzt bis Monatsende enthalten.", + en: "Swapped. This target is now included until the end of the month.", + }; + /// The words for a refused swap, from the agent's `error`. + pub fn swap_refused(error: &str, lang: super::super::Lang) -> String { + use super::super::Lang; + let text = if error.contains("swap_locked") { + Text { + de: "Das gewählte Prüfobjekt wurde in diesem Monat eingetauscht und bleibt bis \ + Monatsende enthalten. Wählen Sie ein anderes.", + en: "The chosen target was swapped in this month and stays included until the \ + end of the month. Choose another one.", + } + } else if error.contains("swap_not_extra") || error.contains("swap_not_included") { + Text { + de: "Die Zuordnung hat sich inzwischen geändert. Laden Sie die Seite neu.", + en: "The included targets changed in the meantime. Reload the page.", + } + } else if error.contains("swap_unlimited") { + Text { + de: "Ihr Tarif enthält alle Prüfobjekte; es gibt nichts zu tauschen.", + en: "Your plan includes every target; there is nothing to swap.", + } + } else { + return match lang { + Lang::De => format!("Nicht getauscht: {error}"), + Lang::En => format!("Not swapped: {error}"), + }; + }; + text.get(lang).to_string() + } pub const EXTRA_HINT: Text = Text { de: "Über die in Ihrem Tarif enthaltenen Prüfobjekte hinaus: wird monatlich \ zusätzlich berechnet, und jede seiner Prüfungen zählt zu Ihrem Kontingent.", diff --git a/compliance-dashboard/src/infrastructure/onboarding.rs b/compliance-dashboard/src/infrastructure/onboarding.rs index 7763fef..f6f3bd9 100644 --- a/compliance-dashboard/src/infrastructure/onboarding.rs +++ b/compliance-dashboard/src/infrastructure/onboarding.rs @@ -545,6 +545,22 @@ pub async fn fetch_target(id: String) -> Result { super::agent_client::json_or_error(resp).await } +/// Swap the extra target `id` with the included target `with` (t72): +/// `id` becomes included until the end of the month, `with` extra. +#[server] +pub async fn swap_target_billing(id: String, with: String) -> Result<(), ServerFnError> { + let resp = super::agent_client::agent_request( + reqwest::Method::POST, + &format!("/api/v1/targets/{id}/billing/swap"), + ) + .await? + .json(&serde_json::json!({ "with": with })) + .send() + .await + .map_err(|e| ServerFnError::new(e.to_string()))?; + super::agent_client::ok_or_error(resp).await +} + /// Run kind-based classification on a target. #[server] pub async fn detect_target(id: String) -> Result { diff --git a/compliance-dashboard/src/pages/target.rs b/compliance-dashboard/src/pages/target.rs index 242ce52..9b43573 100644 --- a/compliance-dashboard/src/pages/target.rs +++ b/compliance-dashboard/src/pages/target.rs @@ -8,6 +8,7 @@ use dioxus_free_icons::Icon; use crate::app::Route; use crate::components::artifact_upload::ArtifactUpload; +use crate::components::billing_swap::BillingSwap; use crate::components::cra_bar::CraBar; use crate::components::evidence_button::EvidencePackButton; use crate::components::layer_pins::LayerPinsCard; @@ -154,6 +155,7 @@ pub fn TargetPage(id: String) -> Element { .as_ref() .and_then(|d| d["sbom_components"].as_u64()); let cves = status_data.as_ref().and_then(|d| d["cve_alerts"].as_u64()); + let is_extra = str_at(&t, "billing") == "extra"; rsx! { BackLink {} @@ -222,6 +224,16 @@ pub fn TargetPage(id: String) -> Element { } } + // An extra target can be swapped with an included one (t72). + if is_extra { + div { class: "card target-billing", + span { class: "badge badge-neutral", title: tx::EXTRA_HINT.get(lang), {tx::EXTRA.get(lang)} } + if can_write { + BillingSwap { target_id: id.clone(), on_swapped: move |_| target.restart() } + } + } + } + div { class: "target-summary", section { class: "card target-cra", div { class: "target-card-head",