Skip to content
463 linesCodeBlameRaw
1//! 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
38/// 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
96#[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())) };
143 let owed = (-account.balance_micros).max(0);
144 // Only a month's close charges no less than the minimum
145 // (`MIN_CHARGE_MICROS`), so a payment's fee is never most of it;
146 // less carries over. A charge because a limit was reached always
147 // goes through, whatever its size, so a new workspace's limit never
148 // strands it.
149 if reason == "month" && !crate::limits::worth_charging(owed, self.plans.min_charge_micros) {
150 return Ok(Err(format!(
151 "{} is owed, under the {} minimum charge; it carries over to the next invoice.",
152 crate::features::dollars(owed),
153 crate::features::dollars(self.plans.min_charge_micros)
154 )));
155 }
156 // What was used since the last invoice, by kind.
157 #[derive(Deserialize)]
158 struct Last {
159 through_at: Option<String>,
160 }
161 let since = self
162 .db
163 .prepare("SELECT MAX(through_at) AS through_at FROM workspace_invoices WHERE workspace = ? AND status <> 'void'")
164 .bind(&[workspace.into()])?
165 .first::<Last>(None)
166 .await?
167 .and_then(|l| l.through_at)
168 .unwrap_or_default();
169 #[derive(Deserialize)]
170 struct Used {
171 kind: String,
172 charged: Option<i64>,
173 }
174 let now = rfc3339(now_ms());
175 let used: Vec<(String, i64)> = self
176 .db
177 .prepare(
178 "SELECT CASE
179 WHEN task = 'sandbox' THEN 'Sandbox time'
180 WHEN task = 'self_hosted' THEN 'Self-hosted runner time'
181 WHEN task = 'deployments' THEN 'Deployments: builds and usage past the plan'
182 WHEN task = 'security' THEN 'Security scans'
183 WHEN task = 'context' THEN 'Search embeddings'
184 WHEN task = 'storage' THEN 'Private repository storage'
185 WHEN task = 'git' THEN 'Git operations'
186 WHEN billed_to = 'workspace' THEN 'Runs on your own model provider'
187 ELSE 'Agents on g1t''s models' END AS kind,
188 -SUM(amount_micros) AS charged
189 FROM ledger WHERE workspace = ? AND kind = 'usage' AND created_at > ? AND created_at <= ?
190 GROUP BY 1 ORDER BY charged DESC",
191 )
192 .bind(&[workspace.into(), since.as_str().into(), now.as_str().into()])?
193 .all()
194 .await?
195 .results::<Used>()?
196 .into_iter()
197 .map(|u| (u.kind, u.charged.unwrap_or(0)))
198 .collect();
199 let lines = invoice_lines(&used, owed);
200 let key = format!("ws-invoice/{workspace}/{reason}/{period}/{}", owed / 10_000);
201 let description = match reason {
202 "month" => format!("g1t usage for {workspace}, {period}"),
203 _ => format!("g1t usage for {workspace}, charged as it neared its limit"),
204 };
205 // The draft first, then its lines on it: lines left pending on the
206 // customer by an attempt that failed half way would otherwise be
207 // swept into the next invoice (this one's retry with a different
208 // total, or the plan's renewal) on top of their own new lines.
209 let draft: StripeInvoice =
210 stripe.post_idempotent("/invoices", &draft_fields(&customer, workspace, reason, period, description), &key).await?;
211 let cents = line_cents(&lines);
212 for (position, (line, cents)) in lines.iter().zip(&cents).enumerate() {
213 let fields = item_fields(&customer, &draft.id, workspace, &line.description, *cents);
214 let _: Value = stripe.post_idempotent("/invoiceitems", &fields, &format!("{key}/item/{position}")).await?;
215 }
216 // A retry finds it finalized already; that is fine.
217 let _ = stripe.post::<Value>(&format!("/invoices/{}/finalize", draft.id), &[]).await;
218 // Charge the card now; a decline comes back as an error.
219 let paid = stripe.post::<StripeInvoice>(&format!("/invoices/{}/pay", draft.id), &[("off_session", "true".to_owned())]).await;
220 let invoice: StripeInvoice = stripe.get(&format!("/invoices/{}", draft.id)).await?;
221 let total = lines.iter().map(|l| l.amount_micros).sum::<i64>();
222 let status = if invoice.status.as_deref() == Some("paid") { "paid" } else { "failed" };
223 // Only the card saying no is a decline, which stops work until it
224 // is paid. Stripe failing to answer, or answering busy, is g1t's
225 // problem and never stops a payer: the invoice stays as it is, and
226 // the next attempt (the same total finds the same invoice) pays it.
227 if status == "failed" && !paid.as_ref().err().is_some_and(|error| is_decline(&error.to_string())) {
228 return Ok(Err("The card processor did not finish the payment; it is tried again.".into()));
229 }
230 let mut writes = vec![self
231 .db
232 .prepare(
233 "INSERT OR REPLACE INTO workspace_invoices
234 (invoice_id, workspace, reason, period, amount_micros, status, hosted_url, pdf_url, through_at, created_at, paid_at)
235 VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
236 )
237 .bind(&[
238 invoice.id.as_str().into(),
239 workspace.into(),
240 reason.into(),
241 period.into(),
242 (total as f64).into(),
243 status.into(),
244 crate::optional(invoice.hosted_invoice_url.as_deref()),
245 crate::optional(invoice.invoice_pdf.as_deref()),
246 now.as_str().into(),
247 now.as_str().into(),
248 crate::optional((status == "paid").then_some(now.as_str())),
249 ])?];
250 for (position, line) in lines.iter().enumerate() {
251 writes.push(
252 self.db
253 .prepare("INSERT OR REPLACE INTO workspace_invoice_lines (invoice_id, position, description, amount_micros) VALUES (?, ?, ?, ?)")
254 .bind(&[invoice.id.as_str().into(), (position as u32).into(), line.description.as_str().into(), (line.amount_micros as f64).into()])?,
255 );
256 }
257 self.db.batch(writes).await?;
258 if status == "paid" {
259 self.credit_invoice(workspace, &invoice).await?;
260 } else {
261 let error = paid.err().map_or_else(|| "the card was declined".to_owned(), |e| e.to_string().chars().take(200).collect());
262 self.mark_declined(workspace, &error).await?;
263 }
264 Ok(Ok(WorkspaceInvoice {
265 invoice_id: invoice.id,
266 workspace: workspace.to_owned(),
267 reason: reason.to_owned(),
268 period: period.to_owned(),
269 amount_micros: total,
270 status: status.to_owned(),
271 hosted_url: invoice.hosted_invoice_url,
272 pdf_url: invoice.invoice_pdf,
273 lines,
274 created_at: now,
275 }))
276 }
277
278 /// Enters an invoice's payment once, with the kind of card that paid.
279 async fn credit_invoice(&self, workspace: &str, invoice: &StripeInvoice) -> Result<bool> {
280 let seen = self
281 .db
282 .prepare("SELECT id FROM ledger WHERE reference = ?")
283 .bind(&[invoice.id.as_str().into()])?
284 .first::<Value>(None)
285 .await?;
286 if seen.is_some() {
287 return Ok(false);
288 }
289 let amount = invoice.amount_paid * 10_000;
290 if amount <= 0 {
291 return Ok(false);
292 }
293 self.enter(workspace, EntryKind::TopUp, amount, &format!("Paid invoice {}", invoice.id), &invoice.id, None, None, None, None)
294 .await?;
295 // Prepaid cards pay, but never raise the limit.
296 if let (Some(stripe), Some(charge)) = (&self.stripe, &invoice.charge)
297 && let Ok(charge) = stripe.get::<Value>(&format!("/charges/{charge}")).await
298 && let Some(funding) = charge["payment_method_details"]["card"]["funding"].as_str() {
299 self.db
300 .prepare("UPDATE ledger SET funding = ? WHERE reference = ?")
301 .bind(&[funding.into(), invoice.id.as_str().into()])?
302 .run()
303 .await?;
304 }
305 Ok(true)
306 }
307
308 pub(crate) async fn mark_declined(&self, workspace: &str, error: &str) -> Result<()> {
309 let now = rfc3339(now_ms());
310 self.db
311 .prepare(
312 "INSERT INTO limits (workspace, autopay_failed_at, autopay_error, updated_at) VALUES (?1, ?2, ?3, ?2)
313 ON CONFLICT (workspace) DO UPDATE SET autopay_failed_at = ?2, autopay_error = ?3, updated_at = ?2",
314 )
315 .bind(&[workspace.into(), now.as_str().into(), error.into()])?
316 .run()
317 .await?;
318 Ok(())
319 }
320
321 /// A workspace invoice paid later, on Stripe's page or by a retry.
322 pub(crate) async fn workspace_invoice_paid(&self, invoice_id: &str) -> Result<Option<String>> {
323 #[derive(Deserialize)]
324 struct Row {
325 workspace: String,
326 }
327 let Some(row) = self
328 .db
329 .prepare("SELECT workspace FROM workspace_invoices WHERE invoice_id = ?")
330 .bind(&[invoice_id.into()])?
331 .first::<Row>(None)
332 .await?
333 else {
334 return Ok(None);
335 };
336 let Some(stripe) = &self.stripe else { return Ok(None) };
337 let invoice: StripeInvoice = stripe.get(&format!("/invoices/{invoice_id}")).await?;
338 self.db
339 .prepare("UPDATE workspace_invoices SET status = 'paid', paid_at = ? WHERE invoice_id = ?")
340 .bind(&[rfc3339(now_ms()).into(), invoice_id.into()])?
341 .run()
342 .await?;
343 let credited = self.credit_invoice(&row.workspace, &invoice).await?;
344 Ok(Some(format!(
345 "invoice {invoice_id} for {} paid{}",
346 row.workspace,
347 if credited { "" } else { " (already credited)" }
348 )))
349 }
350
351 pub(crate) async fn workspace_invoices(&self, workspace: &str) -> Result<Vec<WorkspaceInvoice>> {
352 let rows = self
353 .db
354 .prepare("SELECT * FROM workspace_invoices WHERE workspace = ? ORDER BY created_at DESC LIMIT 36")
355 .bind(&[workspace.into()])?
356 .all()
357 .await?
358 .results::<InvoiceRow>()?;
359 let mut invoices = vec![];
360 for row in rows {
361 let lines = self
362 .db
363 .prepare("SELECT description, amount_micros FROM workspace_invoice_lines WHERE invoice_id = ? ORDER BY position")
364 .bind(&[row.invoice_id.as_str().into()])?
365 .all()
366 .await?
367 .results::<LineRow>()?
368 .into_iter()
369 .map(|l| InvoiceItem { description: l.description, amount_micros: l.amount_micros })
370 .collect();
371 invoices.push(WorkspaceInvoice {
372 invoice_id: row.invoice_id,
373 workspace: row.workspace,
374 reason: row.reason,
375 period: row.period,
376 amount_micros: row.amount_micros,
377 status: row.status,
378 hosted_url: row.hosted_url,
379 pdf_url: row.pdf_url,
380 lines,
381 created_at: row.created_at,
382 });
383 }
384 Ok(invoices)
385 }
386
387 /// `invoices`: for the workspace's members.
388 pub(crate) async fn invoices(&self, a: InvoicesArgs) -> Result<Outcome<Vec<WorkspaceInvoice>>> {
389 let workspace = a.workspace.to_lowercase();
390 if !a.viewer.is_some_and(|viewer| viewer.is_member(&workspace)) {
391 return Ok(Outcome::fail(FailureCode::Forbidden, "Only members can see a workspace's invoices."));
392 }
393 Ok(Outcome::Ok(self.workspace_invoices(&workspace).await?))
394 }
395}
396
397#[cfg(test)]
398mod tests {
399 use super::*;
400
401 #[test]
402 fn an_invoice_adds_up_to_what_is_owed() {
403 let used = vec![("Agents on g1t's models".to_owned(), 40_000_000), ("Sandbox time".to_owned(), 10_000_000)];
404 // $10 of credit was paid in advance.
405 let lines = invoice_lines(&used, 40_000_000);
406 assert_eq!(lines.last().unwrap().description, "Paid in advance");
407 assert_eq!(lines.iter().map(|l| l.amount_micros).sum::<i64>(), 40_000_000);
408 // $5 was left unpaid from before.
409 let lines = invoice_lines(&used, 55_000_000);
410 assert_eq!(lines.last().unwrap().description, "Unpaid from earlier");
411 assert_eq!(lines.iter().map(|l| l.amount_micros).sum::<i64>(), 55_000_000);
412 // Exactly what was used.
413 assert_eq!(invoice_lines(&used, 50_000_000).len(), 2);
414 }
415
416 #[test]
417 fn an_invoice_holds_only_its_own_lines() {
418 let draft = draft_fields("cus_1", "acme", "month", "2026-09", "g1t usage".to_owned());
419 assert!(draft.contains(&("pending_invoice_items_behavior", "exclude".to_owned())));
420 let item = item_fields("cus_1", "in_1", "acme", "Sandbox time", 1_234);
421 assert!(item.contains(&("invoice", "in_1".to_owned())));
422 assert!(item.contains(&("amount", "1234".to_owned())));
423 }
424
425 #[test]
426 fn only_the_card_saying_no_is_a_decline() {
427 let declined = r#"the card processor answered 402: {"error": {"code": "card_declined", "type": "card_error"}}"#;
428 assert!(is_decline(declined));
429 assert!(is_decline(r#"the card processor answered 400: {"error": {"type": "card_error"}}"#));
430 // Stripe down, busy or failing, or the network: tried again, nobody stopped.
431 assert!(!is_decline(r#"the card processor answered 500: {"error": {"type": "api_error"}}"#));
432 assert!(!is_decline(r#"the card processor answered 429: {"error": {"type": "rate_limit_error"}}"#));
433 assert!(!is_decline("Network connection lost."));
434 }
435
436 fn items(micros: &[i64]) -> Vec<InvoiceItem> {
437 micros.iter().map(|&amount_micros| InvoiceItem { description: String::new(), amount_micros }).collect()
438 }
439
440 #[test]
441 fn the_card_is_charged_what_is_owed_rounded_up_to_the_cent_never_down() {
442 // $1.234567 + $2.345678 = $3.580245 owed: 359 cents, where cutting
443 // each line would have charged 357.
444 let cents = line_cents(&items(&[1_234_567, 2_345_678]));
445 assert_eq!(cents.iter().sum::<i64>(), 359);
446 assert_eq!(cents, vec![124, 235]);
447 // Whole cents stay as they are.
448 assert_eq!(line_cents(&items(&[40_000_000, 10_000_000])), vec![4_000, 1_000]);
449 // A credit line keeps its full credit; the total still rounds up.
450 // $50.004 used, $10.0025 paid in advance: $40.0015 owed, 4,001 cents.
451 let cents = line_cents(&items(&[50_004_000, -10_002_500]));
452 assert_eq!(cents.iter().sum::<i64>(), 4_001);
453 // Lines under a cent each add up to the cents they make together.
454 let cents = line_cents(&items(&[4_000, 4_000, 4_000]));
455 assert_eq!(cents.iter().sum::<i64>(), 2);
456 // Every invoice the close makes: never less than owed, never a cent more.
457 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)] {
458 let lines = invoice_lines(&used, owed);
459 let charged = line_cents(&lines).iter().sum::<i64>() * 10_000;
460 assert!(charged >= owed && charged - owed < 10_000, "{charged} for {owed}");
461 }
462 }
463}