Skip to content

g1t/services/billing/src/sales.rs

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