g1t/services/billing/src/sales.rs

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