Skip to content

g1t/services/billing/src/statement.rs

502 lines21,971 bytesCodeBlame
1//! A workspace's statement: a month of its ledger, grouped so it can be
2//! read at a glance (by day or by project, a line per kind of charge),
3//! with each line's entries a page at a time.
4
5use g1t_contracts::billing::{
6 Covered, LedgerEntry, MeterUsage, Statement, StatementArgs, StatementEntriesArgs, StatementGroup, StatementLine, StatementTotals,
7 UsageMetersArgs,
8};
9use g1t_contracts::time::rfc3339;
10use g1t_contracts::Outcome;
11use g1t_kit::now_ms;
12use serde::Deserialize;
13use worker::Result;
14use worker::wasm_bindgen::JsValue;
15
16use crate::{Billing, LedgerRow, members_only};
17
18/// Entries in one page of a line.
19const PAGE: u32 = 50;
20
21/// The kind of charge a ledger row is, as the statement names it. One SQL
22/// expression, so grouping and filtering agree.
23/// `Runs on your own model provider` is only on older months: those runs
24/// carried a flat fee then, and pay only their sandbox time now.
25pub(crate) const KIND_SQL: &str = "CASE
26 WHEN kind = 'top_up' AND credit_kind = 'purchased' THEN 'AI credit'
27 WHEN kind = 'top_up' AND reference LIKE 'crd%' THEN 'Credits from g1t'
28 WHEN kind = 'top_up' AND amount_micros < 0 THEN 'Refunds'
29 WHEN kind = 'top_up' THEN 'Payments'
30 WHEN task = 'sandbox' THEN 'Sandbox time'
31 WHEN task = 'self_hosted' THEN 'Self-hosted runner time'
32 WHEN task = 'deployments' THEN 'Deployments'
33 WHEN task = 'security' THEN 'Security scans'
34 WHEN task = 'context' THEN 'Search embeddings'
35 WHEN task = 'storage' THEN 'Private storage'
36 WHEN task = 'cache' THEN 'Actions cache storage'
37 WHEN task = 'git' THEN 'Git operations'
38 WHEN billed_to = 'workspace' THEN 'Runs on your own model provider'
39 WHEN reference LIKE '%/agent%' THEN 'Agent rate'
40 WHEN task = 'gateway' THEN 'AI Gateway'
41 WHEN task = 'domains' THEN 'Custom domains'
42 WHEN task = 'package_storage' THEN 'Package storage'
43 ELSE 'Agent runs' END";
44
45/// A usage line at its price, in SQL: what was charged, what paid for it
46/// first (the plan's included usage, the trial, a pool, g1t), and what a
47/// discount took off. `line_price`, for a whole column. The one measure of
48/// usage every page shows.
49pub(crate) const PRICE_SQL: &str = "(-amount_micros + COALESCE(credit_micros, 0) + COALESCE(trial_micros, 0) + COALESCE(oss_micros, 0)
50 + COALESCE(given_micros, 0) + COALESCE(discount_micros, 0))";
51
52/// Whether a usage line is an agent run's own line (`run_…`), not its
53/// agent rate, a correction or anything else: what counts as one run.
54pub(crate) const RUN_SQL: &str = "(reference LIKE 'run%' AND instr(reference, '/') = 0)";
55
56/// The order lines appear in within a group.
57pub(crate) fn kind_order(kind: &str) -> u8 {
58 match kind {
59 "Agent runs" => 0,
60 "Agent rate" => 0,
61 "AI Gateway" => 1,
62 "Runs on your own model provider" => 1,
63 "Sandbox time" => 2,
64 "Self-hosted runner time" => 2,
65 "Deployments" => 3,
66 "Private storage" => 4,
67 "Actions cache storage" => 4,
68 "Git operations" => 5,
69 "Search embeddings" => 6,
70 "Security scans" => 7,
71 "Custom domains" => 3,
72 "Package storage" => 4,
73 "Payments" => 8,
74 "AI credit" => 8,
75 "Credits from g1t" => 9,
76 "Refunds" => 10,
77 _ => 11,
78 }
79}
80
81/// Payments, credits and refunds: money in, which has no price.
82pub(crate) fn is_money_in(kind: &str) -> bool {
83 matches!(kind, "Payments" | "AI credit" | "Credits from g1t" | "Refunds")
84}
85
86/// A usage line at its price: what was charged, what paid for it first,
87/// and what the account's discount took off.
88pub(crate) fn line_price(charged: i64, covered: i64, discount: i64) -> i64 {
89 charged + covered + discount
90}
91
92/// The Billing page's meters, in order: key and label.
93pub(crate) const METERS: [(&str, &str); 6] = [
94 ("agents", "Agents & sandboxes"),
95 ("builds", "Builds"),
96 ("requests", "Requests & CPU"),
97 ("domains", "Custom domains"),
98 ("git_storage", "Git operations & storage"),
99 ("search_scans", "Search & security scans"),
100];
101
102/// The meter a ledger row's usage is on. One SQL expression, as `KIND_SQL`.
103pub(crate) const METER_SQL: &str = "CASE
104 WHEN task = 'deployments' AND reference LIKE 'deploy/%' THEN 'builds'
105 WHEN task = 'deployments' THEN 'requests'
106 WHEN task IN ('storage', 'git', 'cache') THEN 'git_storage'
107 WHEN task IN ('security', 'context') THEN 'search_scans'
108 ELSE 'agents' END";
109
110/// The meter usage noted through the month (`pending_usage.source`) is on.
111pub(crate) fn meter_of_source(source: &str) -> &'static str {
112 match source {
113 "deployments" => "requests",
114 "domains" => "domains",
115 "storage" | "git" | "cache" => "git_storage",
116 _ => "search_scans",
117 }
118}
119
120/// `41 build minutes`, from seconds, rounded up.
121pub(crate) fn build_minutes(seconds: i64) -> Option<String> {
122 let minutes = (seconds.max(0) + 59) / 60;
123 (seconds > 0).then(|| format!("{} build minute{}", crate::features::thousands(minutes as u64), if minutes == 1 { "" } else { "s" }))
124}
125
126/// `12 runs`.
127pub(crate) fn runs(count: u32) -> Option<String> {
128 (count > 0).then(|| format!("{} run{}", crate::features::thousands(count.into()), if count == 1 { "" } else { "s" }))
129}
130
131/// `12,345 git operations, 0.42 GB private`.
132pub(crate) fn git_and_storage(operations: u64, private_bytes: i64) -> Option<String> {
133 let mut parts = vec![];
134 if operations > 0 {
135 parts.push(format!("{} git operation{}", crate::features::thousands(operations), if operations == 1 { "" } else { "s" }));
136 }
137 if private_bytes > 0 {
138 parts.push(format!("{:.2} GB private", private_bytes as f64 / 1e9));
139 }
140 (!parts.is_empty()).then(|| parts.join(", "))
141}
142
143/// What paid for usage before it was charged, as the statement names it,
144/// with the ledger column that holds it.
145pub(crate) const COVERED: [(&str, &str, &str); 4] = [
146 ("included", "credit_micros", "Paid by your plan's included usage"),
147 ("trial", "trial_micros", "Paid by your trial credit"),
148 ("oss_pool", "oss_micros", "Paid by g1t's open-source pool"),
149 ("given", "given_micros", "Covered by g1t"),
150];
151
152/// The statement's lines for what paid: each source with anything to show.
153pub(crate) fn covered_lines(sums: [i64; 4]) -> Vec<Covered> {
154 COVERED
155 .iter()
156 .zip(sums)
157 .filter(|(_, micros)| *micros > 0)
158 .map(|((source, _, label), micros)| Covered { source: (*source).to_owned(), label: (*label).to_owned(), micros })
159 .collect()
160}
161
162/// `2026-10` and the first instant of the next month, for a range.
163pub(crate) fn month_range(month: &str) -> Option<(String, String)> {
164 let year: i32 = month.get(..4)?.parse().ok()?;
165 let number: u32 = month.get(5..7)?.parse().ok()?;
166 if month.len() != 7 || !(1..=12).contains(&number) {
167 return None;
168 }
169 let next = if number == 12 { format!("{}-01", year + 1) } else { format!("{year}-{:02}", number + 1) };
170 Some((format!("{month}-01"), format!("{next}-01")))
171}
172
173#[derive(Deserialize)]
174struct Row {
175 group_key: Option<String>,
176 kind: String,
177 count: u32,
178 amount: Option<i64>,
179 cost: Option<i64>,
180 credit: Option<i64>,
181 trial: Option<i64>,
182 oss: Option<i64>,
183 given: Option<i64>,
184 discount: Option<i64>,
185}
186
187#[derive(Deserialize)]
188struct Month {
189 month: String,
190}
191
192impl Billing {
193 pub(crate) async fn statement(&self, a: StatementArgs) -> Result<Outcome<Statement>> {
194 let workspace = a.workspace.to_lowercase();
195 if !a.viewer.is_some_and(|viewer| viewer.is_member(&workspace)) {
196 return Ok(members_only());
197 }
198 let current = rfc3339(now_ms())[..7].to_owned();
199 let month = a.month.filter(|m| month_range(m).is_some()).unwrap_or(current);
200 let (from, until) = month_range(&month).expect("a valid month");
201 let by_project = a.group.as_deref() == Some("project");
202 let group_sql = if by_project { "COALESCE(repo, '')" } else { "substr(created_at, 1, 10)" };
203 let rows = self
204 .db
205 .prepare(format!(
206 "SELECT {group_sql} AS group_key, {KIND_SQL} AS kind, COUNT(*) AS count,
207 SUM(amount_micros) AS amount, SUM(cost_micros) AS cost,
208 SUM(credit_micros) AS credit, SUM(trial_micros) AS trial, SUM(oss_micros) AS oss,
209 SUM(given_micros) AS given, SUM(discount_micros) AS discount
210 FROM ledger WHERE workspace = ?1 AND created_at >= ?2 AND created_at < ?3
211 GROUP BY 1, 2"
212 ))
213 .bind(&[workspace.as_str().into(), from.as_str().into(), until.as_str().into()])?
214 .all()
215 .await?
216 .results::<Row>()?;
217
218 let mut groups: Vec<StatementGroup> = vec![];
219 let mut covered = [0i64; 4];
220 for row in rows {
221 let key = row.group_key.unwrap_or_default();
222 let amount = row.amount.unwrap_or(0);
223 let paid_for = [row.credit.unwrap_or(0), row.trial.unwrap_or(0), row.oss.unwrap_or(0), row.given.unwrap_or(0)];
224 for (total, micros) in covered.iter_mut().zip(paid_for) {
225 *total += micros;
226 }
227 let discount = row.discount.unwrap_or(0);
228 let line = StatementLine {
229 // Charges positive, money in negative, as a statement reads.
230 charged_micros: -amount,
231 cost_micros: row.cost.unwrap_or(0),
232 covered_micros: paid_for.iter().sum(),
233 price_micros: if is_money_in(&row.kind) { 0 } else { line_price(-amount, paid_for.iter().sum(), discount) },
234 discount_micros: discount,
235 kind: row.kind,
236 count: row.count,
237 };
238 match groups.iter_mut().find(|g| g.key == key) {
239 Some(group) => group.lines.push(line),
240 None => groups.push(StatementGroup {
241 label: if key.is_empty() { "Not one project".to_owned() } else { key.clone() },
242 key,
243 lines: vec![line],
244 charged_micros: 0,
245 price_micros: 0,
246 discount_micros: 0,
247 }),
248 }
249 }
250 for group in &mut groups {
251 group.lines.sort_by_key(|line| kind_order(&line.kind));
252 group.charged_micros = group.lines.iter().filter(|l| l.charged_micros > 0).map(|l| l.charged_micros).sum();
253 group.price_micros = group.lines.iter().map(|l| l.price_micros).sum();
254 group.discount_micros = group.lines.iter().map(|l| l.discount_micros).sum();
255 }
256 if by_project {
257 groups.sort_by_key(|a| std::cmp::Reverse(a.charged_micros));
258 } else {
259 groups.sort_by(|a, b| b.key.cmp(&a.key));
260 }
261 let lines = groups.iter().flat_map(|g| g.lines.iter());
262 let totals = StatementTotals {
263 charged_micros: lines.clone().filter(|l| l.charged_micros > 0).map(|l| l.charged_micros).sum(),
264 paid_micros: lines.clone().filter(|l| l.charged_micros < 0).map(|l| -l.charged_micros).sum(),
265 cost_micros: lines.clone().map(|l| l.cost_micros).sum(),
266 price_micros: lines.clone().map(|l| l.price_micros).sum(),
267 discount_micros: lines.clone().map(|l| l.discount_micros).sum(),
268 discount_percent: Some(self.terms_of(&workspace).await?.percent_off()).filter(|p| *p > 0),
269 entries: lines.map(|l| l.count).sum(),
270 covered: covered_lines(covered),
271 carried_micros: self.carried(&workspace, &month).await?,
272 };
273 let months = self
274 .db
275 .prepare("SELECT DISTINCT substr(created_at, 1, 7) AS month FROM ledger WHERE workspace = ? ORDER BY 1 DESC LIMIT 36")
276 .bind(&[workspace.as_str().into()])?
277 .all()
278 .await?
279 .results::<Month>()?
280 .into_iter()
281 .map(|m| m.month)
282 .collect();
283 Ok(Outcome::Ok(Statement { month, months, groups, totals }))
284 }
285
286 /// `usage_meters`: this month's usage by meter, at cost plus the margin
287 /// (with a custom discount, if the account has one) before the plan's
288 /// included usage or a pool paid for any of it. Comped workspaces see
289 /// what it would cost. Usage charged through the month is on the
290 /// ledger; usage charged when the month closes (app traffic, custom
291 /// domains, storage, git operations, search and scans) is what has been
292 /// noted so far.
293 pub(crate) async fn usage_meters(&self, a: UsageMetersArgs) -> Result<Outcome<Vec<MeterUsage>>> {
294 let workspace = a.workspace.to_lowercase();
295 if !a.viewer.is_some_and(|viewer| viewer.is_member(&workspace)) {
296 return Ok(members_only());
297 }
298 let now = rfc3339(now_ms());
299 let month = now[..7].to_owned();
300 let (from, until) = month_range(&month).expect("a valid month");
301 #[derive(Deserialize)]
302 struct Used {
303 meter: String,
304 count: u32,
305 price: Option<f64>,
306 }
307 // A month's close for deployments is charged in the next month;
308 // it is last month's, so it is left out here.
309 let ledger = self
310 .db
311 .prepare(format!(
312 "SELECT {METER_SQL} AS meter, SUM(CASE WHEN {RUN_SQL} THEN 1 ELSE 0 END) AS count, SUM({PRICE_SQL}) AS price
313 FROM ledger WHERE workspace = ?1 AND kind = 'usage' AND created_at >= ?2 AND created_at < ?3
314 AND COALESCE(reference, '') NOT LIKE 'deployments/%'
315 -- Runs on the workspace's own model provider are its provider's to bill, never g1t's.
316 AND COALESCE(billed_to, 'g1t') = 'g1t'
317 GROUP BY 1"
318 ))
319 .bind(&[workspace.as_str().into(), from.as_str().into(), until.as_str().into()])?
320 .all()
321 .await?
322 .results::<Used>()?;
323 #[derive(Deserialize)]
324 struct Pending {
325 source: String,
326 cost_micros: Option<f64>,
327 detail: Option<String>,
328 }
329 let pending = self
330 .db
331 .prepare("SELECT source, cost_micros, detail FROM pending_usage WHERE workspace = ? AND month = ? AND charged_at IS NULL")
332 .bind(&[workspace.as_str().into(), month.as_str().into()])?
333 .all()
334 .await?
335 .results::<Pending>()?;
336 // At price, before any discount, as every page shows usage: the
337 // ledger's lines as they were charged, and what is metered so far
338 // at cost plus the margin.
339 let price = |cost: i64| crate::credits::with_margin(cost, self.margin_percent);
340 let mut meters: Vec<MeterUsage> = METERS
341 .iter()
342 .map(|(key, label)| MeterUsage { key: (*key).to_owned(), label: (*label).to_owned(), micros: 0, quantity: None })
343 .collect();
344 let mut agent_runs = 0;
345 for used in ledger {
346 if let Some(meter) = meters.iter_mut().find(|m| m.key == used.meter) {
347 meter.micros += used.price.unwrap_or(0.0).round() as i64;
348 }
349 if used.meter == "agents" {
350 agent_runs = used.count;
351 }
352 }
353 for row in &pending {
354 let key = meter_of_source(&row.source);
355 if let Some(meter) = meters.iter_mut().find(|m| m.key == key) {
356 meter.micros += price(row.cost_micros.unwrap_or(0.0).round() as i64);
357 if matches!(key, "requests" | "domains") {
358 meter.quantity = row.detail.clone().filter(|d| !d.is_empty());
359 }
360 }
361 }
362 let build_seconds = self.allowance_used("build_seconds", &workspace, &month).await?;
363 let operations = self.git_operations_this_month(&workspace).await?;
364 let stored = self.private_storage(&workspace).await?;
365 for meter in &mut meters {
366 match meter.key.as_str() {
367 "agents" => meter.quantity = runs(agent_runs),
368 "builds" => meter.quantity = build_minutes(build_seconds),
369 "git_storage" => meter.quantity = git_and_storage(operations, stored),
370 _ => {}
371 }
372 }
373 Ok(Outcome::Ok(meters))
374 }
375
376 /// What was owed when `month` closed but was under the minimum charge,
377 /// and so carried over to the next invoice.
378 async fn carried(&self, workspace: &str, month: &str) -> Result<i64> {
379 #[derive(Deserialize)]
380 struct Row {
381 amount_micros: i64,
382 }
383 Ok(self
384 .db
385 .prepare("SELECT amount_micros FROM month_closes WHERE workspace = ? AND month = ? AND status = 'carried'")
386 .bind(&[workspace.into(), month.into()])?
387 .first::<Row>(None)
388 .await?
389 .map_or(0, |row| row.amount_micros))
390 }
391
392 /// One line's entries, newest first, a page at a time.
393 pub(crate) async fn statement_entries(&self, a: StatementEntriesArgs) -> Result<Outcome<Vec<LedgerEntry>>> {
394 let workspace = a.workspace.to_lowercase();
395 if !a.viewer.is_some_and(|viewer| viewer.is_member(&workspace)) {
396 return Ok(members_only());
397 }
398 let Some((from, until)) = month_range(&a.month) else {
399 return Ok(Outcome::Ok(vec![]));
400 };
401 let mut filters = vec![format!("({KIND_SQL}) = ?4")];
402 let mut values: Vec<JsValue> = vec![
403 workspace.as_str().into(),
404 from.as_str().into(),
405 until.as_str().into(),
406 a.kind.as_str().into(),
407 ];
408 if let Some(day) = a.day.as_deref().filter(|d| d.len() == 10) {
409 values.push(day.into());
410 filters.push(format!("substr(created_at, 1, 10) = ?{}", values.len()));
411 }
412 if let Some(project) = &a.project {
413 values.push(project.as_str().into());
414 filters.push(format!("COALESCE(repo, '') = ?{}", values.len()));
415 }
416 if let Some(before) = &a.before {
417 values.push(before.as_str().into());
418 filters.push(format!("id < ?{}", values.len()));
419 }
420 let rows = self
421 .db
422 .prepare(format!(
423 "SELECT * FROM ledger WHERE workspace = ?1 AND created_at >= ?2 AND created_at < ?3 AND {}
424 ORDER BY id DESC LIMIT {PAGE}",
425 filters.join(" AND ")
426 ))
427 .bind(&values)?
428 .all()
429 .await?
430 .results::<LedgerRow>()?;
431 Ok(Outcome::Ok(rows.into_iter().map(LedgerEntry::from).collect()))
432 }
433}
434
435#[cfg(test)]
436mod tests {
437 use super::*;
438
439 #[test]
440 fn a_month_runs_to_the_first_of_the_next() {
441 assert_eq!(month_range("2026-10"), Some(("2026-10-01".into(), "2026-11-01".into())));
442 assert_eq!(month_range("2026-12"), Some(("2026-12-01".into(), "2027-01-01".into())));
443 assert_eq!(month_range("2026-13"), None);
444 assert_eq!(month_range("oops"), None);
445 }
446
447 #[test]
448 fn a_discounted_line_shows_its_price_and_the_discount() {
449 // $1.20 of usage on a 100% discount: charged nothing, all of it off.
450 assert_eq!(line_price(0, 0, 1_200_000), 1_200_000);
451 // 30% off, $0.20 of it paid by included usage first.
452 assert_eq!(line_price(700_000, 140_000, 360_000), 1_200_000);
453 assert!(is_money_in("Payments") && is_money_in("Credits from g1t") && is_money_in("Refunds"));
454 assert!(!is_money_in("Agent runs"));
455 }
456
457 #[test]
458 fn usage_lines_come_before_money_in() {
459 assert!(kind_order("Agent runs") < kind_order("Sandbox time"));
460 assert!(kind_order("Deployments") < kind_order("Payments"));
461 assert!(kind_order("Security scans") < kind_order("Payments"));
462 }
463
464 #[test]
465 fn usage_falls_on_the_meters_the_billing_page_shows() {
466 let keys: Vec<_> = METERS.iter().map(|(key, _)| *key).collect();
467 assert_eq!(keys, ["agents", "builds", "requests", "domains", "git_storage", "search_scans"]);
468 assert_eq!(meter_of_source("deployments"), "requests");
469 assert_eq!(meter_of_source("domains"), "domains");
470 assert_eq!(meter_of_source("git"), "git_storage");
471 assert_eq!(meter_of_source("storage"), "git_storage");
472 assert_eq!(meter_of_source("context"), "search_scans");
473 assert_eq!(meter_of_source("security"), "search_scans");
474 for key in ["builds", "requests", "git_storage", "search_scans", "agents"] {
475 assert!(METER_SQL.contains(&format!("'{key}'")));
476 }
477 }
478
479 #[test]
480 fn quantities_read_plainly() {
481 assert_eq!(build_minutes(0), None);
482 assert_eq!(build_minutes(1).as_deref(), Some("1 build minute"));
483 assert_eq!(build_minutes(2_461).as_deref(), Some("42 build minutes"));
484 assert_eq!(runs(1).as_deref(), Some("1 run"));
485 assert_eq!(runs(1_200).as_deref(), Some("1,200 runs"));
486 assert_eq!(git_and_storage(0, 0), None);
487 assert_eq!(git_and_storage(12_345, 420_000_000).as_deref(), Some("12,345 git operations, 0.42 GB private"));
488 assert_eq!(git_and_storage(1, 0).as_deref(), Some("1 git operation"));
489 }
490
491 #[test]
492 fn the_statement_says_what_paid_before_the_workspace_did() {
493 let lines = covered_lines([0, 250_000, 120_000, 0]);
494 assert_eq!(lines.len(), 2);
495 assert_eq!(lines[0].label, "Paid by your trial credit");
496 assert_eq!(lines[1], Covered { source: "oss_pool".into(), label: "Paid by g1t's open-source pool".into(), micros: 120_000 });
497 assert!(covered_lines([0, 0, 0, 0]).is_empty());
498 let lines = covered_lines([4_000_000, 0, 0, 30_000]);
499 assert_eq!(lines[0].label, "Paid by your plan's included usage");
500 assert_eq!(lines[1].label, "Covered by g1t");
501 }
502}