Skip to content

g1t/services/billing/src/invoices.rs

465 lines21,518 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.

Two limits, real invoices, trust that grows by itself, sales signals1//! A workspace's invoices from g1t.
2//!
3//! Every time g1t charges a workspace's card, it is a real Stripe invoice:
4//! when each month closes, and when the workspace nears its limit mid-month
5//! (a threshold invoice, as Cloudflare and Fly do). Each is itemised by
6//! what was used since the last one, with any credit paid in advance taken
7//! off and anything left unpaid from before added, so its total is exactly
8//! what is owed. Stripe charges the card, emails the receipt, and keeps
9//! the invoice and its PDF in the workspace's billing page.
10
11use g1t_contracts::billing::{EntryKind, InvoiceItem, InvoicesArgs, WorkspaceInvoice};
12use g1t_contracts::time::rfc3339;
13use g1t_contracts::{FailureCode, Outcome};
14use g1t_kit::now_ms;
15use serde::Deserialize;
16use serde_json::Value;
17use worker::Result;
18
19use crate::Billing;
20
21/// The invoice's lines: what was used since the last one, by kind, then
22/// whatever makes the total what is owed.
23pub(crate) fn invoice_lines(used: &[(String, i64)], owed: i64) -> Vec<InvoiceItem> {
24 let mut lines: Vec<InvoiceItem> = used
25 .iter()
26 .filter(|(_, amount)| *amount > 0)
27 .map(|(kind, amount)| InvoiceItem { description: kind.clone(), amount_micros: *amount })
28 .collect();
29 let difference = owed - lines.iter().map(|l| l.amount_micros).sum::<i64>();
30 if difference < 0 {
31 lines.push(InvoiceItem { description: "Paid in advance".to_owned(), amount_micros: difference });
32 } else if difference > 0 {
33 lines.push(InvoiceItem { description: "Unpaid from earlier".to_owned(), amount_micros: difference });
34 }
35 lines
36}
37
Billing: credits with a kind and expiry, discounts instead of comped, and safer charging38/// Each line in whole cents, for the card processor. Their sum is what is
39/// owed rounded up to the next cent, never down: cutting each line to a
40/// cent on its own would charge up to a cent less per line than is owed (and
41/// a credit line a cent less of a credit), and leave the rest stranded under
42/// the minimum charge. The cent each needs is given to the lines with the
43/// largest fractions first.
44pub(crate) fn line_cents(lines: &[InvoiceItem]) -> Vec<i64> {
45 const MICROS_PER_CENT: i64 = 10_000;
46 let total: i64 = lines.iter().map(|l| l.amount_micros).sum();
47 let total_cents = total.div_euclid(MICROS_PER_CENT) + i64::from(total.rem_euclid(MICROS_PER_CENT) > 0);
48 let mut cents: Vec<i64> = lines.iter().map(|l| l.amount_micros.div_euclid(MICROS_PER_CENT)).collect();
49 let mut short = total_cents - cents.iter().sum::<i64>();
50 let mut by_fraction: Vec<usize> = (0..lines.len()).collect();
51 by_fraction.sort_by_key(|&i| std::cmp::Reverse(lines[i].amount_micros.rem_euclid(MICROS_PER_CENT)));
52 for i in by_fraction {
53 if short <= 0 || lines[i].amount_micros.rem_euclid(MICROS_PER_CENT) == 0 {
54 break;
55 }
56 cents[i] += 1;
57 short -= 1;
58 }
59 cents
60}
61
62/// Whether paying an invoice failed because the card said no (Stripe's
63/// 402, a `card_error`), rather than because Stripe could not be reached,
64/// was busy or failed itself. Only a decline stops a workspace's work.
65pub(crate) fn is_decline(error: &str) -> bool {
66 error.contains("answered 402") || error.contains("\"card_error\"")
67}
68
69/// A workspace invoice's draft: charged to the card, and holding only the
70/// lines put on it, never whatever is pending on the customer.
71fn draft_fields(customer: &str, workspace: &str, reason: &str, period: &str, description: String) -> Vec<(&'static str, String)> {
72 vec![
73 ("customer", customer.to_owned()),
74 ("collection_method", "charge_automatically".to_owned()),
75 ("auto_advance", "false".to_owned()),
76 ("pending_invoice_items_behavior", "exclude".to_owned()),
77 ("description", description),
78 ("metadata[g1t_workspace]", workspace.to_owned()),
79 ("metadata[reason]", reason.to_owned()),
80 ("metadata[period]", period.to_owned()),
81 ]
82}
83
84/// One line, on the draft `invoice`.
85fn item_fields(customer: &str, invoice: &str, workspace: &str, description: &str, cents: i64) -> Vec<(&'static str, String)> {
86 vec![
87 ("customer", customer.to_owned()),
88 ("invoice", invoice.to_owned()),
89 ("amount", cents.to_string()),
90 ("currency", "usd".to_owned()),
91 ("description", description.to_owned()),
92 ("metadata[workspace]", workspace.to_owned()),
93 ]
94}
95
Two limits, real invoices, trust that grows by itself, sales signals96#[derive(Deserialize)]
97struct InvoiceRow {
98 invoice_id: String,
99 workspace: String,
100 reason: String,
101 period: String,
102 amount_micros: i64,
103 status: String,
104 hosted_url: Option<String>,
105 pdf_url: Option<String>,
106 created_at: String,
107}
108
109#[derive(Deserialize)]
110struct LineRow {
111 description: String,
112 amount_micros: i64,
113}
114
115/// A Stripe invoice, as far as billing reads it.
116#[derive(Deserialize)]
117struct StripeInvoice {
118 id: String,
119 #[serde(default)]
120 status: Option<String>,
121 #[serde(default)]
122 hosted_invoice_url: Option<String>,
123 #[serde(default)]
124 invoice_pdf: Option<String>,
125 #[serde(default)]
126 amount_paid: i64,
127 #[serde(default)]
128 charge: Option<String>,
129}
130
131impl Billing {
132 /// Invoices the workspace for what it owes, charging its card. `Ok(Err)`
133 /// says why not, when there was nothing to do or no card.
134 pub(crate) async fn invoice_workspace(
135 &self,
136 workspace: &str,
137 reason: &str,
138 period: &str,
139 ) -> Result<std::result::Result<WorkspaceInvoice, String>> {
140 let Some(stripe) = &self.stripe else { return Ok(Err("Payments are not set up.".into())) };
141 let Some(account) = self.row(workspace).await? else { return Ok(Err("Nothing billed yet.".into())) };
142 let Some(customer) = account.customer_id else { return Ok(Err("No card on file.".into())) };
Usage, Billing settings and prepaid AI credit; fixes from the UX audit143 // AI credit left props up the balance but pays only for models: it
144 // is not money for anything else (ai.rs).
145 let owed = self.owed_with(workspace, account.balance_micros).await?;
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look146 // Only a month's close charges no less than the minimum
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put147 // (`MIN_CHARGE_MICROS`), so a payment's fee is never most of it;
148 // less carries over. A charge because a limit was reached always
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look149 // goes through, whatever its size, so a new workspace's limit never
150 // strands it.
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put151 if reason == "month" && !crate::limits::worth_charging(owed, self.plans.min_charge_micros) {
152 return Ok(Err(format!(
153 "{} is owed, under the {} minimum charge; it carries over to the next invoice.",
154 crate::features::dollars(owed),
155 crate::features::dollars(self.plans.min_charge_micros)
156 )));
Two limits, real invoices, trust that grows by itself, sales signals157 }
158 // What was used since the last invoice, by kind.
159 #[derive(Deserialize)]
160 struct Last {
161 through_at: Option<String>,
162 }
163 let since = self
164 .db
165 .prepare("SELECT MAX(through_at) AS through_at FROM workspace_invoices WHERE workspace = ? AND status <> 'void'")
166 .bind(&[workspace.into()])?
167 .first::<Last>(None)
168 .await?
169 .and_then(|l| l.through_at)
170 .unwrap_or_default();
171 #[derive(Deserialize)]
172 struct Used {
173 kind: String,
174 charged: Option<i64>,
175 }
176 let now = rfc3339(now_ms());
177 let used: Vec<(String, i64)> = self
178 .db
179 .prepare(
180 "SELECT CASE
181 WHEN task = 'sandbox' THEN 'Sandbox time'
Fast pages, required checks on the branch, self-hosted runners, honest incidents182 WHEN task = 'self_hosted' THEN 'Self-hosted runner time'
Two limits, real invoices, trust that grows by itself, sales signals183 WHEN task = 'deployments' THEN 'Deployments: builds and usage past the plan'
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put184 WHEN task = 'security' THEN 'Security scans'
185 WHEN task = 'context' THEN 'Search embeddings'
186 WHEN task = 'storage' THEN 'Private repository storage'
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look187 WHEN task = 'git' THEN 'Git operations'
Two limits, real invoices, trust that grows by itself, sales signals188 WHEN billed_to = 'workspace' THEN 'Runs on your own model provider'
189 ELSE 'Agents on g1t''s models' END AS kind,
190 -SUM(amount_micros) AS charged
191 FROM ledger WHERE workspace = ? AND kind = 'usage' AND created_at > ? AND created_at <= ?
192 GROUP BY 1 ORDER BY charged DESC",
193 )
194 .bind(&[workspace.into(), since.as_str().into(), now.as_str().into()])?
195 .all()
196 .await?
197 .results::<Used>()?
198 .into_iter()
199 .map(|u| (u.kind, u.charged.unwrap_or(0)))
200 .collect();
201 let lines = invoice_lines(&used, owed);
202 let key = format!("ws-invoice/{workspace}/{reason}/{period}/{}", owed / 10_000);
203 let description = match reason {
204 "month" => format!("g1t usage for {workspace}, {period}"),
205 _ => format!("g1t usage for {workspace}, charged as it neared its limit"),
206 };
Billing: credits with a kind and expiry, discounts instead of comped, and safer charging207 // The draft first, then its lines on it: lines left pending on the
208 // customer by an attempt that failed half way would otherwise be
209 // swept into the next invoice (this one's retry with a different
210 // total, or the plan's renewal) on top of their own new lines.
211 let draft: StripeInvoice =
212 stripe.post_idempotent("/invoices", &draft_fields(&customer, workspace, reason, period, description), &key).await?;
213 let cents = line_cents(&lines);
214 for (position, (line, cents)) in lines.iter().zip(&cents).enumerate() {
215 let fields = item_fields(&customer, &draft.id, workspace, &line.description, *cents);
216 let _: Value = stripe.post_idempotent("/invoiceitems", &fields, &format!("{key}/item/{position}")).await?;
217 }
Two limits, real invoices, trust that grows by itself, sales signals218 // A retry finds it finalized already; that is fine.
219 let _ = stripe.post::<Value>(&format!("/invoices/{}/finalize", draft.id), &[]).await;
220 // Charge the card now; a decline comes back as an error.
221 let paid = stripe.post::<StripeInvoice>(&format!("/invoices/{}/pay", draft.id), &[("off_session", "true".to_owned())]).await;
222 let invoice: StripeInvoice = stripe.get(&format!("/invoices/{}", draft.id)).await?;
223 let total = lines.iter().map(|l| l.amount_micros).sum::<i64>();
224 let status = if invoice.status.as_deref() == Some("paid") { "paid" } else { "failed" };
Billing: credits with a kind and expiry, discounts instead of comped, and safer charging225 // Only the card saying no is a decline, which stops work until it
226 // is paid. Stripe failing to answer, or answering busy, is g1t's
227 // problem and never stops a payer: the invoice stays as it is, and
228 // the next attempt (the same total finds the same invoice) pays it.
229 if status == "failed" && !paid.as_ref().err().is_some_and(|error| is_decline(&error.to_string())) {
230 return Ok(Err("The card processor did not finish the payment; it is tried again.".into()));
231 }
Two limits, real invoices, trust that grows by itself, sales signals232 let mut writes = vec![self
233 .db
234 .prepare(
235 "INSERT OR REPLACE INTO workspace_invoices
236 (invoice_id, workspace, reason, period, amount_micros, status, hosted_url, pdf_url, through_at, created_at, paid_at)
237 VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
238 )
239 .bind(&[
240 invoice.id.as_str().into(),
241 workspace.into(),
242 reason.into(),
243 period.into(),
244 (total as f64).into(),
245 status.into(),
246 crate::optional(invoice.hosted_invoice_url.as_deref()),
247 crate::optional(invoice.invoice_pdf.as_deref()),
248 now.as_str().into(),
249 now.as_str().into(),
250 crate::optional((status == "paid").then_some(now.as_str())),
251 ])?];
252 for (position, line) in lines.iter().enumerate() {
253 writes.push(
254 self.db
255 .prepare("INSERT OR REPLACE INTO workspace_invoice_lines (invoice_id, position, description, amount_micros) VALUES (?, ?, ?, ?)")
256 .bind(&[invoice.id.as_str().into(), (position as u32).into(), line.description.as_str().into(), (line.amount_micros as f64).into()])?,
257 );
258 }
259 self.db.batch(writes).await?;
260 if status == "paid" {
261 self.credit_invoice(workspace, &invoice).await?;
262 } else {
263 let error = paid.err().map_or_else(|| "the card was declined".to_owned(), |e| e.to_string().chars().take(200).collect());
264 self.mark_declined(workspace, &error).await?;
265 }
266 Ok(Ok(WorkspaceInvoice {
267 invoice_id: invoice.id,
268 workspace: workspace.to_owned(),
269 reason: reason.to_owned(),
270 period: period.to_owned(),
271 amount_micros: total,
272 status: status.to_owned(),
273 hosted_url: invoice.hosted_invoice_url,
274 pdf_url: invoice.invoice_pdf,
275 lines,
276 created_at: now,
277 }))
278 }
279
280 /// Enters an invoice's payment once, with the kind of card that paid.
281 async fn credit_invoice(&self, workspace: &str, invoice: &StripeInvoice) -> Result<bool> {
282 let seen = self
283 .db
284 .prepare("SELECT id FROM ledger WHERE reference = ?")
285 .bind(&[invoice.id.as_str().into()])?
286 .first::<Value>(None)
287 .await?;
288 if seen.is_some() {
289 return Ok(false);
290 }
291 let amount = invoice.amount_paid * 10_000;
292 if amount <= 0 {
293 return Ok(false);
294 }
295 self.enter(workspace, EntryKind::TopUp, amount, &format!("Paid invoice {}", invoice.id), &invoice.id, None, None, None, None)
296 .await?;
297 // Prepaid cards pay, but never raise the limit.
Billing keeps Stripe's view itself: the saved card on the account, missed events replayed every 15 minutes, and the endpoint kept298 if let (Some(stripe), Some(charge)) = (&self.stripe, &invoice.charge)
299 && let Ok(charge) = stripe.get::<Value>(&format!("/charges/{charge}")).await
300 && let Some(funding) = charge["payment_method_details"]["card"]["funding"].as_str() {
Two limits, real invoices, trust that grows by itself, sales signals301 self.db
302 .prepare("UPDATE ledger SET funding = ? WHERE reference = ?")
303 .bind(&[funding.into(), invoice.id.as_str().into()])?
304 .run()
305 .await?;
306 }
307 Ok(true)
308 }
309
310 pub(crate) async fn mark_declined(&self, workspace: &str, error: &str) -> Result<()> {
311 let now = rfc3339(now_ms());
312 self.db
313 .prepare(
314 "INSERT INTO limits (workspace, autopay_failed_at, autopay_error, updated_at) VALUES (?1, ?2, ?3, ?2)
315 ON CONFLICT (workspace) DO UPDATE SET autopay_failed_at = ?2, autopay_error = ?3, updated_at = ?2",
316 )
317 .bind(&[workspace.into(), now.as_str().into(), error.into()])?
318 .run()
319 .await?;
320 Ok(())
321 }
322
323 /// A workspace invoice paid later, on Stripe's page or by a retry.
324 pub(crate) async fn workspace_invoice_paid(&self, invoice_id: &str) -> Result<Option<String>> {
325 #[derive(Deserialize)]
326 struct Row {
327 workspace: String,
328 }
329 let Some(row) = self
330 .db
331 .prepare("SELECT workspace FROM workspace_invoices WHERE invoice_id = ?")
332 .bind(&[invoice_id.into()])?
333 .first::<Row>(None)
334 .await?
335 else {
336 return Ok(None);
337 };
338 let Some(stripe) = &self.stripe else { return Ok(None) };
339 let invoice: StripeInvoice = stripe.get(&format!("/invoices/{invoice_id}")).await?;
340 self.db
341 .prepare("UPDATE workspace_invoices SET status = 'paid', paid_at = ? WHERE invoice_id = ?")
342 .bind(&[rfc3339(now_ms()).into(), invoice_id.into()])?
343 .run()
344 .await?;
345 let credited = self.credit_invoice(&row.workspace, &invoice).await?;
346 Ok(Some(format!(
347 "invoice {invoice_id} for {} paid{}",
348 row.workspace,
349 if credited { "" } else { " (already credited)" }
350 )))
351 }
352
353 pub(crate) async fn workspace_invoices(&self, workspace: &str) -> Result<Vec<WorkspaceInvoice>> {
354 let rows = self
355 .db
356 .prepare("SELECT * FROM workspace_invoices WHERE workspace = ? ORDER BY created_at DESC LIMIT 36")
357 .bind(&[workspace.into()])?
358 .all()
359 .await?
360 .results::<InvoiceRow>()?;
361 let mut invoices = vec![];
362 for row in rows {
363 let lines = self
364 .db
365 .prepare("SELECT description, amount_micros FROM workspace_invoice_lines WHERE invoice_id = ? ORDER BY position")
366 .bind(&[row.invoice_id.as_str().into()])?
367 .all()
368 .await?
369 .results::<LineRow>()?
370 .into_iter()
371 .map(|l| InvoiceItem { description: l.description, amount_micros: l.amount_micros })
372 .collect();
373 invoices.push(WorkspaceInvoice {
374 invoice_id: row.invoice_id,
375 workspace: row.workspace,
376 reason: row.reason,
377 period: row.period,
378 amount_micros: row.amount_micros,
379 status: row.status,
380 hosted_url: row.hosted_url,
381 pdf_url: row.pdf_url,
382 lines,
383 created_at: row.created_at,
384 });
385 }
386 Ok(invoices)
387 }
388
389 /// `invoices`: for the workspace's members.
390 pub(crate) async fn invoices(&self, a: InvoicesArgs) -> Result<Outcome<Vec<WorkspaceInvoice>>> {
391 let workspace = a.workspace.to_lowercase();
392 if !a.viewer.is_some_and(|viewer| viewer.is_member(&workspace)) {
393 return Ok(Outcome::fail(FailureCode::Forbidden, "Only members can see a workspace's invoices."));
394 }
395 Ok(Outcome::Ok(self.workspace_invoices(&workspace).await?))
396 }
397}
398
399#[cfg(test)]
400mod tests {
401 use super::*;
402
403 #[test]
404 fn an_invoice_adds_up_to_what_is_owed() {
405 let used = vec![("Agents on g1t's models".to_owned(), 40_000_000), ("Sandbox time".to_owned(), 10_000_000)];
406 // $10 of credit was paid in advance.
407 let lines = invoice_lines(&used, 40_000_000);
408 assert_eq!(lines.last().unwrap().description, "Paid in advance");
409 assert_eq!(lines.iter().map(|l| l.amount_micros).sum::<i64>(), 40_000_000);
410 // $5 was left unpaid from before.
411 let lines = invoice_lines(&used, 55_000_000);
412 assert_eq!(lines.last().unwrap().description, "Unpaid from earlier");
413 assert_eq!(lines.iter().map(|l| l.amount_micros).sum::<i64>(), 55_000_000);
414 // Exactly what was used.
415 assert_eq!(invoice_lines(&used, 50_000_000).len(), 2);
416 }
Billing: credits with a kind and expiry, discounts instead of comped, and safer charging417
418 #[test]
419 fn an_invoice_holds_only_its_own_lines() {
420 let draft = draft_fields("cus_1", "acme", "month", "2026-09", "g1t usage".to_owned());
421 assert!(draft.contains(&("pending_invoice_items_behavior", "exclude".to_owned())));
422 let item = item_fields("cus_1", "in_1", "acme", "Sandbox time", 1_234);
423 assert!(item.contains(&("invoice", "in_1".to_owned())));
424 assert!(item.contains(&("amount", "1234".to_owned())));
425 }
426
427 #[test]
428 fn only_the_card_saying_no_is_a_decline() {
429 let declined = r#"the card processor answered 402: {"error": {"code": "card_declined", "type": "card_error"}}"#;
430 assert!(is_decline(declined));
431 assert!(is_decline(r#"the card processor answered 400: {"error": {"type": "card_error"}}"#));
432 // Stripe down, busy or failing, or the network: tried again, nobody stopped.
433 assert!(!is_decline(r#"the card processor answered 500: {"error": {"type": "api_error"}}"#));
434 assert!(!is_decline(r#"the card processor answered 429: {"error": {"type": "rate_limit_error"}}"#));
435 assert!(!is_decline("Network connection lost."));
436 }
437
438 fn items(micros: &[i64]) -> Vec<InvoiceItem> {
439 micros.iter().map(|&amount_micros| InvoiceItem { description: String::new(), amount_micros }).collect()
440 }
441
442 #[test]
443 fn the_card_is_charged_what_is_owed_rounded_up_to_the_cent_never_down() {
444 // $1.234567 + $2.345678 = $3.580245 owed: 359 cents, where cutting
445 // each line would have charged 357.
446 let cents = line_cents(&items(&[1_234_567, 2_345_678]));
447 assert_eq!(cents.iter().sum::<i64>(), 359);
448 assert_eq!(cents, vec![124, 235]);
449 // Whole cents stay as they are.
450 assert_eq!(line_cents(&items(&[40_000_000, 10_000_000])), vec![4_000, 1_000]);
451 // A credit line keeps its full credit; the total still rounds up.
452 // $50.004 used, $10.0025 paid in advance: $40.0015 owed, 4,001 cents.
453 let cents = line_cents(&items(&[50_004_000, -10_002_500]));
454 assert_eq!(cents.iter().sum::<i64>(), 4_001);
455 // Lines under a cent each add up to the cents they make together.
456 let cents = line_cents(&items(&[4_000, 4_000, 4_000]));
457 assert_eq!(cents.iter().sum::<i64>(), 2);
458 // Every invoice the close makes: never less than owed, never a cent more.
459 for (used, owed) in [(vec![("a".to_owned(), 7_777_777), ("b".to_owned(), 3)], 6_000_001), (vec![("a".to_owned(), 5_000_001)], 5_000_001)] {
460 let lines = invoice_lines(&used, owed);
461 let charged = line_cents(&lines).iter().sum::<i64>() * 10_000;
462 assert!(charged >= owed && charged - owed < 10_000, "{charged} for {owed}");
463 }
464 }
Two limits, real invoices, trust that grows by itself, sales signals465}