Skip to content

g1t/services/billing/src/statement.rs

504 lines22,095 bytesCodeBlame

Pick any line to see why it is the way it is: the commit, the pull request and issue it came from, and what the agent was thinking.

The statement is a month at a time, a line per kind of charge1//! 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::{
status.g1t.sh with incident management, invites that land you in the workspace, settings as pages, usage without quotas6 Covered, LedgerEntry, MeterUsage, Statement, StatementArgs, StatementEntriesArgs, StatementGroup, StatementLine, StatementTotals,
Billing: credits with a kind and expiry, discounts instead of comped, and safer charging7 UsageMetersArgs,
The statement is a month at a time, a line per kind of charge8};
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.
Prices are what g1t pays plus 20%, from the first second23/// `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.
The statement is a month at a time, a line per kind of charge25pub(crate) const KIND_SQL: &str = "CASE
Usage, Billing settings and prepaid AI credit; fixes from the UX audit26 WHEN kind = 'top_up' AND credit_kind = 'purchased' THEN 'AI credit'
The statement is a month at a time, a line per kind of charge27 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'
Fast pages, required checks on the branch, self-hosted runners, honest incidents31 WHEN task = 'self_hosted' THEN 'Self-hosted runner time'
The statement is a month at a time, a line per kind of charge32 WHEN task = 'deployments' THEN 'Deployments'
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put33 WHEN task = 'security' THEN 'Security scans'
34 WHEN task = 'context' THEN 'Search embeddings'
35 WHEN task = 'storage' THEN 'Private storage'
Fast pages, required checks on the branch, self-hosted runners, honest incidents36 WHEN task = 'cache' THEN 'Actions cache storage'
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look37 WHEN task = 'git' THEN 'Git operations'
Merge branch 'model-routing'38 WHEN reference LIKE '%/agent-own%' THEN 'Agent rate, your own model key'
The statement is a month at a time, a line per kind of charge39 WHEN billed_to = 'workspace' THEN 'Runs on your own model provider'
Usage, Billing settings and prepaid AI credit; fixes from the UX audit40 WHEN reference LIKE '%/agent%' THEN 'Agent rate'
41 WHEN task = 'gateway' THEN 'AI Gateway'
42 WHEN task = 'domains' THEN 'Custom domains'
43 WHEN task = 'package_storage' THEN 'Package storage'
The statement is a month at a time, a line per kind of charge44 ELSE 'Agent runs' END";
45
Usage, Billing settings and prepaid AI credit; fixes from the UX audit46/// A usage line at its price, in SQL: what was charged, what paid for it
47/// first (the plan's included usage, the trial, a pool, g1t), and what a
48/// discount took off. `line_price`, for a whole column. The one measure of
49/// usage every page shows.
50pub(crate) const PRICE_SQL: &str = "(-amount_micros + COALESCE(credit_micros, 0) + COALESCE(trial_micros, 0) + COALESCE(oss_micros, 0)
51 + COALESCE(given_micros, 0) + COALESCE(discount_micros, 0))";
52
53/// Whether a usage line is an agent run's own line (`run_…`), not its
54/// agent rate, a correction or anything else: what counts as one run.
55pub(crate) const RUN_SQL: &str = "(reference LIKE 'run%' AND instr(reference, '/') = 0)";
56
The statement is a month at a time, a line per kind of charge57/// The order lines appear in within a group.
58pub(crate) fn kind_order(kind: &str) -> u8 {
59 match kind {
60 "Agent runs" => 0,
Usage, Billing settings and prepaid AI credit; fixes from the UX audit61 "Agent rate" => 0,
Merge branch 'model-routing'62 "Agent rate, your own model key" => 0,
Usage, Billing settings and prepaid AI credit; fixes from the UX audit63 "AI Gateway" => 1,
The statement is a month at a time, a line per kind of charge64 "Runs on your own model provider" => 1,
65 "Sandbox time" => 2,
Fast pages, required checks on the branch, self-hosted runners, honest incidents66 "Self-hosted runner time" => 2,
The statement is a month at a time, a line per kind of charge67 "Deployments" => 3,
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put68 "Private storage" => 4,
Fast pages, required checks on the branch, self-hosted runners, honest incidents69 "Actions cache storage" => 4,
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look70 "Git operations" => 5,
71 "Search embeddings" => 6,
72 "Security scans" => 7,
Usage, Billing settings and prepaid AI credit; fixes from the UX audit73 "Custom domains" => 3,
74 "Package storage" => 4,
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look75 "Payments" => 8,
Usage, Billing settings and prepaid AI credit; fixes from the UX audit76 "AI credit" => 8,
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look77 "Credits from g1t" => 9,
78 "Refunds" => 10,
79 _ => 11,
The statement is a month at a time, a line per kind of charge80 }
81}
82
Billing: credits with a kind and expiry, discounts instead of comped, and safer charging83/// Payments, credits and refunds: money in, which has no price.
84pub(crate) fn is_money_in(kind: &str) -> bool {
Usage, Billing settings and prepaid AI credit; fixes from the UX audit85 matches!(kind, "Payments" | "AI credit" | "Credits from g1t" | "Refunds")
Billing: credits with a kind and expiry, discounts instead of comped, and safer charging86}
87
88/// A usage line at its price: what was charged, what paid for it first,
89/// and what the account's discount took off.
90pub(crate) fn line_price(charged: i64, covered: i64, discount: i64) -> i64 {
91 charged + covered + discount
92}
93
status.g1t.sh with incident management, invites that land you in the workspace, settings as pages, usage without quotas94/// The Billing page's meters, in order: key and label.
95pub(crate) const METERS: [(&str, &str); 6] = [
96 ("agents", "Agents & sandboxes"),
97 ("builds", "Builds"),
98 ("requests", "Requests & CPU"),
99 ("domains", "Custom domains"),
100 ("git_storage", "Git operations & storage"),
101 ("search_scans", "Search & security scans"),
102];
103
104/// The meter a ledger row's usage is on. One SQL expression, as `KIND_SQL`.
105pub(crate) const METER_SQL: &str = "CASE
106 WHEN task = 'deployments' AND reference LIKE 'deploy/%' THEN 'builds'
107 WHEN task = 'deployments' THEN 'requests'
Fast pages, required checks on the branch, self-hosted runners, honest incidents108 WHEN task IN ('storage', 'git', 'cache') THEN 'git_storage'
status.g1t.sh with incident management, invites that land you in the workspace, settings as pages, usage without quotas109 WHEN task IN ('security', 'context') THEN 'search_scans'
110 ELSE 'agents' END";
111
112/// The meter usage noted through the month (`pending_usage.source`) is on.
113pub(crate) fn meter_of_source(source: &str) -> &'static str {
114 match source {
115 "deployments" => "requests",
116 "domains" => "domains",
Fast pages, required checks on the branch, self-hosted runners, honest incidents117 "storage" | "git" | "cache" => "git_storage",
status.g1t.sh with incident management, invites that land you in the workspace, settings as pages, usage without quotas118 _ => "search_scans",
119 }
120}
121
122/// `41 build minutes`, from seconds, rounded up.
123pub(crate) fn build_minutes(seconds: i64) -> Option<String> {
124 let minutes = (seconds.max(0) + 59) / 60;
125 (seconds > 0).then(|| format!("{} build minute{}", crate::features::thousands(minutes as u64), if minutes == 1 { "" } else { "s" }))
126}
127
128/// `12 runs`.
129pub(crate) fn runs(count: u32) -> Option<String> {
130 (count > 0).then(|| format!("{} run{}", crate::features::thousands(count.into()), if count == 1 { "" } else { "s" }))
131}
132
133/// `12,345 git operations, 0.42 GB private`.
134pub(crate) fn git_and_storage(operations: u64, private_bytes: i64) -> Option<String> {
135 let mut parts = vec![];
136 if operations > 0 {
137 parts.push(format!("{} git operation{}", crate::features::thousands(operations), if operations == 1 { "" } else { "s" }));
138 }
139 if private_bytes > 0 {
140 parts.push(format!("{:.2} GB private", private_bytes as f64 / 1e9));
141 }
142 (!parts.is_empty()).then(|| parts.join(", "))
143}
144
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put145/// What paid for usage before it was charged, as the statement names it,
146/// with the ledger column that holds it.
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look147pub(crate) const COVERED: [(&str, &str, &str); 4] = [
148 ("included", "credit_micros", "Paid by your plan's included usage"),
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put149 ("trial", "trial_micros", "Paid by your trial credit"),
150 ("oss_pool", "oss_micros", "Paid by g1t's open-source pool"),
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look151 ("given", "given_micros", "Covered by g1t"),
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put152];
153
154/// The statement's lines for what paid: each source with anything to show.
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look155pub(crate) fn covered_lines(sums: [i64; 4]) -> Vec<Covered> {
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put156 COVERED
157 .iter()
158 .zip(sums)
159 .filter(|(_, micros)| *micros > 0)
160 .map(|((source, _, label), micros)| Covered { source: (*source).to_owned(), label: (*label).to_owned(), micros })
161 .collect()
162}
163
The statement is a month at a time, a line per kind of charge164/// `2026-10` and the first instant of the next month, for a range.
165pub(crate) fn month_range(month: &str) -> Option<(String, String)> {
166 let year: i32 = month.get(..4)?.parse().ok()?;
167 let number: u32 = month.get(5..7)?.parse().ok()?;
168 if month.len() != 7 || !(1..=12).contains(&number) {
169 return None;
170 }
171 let next = if number == 12 { format!("{}-01", year + 1) } else { format!("{year}-{:02}", number + 1) };
172 Some((format!("{month}-01"), format!("{next}-01")))
173}
174
175#[derive(Deserialize)]
176struct Row {
177 group_key: Option<String>,
178 kind: String,
179 count: u32,
180 amount: Option<i64>,
181 cost: Option<i64>,
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put182 credit: Option<i64>,
183 trial: Option<i64>,
184 oss: Option<i64>,
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look185 given: Option<i64>,
Billing: credits with a kind and expiry, discounts instead of comped, and safer charging186 discount: Option<i64>,
The statement is a month at a time, a line per kind of charge187}
188
189#[derive(Deserialize)]
190struct Month {
191 month: String,
192}
193
194impl Billing {
195 pub(crate) async fn statement(&self, a: StatementArgs) -> Result<Outcome<Statement>> {
196 let workspace = a.workspace.to_lowercase();
197 if !a.viewer.is_some_and(|viewer| viewer.is_member(&workspace)) {
198 return Ok(members_only());
199 }
200 let current = rfc3339(now_ms())[..7].to_owned();
201 let month = a.month.filter(|m| month_range(m).is_some()).unwrap_or(current);
202 let (from, until) = month_range(&month).expect("a valid month");
203 let by_project = a.group.as_deref() == Some("project");
204 let group_sql = if by_project { "COALESCE(repo, '')" } else { "substr(created_at, 1, 10)" };
205 let rows = self
206 .db
207 .prepare(format!(
208 "SELECT {group_sql} AS group_key, {KIND_SQL} AS kind, COUNT(*) AS count,
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put209 SUM(amount_micros) AS amount, SUM(cost_micros) AS cost,
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look210 SUM(credit_micros) AS credit, SUM(trial_micros) AS trial, SUM(oss_micros) AS oss,
Billing: credits with a kind and expiry, discounts instead of comped, and safer charging211 SUM(given_micros) AS given, SUM(discount_micros) AS discount
The statement is a month at a time, a line per kind of charge212 FROM ledger WHERE workspace = ?1 AND created_at >= ?2 AND created_at < ?3
213 GROUP BY 1, 2"
214 ))
215 .bind(&[workspace.as_str().into(), from.as_str().into(), until.as_str().into()])?
216 .all()
217 .await?
218 .results::<Row>()?;
219
220 let mut groups: Vec<StatementGroup> = vec![];
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look221 let mut covered = [0i64; 4];
The statement is a month at a time, a line per kind of charge222 for row in rows {
223 let key = row.group_key.unwrap_or_default();
224 let amount = row.amount.unwrap_or(0);
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look225 let paid_for = [row.credit.unwrap_or(0), row.trial.unwrap_or(0), row.oss.unwrap_or(0), row.given.unwrap_or(0)];
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put226 for (total, micros) in covered.iter_mut().zip(paid_for) {
227 *total += micros;
228 }
Billing: credits with a kind and expiry, discounts instead of comped, and safer charging229 let discount = row.discount.unwrap_or(0);
The statement is a month at a time, a line per kind of charge230 let line = StatementLine {
231 // Charges positive, money in negative, as a statement reads.
232 charged_micros: -amount,
233 cost_micros: row.cost.unwrap_or(0),
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put234 covered_micros: paid_for.iter().sum(),
Billing: credits with a kind and expiry, discounts instead of comped, and safer charging235 price_micros: if is_money_in(&row.kind) { 0 } else { line_price(-amount, paid_for.iter().sum(), discount) },
236 discount_micros: discount,
237 kind: row.kind,
238 count: row.count,
The statement is a month at a time, a line per kind of charge239 };
240 match groups.iter_mut().find(|g| g.key == key) {
241 Some(group) => group.lines.push(line),
242 None => groups.push(StatementGroup {
243 label: if key.is_empty() { "Not one project".to_owned() } else { key.clone() },
244 key,
245 lines: vec![line],
246 charged_micros: 0,
Billing: credits with a kind and expiry, discounts instead of comped, and safer charging247 price_micros: 0,
248 discount_micros: 0,
The statement is a month at a time, a line per kind of charge249 }),
250 }
251 }
252 for group in &mut groups {
253 group.lines.sort_by_key(|line| kind_order(&line.kind));
254 group.charged_micros = group.lines.iter().filter(|l| l.charged_micros > 0).map(|l| l.charged_micros).sum();
Billing: credits with a kind and expiry, discounts instead of comped, and safer charging255 group.price_micros = group.lines.iter().map(|l| l.price_micros).sum();
256 group.discount_micros = group.lines.iter().map(|l| l.discount_micros).sum();
The statement is a month at a time, a line per kind of charge257 }
258 if by_project {
Billing keeps Stripe's view itself: the saved card on the account, missed events replayed every 15 minutes, and the endpoint kept259 groups.sort_by_key(|a| std::cmp::Reverse(a.charged_micros));
The statement is a month at a time, a line per kind of charge260 } else {
261 groups.sort_by(|a, b| b.key.cmp(&a.key));
262 }
263 let lines = groups.iter().flat_map(|g| g.lines.iter());
264 let totals = StatementTotals {
265 charged_micros: lines.clone().filter(|l| l.charged_micros > 0).map(|l| l.charged_micros).sum(),
266 paid_micros: lines.clone().filter(|l| l.charged_micros < 0).map(|l| -l.charged_micros).sum(),
267 cost_micros: lines.clone().map(|l| l.cost_micros).sum(),
Billing: credits with a kind and expiry, discounts instead of comped, and safer charging268 price_micros: lines.clone().map(|l| l.price_micros).sum(),
269 discount_micros: lines.clone().map(|l| l.discount_micros).sum(),
270 discount_percent: Some(self.terms_of(&workspace).await?.percent_off()).filter(|p| *p > 0),
The statement is a month at a time, a line per kind of charge271 entries: lines.map(|l| l.count).sum(),
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put272 covered: covered_lines(covered),
273 carried_micros: self.carried(&workspace, &month).await?,
The statement is a month at a time, a line per kind of charge274 };
275 let months = self
276 .db
277 .prepare("SELECT DISTINCT substr(created_at, 1, 7) AS month FROM ledger WHERE workspace = ? ORDER BY 1 DESC LIMIT 36")
278 .bind(&[workspace.as_str().into()])?
279 .all()
280 .await?
281 .results::<Month>()?
282 .into_iter()
283 .map(|m| m.month)
284 .collect();
285 Ok(Outcome::Ok(Statement { month, months, groups, totals }))
286 }
287
status.g1t.sh with incident management, invites that land you in the workspace, settings as pages, usage without quotas288 /// `usage_meters`: this month's usage by meter, at cost plus the margin
289 /// (with a custom discount, if the account has one) before the plan's
290 /// included usage or a pool paid for any of it. Comped workspaces see
291 /// what it would cost. Usage charged through the month is on the
292 /// ledger; usage charged when the month closes (app traffic, custom
293 /// domains, storage, git operations, search and scans) is what has been
294 /// noted so far.
295 pub(crate) async fn usage_meters(&self, a: UsageMetersArgs) -> Result<Outcome<Vec<MeterUsage>>> {
296 let workspace = a.workspace.to_lowercase();
297 if !a.viewer.is_some_and(|viewer| viewer.is_member(&workspace)) {
298 return Ok(members_only());
299 }
300 let now = rfc3339(now_ms());
301 let month = now[..7].to_owned();
302 let (from, until) = month_range(&month).expect("a valid month");
303 #[derive(Deserialize)]
304 struct Used {
305 meter: String,
306 count: u32,
Usage, Billing settings and prepaid AI credit; fixes from the UX audit307 price: Option<f64>,
status.g1t.sh with incident management, invites that land you in the workspace, settings as pages, usage without quotas308 }
309 // A month's close for deployments is charged in the next month;
310 // it is last month's, so it is left out here.
311 let ledger = self
312 .db
313 .prepare(format!(
Usage, Billing settings and prepaid AI credit; fixes from the UX audit314 "SELECT {METER_SQL} AS meter, SUM(CASE WHEN {RUN_SQL} THEN 1 ELSE 0 END) AS count, SUM({PRICE_SQL}) AS price
status.g1t.sh with incident management, invites that land you in the workspace, settings as pages, usage without quotas315 FROM ledger WHERE workspace = ?1 AND kind = 'usage' AND created_at >= ?2 AND created_at < ?3
316 AND COALESCE(reference, '') NOT LIKE 'deployments/%'
Billing and Usage reconcile: own-provider runs leave Billing's at-price total, and Usage's not-charged part is at price less charged317 -- Runs on the workspace's own model provider are its provider's to bill, never g1t's.
318 AND COALESCE(billed_to, 'g1t') = 'g1t'
status.g1t.sh with incident management, invites that land you in the workspace, settings as pages, usage without quotas319 GROUP BY 1"
320 ))
321 .bind(&[workspace.as_str().into(), from.as_str().into(), until.as_str().into()])?
322 .all()
323 .await?
324 .results::<Used>()?;
325 #[derive(Deserialize)]
326 struct Pending {
327 source: String,
328 cost_micros: Option<f64>,
329 detail: Option<String>,
330 }
331 let pending = self
332 .db
333 .prepare("SELECT source, cost_micros, detail FROM pending_usage WHERE workspace = ? AND month = ? AND charged_at IS NULL")
334 .bind(&[workspace.as_str().into(), month.as_str().into()])?
335 .all()
336 .await?
337 .results::<Pending>()?;
Usage, Billing settings and prepaid AI credit; fixes from the UX audit338 // At price, before any discount, as every page shows usage: the
339 // ledger's lines as they were charged, and what is metered so far
340 // at cost plus the margin.
341 let price = |cost: i64| crate::credits::with_margin(cost, self.margin_percent);
status.g1t.sh with incident management, invites that land you in the workspace, settings as pages, usage without quotas342 let mut meters: Vec<MeterUsage> = METERS
343 .iter()
344 .map(|(key, label)| MeterUsage { key: (*key).to_owned(), label: (*label).to_owned(), micros: 0, quantity: None })
345 .collect();
346 let mut agent_runs = 0;
347 for used in ledger {
348 if let Some(meter) = meters.iter_mut().find(|m| m.key == used.meter) {
Usage, Billing settings and prepaid AI credit; fixes from the UX audit349 meter.micros += used.price.unwrap_or(0.0).round() as i64;
status.g1t.sh with incident management, invites that land you in the workspace, settings as pages, usage without quotas350 }
351 if used.meter == "agents" {
352 agent_runs = used.count;
353 }
354 }
355 for row in &pending {
356 let key = meter_of_source(&row.source);
357 if let Some(meter) = meters.iter_mut().find(|m| m.key == key) {
358 meter.micros += price(row.cost_micros.unwrap_or(0.0).round() as i64);
359 if matches!(key, "requests" | "domains") {
360 meter.quantity = row.detail.clone().filter(|d| !d.is_empty());
361 }
362 }
363 }
364 let build_seconds = self.allowance_used("build_seconds", &workspace, &month).await?;
365 let operations = self.git_operations_this_month(&workspace).await?;
366 let stored = self.private_storage(&workspace).await?;
367 for meter in &mut meters {
368 match meter.key.as_str() {
369 "agents" => meter.quantity = runs(agent_runs),
370 "builds" => meter.quantity = build_minutes(build_seconds),
371 "git_storage" => meter.quantity = git_and_storage(operations, stored),
372 _ => {}
373 }
374 }
375 Ok(Outcome::Ok(meters))
376 }
377
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put378 /// What was owed when `month` closed but was under the minimum charge,
379 /// and so carried over to the next invoice.
380 async fn carried(&self, workspace: &str, month: &str) -> Result<i64> {
381 #[derive(Deserialize)]
382 struct Row {
383 amount_micros: i64,
384 }
385 Ok(self
386 .db
387 .prepare("SELECT amount_micros FROM month_closes WHERE workspace = ? AND month = ? AND status = 'carried'")
388 .bind(&[workspace.into(), month.into()])?
389 .first::<Row>(None)
390 .await?
391 .map_or(0, |row| row.amount_micros))
392 }
393
The statement is a month at a time, a line per kind of charge394 /// One line's entries, newest first, a page at a time.
395 pub(crate) async fn statement_entries(&self, a: StatementEntriesArgs) -> Result<Outcome<Vec<LedgerEntry>>> {
396 let workspace = a.workspace.to_lowercase();
397 if !a.viewer.is_some_and(|viewer| viewer.is_member(&workspace)) {
398 return Ok(members_only());
399 }
400 let Some((from, until)) = month_range(&a.month) else {
401 return Ok(Outcome::Ok(vec![]));
402 };
403 let mut filters = vec![format!("({KIND_SQL}) = ?4")];
404 let mut values: Vec<JsValue> = vec![
405 workspace.as_str().into(),
406 from.as_str().into(),
407 until.as_str().into(),
408 a.kind.as_str().into(),
409 ];
410 if let Some(day) = a.day.as_deref().filter(|d| d.len() == 10) {
411 values.push(day.into());
412 filters.push(format!("substr(created_at, 1, 10) = ?{}", values.len()));
413 }
414 if let Some(project) = &a.project {
415 values.push(project.as_str().into());
416 filters.push(format!("COALESCE(repo, '') = ?{}", values.len()));
417 }
418 if let Some(before) = &a.before {
419 values.push(before.as_str().into());
420 filters.push(format!("id < ?{}", values.len()));
421 }
422 let rows = self
423 .db
424 .prepare(format!(
425 "SELECT * FROM ledger WHERE workspace = ?1 AND created_at >= ?2 AND created_at < ?3 AND {}
426 ORDER BY id DESC LIMIT {PAGE}",
427 filters.join(" AND ")
428 ))
429 .bind(&values)?
430 .all()
431 .await?
432 .results::<LedgerRow>()?;
433 Ok(Outcome::Ok(rows.into_iter().map(LedgerEntry::from).collect()))
434 }
435}
436
437#[cfg(test)]
438mod tests {
439 use super::*;
440
441 #[test]
442 fn a_month_runs_to_the_first_of_the_next() {
443 assert_eq!(month_range("2026-10"), Some(("2026-10-01".into(), "2026-11-01".into())));
444 assert_eq!(month_range("2026-12"), Some(("2026-12-01".into(), "2027-01-01".into())));
445 assert_eq!(month_range("2026-13"), None);
446 assert_eq!(month_range("oops"), None);
447 }
448
449 #[test]
Billing: credits with a kind and expiry, discounts instead of comped, and safer charging450 fn a_discounted_line_shows_its_price_and_the_discount() {
451 // $1.20 of usage on a 100% discount: charged nothing, all of it off.
452 assert_eq!(line_price(0, 0, 1_200_000), 1_200_000);
453 // 30% off, $0.20 of it paid by included usage first.
454 assert_eq!(line_price(700_000, 140_000, 360_000), 1_200_000);
455 assert!(is_money_in("Payments") && is_money_in("Credits from g1t") && is_money_in("Refunds"));
456 assert!(!is_money_in("Agent runs"));
457 }
458
459 #[test]
The statement is a month at a time, a line per kind of charge460 fn usage_lines_come_before_money_in() {
461 assert!(kind_order("Agent runs") < kind_order("Sandbox time"));
462 assert!(kind_order("Deployments") < kind_order("Payments"));
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put463 assert!(kind_order("Security scans") < kind_order("Payments"));
464 }
465
466 #[test]
status.g1t.sh with incident management, invites that land you in the workspace, settings as pages, usage without quotas467 fn usage_falls_on_the_meters_the_billing_page_shows() {
468 let keys: Vec<_> = METERS.iter().map(|(key, _)| *key).collect();
469 assert_eq!(keys, ["agents", "builds", "requests", "domains", "git_storage", "search_scans"]);
470 assert_eq!(meter_of_source("deployments"), "requests");
471 assert_eq!(meter_of_source("domains"), "domains");
472 assert_eq!(meter_of_source("git"), "git_storage");
473 assert_eq!(meter_of_source("storage"), "git_storage");
474 assert_eq!(meter_of_source("context"), "search_scans");
475 assert_eq!(meter_of_source("security"), "search_scans");
476 for key in ["builds", "requests", "git_storage", "search_scans", "agents"] {
477 assert!(METER_SQL.contains(&format!("'{key}'")));
478 }
479 }
480
481 #[test]
482 fn quantities_read_plainly() {
483 assert_eq!(build_minutes(0), None);
484 assert_eq!(build_minutes(1).as_deref(), Some("1 build minute"));
485 assert_eq!(build_minutes(2_461).as_deref(), Some("42 build minutes"));
486 assert_eq!(runs(1).as_deref(), Some("1 run"));
487 assert_eq!(runs(1_200).as_deref(), Some("1,200 runs"));
488 assert_eq!(git_and_storage(0, 0), None);
489 assert_eq!(git_and_storage(12_345, 420_000_000).as_deref(), Some("12,345 git operations, 0.42 GB private"));
490 assert_eq!(git_and_storage(1, 0).as_deref(), Some("1 git operation"));
491 }
492
493 #[test]
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put494 fn the_statement_says_what_paid_before_the_workspace_did() {
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look495 let lines = covered_lines([0, 250_000, 120_000, 0]);
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put496 assert_eq!(lines.len(), 2);
497 assert_eq!(lines[0].label, "Paid by your trial credit");
498 assert_eq!(lines[1], Covered { source: "oss_pool".into(), label: "Paid by g1t's open-source pool".into(), micros: 120_000 });
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look499 assert!(covered_lines([0, 0, 0, 0]).is_empty());
500 let lines = covered_lines([4_000_000, 0, 0, 30_000]);
501 assert_eq!(lines[0].label, "Paid by your plan's included usage");
502 assert_eq!(lines[1].label, "Covered by g1t");
The statement is a month at a time, a line per kind of charge503 }
504}

This file's history is long; its oldest lines are credited to the oldest commit read.