diff --git a/app/.env.example b/app/.env.example index c9dd52a2..7cde582c 100644 --- a/app/.env.example +++ b/app/.env.example @@ -232,6 +232,12 @@ VISUALCI_STRIPE_WEBHOOK_SECRET= # Secret. The groups check's token. # VISUALCI_GROUPS_CHECK_HEARTBEAT_TOKEN= +# The daily reminder to organizations whose credit override ends within a week. +# VISUALCI_CREDIT_OVERRIDES_HEARTBEAT_URL= + +# Secret. The credit override reminder's token. +# VISUALCI_CREDIT_OVERRIDES_HEARTBEAT_TOKEN= + ###################################################################################################################### # Laravel Rust ###################################################################################################################### diff --git a/app/database/migrations/2026_12_04_100000_credit_overrides.rs b/app/database/migrations/2026_12_04_100000_credit_overrides.rs new file mode 100644 index 00000000..bd3d6d49 --- /dev/null +++ b/app/database/migrations/2026_12_04_100000_credit_overrides.rs @@ -0,0 +1,50 @@ +//! Per-organization credit overrides (sc-8900): staff raise an organization's monthly credits for a while, such as a +//! big open source project that needs more than the standard pool (`domain::credit_overrides`). +//! +//! `credit_overrides` holds at most one override per organization. It applies through `until` (a UTC date, inclusive) +//! and is read at the time it's needed, so once that day is over the organization is back on its plan's allowance +//! with nothing to run. `label` is what the organization's billing page shows ("Open source sponsorship"); `reason` is +//! staff's own note and isn't shown to customers. Clearing one deletes the row. +//! +//! `credit_override_audit` is every change, for staff: who made it (a user, or `console`), the monthly allowance +//! before and after, the override set (none when it was cleared) and the reason. + +use laravel::db::AnyTransaction; + +pub async fn migrate(tx: &mut AnyTransaction<'_>) -> laravel::Result<()> { + tx.query(SCHEMA).unprepared().await?; + Ok(()) +} + +const SCHEMA: &str = r#" +CREATE TABLE credit_overrides ( + organization_id BIGINT PRIMARY KEY REFERENCES organizations(id) ON DELETE CASCADE, + -- The monthly allowance while it applies, in place of the plan's. + credits BIGINT NOT NULL CHECK (credits > 0), + -- The last day it applies (UTC). + until DATE NOT NULL, + label TEXT NOT NULL, + reason TEXT NOT NULL, + set_by BIGINT REFERENCES users(id) ON DELETE SET NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT now(), + updated_at TIMESTAMPTZ NOT NULL DEFAULT now() +); +CREATE INDEX credit_overrides_until ON credit_overrides (until); + +CREATE TABLE credit_override_audit ( + id BIGSERIAL PRIMARY KEY, + organization_id BIGINT NOT NULL REFERENCES organizations(id) ON DELETE CASCADE, + user_id BIGINT REFERENCES users(id) ON DELETE SET NULL, + -- Who: a staff member's email, or `console`. + actor TEXT NOT NULL, + old_allowance BIGINT NOT NULL, + new_allowance BIGINT NOT NULL, + -- The override set; all NULL when it was cleared. + credits BIGINT, + until DATE, + label TEXT, + reason TEXT NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT now() +); +CREATE INDEX credit_override_audit_organization ON credit_override_audit (organization_id, created_at); +"#; diff --git a/app/src/config.rs b/app/src/config.rs index 6b2fa2d6..d68bc35b 100644 --- a/app/src/config.rs +++ b/app/src/config.rs @@ -311,6 +311,12 @@ pub struct Heartbeats { /// The groups check's token. #[env("VISUALCI_GROUPS_CHECK_HEARTBEAT_TOKEN", secret)] pub groups_check_token: Option, + /// The daily reminder to organizations whose credit override ends within a week. + #[env("VISUALCI_CREDIT_OVERRIDES_HEARTBEAT_URL")] + pub credit_overrides_url: Option, + /// The credit override reminder's token. + #[env("VISUALCI_CREDIT_OVERRIDES_HEARTBEAT_TOKEN", secret)] + pub credit_overrides_token: Option, } /// The variables Laravel Rust reads itself. VisualCI keeps the framework's names for them. diff --git a/app/src/console/credits.rs b/app/src/console/credits.rs new file mode 100644 index 00000000..162455e2 --- /dev/null +++ b/app/src/console/credits.rs @@ -0,0 +1,92 @@ +//! Credit overrides from the console (`domain::credit_overrides`): `org:set-credits` for staff, and the daily +//! reminder the schedule runs. + +use laravel::console::{Console, clap, command}; +use laravel::time::civil::Date; + +use super::heartbeat; +use crate::domain::credit_overrides::{self, Actor, Change}; + +/// `org:set-credits`: raise an organization's monthly credits until a date, or end that now (`--clear`). Recorded in +/// `credit_override_audit` as `console`, with the reason. Setting the same values again records it again and changes +/// nothing else. +/// +/// `visualci-app org:set-credits --org acme --credits 3000000 --until 2027-06-01 --label "Open source sponsorship" +/// --reason "big open source project, agreed with marketing"` +#[derive(clap::Parser)] +#[command(name = "org:set-credits")] +pub struct OrgSetCredits { + /// The organization's slug. + #[arg(long)] + org: String, + /// Credits a month while it applies, in place of the plan's (more than the plan's). + #[arg(long, required_unless_present = "clear", conflicts_with = "clear")] + credits: Option, + /// The last day it applies (UTC), YYYY-MM-DD; after today. + #[arg(long, required_unless_present = "clear", conflicts_with = "clear")] + until: Option, + /// What the organization's billing page shows, such as "Open source sponsorship". + #[arg(long, conflicts_with = "clear")] + label: Option, + /// Why, for the audit log (not shown to the customer). + #[arg(long)] + reason: String, + /// End the override now: back to the plan's allowance. + #[arg(long)] + clear: bool, +} + +#[command] +impl OrgSetCredits { + async fn handle(self, console: &mut Console) -> laravel::Result<()> { + let outcome = match (self.clear, self.credits, self.until) { + (true, _, _) => credit_overrides::clear(&self.org, &self.reason, Actor::Console).await?, + (false, Some(credits), Some(until)) => { + let change = + Change { org: &self.org, credits, until, label: self.label.as_deref(), reason: &self.reason }; + credit_overrides::set(change, Actor::Console).await? + } + _ => Err("give --credits and --until, or --clear".to_string()), + }; + let answer = outcome.map_err(laravel::Error::msg)?; + let line = match answer["override"].as_object() { + Some(o) => format!( + "{}: {} credits a month until {} ({}), was {}", + answer["org"].as_str().unwrap_or_default(), + o["credits"], + o["until"].as_str().unwrap_or_default(), + o["label"].as_str().unwrap_or_default(), + answer["was"]["allowance"] + ), + None => format!( + "{}: back to the plan's {} credits a month, was {}", + answer["org"].as_str().unwrap_or_default(), + answer["allowance"], + answer["was"]["allowance"] + ), + }; + console.line(line); + Ok(()) + } +} + +/// `credits:override-reminders`, daily: email the admins of organizations whose credit override ends within a week, +/// once per end date ([`credit_overrides::remind`]). Pushes its result to `VISUALCI_CREDIT_OVERRIDES_HEARTBEAT_URL` +/// (and `_TOKEN`): Gatus alerts on a failed run and on a day with no run. +#[derive(clap::Parser)] +#[command(name = "credits:override-reminders")] +pub struct OverrideReminders; + +#[command] +impl OverrideReminders { + async fn handle(self, console: &mut Console) -> laravel::Result<()> { + let outcome = credit_overrides::remind().await; + heartbeat::push( + heartbeat::Heartbeat::CreditOverrides, + outcome.as_ref().map(|_| ()).map_err(ToString::to_string), + ) + .await; + console.line(format!("credits:override-reminders: queued {} emails", outcome?)); + Ok(()) + } +} diff --git a/app/src/console/mod.rs b/app/src/console/mod.rs index e3b6b1c5..6c562a13 100644 --- a/app/src/console/mod.rs +++ b/app/src/console/mod.rs @@ -1,11 +1,12 @@ //! The schedule (`laravel schedule:run` every minute, in production a CronJob): the builds sweep every five minutes; -//! retention, the groups check and the demo reset daily. Each run pushes its result to a heartbeat, so a task that -//! failed or stopped running alerts. +//! retention, the groups check, the demo reset and the credit override reminders daily. Each run pushes its result to +//! a heartbeat, so a task that failed or stopped running alerts. use laravel::schedule::{self, Schedule}; // The heartbeat every scheduled task pushes to (`crate::heartbeat`). pub use crate::heartbeat; +pub mod credits; pub mod demo; pub mod retention; pub mod staff; @@ -16,6 +17,7 @@ fn schedule(schedule: &mut Schedule) { schedule.command("retention:prune").daily_at("03:00").without_overlapping().on_one_runner(); schedule.command("groups:check").daily_at("04:00").without_overlapping().on_one_runner(); schedule.command("demo:reset").name("demo-reset").daily_at("05:00").without_overlapping().on_one_runner(); + schedule.command("credits:override-reminders").daily_at("06:00").without_overlapping().on_one_runner(); } /// [`crate::domain::processing::sweep`], with its heartbeat (`VISUALCI_BUILDS_EXPIRE_HEARTBEAT_URL` and `_TOKEN`). diff --git a/app/src/domain/credit_overrides.rs b/app/src/domain/credit_overrides.rs new file mode 100644 index 00000000..1ea71a4c --- /dev/null +++ b/app/src/domain/credit_overrides.rs @@ -0,0 +1,306 @@ +//! Per-organization credit overrides (sc-8900): staff raise an organization's monthly credits for a while, such as a +//! big open source project that needs more than the standard 1,000,000 open source pool. +//! +//! - **What it replaces:** the plan's monthly allowance (`Plan::included_credits`), and nothing else. While it applies +//! the organization's allowance is the override's `credits` (never less than the plan's: it only raises it). The open +//! source pool still comes first for open source projects, and pack credits still come last. +//! - **How long:** through `until`, a UTC date, inclusive. It's read whenever the allowance is (`live`), so on the day +//! after, the organization is back on the plan's allowance with nothing to run. A month's credits already used +//! still count, so an organization over the plan's allowance then stops until the month renews or it buys a pack. +//! - **What customers see:** the billing page's `label` line ("Open source sponsorship: 3,000,000 a month, until +//! 1 June 2027"), never staff's `reason`. +//! - **Who sets it:** staff, through the admin MCP server or `org:set-credits`; each change writes a +//! `credit_override_audit` row with the allowance before and after. +//! - **The reminder:** a week before it ends, the organization's admins get an email (`credits:override-reminders`, +//! daily, [`remind`]), once per end date. + +use laravel::db; +use laravel::time::{ToSpan, civil::Date}; +use serde_json::{Value, json}; + +use crate::billing::plan_by_id; +use crate::models::{Organization, User}; + +/// The billing page's label when staff don't give one. +pub const DEFAULT_LABEL: &str = "Raised by VisualCI"; + +/// How many days before an override ends its organization's admins are emailed. +pub const REMIND_DAYS: i64 = 7; + +/// An organization's override. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Override { + pub credits: i64, + pub until: Date, + pub label: String, + pub reason: String, +} + +impl Override { + /// What the billing page and the usage answer show. + #[must_use] + pub fn public(&self) -> Value { + json!({ "credits": self.credits, "until": self.until.to_string(), "label": self.label }) + } + + fn staff(&self) -> Value { + json!({ "credits": self.credits, "until": self.until.to_string(), "label": self.label, "reason": self.reason }) + } +} + +/// Today, as allowances count time (`credits::now`, UTC). +#[must_use] +pub fn today() -> Date { + let now = super::credits::now(); + now.in_tz("UTC").map_or_else(|_| laravel::time::civil::date(1970, 1, 1), |z| z.date()) +} + +/// "1 June 2027". +#[must_use] +pub fn long_date(d: Date) -> String { + d.strftime("%-d %B %Y").to_string() +} + +/// The organization's override, whether or not it still applies. +/// +/// # Errors +/// On a database error. +pub async fn of(organization_id: i64) -> laravel::Result> { + let rows = db::query!( + "SELECT credits, until, label, reason FROM credit_overrides WHERE organization_id = {organization_id}" + ) + .select() + .await?; + let Some(r) = rows.first() else { return Ok(None) }; + Ok(Some(Override { + credits: r.try_get("credits")?, + until: r.try_get("until")?, + label: r.try_get("label")?, + reason: r.try_get("reason")?, + })) +} + +/// The organization's override while it applies (through its `until` date): `None` once it has ended. +/// +/// # Errors +/// On a database error. +pub async fn live(organization_id: i64) -> laravel::Result> { + let today = today(); + Ok(of(organization_id).await?.filter(|o| o.until >= today)) +} + +/// The monthly allowance: the plan's, or a live override's when that's more. +#[must_use] +pub fn allowance(plan_credits: i64, live: Option<&Override>) -> i64 { + live.map_or(plan_credits, |o| o.credits.max(plan_credits)) +} + +/// An organization's monthly allowance now. +/// +/// # Errors +/// On a database error. +pub async fn allowance_of(organization_id: i64, plan: &str) -> laravel::Result { + let plan = plan_by_id(plan); + Ok(allowance(plan.included_credits, live(organization_id).await?.as_ref())) +} + +/// Who changed an override, for the audit row. +#[derive(Debug, Clone, Copy)] +pub enum Actor<'a> { + /// Staff through the admin MCP server. + Staff(&'a User), + /// `org:set-credits`. + Console, +} + +impl Actor<'_> { + fn user_id(&self) -> Option { + match self { + Self::Staff(u) => Some(u.id), + Self::Console => None, + } + } + + fn name(&self) -> String { + match self { + Self::Staff(u) => u.email.clone(), + Self::Console => "console".to_string(), + } + } +} + +/// What staff ask for: raise `org`'s monthly credits to `credits` through `until`. +#[derive(Debug, Clone)] +pub struct Change<'a> { + /// The organization's slug. + pub org: &'a str, + pub credits: i64, + /// The last day it applies (UTC); after today. + pub until: Date, + /// What the billing page shows; [`DEFAULT_LABEL`] when `None`. + pub label: Option<&'a str>, + /// Why, for the audit log (a short sentence). + pub reason: &'a str, +} + +/// A refusal staff can act on (`Err` inside `Ok`), or a server error. +pub type Outcome = laravel::Result>; + +fn reason_ok(reason: &str) -> Result { + let reason = reason.trim(); + if reason.chars().count() < 5 { + return Err("give a reason (a short sentence), for the audit log".to_string()); + } + Ok(reason.to_string()) +} + +async fn find_org(slug: &str) -> laravel::Result> { + Organization::query().filter(Organization::slug.eq(slug)).first().await +} + +/// Set an organization's override (replacing any it had), recording who, the allowance before and after and the +/// reason. Setting the same values again records it again and changes nothing else. Answers the organization, the +/// override, the allowance now and before (`was`). +/// +/// Refuses (inner `Err`) an unknown organization, a missing reason, an end date that isn't after today, credits that +/// don't raise the plan's allowance, an unlimited plan and a label over 60 characters. +/// +/// # Errors +/// On a database error. +pub async fn set(change: Change<'_>, by: Actor<'_>) -> Outcome { + let reason = match reason_ok(change.reason) { + Ok(r) => r, + Err(e) => return Ok(Err(e)), + }; + let Some(org) = find_org(change.org).await? else { + return Ok(Err(format!("no organization {}", change.org))); + }; + let plan = plan_by_id(&org.plan); + if plan.unlimited { + return Ok(Err(format!("{} is on the {} plan, which has no limit to raise", org.slug, plan.name))); + } + if change.credits <= plan.included_credits { + return Ok(Err(format!( + "an override raises the allowance: {} credits isn't more than the {} plan's {}", + super::credits::thousands(change.credits), + plan.name, + super::credits::thousands(plan.included_credits) + ))); + } + let today = today(); + if change.until <= today { + return Ok(Err(format!("the end date must be after today ({today}); it was {}", change.until))); + } + let label = change.label.map(str::trim).filter(|l| !l.is_empty()).unwrap_or(DEFAULT_LABEL).to_string(); + if label.chars().count() > 60 { + return Ok(Err("the label is what the billing page shows: at most 60 characters".to_string())); + } + let before = live(org.id).await?; + let was = allowance(plan.included_credits, before.as_ref()); + let new = Override { credits: change.credits, until: change.until, label, reason }; + let now_allowance = allowance(plan.included_credits, Some(&new)); + let (org_id, credits, until, label, reason) = + (org.id, new.credits, new.until, new.label.clone(), new.reason.clone()); + let (user_id, actor) = (by.user_id(), by.name()); + db::transaction(async |_| { + db::query!( + "INSERT INTO credit_overrides (organization_id, credits, until, label, reason, set_by) \ + VALUES ({org_id}, {credits}, {until}, {label}, {reason}, {user_id}) \ + ON CONFLICT (organization_id) DO UPDATE SET credits = EXCLUDED.credits, until = EXCLUDED.until, \ + label = EXCLUDED.label, reason = EXCLUDED.reason, set_by = EXCLUDED.set_by, updated_at = now()" + ) + .insert() + .await?; + db::query!( + "INSERT INTO credit_override_audit (organization_id, user_id, actor, old_allowance, new_allowance, \ + credits, until, label, reason) \ + VALUES ({org_id}, {user_id}, {actor}, {was}, {now_allowance}, {credits}, {until}, {label}, {reason})" + ) + .insert() + .await?; + Ok(()) + }) + .await?; + tracing::info!(org = %org.slug, credits, %until, actor = %by.name(), "credit override set"); + Ok(Ok(json!({ + "org": org.slug, + "override": new.staff(), + "allowance": now_allowance, + "was": { "allowance": was, "override": before.as_ref().map(Override::staff) }, + }))) +} + +/// End an organization's override now, recording it like [`set`]. Refuses an unknown organization, a missing reason +/// and an organization with no override. +/// +/// # Errors +/// On a database error. +pub async fn clear(org: &str, reason: &str, by: Actor<'_>) -> Outcome { + let reason = match reason_ok(reason) { + Ok(r) => r, + Err(e) => return Ok(Err(e)), + }; + let Some(org) = find_org(org).await? else { + return Ok(Err(format!("no organization {org}"))); + }; + let Some(before) = of(org.id).await? else { + return Ok(Err(format!("{} has no credit override", org.slug))); + }; + let plan = plan_by_id(&org.plan); + let today = today(); + let was = allowance(plan.included_credits, Some(&before).filter(|o| o.until >= today)); + let now_allowance = plan.included_credits; + let (org_id, user_id, actor) = (org.id, by.user_id(), by.name()); + db::transaction(async |_| { + db::query!("DELETE FROM credit_overrides WHERE organization_id = {org_id}").delete().await?; + db::query!( + "INSERT INTO credit_override_audit (organization_id, user_id, actor, old_allowance, new_allowance, reason) \ + VALUES ({org_id}, {user_id}, {actor}, {was}, {now_allowance}, {reason})" + ) + .insert() + .await?; + Ok(()) + }) + .await?; + tracing::info!(org = %org.slug, actor = %by.name(), "credit override cleared"); + Ok(Ok(json!({ + "org": org.slug, + "override": null, + "allowance": now_allowance, + "was": { "allowance": was, "override": before.staff() }, + }))) +} + +/// Email the admins of each organization whose override ends within [`REMIND_DAYS`] days (today included): once per +/// organization and end date, so a run that's repeated sends nothing new, and an override extended to a later date is +/// reminded again before that one. Returns how many emails were queued. +/// +/// # Errors +/// On a database error. +pub async fn remind() -> laravel::Result { + let today = today(); + let last = today.checked_add(REMIND_DAYS.days()).map_err(|e| laravel::Error::msg(e.to_string()))?; + let rows = db::query!( + "SELECT c.organization_id, c.credits, c.until, c.label, o.plan FROM credit_overrides c \ + JOIN organizations o ON o.id = c.organization_id \ + WHERE c.until >= {today} AND c.until <= {last} ORDER BY c.organization_id" + ) + .select() + .await?; + let mut queued = 0; + for r in rows { + let org_id: i64 = r.try_get("organization_id")?; + let until: Date = r.try_get("until")?; + let plan = plan_by_id(&r.try_get::("plan")?); + let kind = crate::notify::Kind::CreditOverrideEnding { + label: r.try_get("label")?, + credits: r.try_get("credits")?, + until: long_date(until), + plan: plan.name.to_string(), + plan_credits: plan.included_credits, + }; + let key = format!("{}:{org_id}:{until}", kind.name()); + queued += crate::notify::queue(&kind, crate::notify::To::Admins(org_id), Some(org_id), &key).await?; + } + Ok(queued) +} diff --git a/app/src/domain/credits.rs b/app/src/domain/credits.rs index 233fc52f..cd4396bc 100644 --- a/app/src/domain/credits.rs +++ b/app/src/domain/credits.rs @@ -2,6 +2,7 @@ use laravel::db; +use super::credit_overrides; use crate::billing::{CREDIT_PACK, plan_by_id}; /// Add (or, with a negative amount, take away) pack credits, recording the transaction. Returns the new balance. @@ -172,7 +173,8 @@ pub async fn credits_left(org: &crate::models::Organization) -> laravel::Result< if plan.unlimited { return Ok(i64::MAX); } - Ok((plan.included_credits - used_this_month(org.id).await?).max(0) + org.credits_balance.max(0)) + let allowance = credit_overrides::allowance_of(org.id, &org.plan).await?; + Ok((allowance - used_this_month(org.id).await?).max(0) + org.credits_balance.max(0)) } /// Whether this month's allowance and every pack credit are used up: new builds stop until the month renews or @@ -185,7 +187,8 @@ pub async fn out_of_credits(org: &crate::models::Organization) -> laravel::Resul if plan.unlimited { return Ok(false); } - Ok(org.credits_balance <= 0 && used_this_month(org.id).await? >= plan.included_credits) + let allowance = credit_overrides::allowance_of(org.id, &org.plan).await?; + Ok(org.credits_balance <= 0 && used_this_month(org.id).await? >= allowance) } /// Whether a project's next build has nothing to spend: an open source project still has the pool while it lasts. @@ -218,6 +221,7 @@ pub async fn blocked( return Ok(None); } let plan = plan_by_id(&org.plan); + let allowance = credit_overrides::allowance_of(org.id, &org.plan).await?; let used = used_this_month(org.id).await?; let billing = format!("{}/{}/billing", app_url.trim_end_matches('/'), org.slug); let renews_at = renews_at(); @@ -241,14 +245,14 @@ pub async fn blocked( "{} is out of VisualCI credits until {renews}: it has used all {} credits on the {} plan, so builds aren't \ compared. An admin can {what} at {billing}", org.name, - thousands(plan.included_credits), + thousands(allowance), plan.name, ); Ok(Some(serde_json::json!({ "reason": "out_of_credits", "plan": plan.name, "credits_used": used, - "credits_limit": plan.included_credits, + "credits_limit": allowance, "pack_credits": org.credits_balance.max(0), "renews_at": renews_at.map(|t| t.to_string()), "fixes": fixes, @@ -335,6 +339,7 @@ async fn take(organization_id: i64, credits: i64, spender: Option) -> l .scalar() .await? .ok_or_else(|| laravel::Error::msg(format!("no organization {organization_id}")))?; + let allowance = credit_overrides::allowance_of(organization_id, &plan).await?; let plan = plan_by_id(&plan); let from_pool = match spender { Some(s) if s.open_source && credits > 0 => { @@ -347,7 +352,7 @@ async fn take(organization_id: i64, credits: i64, spender: Option) -> l let from_packs = if plan.unlimited { 0 } else { - let allowance_left = (plan.included_credits - used_this_month(organization_id).await?).max(0); + let allowance_left = (allowance - used_this_month(organization_id).await?).max(0); (for_plan - allowance_left).clamp(0, for_plan.max(0)) }; let balance: i64 = db::query!( @@ -390,23 +395,27 @@ pub async fn open_source_projects(organization_id: i64) -> laravel::Result } /// The plan, this month's credits, pack credits and what things cost, as the web app and the MCP server show them. +/// `included_credits` is this month's allowance: the plan's, or a staff override's while it applies, which then shows +/// as `credit_override` (`credits`, `until` and the `label` the billing page shows; left out when there's none). /// /// # Errors /// On a database error. pub async fn usage(org: &crate::models::Organization) -> laravel::Result { let plan = plan_by_id(&org.plan); let used = used_this_month(org.id).await?; - Ok(serde_json::json!({ + let live = credit_overrides::live(org.id).await?; + let allowance = credit_overrides::allowance(plan.included_credits, live.as_ref()); + let mut usage = serde_json::json!({ "plan": plan, "credits_this_month": used, - "included_credits": plan.included_credits, + "included_credits": allowance, "pack_credits": org.credits_balance.max(0), "credit_pack": CREDIT_PACK, "auto_reload_packs": org.auto_reload_packs, "reloads_this_month": reloads_this_month(org.id).await?, "rates": credit_rates(), "renews_at": renews_at().map(|t| t.to_string()), - "out_of_credits": !plan.unlimited && used >= plan.included_credits && org.credits_balance <= 0, + "out_of_credits": !plan.unlimited && used >= allowance && org.credits_balance <= 0, "unlimited": plan.unlimited, "billing_problem": org.billing_problem, // The open source pool: shown when the organization has open source projects or used the pool this month. @@ -416,5 +425,9 @@ pub async fn usage(org: &crate::models::Organization) -> laravel::Result lara seed_token("project_tokens", invoices.id, "CircleCI", "vci").await?; seed_token("user_tokens", ada.id, "Claude Code", "vcu").await?; - // Side project: the Free plan, one project. + // Side project: the Free plan, one project, with its monthly credits raised by staff (a credit override) until a + // date after the screenshots' clock (`VISUALCI_NOW`, 20 November 2026). let side = seed_org("side-project", "Side project", ada.id).await?; + let side_id = side.id; + db::query!( + "INSERT INTO credit_overrides (organization_id, credits, until, label, reason) \ + VALUES ({side_id}, 3000000, '2027-06-01', 'Open source sponsorship', 'Screenshots: a seeded override')" + ) + .insert() + .await?; let blog = seed_project(&side, "blog", "Blog").await?; let seeder = Seeder { store, renderer_version }; diff --git a/app/src/domain/mod.rs b/app/src/domain/mod.rs index 516d3582..0d325051 100644 --- a/app/src/domain/mod.rs +++ b/app/src/domain/mod.rs @@ -8,6 +8,7 @@ pub mod builds; pub mod changeset; pub mod comments; pub mod compare; +pub mod credit_overrides; pub mod credits; pub mod demo; pub mod detail; diff --git a/app/src/domain/processing.rs b/app/src/domain/processing.rs index 3819b911..d6666023 100644 --- a/app/src/domain/processing.rs +++ b/app/src/domain/processing.rs @@ -884,7 +884,7 @@ pub async fn stop_if_out_of_credits(mut build: Build) -> laravel::Result "{} has used this month's {} credits on the {} plan and has no pack credits left, so this build wasn't \ compared. {what_now}", org.name, - credits::thousands(plan.included_credits), + credits::thousands(super::credit_overrides::allowance_of(org.id, &org.plan).await?), plan.name )); update!(build { state: "failed", error_code: Some(OUT_OF_CREDITS.to_string()), error }).await?; diff --git a/app/src/heartbeat.rs b/app/src/heartbeat.rs index 10b3aea3..b0253639 100644 --- a/app/src/heartbeat.rs +++ b/app/src/heartbeat.rs @@ -18,6 +18,7 @@ pub enum Heartbeat { Demo, BuildsExpire, GroupsCheck, + CreditOverrides, } impl Heartbeats { @@ -34,6 +35,7 @@ impl Heartbeats { Heartbeat::Demo => (&self.demo_url, &self.demo_token), Heartbeat::BuildsExpire => (&self.builds_expire_url, &self.builds_expire_token), Heartbeat::GroupsCheck => (&self.groups_check_url, &self.groups_check_token), + Heartbeat::CreditOverrides => (&self.credit_overrides_url, &self.credit_overrides_token), }; (url.as_deref(), token.as_deref()) } diff --git a/app/src/lib.rs b/app/src/lib.rs index f214ea91..db52982e 100644 --- a/app/src/lib.rs +++ b/app/src/lib.rs @@ -117,5 +117,7 @@ pub fn configure() -> ApplicationBuilder { commands.add::(); commands.add::(); commands.add::(); + commands.add::(); + commands.add::(); }) } diff --git a/app/src/notify/render.rs b/app/src/notify/render.rs index b663f634..596f4876 100644 --- a/app/src/notify/render.rs +++ b/app/src/notify/render.rs @@ -22,6 +22,14 @@ pub enum Kind { renews: String, next: String, }, + /// A week before a staff override of the monthly credits ends (`domain::credit_overrides`): back to the plan's. + CreditOverrideEnding { + label: String, + credits: i64, + until: String, + plan: String, + plan_credits: i64, + }, /// The plan's credits and packs are used up: builds fail with "out of credits". OutOfCredits { plan: String, @@ -88,6 +96,7 @@ impl Kind { pub const fn name(&self) -> &'static str { match self { Self::CreditsLow { .. } => "credits_low", + Self::CreditOverrideEnding { .. } => "credit_override_ending", Self::OutOfCredits { .. } => "out_of_credits", Self::PackBought { .. } => "pack_bought", Self::AutoBuyPaused(_) => "auto_buy_paused", @@ -233,6 +242,21 @@ pub fn render(kind: &Kind, about: &About<'_>) -> Rendered { ("Open billing".into(), billing), ) } + Kind::CreditOverrideEnding { label, credits, until, plan, plan_credits } => ( + format!("{org}'s extra VisualCI credits run until {until}"), + vec![ + format!( + "{org} has {} credits a month from VisualCI ({label}) until {until}. After that it's back to the {plan} \ + plan's {} credits a month.", + n(*credits), + n(*plan_credits) + ), + "If you still need more, reply to this email and tell us about your project. Otherwise there's nothing \ + to do." + .to_string(), + ], + ("Open billing".into(), billing), + ), Kind::OutOfCredits { plan, renews, packs } => ( format!("{org} is out of VisualCI credits"), vec![ @@ -426,6 +450,13 @@ pub fn samples() -> Vec<(&'static str, Kind)> { renews: renews.clone(), next: "When they run out, open source projects use the plan's credits.".into(), }), + ("Extra credits ending", Kind::CreditOverrideEnding { + label: "Open source sponsorship".into(), + credits: 3_000_000, + until: "1 June 2027".into(), + plan: "Free".into(), + plan_credits: 25_000, + }), ("Out of credits (Free)", Kind::OutOfCredits { plan: "Free".into(), renews: renews.clone(), packs: false }), ("Out of credits (Team)", Kind::OutOfCredits { plan: "Team".into(), renews, packs: true }), ("Pack bought", Kind::PackBought { diff --git a/app/tests/credit_overrides.rs b/app/tests/credit_overrides.rs new file mode 100644 index 00000000..0d7f465c --- /dev/null +++ b/app/tests/credit_overrides.rs @@ -0,0 +1,211 @@ +//! Credit overrides: staff raise an organization's monthly credits until a date, with an audit row; the usage answer +//! and the allowance follow it; once it ends the organization is back on its plan's allowance; its admins are +//! emailed once a week before it ends; and `org:set-credits` refuses what it should. + +use app::domain::credit_overrides::{self, Actor, Change}; +use app::domain::credits; +use app::models::User; +use app::testing::fixtures; +use laravel::db; +use laravel::model::create; +use laravel::testing::prelude::*; +use laravel::time::{ToSpan, civil::Date}; + +/// An audit row: actor, old and new allowance, credits, reason, user. +type AuditRow = (String, i64, i64, Option, String, Option); + +fn days(n: i64) -> Date { + credit_overrides::today().checked_add(n.days()).expect("a date") +} + +fn change<'a>(org: &'a str, credits: i64, until: Date, reason: &'a str) -> Change<'a> { + Change { org, credits, until, label: Some("Open source sponsorship"), reason } +} + +async fn staff() -> laravel::Result { + create!(User { pid: laravel::str::uuid7(), name: "Nathan", email: "staff@example.com", staff: true }).await +} + +#[laravel::test] +async fn staff_raise_the_allowance_with_an_audit_row(_app: Application) -> laravel::Result<()> { + let org = fixtures::organization("acme").await?; + let staff = staff().await?; + let until = days(30); + let answer = + credit_overrides::set(change("acme", 3_000_000, until, "big open source project"), Actor::Staff(&staff)) + .await? + .expect("set"); + assert_eq!(answer["allowance"], 3_000_000, "{answer}"); + assert_eq!(answer["was"]["allowance"], 25_000, "{answer}"); + assert_eq!(answer["override"]["until"], until.to_string(), "{answer}"); + + let usage = credits::usage(&org).await?; + assert_eq!(usage["included_credits"], 3_000_000); + assert_eq!(usage["credit_override"]["label"], "Open source sponsorship"); + assert_eq!(usage["credit_override"]["credits"], 3_000_000); + assert!(usage["credit_override"].get("reason").is_none(), "staff's reason isn't shown to customers: {usage}"); + + // Builds can use the raised allowance: 100,000 credits on Free would otherwise be out of credits. + credits::spend(org.id, 100_000, "build", None, None, None).await?; + assert!(!credits::out_of_credits(&org).await?); + assert_eq!(credits::credits_left(&org).await?, 2_900_000); + + // The same again records it again; clearing it records the way back. + credit_overrides::set(change("acme", 3_000_000, until, "big open source project"), Actor::Console).await?.unwrap(); + credit_overrides::clear("acme", "the project moved to Team", Actor::Console).await?.expect("cleared"); + let id = org.id; + let rows = db::query!( + "SELECT actor, old_allowance, new_allowance, credits, reason, user_id FROM credit_override_audit \ + WHERE organization_id = {id} ORDER BY id" + ) + .select() + .await?; + let audit: Vec = rows + .iter() + .map(|r| { + Ok(( + r.try_get("actor")?, + r.try_get("old_allowance")?, + r.try_get("new_allowance")?, + r.try_get("credits")?, + r.try_get("reason")?, + r.try_get("user_id")?, + )) + }) + .collect::>()?; + assert_eq!( + audit, + [ + ( + "staff@example.com".into(), + 25_000, + 3_000_000, + Some(3_000_000), + "big open source project".into(), + Some(staff.id) + ), + ("console".into(), 3_000_000, 3_000_000, Some(3_000_000), "big open source project".into(), None), + ("console".into(), 3_000_000, 25_000, None, "the project moved to Team".into(), None), + ] + ); + assert!(credits::usage(&org).await?.get("credit_override").is_none()); + assert!(credits::out_of_credits(&org).await?, "back on Free's 25,000 with 100,000 used"); + Ok(()) +} + +#[laravel::test] +async fn an_ended_override_falls_back_to_the_plans_allowance(_app: Application) -> laravel::Result<()> { + let org = fixtures::organization("acme").await?; + credit_overrides::set(change("acme", 3_000_000, days(1), "a short trial of more credits"), Actor::Console) + .await? + .unwrap(); + credits::spend(org.id, 30_000, "build", None, None, None).await?; + assert!(!credits::out_of_credits(&org).await?); + + // Its last day was yesterday. + let (id, yesterday) = (org.id, days(-1)); + db::query!("UPDATE credit_overrides SET until = {yesterday} WHERE organization_id = {id}").update().await?; + let usage = credits::usage(&org).await?; + assert_eq!(usage["included_credits"], 25_000); + assert!(usage.get("credit_override").is_none(), "{usage}"); + assert_eq!(usage["out_of_credits"], true); + assert!(credits::out_of_credits(&org).await?); + let blocked = credits::blocked(&org, "https://app.visualci.test", None).await?.expect("blocked"); + assert_eq!(blocked["credits_limit"], 25_000); + Ok(()) +} + +#[laravel::test] +async fn refuses_what_staff_should_fix(_app: Application) -> laravel::Result<()> { + fixtures::organization("acme").await?; + let refused = + |c: Change<'static>| async move { credit_overrides::set(c, Actor::Console).await.unwrap().unwrap_err() }; + assert!(refused(change("nope", 3_000_000, days(30), "a good reason")).await.contains("no organization nope")); + assert!(refused(change("acme", 3_000_000, days(30), " ")).await.contains("give a reason")); + assert!(refused(change("acme", 3_000_000, days(0), "a good reason")).await.contains("after today")); + assert!(refused(change("acme", 20_000, days(30), "a good reason")).await.contains("raises the allowance")); + assert!( + credit_overrides::clear("acme", "nothing to clear", Actor::Console) + .await? + .unwrap_err() + .contains("has no credit override") + ); + Ok(()) +} + +#[laravel::test] +async fn the_console_command_sets_clears_and_refuses(app: Application) -> laravel::Result<()> { + fixtures::organization("acme").await?; + let until = days(30); + app.command(&format!( + "org:set-credits --org acme --credits 3000000 --until {until} --label \"Open source sponsorship\" \ + --reason \"big open source project\"" + )) + .await + .assert_successful() + .assert_output_contains("acme: 3000000 credits a month until"); + app.command("org:set-credits --org acme --clear --reason \"back to Free\"") + .await + .assert_successful() + .assert_output_contains("back to the plan's 25000"); + app.command(&format!("org:set-credits --org nope --credits 3000000 --until {until} --reason \"a good reason\"")) + .await + .assert_failed() + .assert_error_output_contains("no organization nope"); + let past = days(-3); + app.command(&format!("org:set-credits --org acme --credits 3000000 --until {past} --reason \"a good reason\"")) + .await + .assert_failed() + .assert_error_output_contains("after today"); + app.command(&format!("org:set-credits --org acme --credits 3000000 --until {until} --reason x")) + .await + .assert_failed() + .assert_error_output_contains("give a reason"); + Ok(()) +} + +#[laravel::test] +async fn admins_are_emailed_once_a_week_before_it_ends(app: Application) -> laravel::Result<()> { + let ending = fixtures::organization("ending").await?; + let later = fixtures::organization("later").await?; + let admin = + create!(User { pid: laravel::str::uuid7(), name: "Ada", email: "ada@example.com", staff: false }).await?; + let member = + create!(User { pid: laravel::str::uuid7(), name: "Bea", email: "bea@example.com", staff: false }).await?; + fixtures::member(&ending, &admin, "admin").await?; + fixtures::member(&ending, &member, "member").await?; + fixtures::member(&later, &admin, "admin").await?; + credit_overrides::set(change("ending", 3_000_000, days(5), "ends this week"), Actor::Console).await?.unwrap(); + credit_overrides::set(change("later", 3_000_000, days(30), "ends next month"), Actor::Console).await?.unwrap(); + + app.command("credits:override-reminders").await.assert_successful().assert_output_contains("queued 1 emails"); + app.command("credits:override-reminders").await.assert_successful().assert_output_contains("queued 0 emails"); + let rows = db::query!("SELECT kind, recipient, organization_id FROM emails ORDER BY id").select().await?; + let sent: Vec<(String, String, i64)> = rows + .iter() + .map(|r| Ok((r.try_get("kind")?, r.try_get("recipient")?, r.try_get("organization_id")?))) + .collect::>()?; + assert_eq!(sent, [("credit_override_ending".to_string(), "ada@example.com".to_string(), ending.id)]); + + // Extended to a date that's again within the week: reminded again, for the new date. + credit_overrides::set(change("ending", 3_000_000, days(6), "extended by a day"), Actor::Console).await?.unwrap(); + app.command("credits:override-reminders").await.assert_successful().assert_output_contains("queued 1 emails"); + Ok(()) +} + +#[test] +fn the_reminder_says_what_happens_next() { + let kind = app::notify::Kind::CreditOverrideEnding { + label: "Open source sponsorship".into(), + credits: 3_000_000, + until: "1 June 2027".into(), + plan: "Free".into(), + plan_credits: 25_000, + }; + let about = app::notify::About { org_name: "Acme", org_slug: "acme", app_url: "https://app.visualci.test" }; + let r = app::notify::render(&kind, &about); + assert_eq!(r.subject, "Acme's extra VisualCI credits run until 1 June 2027"); + assert!(r.text.contains("3,000,000 credits a month from VisualCI (Open source sponsorship) until 1 June 2027")); + assert!(r.text.contains("back to the Free plan's 25,000 credits a month"), "{}", r.text); + assert!(r.text.contains("https://app.visualci.test/acme/billing")); +} diff --git a/app/tests/screenshots_seed.rs b/app/tests/screenshots_seed.rs index cf81190b..0c7d83ec 100644 --- a/app/tests/screenshots_seed.rs +++ b/app/tests/screenshots_seed.rs @@ -23,6 +23,13 @@ async fn seeded() -> laravel::Result<()> { .map(|o| (o.slug, o.plan)) .collect(); assert_eq!(plans, [("acme".to_string(), "team".to_string()), ("side-project".to_string(), "free".to_string())]); + // Side project's billing page shows a credit override (an open source sponsorship). + let side = Organization::query().filter(Organization::slug.eq("side-project")).first().await?.expect("side"); + let ov = app::domain::credit_overrides::of(side.id).await?.expect("the seeded override"); + assert_eq!( + (ov.credits, ov.until.to_string(), ov.label.as_str()), + (3_000_000, "2027-06-01".into(), "Open source sponsorship") + ); let builds = Build::query().order_by(Build::id.asc()).get().await?; assert!(builds.len() >= 7, "{} builds", builds.len()); assert!(builds.iter().all(|b| b.state == "completed"), "every build concluded"); diff --git a/docs/deploy.md b/docs/deploy.md index 15465949..fefd1518 100644 --- a/docs/deploy.md +++ b/docs/deploy.md @@ -119,7 +119,9 @@ GitLab is parked in app/: production sets none of its variables (`GITLAB_CLIENT_ - every five minutes, email delivery (`EMAILS`); every minute, sign-up notices (`SIGNUPS`) and the live-update check (`LIVE`); daily, device sign-in pruning (`DEVICE_PRUNE`); - daily at 03:00 UTC, image retention (`retention:prune`, `RETENTION`); at 04:00, the groups check (`groups:check`, - `GROUPS_CHECK`); at 05:00, the demo reset (`demo:reset`, `DEMO`). + `GROUPS_CHECK`); at 05:00, the demo reset (`demo:reset`, `DEMO`); at 06:00, the credit override reminders + (`credits:override-reminders`, `CREDIT_OVERRIDES`, "VisualCI / Credit override reminders"): emails the admins of + organizations whose credit override ends within a week, once per end date. - Render metrics: `/internal/renderer/metrics` (cluster-internal host, `VISUALCI_METRICS_TOKEN`; the renderer token is refused), Prometheus text, scraped by the PodMonitor visualci-renders. Each web pod reports the same database's numbers: aggregate with `max`, not `sum`. - What's deployed: `curl -s https://api.visualci.com/status` gives the app's `commit`, @@ -131,6 +133,10 @@ GitLab is parked in app/: production sets none of its variables (`GITLAB_CLIENT_ Run in a web pod (`visualci-app `): - `retention:prune`, `groups:check`, `demo:reset`: what the scheduler runs daily, now. +- `org:set-credits --org --credits --until [--label ""] + --reason ""`: raise an organization's monthly credits until that day (UTC, inclusive); `--clear --reason` ends + it now. Recorded in `credit_override_audit` as `console`. +- `credits:override-reminders`: what the scheduler runs daily, now. - `screenshots:seed`: fills an empty database with the fixed dataset VisualCI's own screenshots are taken against (CI and development). - Staff commands (`app/src/console/staff.rs`), each safe to run again with the same arguments: diff --git a/docs/design.md b/docs/design.md index cf652a42..831d7c54 100644 --- a/docs/design.md +++ b/docs/design.md @@ -552,6 +552,16 @@ DocSpring's own ops agents (triage, support) work on customers' issues through a it's newer than the last one applied (`organizations.stripe_event_at`) and about its own subscription; a second Team subscription (two checkout tabs) becomes a billing problem, not the plan. A purchase's credits are added once per reference (a unique index), even when a reload and its `invoice.paid` race. +- Credit overrides (`app/src/domain/credit_overrides.rs`): staff raise an organization's monthly credits until a date, + such as a big open source project that needs more than the 1,000,000 open source pool. The override replaces the + plan's monthly allowance (never lowering it) and nothing else: the open source pool still comes first and pack + credits last. It applies through its `until` date (UTC, inclusive) and is read whenever the allowance is, so the day + after, the organization is back on its plan's allowance with nothing to run; credits already used that month still + count. Staff set it through the admin MCP server or `org:set-credits`, with a reason; each change writes a + `credit_override_audit` row (who, when, the allowance before and after, the reason). The billing page shows only its + public `label` ("Open source sponsorship: 3,000,000 a month until 1 Jun 2027, then 25,000."), never the reason. A + week before it ends, `credits:override-reminders` (daily, its own heartbeat) emails the organization's admins, once + per end date. ## Stack and hosting diff --git a/frontend/content/docs/reference/credits.md b/frontend/content/docs/reference/credits.md index e858a491..043f2d46 100644 --- a/frontend/content/docs/reference/credits.md +++ b/frontend/content/docs/reference/credits.md @@ -54,6 +54,10 @@ project's credits. If a repository's licence changes, the project uses the plan' billing page says so. Only a project linked to a public repository can be public, so if its repository goes private, the project is made private too. +A large open source project that needs more can ask us (reply to any VisualCI email): we can raise its +organization's monthly credits until a date. The billing page then shows the raised allowance and when it ends, and +the organization's admins get an email a week before. After that date it's back to the plan's credits. + ## Credit packs On Team, a pack is 500,000 credits for $15, paid up front. Pack credits don't expire. Builds use the month's allowance first, then pack credits. diff --git a/frontend/content/docs/self-hosting/environment-variables.md b/frontend/content/docs/self-hosting/environment-variables.md index bd27c98c..9af60336 100644 --- a/frontend/content/docs/self-hosting/environment-variables.md +++ b/frontend/content/docs/self-hosting/environment-variables.md @@ -161,6 +161,8 @@ Each scheduled job pushes its result to a [Gatus](https://gatus.io) external end | `VISUALCI_BUILDS_EXPIRE_HEARTBEAT_TOKEN` | string | | Secret. The builds sweep's token. | | `VISUALCI_GROUPS_CHECK_HEARTBEAT_URL` | string | | The daily check of snapshot groups. | | `VISUALCI_GROUPS_CHECK_HEARTBEAT_TOKEN` | string | | Secret. The groups check's token. | +| `VISUALCI_CREDIT_OVERRIDES_HEARTBEAT_URL` | string | | The daily reminder to organizations whose credit override ends within a week. | +| `VISUALCI_CREDIT_OVERRIDES_HEARTBEAT_TOKEN` | string | | Secret. The credit override reminder's token. | ## Laravel Rust diff --git a/frontend/src/__tests__/credit-override.test.ts b/frontend/src/__tests__/credit-override.test.ts new file mode 100644 index 00000000..21ab0e66 --- /dev/null +++ b/frontend/src/__tests__/credit-override.test.ts @@ -0,0 +1,11 @@ +import { describe, expect, it } from 'vitest' +import { calendarDate, overrideLine } from '../lib/credits' + +describe('a credit override on the billing page', () => { + it('says the credits, the last day (UTC) and what comes after', () => { + expect(calendarDate('2027-06-01')).toBe('1 Jun 2027') + expect(overrideLine({ credits: 3_000_000, until: '2027-06-01', label: 'Open source sponsorship' }, 25_000)).toBe( + 'Open source sponsorship: 3,000,000 a month until 1 Jun 2027, then 25,000.', + ) + }) +}) diff --git a/frontend/src/api/types.ts b/frontend/src/api/types.ts index 982fe28f..eb9e721b 100644 --- a/frontend/src/api/types.ts +++ b/frontend/src/api/types.ts @@ -1,4 +1,5 @@ // Shapes of the `/api/ui` and `/auth` JSON responses. Kept by hand, next to the server's `controllers/ui.rs`. +import type { CreditOverride } from '../lib/credits' export type Providers = { forges: string[]; dev_login: boolean } @@ -59,6 +60,8 @@ export type Usage = { reloads_paused?: boolean /** The open source pool: open source projects use it before the plan. */ open_source: { pool: number; used: number; projects: number } + /** Staff raised the monthly credits until a date: `included_credits` is this while it applies. */ + credit_override?: CreditOverride } /** This month's credits for one project, and how many came from the open source pool. */ diff --git a/frontend/src/lib/credits.ts b/frontend/src/lib/credits.ts new file mode 100644 index 00000000..650a2575 --- /dev/null +++ b/frontend/src/lib/credits.ts @@ -0,0 +1,14 @@ +import { n } from './format' + +/** A staff override of an organization's monthly credits, while it applies (`usage.credit_override`). */ +export type CreditOverride = { credits: number; until: string; label: string } + +const day = new Intl.DateTimeFormat('en-GB', { day: 'numeric', month: 'short', year: 'numeric', timeZone: 'UTC' }) + +/** `2027-06-01` → "1 Jun 2027": the override's last day, a UTC date. */ +export const calendarDate = (ymd: string) => day.format(new Date(`${ymd}T00:00:00Z`)) + +/** "Open source sponsorship: 3,000,000 a month until 1 Jun 2027, then 25,000." */ +export function overrideLine(o: CreditOverride, planCredits: number) { + return `${o.label}: ${n(o.credits)} a month until ${calendarDate(o.until)}, then ${n(planCredits)}.` +} diff --git a/frontend/src/pages/BillingPage.tsx b/frontend/src/pages/BillingPage.tsx index 0ba3914c..fb544765 100644 --- a/frontend/src/pages/BillingPage.tsx +++ b/frontend/src/pages/BillingPage.tsx @@ -18,6 +18,7 @@ import type { Org, Plan, PlansData } from '../api/types' import { QueryState } from '../components/QueryState' import { Button, ErrorBox, Help, Pill, Skeleton } from '../components/ui' import { errorMessage } from '../api/client' +import { overrideLine } from '../lib/credits' import { fullDate, money, n } from '../lib/format' /** The billing tabs, each at its own address: /$org/billing, /$org/billing/usage and so on. */ @@ -99,6 +100,7 @@ export function BillingPage({ tab }: { tab: BillingTab }) { of {n(u.included_credits)} credits on {u.plan.name} )} + {u.credit_override &&
{overrideLine(u.credit_override, u.plan.included_credits)}
} {!u.unlimited && (