g1t/services/billing/src/sales.rs
| 1 | //! What g1t's team needs to sell and support: month-by-month figures, the |
| 2 | //! signals that say a workspace is worth a call, and what was done about |
| 3 | //! it. Staff only, through sudo.g1t.sh. |
| 4 | |
| 5 | use g1t_contracts::billing::{ |
| 6 | AdminAddNoteArgs, AdminOverviewArgs, AdminOveragesArgs, AdminSalesArgs, AdminSetSalesArgs, AdminSignalsArgs, GivenFigures, |
| 7 | InternalUse, KindFigures, LimitState, MonthFigures, Overview, SalesNote, SalesRecord, Signal, SignalKind, TermsKind, Trust, |
| 8 | }; |
| 9 | use g1t_contracts::time::rfc3339; |
| 10 | use g1t_contracts::{FailureCode, Outcome, new_id}; |
| 11 | use g1t_kit::now_ms; |
| 12 | use serde::Deserialize; |
| 13 | use worker::Result; |
| 14 | use worker::wasm_bindgen::JsValue; |
| 15 | |
| 16 | use crate::Billing; |
| 17 | use crate::features::dollars; |
| 18 | use crate::limits::previous_month; |
| 19 | |
| 20 | pub(crate) const STAGES: &[&str] = &["none", "lead", "contacted", "negotiating", "won", "lost", "churn_risk"]; |
| 21 | |
| 22 | /// A workspace this much ahead of last month's pace is growing. |
| 23 | const GROWING_FACTOR: f64 = 1.5; |
| 24 | /// Below this last month, growth is noise. |
| 25 | const GROWING_FROM_MICROS: i64 = 10_000_000; |
| 26 | /// Spending this much a month may suit custom terms or an enterprise. |
| 27 | const HIGH_SPEND_MICROS: i64 = 500_000_000; |
| 28 | |
| 29 | /// The six months ending with `month`, oldest first. |
| 30 | pub(crate) fn last_months(month: &str, count: usize) -> Vec<String> { |
| 31 | let mut months = vec![month.to_owned()]; |
| 32 | while months.len() < count { |
| 33 | let earlier = previous_month(months.last().unwrap()); |
| 34 | months.push(earlier); |
| 35 | } |
| 36 | months.reverse(); |
| 37 | months |
| 38 | } |
| 39 | |
| 40 | /// How urgent a kind of signal is: lower first. |
| 41 | fn urgency(kind: SignalKind) -> u8 { |
| 42 | match kind { |
| 43 | SignalKind::AtLimit => 0, |
| 44 | SignalKind::Declined => 1, |
| 45 | SignalKind::NearCeiling => 2, |
| 46 | SignalKind::HighSpend => 3, |
| 47 | SignalKind::Growing => 4, |
| 48 | SignalKind::Established => 5, |
| 49 | SignalKind::FirstPayment => 6, |
| 50 | } |
| 51 | } |
| 52 | |
| 53 | /// Whether this month, at its pace so far, is well ahead of last month. |
| 54 | pub(crate) fn growing(this_month: i64, last_month: i64, day: u32, days_in_month: u32) -> bool { |
| 55 | if last_month < GROWING_FROM_MICROS || day == 0 { |
| 56 | return false; |
| 57 | } |
| 58 | let pace = this_month as f64 * f64::from(days_in_month) / f64::from(day); |
| 59 | pace >= last_month as f64 * GROWING_FACTOR |
| 60 | } |
| 61 | |
| 62 | fn days_in(month: &str) -> u32 { |
| 63 | let year: i32 = month[..4].parse().unwrap_or(1970); |
| 64 | match month[5..7].parse::<u32>().unwrap_or(1) { |
| 65 | 2 if (year % 4 == 0 && year % 100 != 0) || year % 400 == 0 => 29, |
| 66 | 2 => 28, |
| 67 | 4 | 6 | 9 | 11 => 30, |
| 68 | _ => 31, |
| 69 | } |
| 70 | } |
| 71 | |
| 72 | /// The workspaces g1t does not charge (comped terms): its own and |
| 73 | /// Flagon's, and any enterprise on comped terms. Their usage is recorded at |
| 74 | /// what it cost and shown as given, apart from margin. |
| 75 | pub(crate) const INTERNAL_SQL: &str = "SELECT substr(id, 4) FROM billing_accounts WHERE kind = 'workspace' AND terms_kind = 'comped' |
| 76 | UNION SELECT m.workspace FROM account_members m JOIN billing_accounts b ON b.id = m.account_id WHERE b.terms_kind = 'comped'"; |
| 77 | |
| 78 | /// One group of ledger rows in a month, as sudo's figures add them up. |
| 79 | #[derive(Clone, Debug, Default, Deserialize)] |
| 80 | pub(crate) struct LedgerGroup { |
| 81 | pub month: String, |
| 82 | /// `usage` or `top_up`. |
| 83 | pub kind: String, |
| 84 | /// `g1t`, or `workspace` for a run on the workspace's own provider. |
| 85 | pub billed_to: Option<String>, |
| 86 | /// A credit from g1t rather than a payment (`crd…`), and of those, a |
| 87 | /// goodwill credit. |
| 88 | pub credit: i64, |
| 89 | pub goodwill: i64, |
| 90 | /// One of g1t's own workspaces (comped). |
| 91 | pub internal: i64, |
| 92 | pub amount: Option<i64>, |
| 93 | pub cost: Option<i64>, |
| 94 | /// What the trial, the open-source pool and g1t itself paid. |
| 95 | pub pools: Option<i64>, |
| 96 | } |
| 97 | |
| 98 | /// A month's figures from its ledger groups and the plan's price paid. |
| 99 | /// |
| 100 | /// - **Cost** is only what g1t paid: a run on the workspace's own model |
| 101 | /// provider was paid for there, so its cost is never g1t's. |
| 102 | /// - **Given** is what g1t gave at price, apart from its margin: internal |
| 103 | /// use (its cost plus the margin, since nothing was charged), what the |
| 104 | /// trial, the open-source pool and g1t itself paid, and goodwill credits. |
| 105 | /// - **Paid** is money in: payments, never credits from g1t. |
| 106 | pub(crate) fn fold_month(month: &str, groups: &[LedgerGroup], plans: i64, margin_percent: u32) -> MonthFigures { |
| 107 | let mut figures = MonthFigures { month: month.to_owned(), plans_micros: plans, ..MonthFigures::default() }; |
| 108 | for g in groups.iter().filter(|g| g.month == month) { |
| 109 | let amount = g.amount.unwrap_or(0); |
| 110 | let own_provider = g.billed_to.as_deref() == Some("workspace"); |
| 111 | if g.kind == "usage" { |
| 112 | figures.charged_micros += -amount; |
| 113 | if !own_provider { |
| 114 | let cost = g.cost.unwrap_or(0); |
| 115 | figures.cost_micros += cost; |
| 116 | if g.internal == 1 { |
| 117 | figures.given_micros += crate::credits::with_margin(cost, margin_percent); |
| 118 | } |
| 119 | } |
| 120 | figures.given_micros += g.pools.unwrap_or(0); |
| 121 | } else if g.credit == 0 { |
| 122 | figures.paid_micros += amount; |
| 123 | } else if g.goodwill == 1 { |
| 124 | figures.given_micros += amount; |
| 125 | } |
| 126 | } |
| 127 | figures |
| 128 | } |
| 129 | |
| 130 | #[derive(Deserialize)] |
| 131 | struct RecordRow { |
| 132 | stage: String, |
| 133 | owner: Option<String>, |
| 134 | next_step: Option<String>, |
| 135 | next_at: Option<String>, |
| 136 | updated_at: String, |
| 137 | } |
| 138 | |
| 139 | #[derive(Deserialize)] |
| 140 | struct NoteRow { |
| 141 | id: String, |
| 142 | text: String, |
| 143 | by: String, |
| 144 | created_at: String, |
| 145 | } |
| 146 | |
| 147 | impl Billing { |
| 148 | /// Month-by-month figures for some workspaces (all, when empty): usage |
| 149 | /// charged, what it cost g1t (never a workspace's own provider), money |
| 150 | /// paid, the plan's price paid, and what g1t gave. |
| 151 | pub(crate) async fn months_for(&self, workspaces: &[String], count: usize) -> Result<Vec<MonthFigures>> { |
| 152 | let months = last_months(&rfc3339(now_ms())[..7], count); |
| 153 | let since = format!("{}-01", months[0]); |
| 154 | let (filter, values): (String, Vec<JsValue>) = if workspaces.is_empty() { |
| 155 | (String::new(), vec![]) |
| 156 | } else { |
| 157 | let marks = vec!["?"; workspaces.len()].join(", "); |
| 158 | (format!("AND workspace IN ({marks})"), workspaces.iter().map(|w| JsValue::from(w.as_str())).collect()) |
| 159 | }; |
| 160 | let groups = self |
| 161 | .db |
| 162 | .prepare(format!( |
| 163 | "SELECT substr(created_at, 1, 7) AS month, kind, COALESCE(billed_to, 'g1t') AS billed_to, |
| 164 | CASE WHEN reference LIKE 'crd%' THEN 1 ELSE 0 END AS credit, |
| 165 | CASE WHEN reference LIKE '{goodwill}%' THEN 1 ELSE 0 END AS goodwill, |
| 166 | CASE WHEN workspace IN ({INTERNAL_SQL}) THEN 1 ELSE 0 END AS internal, |
| 167 | SUM(amount_micros) AS amount, SUM(cost_micros) AS cost, |
| 168 | SUM(trial_micros + oss_micros + given_micros) AS pools |
| 169 | FROM ledger WHERE created_at >= '{since}' {filter} GROUP BY 1, 2, 3, 4, 5, 6", |
| 170 | goodwill = crate::overages::GOODWILL_PREFIX |
| 171 | )) |
| 172 | .bind(&values)? |
| 173 | .all() |
| 174 | .await? |
| 175 | .results::<LedgerGroup>()?; |
| 176 | #[derive(Deserialize)] |
| 177 | struct Plans { |
| 178 | month: String, |
| 179 | micros: Option<i64>, |
| 180 | } |
| 181 | let plans = self |
| 182 | .db |
| 183 | .prepare(format!( |
| 184 | "SELECT substr(paid_at, 1, 7) AS month, SUM(amount_micros) AS micros FROM plan_payments |
| 185 | WHERE paid_at >= '{since}' {filter} GROUP BY 1" |
| 186 | )) |
| 187 | .bind(&values)? |
| 188 | .all() |
| 189 | .await? |
| 190 | .results::<Plans>()?; |
| 191 | Ok(months |
| 192 | .into_iter() |
| 193 | .map(|month| { |
| 194 | let paid_plans = plans.iter().find(|p| p.month == month).and_then(|p| p.micros).unwrap_or(0); |
| 195 | fold_month(&month, &groups, paid_plans, self.margin_percent) |
| 196 | }) |
| 197 | .collect()) |
| 198 | } |
| 199 | |
| 200 | async fn record_row(&self, workspace: &str) -> Result<Option<RecordRow>> { |
| 201 | self.db |
| 202 | .prepare("SELECT * FROM sales_records WHERE workspace = ?") |
| 203 | .bind(&[workspace.into()])? |
| 204 | .first::<RecordRow>(None) |
| 205 | .await |
| 206 | } |
| 207 | |
| 208 | pub(crate) async fn admin_sales(&self, a: AdminSalesArgs) -> Result<SalesRecord> { |
| 209 | let workspace = a.workspace.trim().to_lowercase(); |
| 210 | let row = self.record_row(&workspace).await?; |
| 211 | let notes = self |
| 212 | .db |
| 213 | .prepare("SELECT id, text, by, created_at FROM sales_notes WHERE workspace = ? ORDER BY created_at DESC LIMIT 100") |
| 214 | .bind(&[workspace.as_str().into()])? |
| 215 | .all() |
| 216 | .await? |
| 217 | .results::<NoteRow>()? |
| 218 | .into_iter() |
| 219 | .map(|n| SalesNote { id: n.id, text: n.text, by: n.by, created_at: n.created_at }) |
| 220 | .collect(); |
| 221 | Ok(match row { |
| 222 | Some(row) => SalesRecord { |
| 223 | workspace, |
| 224 | stage: row.stage, |
| 225 | owner: row.owner, |
| 226 | next_step: row.next_step, |
| 227 | next_at: row.next_at, |
| 228 | notes, |
| 229 | updated_at: Some(row.updated_at), |
| 230 | }, |
| 231 | None => SalesRecord { |
| 232 | workspace, |
| 233 | stage: "none".to_owned(), |
| 234 | owner: None, |
| 235 | next_step: None, |
| 236 | next_at: None, |
| 237 | notes, |
| 238 | updated_at: None, |
| 239 | }, |
| 240 | }) |
| 241 | } |
| 242 | |
| 243 | pub(crate) async fn admin_set_sales(&self, a: AdminSetSalesArgs) -> Result<Outcome<SalesRecord>> { |
| 244 | let workspace = a.workspace.trim().to_lowercase(); |
| 245 | if workspace.is_empty() || a.by.trim().is_empty() { |
| 246 | return Ok(Outcome::fail(FailureCode::Invalid, "Name the workspace, and who is making the change.")); |
| 247 | } |
| 248 | if !STAGES.contains(&a.stage.as_str()) { |
| 249 | return Ok(Outcome::fail(FailureCode::Invalid, format!("A stage is one of: {}.", STAGES.join(", ")))); |
| 250 | } |
| 251 | let clean = |value: &Option<String>| value.as_deref().map(str::trim).filter(|v| !v.is_empty()).map(str::to_owned); |
| 252 | let (owner, next_step, next_at) = (clean(&a.owner), clean(&a.next_step), clean(&a.next_at)); |
| 253 | let before = self.record_row(&workspace).await?; |
| 254 | self.db |
| 255 | .prepare( |
| 256 | "INSERT INTO sales_records (workspace, stage, owner, next_step, next_at, updated_by, updated_at) |
| 257 | VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7) |
| 258 | ON CONFLICT (workspace) DO UPDATE SET stage = ?2, owner = ?3, next_step = ?4, next_at = ?5, |
| 259 | updated_by = ?6, updated_at = ?7", |
| 260 | ) |
| 261 | .bind(&[ |
| 262 | workspace.as_str().into(), |
| 263 | a.stage.as_str().into(), |
| 264 | crate::optional(owner.as_deref()), |
| 265 | crate::optional(next_step.as_deref()), |
| 266 | crate::optional(next_at.as_deref()), |
| 267 | a.by.as_str().into(), |
| 268 | rfc3339(now_ms()).into(), |
| 269 | ])? |
| 270 | .run() |
| 271 | .await?; |
| 272 | let account = self.account_of(&workspace).await?; |
| 273 | let was = before.map_or_else(|| "none".to_owned(), |b| b.stage); |
| 274 | let detail = format!( |
| 275 | "{workspace}: stage {was} → {}{}{}", |
| 276 | a.stage, |
| 277 | owner.as_deref().map(|o| format!(", owner {o}")).unwrap_or_default(), |
| 278 | next_step.as_deref().map(|s| format!(", next: {s}")).unwrap_or_default(), |
| 279 | ); |
| 280 | self.audit(&account.id, "sales", &detail, &a.by).await?; |
| 281 | Ok(Outcome::Ok(self.admin_sales(AdminSalesArgs { workspace }).await?)) |
| 282 | } |
| 283 | |
| 284 | pub(crate) async fn admin_add_note(&self, a: AdminAddNoteArgs) -> Result<Outcome<SalesRecord>> { |
| 285 | let workspace = a.workspace.trim().to_lowercase(); |
| 286 | let text = a.text.trim(); |
| 287 | if workspace.is_empty() || text.is_empty() || a.by.trim().is_empty() { |
| 288 | return Ok(Outcome::fail(FailureCode::Invalid, "A note needs a workspace, some words, and who wrote it.")); |
| 289 | } |
| 290 | if text.chars().count() > 4000 { |
| 291 | return Ok(Outcome::fail(FailureCode::Invalid, "Keep a note under 4,000 characters.")); |
| 292 | } |
| 293 | let now = now_ms(); |
| 294 | self.db |
| 295 | .prepare("INSERT INTO sales_notes (id, workspace, text, by, created_at) VALUES (?, ?, ?, ?, ?)") |
| 296 | .bind(&[new_id("note", now).into(), workspace.as_str().into(), text.into(), a.by.as_str().into(), rfc3339(now).into()])? |
| 297 | .run() |
| 298 | .await?; |
| 299 | Ok(Outcome::Ok(self.admin_sales(AdminSalesArgs { workspace }).await?)) |
| 300 | } |
| 301 | |
| 302 | /// Every workspace worth reaching out to, most urgent first. |
| 303 | pub(crate) async fn admin_signals(&self, _: AdminSignalsArgs) -> Result<Vec<Signal>> { |
| 304 | let now = rfc3339(now_ms()); |
| 305 | let month = &now[..7]; |
| 306 | let last = previous_month(month); |
| 307 | #[derive(Deserialize)] |
| 308 | struct Active { |
| 309 | workspace: String, |
| 310 | this_month: Option<i64>, |
| 311 | last_month: Option<i64>, |
| 312 | first_paid: Option<String>, |
| 313 | } |
| 314 | let active = self |
| 315 | .db |
| 316 | .prepare( |
| 317 | "SELECT workspace, |
| 318 | -SUM(CASE WHEN kind = 'usage' AND created_at >= ?1 THEN amount_micros END) AS this_month, |
| 319 | -SUM(CASE WHEN kind = 'usage' AND created_at >= ?2 AND created_at < ?1 THEN amount_micros END) AS last_month, |
| 320 | MIN(CASE WHEN kind = 'top_up' AND amount_micros > 0 AND reference NOT LIKE 'crd%' THEN created_at END) AS first_paid |
| 321 | FROM ledger GROUP BY workspace |
| 322 | HAVING MAX(created_at) >= ?2 |
| 323 | LIMIT 500", |
| 324 | ) |
| 325 | .bind(&[format!("{month}-01").into(), format!("{last}-01").into()])? |
| 326 | .all() |
| 327 | .await? |
| 328 | .results::<Active>()?; |
| 329 | let day: u32 = now[8..10].parse().unwrap_or(1); |
| 330 | let fortnight_ago = rfc3339(now_ms() - 14 * 24 * 60 * 60 * 1000); |
| 331 | let mut signals = vec![]; |
| 332 | for row in active { |
| 333 | let limit = self.limit_of(&row.workspace).await?; |
| 334 | if limit.trust == Trust::Internal { |
| 335 | continue; |
| 336 | } |
| 337 | let this_month = row.this_month.unwrap_or(0).max(0); |
| 338 | let last_month = row.last_month.unwrap_or(0).max(0); |
| 339 | let record = self.record_row(&row.workspace).await?; |
| 340 | let (stage, owner, next_step, next_at) = |
| 341 | record.map_or((None, None, None, None), |r| (Some(r.stage), r.owner, r.next_step, r.next_at)); |
| 342 | let mut push = |kind: SignalKind, detail: String, value: i64| { |
| 343 | signals.push(Signal { |
| 344 | workspace: row.workspace.clone(), |
| 345 | kind, |
| 346 | detail, |
| 347 | value_micros: value, |
| 348 | stage: stage.clone(), |
| 349 | owner: owner.clone(), |
| 350 | next_step: next_step.clone(), |
| 351 | next_at: next_at.clone(), |
| 352 | }); |
| 353 | }; |
| 354 | let declined = limit.message.as_deref().is_some_and(|m| m.contains("could not be charged")); |
| 355 | if declined { |
| 356 | push(SignalKind::Declined, limit.message.clone().unwrap_or_default(), limit.exposure_micros); |
| 357 | } else if limit.state == LimitState::Stopped { |
| 358 | push(SignalKind::AtLimit, limit.message.clone().unwrap_or_default(), limit.exposure_micros.max(limit.spent_micros)); |
| 359 | } else if let Some(available) = limit.available_micros.filter(|a| *a > 0) { |
| 360 | if limit.exposure_micros * 5 >= available * 4 { |
| 361 | push( |
| 362 | SignalKind::NearCeiling, |
| 363 | format!( |
| 364 | "{} unpaid of the {} g1t allows it ({:?}); a call could raise it before it stops.", |
| 365 | dollars(limit.exposure_micros), |
| 366 | dollars(available), |
| 367 | limit.trust |
| 368 | ), |
| 369 | limit.exposure_micros, |
| 370 | ); |
| 371 | } |
| 372 | } |
| 373 | if last_month >= HIGH_SPEND_MICROS { |
| 374 | let terms = self.terms_of(&row.workspace).await?; |
| 375 | if terms.kind == TermsKind::Standard && !limit.account.starts_with("ent_") { |
| 376 | push( |
| 377 | SignalKind::HighSpend, |
| 378 | format!("Spent {} last month on standard terms: worth offering custom terms or an enterprise.", dollars(last_month)), |
| 379 | last_month, |
| 380 | ); |
| 381 | } |
| 382 | } |
| 383 | if growing(this_month, last_month, day, days_in(month)) { |
| 384 | push( |
| 385 | SignalKind::Growing, |
| 386 | format!( |
| 387 | "{} so far this month, on pace for about {}, against {} last month.", |
| 388 | dollars(this_month), |
| 389 | dollars((this_month as f64 * f64::from(days_in(month)) / f64::from(day.max(1))) as i64), |
| 390 | dollars(last_month) |
| 391 | ), |
| 392 | this_month, |
| 393 | ); |
| 394 | } |
| 395 | if limit.trust == Trust::Established { |
| 396 | push( |
| 397 | SignalKind::Established, |
| 398 | format!( |
| 399 | "A steady customer: its limit now follows its spend ({} available).", |
| 400 | limit.available_micros.map(dollars).unwrap_or_default() |
| 401 | ), |
| 402 | last_month, |
| 403 | ); |
| 404 | } |
| 405 | if row.first_paid.as_deref().is_some_and(|at| at >= fortnight_ago.as_str()) { |
| 406 | push(SignalKind::FirstPayment, "Paid g1t for the first time in the last two weeks: say hello.".to_owned(), this_month); |
| 407 | } |
| 408 | } |
| 409 | signals.sort_by(|a, b| urgency(a.kind).cmp(&urgency(b.kind)).then(b.value_micros.cmp(&a.value_micros))); |
| 410 | Ok(signals) |
| 411 | } |
| 412 | |
| 413 | /// Every invoice g1t has sent, workspaces' and enterprises'. |
| 414 | pub(crate) async fn admin_invoices(&self, a: g1t_contracts::billing::AdminInvoicesArgs) -> Result<Vec<g1t_contracts::billing::InvoiceSummary>> { |
| 415 | #[derive(Deserialize)] |
| 416 | struct Row { |
| 417 | invoice_id: String, |
| 418 | kind: String, |
| 419 | account: String, |
| 420 | name: String, |
| 421 | reason: String, |
| 422 | period: String, |
| 423 | amount_micros: i64, |
| 424 | status: String, |
| 425 | hosted_url: Option<String>, |
| 426 | created_at: String, |
| 427 | paid_at: Option<String>, |
| 428 | } |
| 429 | let status = a.status.filter(|s| ["paid", "open", "failed", "overdue", "void"].contains(&s.as_str())); |
| 430 | let month = a.month.filter(|m| m.len() == 7 && m.chars().all(|c| c.is_ascii_digit() || c == '-')); |
| 431 | let rows = self |
| 432 | .db |
| 433 | .prepare( |
| 434 | "SELECT * FROM ( |
| 435 | SELECT invoice_id, 'workspace' AS kind, workspace AS account, workspace AS name, reason, period, |
| 436 | amount_micros, status, hosted_url, created_at, paid_at |
| 437 | FROM workspace_invoices |
| 438 | UNION ALL |
| 439 | SELECT i.invoice_id, 'enterprise', i.account_id, COALESCE(b.name, i.account_id), 'enterprise', i.period, |
| 440 | i.amount_micros, i.status, i.hosted_url, i.created_at, i.paid_at |
| 441 | FROM enterprise_invoices i LEFT JOIN billing_accounts b ON b.id = i.account_id |
| 442 | ) |
| 443 | WHERE (?1 IS NULL OR status = ?1) AND (?2 IS NULL OR substr(created_at, 1, 7) = ?2) |
| 444 | ORDER BY created_at DESC LIMIT 200", |
| 445 | ) |
| 446 | .bind(&[crate::optional(status.as_deref()), crate::optional(month.as_deref())])? |
| 447 | .all() |
| 448 | .await? |
| 449 | .results::<Row>()?; |
| 450 | Ok(rows |
| 451 | .into_iter() |
| 452 | .map(|r| g1t_contracts::billing::InvoiceSummary { |
| 453 | invoice_id: r.invoice_id, |
| 454 | kind: r.kind, |
| 455 | account: r.account, |
| 456 | name: r.name, |
| 457 | reason: r.reason, |
| 458 | period: r.period, |
| 459 | amount_micros: r.amount_micros, |
| 460 | status: r.status, |
| 461 | hosted_url: r.hosted_url, |
| 462 | created_at: r.created_at, |
| 463 | paid_at: r.paid_at, |
| 464 | }) |
| 465 | .collect()) |
| 466 | } |
| 467 | |
| 468 | /// Every change made in sudo and by Stripe, newest first. |
| 469 | pub(crate) async fn admin_audit(&self, a: g1t_contracts::billing::AdminAuditArgs) -> Result<Vec<g1t_contracts::billing::AdminAction>> { |
| 470 | #[derive(Deserialize)] |
| 471 | struct Row { |
| 472 | id: String, |
| 473 | account: String, |
| 474 | action: String, |
| 475 | detail: String, |
| 476 | by: String, |
| 477 | created_at: String, |
| 478 | } |
| 479 | let rows = self |
| 480 | .db |
| 481 | .prepare( |
| 482 | "SELECT id, account, action, detail, by, created_at FROM admin_actions |
| 483 | WHERE (?1 IS NULL OR by = ?1) AND (?2 IS NULL OR action = ?2) AND (?3 IS NULL OR created_at < ?3) |
| 484 | ORDER BY created_at DESC LIMIT 100", |
| 485 | ) |
| 486 | .bind(&[ |
| 487 | crate::optional(a.by.as_deref().map(str::trim).filter(|s| !s.is_empty())), |
| 488 | crate::optional(a.action.as_deref().map(str::trim).filter(|s| !s.is_empty())), |
| 489 | crate::optional(a.before.as_deref()), |
| 490 | ])? |
| 491 | .all() |
| 492 | .await? |
| 493 | .results::<Row>()?; |
| 494 | Ok(rows |
| 495 | .into_iter() |
| 496 | .map(|r| g1t_contracts::billing::AdminAction { |
| 497 | id: r.id, |
| 498 | account: r.account, |
| 499 | action: r.action, |
| 500 | detail: r.detail, |
| 501 | by: r.by, |
| 502 | created_at: r.created_at, |
| 503 | }) |
| 504 | .collect()) |
| 505 | } |
| 506 | |
| 507 | /// The business at a glance. |
| 508 | pub(crate) async fn admin_overview(&self, _: AdminOverviewArgs) -> Result<Overview> { |
| 509 | let now = rfc3339(now_ms()); |
| 510 | let month = now[..7].to_owned(); |
| 511 | let months = self.months_for(&[], 6).await?; |
| 512 | #[derive(Deserialize)] |
| 513 | struct KindRow { |
| 514 | kind: Option<String>, |
| 515 | charged: Option<i64>, |
| 516 | cost: Option<i64>, |
| 517 | } |
| 518 | let by_kind = self |
| 519 | .db |
| 520 | .prepare( |
| 521 | "SELECT CASE |
| 522 | WHEN task = 'sandbox' THEN 'Sandbox time' |
| 523 | WHEN task = 'deployments' THEN 'Deployments' |
| 524 | WHEN task = 'security' THEN 'Security scans' |
| 525 | WHEN task = 'context' THEN 'Search embeddings' |
| 526 | WHEN task = 'storage' THEN 'Private storage' |
| 527 | WHEN task = 'git' THEN 'Git operations' |
| 528 | WHEN billed_to = 'workspace' THEN 'Own-provider runs' |
| 529 | ELSE 'Models' END AS kind, |
| 530 | -SUM(amount_micros) AS charged, |
| 531 | SUM(CASE WHEN COALESCE(billed_to, 'g1t') = 'g1t' THEN cost_micros ELSE 0 END) AS cost |
| 532 | FROM ledger WHERE kind = 'usage' AND created_at >= ? GROUP BY 1 ORDER BY charged DESC", |
| 533 | ) |
| 534 | .bind(&[format!("{month}-01").into()])? |
| 535 | .all() |
| 536 | .await? |
| 537 | .results::<KindRow>()? |
| 538 | .into_iter() |
| 539 | .map(|r| KindFigures { |
| 540 | kind: r.kind.unwrap_or_else(|| "Other".to_owned()), |
| 541 | charged_micros: r.charged.unwrap_or(0), |
| 542 | cost_micros: r.cost.unwrap_or(0), |
| 543 | }) |
| 544 | .collect(); |
| 545 | #[derive(Deserialize)] |
| 546 | struct Count { |
| 547 | n: Option<i64>, |
| 548 | } |
| 549 | let count = |sql: &'static str, args: Vec<JsValue>| { |
| 550 | let db = &self.db; |
| 551 | async move { |
| 552 | Ok::<i64, worker::Error>(db.prepare(sql).bind(&args)?.first::<Count>(None).await?.and_then(|c| c.n).unwrap_or(0)) |
| 553 | } |
| 554 | }; |
| 555 | let paying = count( |
| 556 | "SELECT COUNT(DISTINCT workspace) AS n FROM ledger |
| 557 | WHERE kind = 'top_up' AND amount_micros > 0 AND reference NOT LIKE 'crd%' AND created_at >= ?", |
| 558 | vec![rfc3339(now_ms() - 60 * 24 * 60 * 60 * 1000).into()], |
| 559 | ) |
| 560 | .await?; |
| 561 | let open_invoices = count( |
| 562 | "SELECT (SELECT COALESCE(SUM(amount_micros), 0) FROM workspace_invoices WHERE status IN ('open', 'failed')) |
| 563 | + (SELECT COALESCE(SUM(amount_micros), 0) FROM enterprise_invoices WHERE status IN ('open', 'overdue')) AS n", |
| 564 | vec![], |
| 565 | ) |
| 566 | .await?; |
| 567 | let follow_ups = count( |
| 568 | "SELECT COUNT(*) AS n FROM sales_records WHERE next_at IS NOT NULL AND next_at <= ? AND stage NOT IN ('won', 'lost')", |
| 569 | vec![now[..10].into()], |
| 570 | ) |
| 571 | .await?; |
| 572 | let signals = self.admin_signals(AdminSignalsArgs {}).await?; |
| 573 | let tally = |kind: SignalKind| signals.iter().filter(|s| s.kind == kind).count() as u32; |
| 574 | let this = months.last().cloned().unwrap_or_default(); |
| 575 | let active_plans = count( |
| 576 | "SELECT COUNT(*) AS n FROM subscriptions WHERE feature = 'plan' AND status IN ('active', 'canceling')", |
| 577 | vec![], |
| 578 | ) |
| 579 | .await?; |
| 580 | let open_requests = count("SELECT COUNT(*) AS n FROM limit_requests WHERE status = 'open'", vec![]).await?; |
| 581 | let open_spikes = count("SELECT COUNT(*) AS n FROM spikes WHERE status = 'open'", vec![]).await?; |
| 582 | let overages = self.admin_overages(AdminOveragesArgs {}).await?.len() as u32; |
| 583 | Ok(Overview { |
| 584 | revenue_micros: this.charged_micros + this.plans_micros, |
| 585 | active_plans: active_plans as u32, |
| 586 | plan_mrr_micros: active_plans * i64::from(self.plans.plan_monthly_cents) * 10_000, |
| 587 | given: self.given_this_month(&month).await?, |
| 588 | internal: self.internal_use(&month).await?, |
| 589 | open_requests: open_requests as u32, |
| 590 | open_spikes: open_spikes as u32, |
| 591 | overages, |
| 592 | month, |
| 593 | months, |
| 594 | by_kind, |
| 595 | paying_workspaces: paying as u32, |
| 596 | stopped: tally(SignalKind::AtLimit), |
| 597 | near_ceiling: tally(SignalKind::NearCeiling), |
| 598 | declined: tally(SignalKind::Declined), |
| 599 | open_invoices_micros: open_invoices, |
| 600 | follow_ups_due: follow_ups as u32, |
| 601 | pools: Some(self.pools().await?), |
| 602 | }) |
| 603 | } |
| 604 | |
| 605 | /// What g1t gave in `month`, by source, at price and at cost. |
| 606 | async fn given_this_month(&self, month: &str) -> Result<Vec<GivenFigures>> { |
| 607 | #[derive(Deserialize)] |
| 608 | struct Row { |
| 609 | internal_cost: Option<i64>, |
| 610 | trial: Option<i64>, |
| 611 | oss: Option<i64>, |
| 612 | covered: Option<i64>, |
| 613 | goodwill: Option<i64>, |
| 614 | } |
| 615 | let row = self |
| 616 | .db |
| 617 | .prepare(format!( |
| 618 | "SELECT |
| 619 | SUM(CASE WHEN kind = 'usage' AND COALESCE(billed_to, 'g1t') = 'g1t' AND workspace IN ({INTERNAL_SQL}) |
| 620 | THEN cost_micros END) AS internal_cost, |
| 621 | SUM(CASE WHEN kind = 'usage' THEN trial_micros END) AS trial, |
| 622 | SUM(CASE WHEN kind = 'usage' THEN oss_micros END) AS oss, |
| 623 | SUM(CASE WHEN kind = 'usage' THEN given_micros END) AS covered, |
| 624 | SUM(CASE WHEN kind = 'top_up' AND reference LIKE '{goodwill}%' THEN amount_micros END) AS goodwill |
| 625 | FROM ledger WHERE created_at >= ?", |
| 626 | goodwill = crate::overages::GOODWILL_PREFIX |
| 627 | )) |
| 628 | .bind(&[format!("{month}-01").into()])? |
| 629 | .first::<Row>(None) |
| 630 | .await?; |
| 631 | let Some(row) = row else { return Ok(vec![]) }; |
| 632 | let at_cost = |price: i64| price * 100 / i64::from(100 + self.margin_percent); |
| 633 | let internal_cost = row.internal_cost.unwrap_or(0); |
| 634 | Ok([ |
| 635 | ("internal", "g1t's and Flagon's own use", crate::credits::with_margin(internal_cost, self.margin_percent), internal_cost), |
| 636 | ("trial", "Trials", row.trial.unwrap_or(0), at_cost(row.trial.unwrap_or(0))), |
| 637 | ("oss_pool", "Open-source pool", row.oss.unwrap_or(0), at_cost(row.oss.unwrap_or(0))), |
| 638 | ("covered", "Covered past a trial's end", row.covered.unwrap_or(0), at_cost(row.covered.unwrap_or(0))), |
| 639 | ("goodwill", "Goodwill credits", row.goodwill.unwrap_or(0), row.goodwill.unwrap_or(0)), |
| 640 | ] |
| 641 | .into_iter() |
| 642 | .map(|(source, label, micros, cost)| GivenFigures { source: source.to_owned(), label: label.to_owned(), micros, cost_micros: cost }) |
| 643 | .collect()) |
| 644 | } |
| 645 | |
| 646 | /// g1t's own workspaces' use in `month`, with why each is not charged. |
| 647 | async fn internal_use(&self, month: &str) -> Result<Vec<InternalUse>> { |
| 648 | #[derive(Deserialize)] |
| 649 | struct Row { |
| 650 | workspace: String, |
| 651 | cost: Option<i64>, |
| 652 | entries: Option<u32>, |
| 653 | } |
| 654 | let rows = self |
| 655 | .db |
| 656 | .prepare(format!( |
| 657 | "SELECT workspace, SUM(cost_micros) AS cost, COUNT(*) AS entries FROM ledger |
| 658 | WHERE kind = 'usage' AND COALESCE(billed_to, 'g1t') = 'g1t' AND created_at >= ? AND workspace IN ({INTERNAL_SQL}) |
| 659 | GROUP BY workspace ORDER BY cost DESC" |
| 660 | )) |
| 661 | .bind(&[format!("{month}-01").into()])? |
| 662 | .all() |
| 663 | .await? |
| 664 | .results::<Row>()?; |
| 665 | let mut list = vec![]; |
| 666 | for row in rows { |
| 667 | let terms = self.terms_of(&row.workspace).await?; |
| 668 | list.push(InternalUse { |
| 669 | reason: if terms.note.is_empty() { "Comped".to_owned() } else { terms.note }, |
| 670 | cost_micros: row.cost.unwrap_or(0), |
| 671 | entries: row.entries.unwrap_or(0), |
| 672 | workspace: row.workspace, |
| 673 | }); |
| 674 | } |
| 675 | Ok(list) |
| 676 | } |
| 677 | } |
| 678 | |
| 679 | #[cfg(test)] |
| 680 | mod tests { |
| 681 | use super::*; |
| 682 | |
| 683 | fn group(kind: &str, billed_to: &str, amount: i64, cost: i64) -> LedgerGroup { |
| 684 | LedgerGroup { |
| 685 | month: "2026-10".into(), |
| 686 | kind: kind.into(), |
| 687 | billed_to: Some(billed_to.into()), |
| 688 | amount: Some(amount), |
| 689 | cost: Some(cost), |
| 690 | ..LedgerGroup::default() |
| 691 | } |
| 692 | } |
| 693 | |
| 694 | #[test] |
| 695 | fn a_workspaces_own_provider_is_never_g1ts_cost() { |
| 696 | let groups = [ |
| 697 | // Runs on g1t's models: charged $12, cost g1t $10. |
| 698 | group("usage", "g1t", -12_000_000, 10_000_000), |
| 699 | // A run on the workspace's own provider: it paid that $0.21 itself. |
| 700 | group("usage", "workspace", -100_000, 209_700), |
| 701 | ]; |
| 702 | let month = fold_month("2026-10", &groups, 0, 20); |
| 703 | assert_eq!(month.cost_micros, 10_000_000); |
| 704 | assert_eq!(month.charged_micros, 12_100_000); |
| 705 | } |
| 706 | |
| 707 | #[test] |
| 708 | fn plan_revenue_counts_and_what_g1t_gives_is_kept_apart() { |
| 709 | let groups = [ |
| 710 | group("usage", "g1t", -12_000_000, 10_000_000), |
| 711 | // Paid for by the trial and the open-source pool: $3 at price. |
| 712 | LedgerGroup { pools: Some(3_000_000), ..group("usage", "g1t", 0, 2_500_000) }, |
| 713 | // g1t's own workspace: nothing charged, $5 of cost. |
| 714 | LedgerGroup { internal: 1, ..group("usage", "g1t", 0, 5_000_000) }, |
| 715 | // A payment, a goodwill credit, and another credit from g1t. |
| 716 | group("top_up", "g1t", 40_000_000, 0), |
| 717 | LedgerGroup { credit: 1, goodwill: 1, ..group("top_up", "g1t", 15_000_000, 0) }, |
| 718 | LedgerGroup { credit: 1, ..group("top_up", "g1t", 2_000_000, 0) }, |
| 719 | // Another month is not this one. |
| 720 | LedgerGroup { month: "2026-09".into(), ..group("usage", "g1t", -1, 1) }, |
| 721 | ]; |
| 722 | let month = fold_month("2026-10", &groups, 20_000_000, 20); |
| 723 | assert_eq!(month.plans_micros, 20_000_000); |
| 724 | assert_eq!(month.paid_micros, 40_000_000); |
| 725 | assert_eq!(month.charged_micros, 12_000_000); |
| 726 | assert_eq!(month.cost_micros, 17_500_000); |
| 727 | // $6 of internal use at price, $3 of pools, $15 of goodwill. |
| 728 | assert_eq!(month.given_micros, 6_000_000 + 3_000_000 + 15_000_000); |
| 729 | } |
| 730 | |
| 731 | #[test] |
| 732 | fn six_months_end_with_this_one() { |
| 733 | assert_eq!(last_months("2026-02", 3), vec!["2025-12", "2026-01", "2026-02"]); |
| 734 | } |
| 735 | |
| 736 | #[test] |
| 737 | fn growth_is_judged_on_pace_not_on_the_month_so_far() { |
| 738 | // Ten days in, $20 on a 30-day month is a $60 pace against $30. |
| 739 | assert!(growing(20_000_000, 30_000_000, 10, 30)); |
| 740 | assert!(!growing(10_000_000, 30_000_000, 10, 30)); |
| 741 | // Too small last month to say. |
| 742 | assert!(!growing(9_000_000, 1_000_000, 10, 30)); |
| 743 | } |
| 744 | |
| 745 | #[test] |
| 746 | fn the_most_urgent_comes_first() { |
| 747 | assert!(urgency(SignalKind::AtLimit) < urgency(SignalKind::NearCeiling)); |
| 748 | assert!(urgency(SignalKind::Declined) < urgency(SignalKind::Growing)); |
| 749 | } |
| 750 | |
| 751 | #[test] |
| 752 | fn february_knows_its_leap_years() { |
| 753 | assert_eq!(days_in("2028-02"), 29); |
| 754 | assert_eq!(days_in("2026-02"), 28); |
| 755 | assert_eq!(days_in("2026-10"), 31); |
| 756 | } |
| 757 | } |