Skip to content

Where people and agents ship software together. The open-source git platform for the whole job: issues, agents, checks and deploys to the edge.

957 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;
18use worker::wasm_bindgen::JsValue;
19
20use crate::Billing;
21
22/// The invoice's lines: what was used since the last one, by kind, then
23/// whatever makes the total what is owed.
24pub(crate) fn invoice_lines(used: &[(String, i64)], owed: i64) -> Vec<InvoiceItem> {
25 let mut lines: Vec<InvoiceItem> = used
26 .iter()
27 .filter(|(_, amount)| *amount > 0)
28 .map(|(kind, amount)| InvoiceItem { description: kind.clone(), amount_micros: *amount })
29 .collect();
30 let difference = owed - lines.iter().map(|l| l.amount_micros).sum::<i64>();
31 if difference < 0 {
32 lines.push(InvoiceItem { description: "Paid in advance".to_owned(), amount_micros: difference });
33 } else if difference > 0 {
34 lines.push(InvoiceItem { description: "Unpaid from earlier".to_owned(), amount_micros: difference });
35 }
36 lines
37}
38
39/// Each line in whole cents, for the card processor. Their sum is what is
40/// owed rounded up to the next cent, never down: cutting each line to a
41/// cent on its own would charge up to a cent less per line than is owed (and
42/// a credit line a cent less of a credit), and leave the rest stranded under
43/// the minimum charge. The cent each needs is given to the lines with the
44/// largest fractions first.
45pub(crate) fn line_cents(lines: &[InvoiceItem]) -> Vec<i64> {
46 const MICROS_PER_CENT: i64 = 10_000;
47 let total: i64 = lines.iter().map(|l| l.amount_micros).sum();
48 let total_cents = total.div_euclid(MICROS_PER_CENT) + i64::from(total.rem_euclid(MICROS_PER_CENT) > 0);
49 let mut cents: Vec<i64> = lines.iter().map(|l| l.amount_micros.div_euclid(MICROS_PER_CENT)).collect();
50 let mut short = total_cents - cents.iter().sum::<i64>();
51 let mut by_fraction: Vec<usize> = (0..lines.len()).collect();
52 by_fraction.sort_by_key(|&i| std::cmp::Reverse(lines[i].amount_micros.rem_euclid(MICROS_PER_CENT)));
53 for i in by_fraction {
54 if short <= 0 || lines[i].amount_micros.rem_euclid(MICROS_PER_CENT) == 0 {
55 break;
56 }
57 cents[i] += 1;
58 short -= 1;
59 }
60 cents
61}
62
63/// Whether paying an invoice failed because the card said no (Stripe's
64/// 402, a `card_error`), rather than because Stripe could not be reached,
65/// was busy or failed itself. Only a decline stops a workspace's work.
66pub(crate) fn is_decline(error: &str) -> bool {
67 error.contains("answered 402") || error.contains("\"card_error\"")
68}
69
70/// The HTTP status in an error from the card processor ("the card
71/// processor answered 400: …"), if it is one.
72fn answered(error: &str) -> Option<u16> {
73 let rest = error.split_once("the card processor answered ")?.1;
74 rest.get(..3)?.parse().ok()
75}
76
77/// Whether Stripe refused to charge for good, for want of a way to pay:
78/// a 400 or 404 `invalid_request_error` (no default payment method, a
79/// payment method gone or unusable off session, and the like). Trying
80/// again never changes that, so it stops like a decline, with Stripe's
81/// reason. A 5xx, a 429 or no answer at all is tried again, and so is a
82/// 401 or 403: g1t's key, never the payer's card.
83pub(crate) fn needs_card(error: &str) -> bool {
84 matches!(answered(error), Some(400 | 404)) && error.contains("\"invalid_request_error\"")
85}
86
87/// Stripe's own sentence in an error, else the error, short.
88pub(crate) fn stripe_reason(error: &str) -> String {
89 error
90 .split_once(": ")
91 .and_then(|(_, body)| serde_json::from_str::<Value>(body).ok())
92 .and_then(|body| body["error"]["message"].as_str().map(str::to_owned))
93 .unwrap_or_else(|| error.to_owned())
94 .chars()
95 .take(200)
96 .collect()
97}
98
99/// What charging an invoice came to.
100#[derive(Debug, PartialEq, Eq)]
101pub(crate) enum PayOutcome {
102 Paid,
103 /// The card said no: work stops until it is paid.
104 Declined,
105 /// Stripe will not charge it at all (no card it can use): work stops
106 /// until one is added and it is paid, as for a decline.
107 NeedsCard,
108 /// Voided or marked uncollectible at Stripe meanwhile: never to be paid.
109 Void,
110 /// Stripe did not answer, or failed: tried again, nobody stopped.
111 Retry,
112}
113
114/// What charging an invoice came to, from the invoice's status after the
115/// attempt and the error the attempt came back with, if any.
116pub(crate) fn pay_outcome(status: Option<&str>, error: Option<&str>) -> PayOutcome {
117 match status {
118 Some("paid") => PayOutcome::Paid,
119 Some("void" | "uncollectible") => PayOutcome::Void,
120 _ => match error {
121 Some(error) if is_decline(error) => PayOutcome::Declined,
122 Some(error) if needs_card(error) => PayOutcome::NeedsCard,
123 _ => PayOutcome::Retry,
124 },
125 }
126}
127
128/// The idempotency key of a workspace invoice's draft and lines: the same
129/// workspace, customer, reason, period and total is the same invoice
130/// however often it is attempted, until one of its invoices is paid
131/// (`paid_today` counts the workspace's invoices paid that day) or voided
132/// (`voided` counts them), when the next is a new one. With the customer
133/// in it, a key never comes back with another customer's fields, which
134/// Stripe refuses.
135pub(crate) fn invoice_key(workspace: &str, customer: &str, reason: &str, period: &str, owed: i64, paid_today: u32, voided: u32) -> String {
136 let key = format!("ws-invoice/{workspace}/{customer}/{reason}/{period}/{}/p{paid_today}", owed / 10_000);
137 if voided == 0 { key } else { format!("{key}/v{voided}") }
138}
139
140/// Whether `viewer` may see a workspace's invoices: its owners and billing
141/// managers, as for its billing details; never any other member.
142pub(crate) fn may_see_invoices(viewer: &g1t_contracts::Viewer, workspace: &str) -> bool {
143 viewer.as_ref().is_some_and(|viewer| viewer.manages_billing(workspace))
144}
145
146/// What settling a workspace's unpaid invoices came to.
147pub(crate) enum Settled {
148 /// None is left unpaid; the last one paid now, if any.
149 Clear(Option<WorkspaceInvoice>),
150 /// One is still unpaid (declined, no card, or Stripe not finished):
151 /// nothing else is invoiced until it is paid.
152 Stop(std::result::Result<WorkspaceInvoice, String>),
153}
154
155#[derive(Deserialize)]
156struct Count {
157 n: Option<f64>,
158}
159
160/// A workspace invoice's draft: charged to the card, taxed by Stripe Tax,
161/// and holding only the lines put on it, never whatever is pending on the
162/// customer.
163fn draft_fields(customer: &str, workspace: &str, reason: &str, period: &str, description: String) -> Vec<(&'static str, String)> {
164 let mut fields = vec![
165 ("customer", customer.to_owned()),
166 ("collection_method", "charge_automatically".to_owned()),
167 ("auto_advance", "false".to_owned()),
168 ("pending_invoice_items_behavior", "exclude".to_owned()),
169 ("description", description),
170 ("metadata[g1t_workspace]", workspace.to_owned()),
171 ("metadata[reason]", reason.to_owned()),
172 ("metadata[period]", period.to_owned()),
173 ];
174 fields.extend(crate::stripe::invoice_tax_fields());
175 fields
176}
177
178/// One line, on the draft `invoice`, at g1t's tax code, excluding tax.
179fn item_fields(customer: &str, invoice: &str, workspace: &str, description: &str, cents: i64) -> Vec<(&'static str, String)> {
180 let mut fields = vec![
181 ("customer", customer.to_owned()),
182 ("invoice", invoice.to_owned()),
183 ("amount", cents.to_string()),
184 ("currency", "usd".to_owned()),
185 ("description", description.to_owned()),
186 ("metadata[workspace]", workspace.to_owned()),
187 ];
188 fields.extend(crate::stripe::item_tax_fields());
189 fields
190}
191
192/// Whether Stripe left an invoice a draft because Stripe Tax could not
193/// place the customer.
194pub(crate) fn needs_tax_location(invoice: &Value) -> bool {
195 invoice["automatic_tax"]["status"].as_str() == Some("requires_location_inputs")
196}
197
198#[derive(Deserialize)]
199struct InvoiceRow {
200 invoice_id: String,
201 workspace: String,
202 reason: String,
203 period: String,
204 amount_micros: i64,
205 status: String,
206 hosted_url: Option<String>,
207 pdf_url: Option<String>,
208 created_at: String,
209 #[serde(default)]
210 fee_micros: i64,
211 #[serde(default)]
212 tax_micros: i64,
213}
214
215#[derive(Deserialize)]
216struct LineRow {
217 description: String,
218 amount_micros: i64,
219}
220
221/// A Stripe invoice, as far as billing reads it.
222#[derive(Deserialize)]
223struct StripeInvoice {
224 id: String,
225 #[serde(default)]
226 status: Option<String>,
227 #[serde(default)]
228 hosted_invoice_url: Option<String>,
229 #[serde(default)]
230 invoice_pdf: Option<String>,
231 #[serde(default)]
232 amount_paid: i64,
233 #[serde(default)]
234 charge: Option<String>,
235 #[serde(default)]
236 payment_intent: Option<String>,
237 /// The tax Stripe added, in cents (`tax`, in this API version).
238 #[serde(default)]
239 tax: Option<i64>,
240}
241
242impl StripeInvoice {
243 fn tax_cents(&self) -> i64 {
244 self.tax.unwrap_or(0).max(0)
245 }
246}
247
248impl Billing {
249 /// Invoices the workspace for what it owes, charging its card. `Ok(Err)`
250 /// says why not, when there was nothing to do or no card.
251 pub(crate) async fn invoice_workspace(
252 &self,
253 workspace: &str,
254 reason: &str,
255 period: &str,
256 ) -> Result<std::result::Result<WorkspaceInvoice, String>> {
257 let Some(stripe) = &self.stripe else { return Ok(Err("Payments are not set up.".into())) };
258 if self.row(workspace).await?.and_then(|row| row.customer_id).is_none() {
259 return Ok(Err("No card on file.".into()));
260 }
261 // An invoice already sent and not paid is paid (or found paid, or
262 // found voided) before any other is made: two invoices for the same
263 // money would charge it twice. Once all are paid, what is owed
264 // beyond them is invoiced too; one still unpaid stops here.
265 let settled = match self.settle_unpaid_invoices(workspace).await? {
266 Settled::Clear(paid) => paid,
267 Settled::Stop(unpaid) => return Ok(unpaid),
268 };
269 // Read again: paying an earlier invoice credited the balance.
270 let Some(account) = self.row(workspace).await? else { return Ok(Err("Nothing billed yet.".into())) };
271 let Some(customer) = account.customer_id else { return Ok(Err("No card on file.".into())) };
272 // AI credit left (bought before g1t stopped selling it) props up the
273 // balance but pays only for models: it is not money for anything else.
274 let owed = self.owed_with(workspace, account.balance_micros).await?;
275 // Nothing owed is nothing to invoice, whatever the reason: a limit
276 // reached on usage not entered yet is not a charge. An earlier
277 // invoice paid just now is what this came to.
278 if owed <= 0 {
279 return Ok(settled.ok_or_else(|| "Nothing is owed.".to_owned()));
280 }
281 // Only a month's close charges no less than the minimum
282 // (`MIN_CHARGE_MICROS`), so a payment's fee is never most of it;
283 // less carries over. A charge because a limit was reached always
284 // goes through, whatever its size, so a new workspace's limit never
285 // strands it.
286 if reason == "month" && !crate::limits::worth_charging(owed, self.plans.min_charge_micros) {
287 if let Some(paid) = settled {
288 return Ok(Ok(paid));
289 }
290 return Ok(Err(format!(
291 "{} is owed, under the {} minimum charge; it carries over to the next invoice.",
292 crate::features::dollars(owed),
293 crate::features::dollars(self.plans.min_charge_micros)
294 )));
295 }
296 // What was used since the last invoice, by kind.
297 #[derive(Deserialize)]
298 struct Last {
299 through_at: Option<String>,
300 }
301 let since = self
302 .db
303 .prepare("SELECT MAX(through_at) AS through_at FROM workspace_invoices WHERE workspace = ? AND status <> 'void'")
304 .bind(&[workspace.into()])?
305 .first::<Last>(None)
306 .await?
307 .and_then(|l| l.through_at)
308 .unwrap_or_default();
309 #[derive(Deserialize)]
310 struct Used {
311 kind: String,
312 charged: Option<i64>,
313 }
314 let now = rfc3339(now_ms());
315 let used: Vec<(String, i64)> = self
316 .db
317 .prepare(
318 "SELECT CASE
319 WHEN task = 'sandbox' AND machine IS NOT NULL THEN 'Runner minutes, ' || machine
320 WHEN task = 'sandbox' THEN 'Sandbox time'
321 WHEN task = 'self_hosted' THEN 'Self-hosted runner time'
322 WHEN task = 'deployments' THEN 'Deployments: builds and usage past the plan'
323 WHEN task = 'security' THEN 'Security scans'
324 WHEN task = 'context' THEN 'Search embeddings'
325 WHEN task = 'storage' THEN 'Private repository storage'
326 WHEN task = 'git' THEN 'Git operations'
327 WHEN task = 'cache' THEN 'Actions cache storage'
328 WHEN task = 'domains' THEN 'Custom domains'
329 WHEN task = 'package_storage' THEN 'Package storage'
330 WHEN task = 'telemetry' THEN 'Observability data'
331 -- From when g1t ran agents and sold model access.
332 WHEN billed_to = 'workspace' THEN 'Runs on your own model provider'
333 WHEN reference LIKE 'run%' OR task = 'gateway' THEN 'Agents on g1t''s models'
334 ELSE 'Other usage' END AS kind,
335 -SUM(amount_micros) AS charged
336 FROM ledger WHERE workspace = ? AND kind = 'usage' AND created_at > ? AND created_at <= ?
337 GROUP BY 1 ORDER BY charged DESC",
338 )
339 .bind(&[workspace.into(), since.as_str().into(), now.as_str().into()])?
340 .all()
341 .await?
342 .results::<Used>()?
343 .into_iter()
344 .map(|u| (u.kind, u.charged.unwrap_or(0)))
345 .collect();
346 let lines = invoice_lines(&used, owed);
347 // Stripe Tax needs to know where the customer is. Without an
348 // address nothing is charged: the owners are asked for one, and the
349 // charge goes through once it is there.
350 match stripe.customer_placed(&customer).await {
351 Ok(true) => {}
352 Ok(false) => {
353 self.tax_address_needed(workspace).await?;
354 return Ok(Err(crate::tax::address_needed_message(workspace)));
355 }
356 // A customer Stripe no longer has: forgotten, so the next card
357 // saved makes a new one.
358 Err(error) if crate::stripe::is_missing(&error) => {
359 self.forget_customer(workspace).await?;
360 return Ok(Err("No card on file.".into()));
361 }
362 Err(error) => return Err(error),
363 }
364 // Each line in cents; no card fee on top, as g1t's prices include it.
365 let cents = line_cents(&lines);
366 // How many of its invoices were voided, and paid today, is part of
367 // the key: one voided at Stripe, or paid, is never handed back for
368 // the same total within the day.
369 let today = &now[..10];
370 let count = |sql: &'static str| async move {
371 Ok::<u32, worker::Error>(
372 self.db
373 .prepare(sql)
374 .bind(&[workspace.into(), today.into()])?
375 .first::<Count>(None)
376 .await?
377 .and_then(|c| c.n)
378 .unwrap_or(0.0) as u32,
379 )
380 };
381 let voided = count("SELECT COUNT(*) AS n FROM workspace_invoices WHERE workspace = ?1 AND status = 'void' AND ?2 IS NOT NULL").await?;
382 let paid_today =
383 count("SELECT COUNT(*) AS n FROM workspace_invoices WHERE workspace = ?1 AND status = 'paid' AND substr(paid_at, 1, 10) = ?2")
384 .await?;
385 let key = invoice_key(workspace, &customer, reason, period, owed, paid_today, voided);
386 let description = match reason {
387 "month" => format!("g1t usage for {workspace}, {period}"),
388 _ => format!("g1t usage for {workspace}, charged as it neared its limit"),
389 };
390 // The draft first, then its lines on it: lines left pending on the
391 // customer by an attempt that failed half way would otherwise be
392 // swept into the next invoice (this one's retry with a different
393 // total, or the plan's renewal) on top of their own new lines.
394 let draft: StripeInvoice =
395 stripe.post_idempotent("/invoices", &draft_fields(&customer, workspace, reason, period, description), &key).await?;
396 for (position, (line, cents)) in lines.iter().zip(&cents).enumerate() {
397 let fields = item_fields(&customer, &draft.id, workspace, &line.description, *cents);
398 let _: Value = stripe.post_idempotent("/invoiceitems", &fields, &format!("{key}/item/{position}")).await?;
399 }
400 // A retry finds it finalized already; that is fine.
401 let finalized = stripe.post::<Value>(&format!("/invoices/{}/finalize", draft.id), &[]).await;
402 if let Err(error) = &finalized
403 && crate::stripe::is_tax_location_error(error)
404 {
405 self.tax_address_needed(workspace).await?;
406 return Ok(Err(crate::tax::address_needed_message(workspace)));
407 }
408 if let Ok(left) = stripe.get::<Value>(&format!("/invoices/{}", draft.id)).await
409 && left["status"].as_str() == Some("draft")
410 && needs_tax_location(&left)
411 {
412 self.tax_address_needed(workspace).await?;
413 return Ok(Err(crate::tax::address_needed_message(workspace)));
414 }
415 self.tax_address_given(workspace).await?;
416 // Kept as open before the card is charged: whatever happens to the
417 // charge, the invoice is known here, so paying it later (on Stripe's
418 // page, or by the next attempt) is credited, and no second invoice
419 // is made for the same money while it is open.
420 let invoice: StripeInvoice = stripe.get(&format!("/invoices/{}", draft.id)).await?;
421 let total = lines.iter().map(|l| l.amount_micros).sum::<i64>();
422 let tax_micros = invoice.tax_cents() * 10_000;
423 let mut writes = vec![self
424 .db
425 .prepare(
426 "INSERT OR REPLACE INTO workspace_invoices
427 (invoice_id, workspace, reason, period, amount_micros, status, hosted_url, pdf_url, through_at, created_at, paid_at,
428 fee_micros, tax_micros)
429 VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
430 )
431 .bind(&[
432 invoice.id.as_str().into(),
433 workspace.into(),
434 reason.into(),
435 period.into(),
436 (total as f64).into(),
437 "open".into(),
438 crate::optional(invoice.hosted_invoice_url.as_deref()),
439 crate::optional(invoice.invoice_pdf.as_deref()),
440 now.as_str().into(),
441 now.as_str().into(),
442 JsValue::NULL,
443 // No card fee on new invoices; the column keeps old ones'.
444 0.into(),
445 (tax_micros as f64).into(),
446 ])?];
447 for (position, line) in lines.iter().enumerate() {
448 writes.push(
449 self.db
450 .prepare("INSERT OR REPLACE INTO workspace_invoice_lines (invoice_id, position, description, amount_micros) VALUES (?, ?, ?, ?)")
451 .bind(&[invoice.id.as_str().into(), (position as u32).into(), line.description.as_str().into(), (line.amount_micros as f64).into()])?,
452 );
453 }
454 self.db.batch(writes).await?;
455 self.pay_invoice(workspace, &invoice.id, 0).await
456 }
457
458 /// Charges the card for an invoice kept as open (or declined before),
459 /// and records what came of it. Paid: credited, then marked paid. The
460 /// card saying no, or Stripe refusing for want of a card it can charge:
461 /// marked failed, and work stops until it is paid. Voided at Stripe
462 /// meanwhile: closed here.
463 /// Stripe failing to answer, or answering busy, is g1t's problem and
464 /// never stops a payer: the invoice stays open, an `Err` says so, and
465 /// the next attempt pays this same invoice.
466 async fn pay_invoice(&self, workspace: &str, invoice_id: &str, fee_cents: i64) -> Result<std::result::Result<WorkspaceInvoice, String>> {
467 let Some(stripe) = &self.stripe else { return Ok(Err("Payments are not set up.".into())) };
468 let paid = stripe.post::<StripeInvoice>(&format!("/invoices/{invoice_id}/pay"), &[("off_session", "true".to_owned())]).await;
469 let invoice: StripeInvoice = stripe.get(&format!("/invoices/{invoice_id}")).await?;
470 let error = paid.as_ref().err().map(ToString::to_string);
471 match pay_outcome(invoice.status.as_deref(), error.as_deref()) {
472 PayOutcome::Paid => {
473 self.credit_invoice(workspace, &invoice, fee_cents).await?;
474 self.db
475 .prepare("UPDATE workspace_invoices SET status = 'paid', paid_at = ?, tax_micros = ? WHERE invoice_id = ?")
476 .bind(&[rfc3339(now_ms()).into(), ((invoice.tax_cents() * 10_000) as f64).into(), invoice_id.into()])?
477 .run()
478 .await?;
479 }
480 PayOutcome::Declined => {
481 self.db
482 .prepare("UPDATE workspace_invoices SET status = 'failed' WHERE invoice_id = ? AND status <> 'paid'")
483 .bind(&[invoice_id.into()])?
484 .run()
485 .await?;
486 let error = error.map_or_else(|| "the card was declined".to_owned(), |e| e.chars().take(200).collect());
487 self.mark_declined(workspace, &error).await?;
488 }
489 PayOutcome::NeedsCard => {
490 self.db
491 .prepare("UPDATE workspace_invoices SET status = 'failed' WHERE invoice_id = ? AND status <> 'paid'")
492 .bind(&[invoice_id.into()])?
493 .run()
494 .await?;
495 let why = format!(
496 "Stripe could not charge the card on file ({}). Add a card on the Billing page.",
497 stripe_reason(error.as_deref().unwrap_or_default()).trim_end_matches('.')
498 );
499 self.mark_declined(workspace, &why).await?;
500 }
501 PayOutcome::Void => {
502 self.void_row(invoice_id).await?;
503 return Ok(Err(format!("Invoice {invoice_id} was voided at Stripe.")));
504 }
505 PayOutcome::Retry => {
506 let why = error.unwrap_or_else(|| format!("invoice is {}", invoice.status.as_deref().unwrap_or("unknown")));
507 return Err(worker::Error::RustError(format!(
508 "{workspace}: the card processor did not finish paying invoice {invoice_id}; it is tried again: {}",
509 why.chars().take(200).collect::<String>()
510 )));
511 }
512 }
513 Ok(self.workspace_invoice(invoice_id).await?.ok_or_else(|| "The invoice was not recorded.".to_owned()))
514 }
515
516 /// Settles the workspace's invoices that were sent but not paid
517 /// (`open`, or `failed` for a decline) before another is made, oldest
518 /// first: found paid at Stripe, credited; voided or gone, closed here;
519 /// still open, charged again. Each paid goes on to the next; the first
520 /// still unpaid after its charge stops it there.
521 async fn settle_unpaid_invoices(&self, workspace: &str) -> Result<Settled> {
522 let Some(stripe) = &self.stripe else { return Ok(Settled::Clear(None)) };
523 #[derive(Deserialize)]
524 struct Unpaid {
525 invoice_id: String,
526 #[serde(default)]
527 fee_micros: i64,
528 }
529 let unpaid = self
530 .db
531 .prepare("SELECT invoice_id, fee_micros FROM workspace_invoices WHERE workspace = ? AND status IN ('open', 'failed') ORDER BY created_at")
532 .bind(&[workspace.into()])?
533 .all()
534 .await?
535 .results::<Unpaid>()?;
536 let mut last_paid = None;
537 for row in unpaid {
538 let found = match stripe.get::<StripeInvoice>(&format!("/invoices/{}", row.invoice_id)).await {
539 Ok(found) => found,
540 // From another Stripe account: never to be paid here.
541 Err(error) if crate::stripe::is_missing(&error) => {
542 self.void_row(&row.invoice_id).await?;
543 continue;
544 }
545 Err(error) => return Err(error),
546 };
547 let charged = match found.status.as_deref() {
548 Some("paid") => {
549 self.workspace_invoice_paid(&row.invoice_id).await?;
550 last_paid = self.workspace_invoice(&row.invoice_id).await?.or(last_paid);
551 continue;
552 }
553 Some("void") | Some("uncollectible") => {
554 self.void_row(&row.invoice_id).await?;
555 continue;
556 }
557 Some("draft") => {
558 // Kept before it was finalized: finalize, then charge.
559 let _ = stripe.post::<Value>(&format!("/invoices/{}/finalize", row.invoice_id), &[]).await;
560 self.pay_invoice(workspace, &row.invoice_id, row.fee_micros / 10_000).await?
561 }
562 _ => self.pay_invoice(workspace, &row.invoice_id, row.fee_micros / 10_000).await?,
563 };
564 match charged {
565 Ok(invoice) if invoice.status == "paid" => last_paid = Some(invoice),
566 // Voided at Stripe as it was charged: closed, on to the next.
567 Err(_) if self.workspace_invoice(&row.invoice_id).await?.is_some_and(|i| i.status == "void") => {}
568 other => return Ok(Settled::Stop(other)),
569 }
570 }
571 Ok(Settled::Clear(last_paid))
572 }
573
574 async fn void_row(&self, invoice_id: &str) -> Result<()> {
575 self.db
576 .prepare("UPDATE workspace_invoices SET status = 'void' WHERE invoice_id = ? AND status <> 'paid'")
577 .bind(&[invoice_id.into()])?
578 .run()
579 .await?;
580 Ok(())
581 }
582
583 /// A late `invoice.payment_failed` for a workspace invoice: the invoice
584 /// is read as it is now, and a decline counts only if it is still
585 /// unpaid (a retry or Stripe's page may have paid it since).
586 pub(crate) async fn workspace_invoice_failed(&self, invoice_id: &str, tagged: &str) -> Result<String> {
587 let Some(stripe) = &self.stripe else { return Ok("ignored: payments off".to_owned()) };
588 let invoice: StripeInvoice = stripe.get(&format!("/invoices/{invoice_id}")).await?;
589 if matches!(invoice.status.as_deref(), Some("paid" | "void" | "uncollectible")) {
590 return Ok(format!("ignored: invoice {invoice_id} is {} now", invoice.status.as_deref().unwrap_or_default()));
591 }
592 // The invoice's own row names the workspace as it is now; the
593 // metadata keeps the slug it was sent under.
594 let workspace = self.workspace_of_invoice(invoice_id).await?.unwrap_or_else(|| tagged.to_owned());
595 self.db
596 .prepare("UPDATE workspace_invoices SET status = 'failed' WHERE invoice_id = ? AND status = 'open'")
597 .bind(&[invoice_id.into()])?
598 .run()
599 .await?;
600 self.mark_declined(&workspace, "the card was declined for an invoice").await?;
601 Ok(format!("{workspace}: invoice payment failed; work stopped"))
602 }
603
604 /// Enters an invoice's payment once, with the kind of card that paid:
605 /// what it paid for usage, never its tax or card fee, which are kept
606 /// apart (`tax_and_fees`).
607 async fn credit_invoice(&self, workspace: &str, invoice: &StripeInvoice, fee_cents: i64) -> Result<bool> {
608 let seen = self
609 .db
610 .prepare("SELECT id FROM ledger WHERE reference = ?")
611 .bind(&[invoice.id.as_str().into()])?
612 .first::<Value>(None)
613 .await?;
614 if seen.is_some() {
615 return Ok(false);
616 }
617 let extras = crate::tax::Extras { tax_cents: invoice.tax_cents(), fee_cents };
618 let amount = (invoice.amount_paid - extras.tax_cents - extras.fee_cents).max(0) * 10_000;
619 if amount <= 0 {
620 return Ok(false);
621 }
622 let description = format!("Paid invoice {}{}", invoice.id, crate::tax::paid_with(extras));
623 match self.enter(workspace, EntryKind::TopUp, amount, &description, &invoice.id, None, None, None).await {
624 Ok(()) => {}
625 // Credited a moment ago by the event or the charge alongside.
626 Err(error) if crate::is_duplicate(&error) => return Ok(false),
627 Err(error) => return Err(error),
628 }
629 self.record_extras(workspace, &invoice.id, invoice.payment_intent.as_deref(), extras, None).await?;
630 // Prepaid cards pay, but never raise the limit.
631 if let (Some(stripe), Some(charge)) = (&self.stripe, &invoice.charge)
632 && let Ok(charge) = stripe.get::<Value>(&format!("/charges/{charge}")).await
633 && let Some(funding) = charge["payment_method_details"]["card"]["funding"].as_str() {
634 self.db
635 .prepare("UPDATE ledger SET funding = ? WHERE reference = ?")
636 .bind(&[funding.into(), invoice.id.as_str().into()])?
637 .run()
638 .await?;
639 }
640 Ok(true)
641 }
642
643 pub(crate) async fn mark_declined(&self, workspace: &str, error: &str) -> Result<()> {
644 let now = rfc3339(now_ms());
645 self.db
646 .prepare(
647 "INSERT INTO limits (workspace, autopay_failed_at, autopay_error, updated_at) VALUES (?1, ?2, ?3, ?2)
648 ON CONFLICT (workspace) DO UPDATE SET autopay_failed_at = ?2, autopay_error = ?3, updated_at = ?2",
649 )
650 .bind(&[workspace.into(), now.as_str().into(), error.into()])?
651 .run()
652 .await?;
653 Ok(())
654 }
655
656 /// Why the workspace's card last could not be charged, while it still
657 /// cannot.
658 pub(crate) async fn autopay_error(&self, workspace: &str) -> Result<Option<String>> {
659 #[derive(Deserialize)]
660 struct Row {
661 autopay_error: Option<String>,
662 }
663 Ok(self
664 .db
665 .prepare("SELECT autopay_error FROM limits WHERE workspace = ? AND autopay_failed_at IS NOT NULL")
666 .bind(&[workspace.into()])?
667 .first::<Row>(None)
668 .await?
669 .and_then(|row| row.autopay_error))
670 }
671
672 /// A workspace invoice paid later, on Stripe's page or by a retry. One
673 /// g1t made but never kept (from before invoices were kept as open
674 /// before they were charged) is found by its `metadata[g1t_workspace]`
675 /// and kept now. Credited first, then marked paid. None when it is not
676 /// a workspace invoice.
677 pub(crate) async fn workspace_invoice_paid(&self, invoice_id: &str) -> Result<Option<String>> {
678 #[derive(Deserialize)]
679 struct Row {
680 workspace: String,
681 #[serde(default)]
682 fee_micros: i64,
683 }
684 let Some(stripe) = &self.stripe else { return Ok(None) };
685 let kept = self
686 .db
687 .prepare("SELECT workspace, fee_micros FROM workspace_invoices WHERE invoice_id = ?")
688 .bind(&[invoice_id.into()])?
689 .first::<Row>(None)
690 .await?;
691 // Read at billing's API version, whatever the event's was.
692 let found: Value = stripe.get(&format!("/invoices/{invoice_id}")).await?;
693 let invoice: StripeInvoice = serde_json::from_value(found.clone()).map_err(|e| worker::Error::RustError(e.to_string()))?;
694 let row = match kept {
695 Some(row) => row,
696 None => {
697 let Some(tagged) = found["metadata"]["g1t_workspace"].as_str().filter(|_| crate::webhooks::invoice_subscription(&found).is_none())
698 else {
699 return Ok(None);
700 };
701 // Under its slug now, by its customer; else as it was sent.
702 let workspace = match found["customer"].as_str() {
703 Some(customer) => self.workspace_of_customer(customer).await?,
704 None => None,
705 }
706 .unwrap_or_else(|| tagged.to_owned());
707 let split = crate::stripe::invoice_split(&found, invoice.amount_paid);
708 let created = rfc3339(found["created"].as_i64().unwrap_or(0).max(0) as u64 * 1000);
709 self.db
710 .prepare(
711 "INSERT OR IGNORE INTO workspace_invoices
712 (invoice_id, workspace, reason, period, amount_micros, status, hosted_url, pdf_url, through_at, created_at, paid_at,
713 fee_micros, tax_micros)
714 VALUES (?, ?, ?, ?, ?, 'open', ?, ?, ?, ?, NULL, ?, ?)",
715 )
716 .bind(&[
717 invoice_id.into(),
718 workspace.as_str().into(),
719 found["metadata"]["reason"].as_str().unwrap_or("month").into(),
720 found["metadata"]["period"].as_str().unwrap_or_default().into(),
721 ((split.net_cents * 10_000) as f64).into(),
722 crate::optional(invoice.hosted_invoice_url.as_deref()),
723 crate::optional(invoice.invoice_pdf.as_deref()),
724 created.as_str().into(),
725 created.as_str().into(),
726 ((split.fee_cents * 10_000) as f64).into(),
727 ((split.tax_cents * 10_000) as f64).into(),
728 ])?
729 .run()
730 .await?;
731 Row { workspace, fee_micros: split.fee_cents * 10_000 }
732 }
733 };
734 if invoice.status.as_deref() != Some("paid") {
735 return Ok(Some(format!("ignored: invoice {invoice_id} is {} now", invoice.status.as_deref().unwrap_or("unknown"))));
736 }
737 let credited = self.credit_invoice(&row.workspace, &invoice, row.fee_micros / 10_000).await?;
738 self.db
739 .prepare("UPDATE workspace_invoices SET status = 'paid', paid_at = ?, tax_micros = ? WHERE invoice_id = ?")
740 .bind(&[rfc3339(now_ms()).into(), ((invoice.tax_cents() * 10_000) as f64).into(), invoice_id.into()])?
741 .run()
742 .await?;
743 Ok(Some(format!(
744 "invoice {invoice_id} for {} paid{}",
745 row.workspace,
746 if credited { "" } else { " (already credited)" }
747 )))
748 }
749
750 pub(crate) async fn workspace_invoices(&self, workspace: &str) -> Result<Vec<WorkspaceInvoice>> {
751 let rows = self
752 .db
753 .prepare("SELECT * FROM workspace_invoices WHERE workspace = ? ORDER BY created_at DESC LIMIT 36")
754 .bind(&[workspace.into()])?
755 .all()
756 .await?
757 .results::<InvoiceRow>()?;
758 let mut invoices = vec![];
759 for row in rows {
760 invoices.push(self.with_lines(row).await?);
761 }
762 Ok(invoices)
763 }
764
765 /// One workspace invoice as kept, with its lines.
766 async fn workspace_invoice(&self, invoice_id: &str) -> Result<Option<WorkspaceInvoice>> {
767 let row = self
768 .db
769 .prepare("SELECT * FROM workspace_invoices WHERE invoice_id = ?")
770 .bind(&[invoice_id.into()])?
771 .first::<InvoiceRow>(None)
772 .await?;
773 Ok(match row {
774 Some(row) => Some(self.with_lines(row).await?),
775 None => None,
776 })
777 }
778
779 async fn with_lines(&self, row: InvoiceRow) -> Result<WorkspaceInvoice> {
780 let lines = self
781 .db
782 .prepare("SELECT description, amount_micros FROM workspace_invoice_lines WHERE invoice_id = ? ORDER BY position")
783 .bind(&[row.invoice_id.as_str().into()])?
784 .all()
785 .await?
786 .results::<LineRow>()?
787 .into_iter()
788 .map(|l| InvoiceItem { description: l.description, amount_micros: l.amount_micros })
789 .collect();
790 Ok(WorkspaceInvoice {
791 invoice_id: row.invoice_id,
792 workspace: row.workspace,
793 reason: row.reason,
794 period: row.period,
795 amount_micros: row.amount_micros,
796 status: row.status,
797 hosted_url: row.hosted_url,
798 pdf_url: row.pdf_url,
799 lines,
800 created_at: row.created_at,
801 fee_micros: row.fee_micros,
802 tax_micros: row.tax_micros,
803 })
804 }
805
806 /// `invoices`: for the workspace's owners and billing managers, as its
807 /// billing details are.
808 pub(crate) async fn invoices(&self, a: InvoicesArgs) -> Result<Outcome<Vec<WorkspaceInvoice>>> {
809 let workspace = a.workspace.to_lowercase();
810 if !may_see_invoices(&a.viewer, &workspace) {
811 return Ok(Outcome::fail(FailureCode::Forbidden, "Only an owner or a billing manager can see a workspace's invoices."));
812 }
813 Ok(Outcome::Ok(self.workspace_invoices(&workspace).await?))
814 }
815}
816
817#[cfg(test)]
818mod tests {
819 use super::*;
820
821 #[test]
822 fn an_invoice_adds_up_to_what_is_owed() {
823 let used = vec![("Agents on g1t's models".to_owned(), 40_000_000), ("Sandbox time".to_owned(), 10_000_000)];
824 // $10 of credit was paid in advance.
825 let lines = invoice_lines(&used, 40_000_000);
826 assert_eq!(lines.last().unwrap().description, "Paid in advance");
827 assert_eq!(lines.iter().map(|l| l.amount_micros).sum::<i64>(), 40_000_000);
828 // $5 was left unpaid from before.
829 let lines = invoice_lines(&used, 55_000_000);
830 assert_eq!(lines.last().unwrap().description, "Unpaid from earlier");
831 assert_eq!(lines.iter().map(|l| l.amount_micros).sum::<i64>(), 55_000_000);
832 // Exactly what was used.
833 assert_eq!(invoice_lines(&used, 50_000_000).len(), 2);
834 }
835
836 #[test]
837 fn an_invoice_holds_only_its_own_lines() {
838 let draft = draft_fields("cus_1", "acme", "month", "2026-09", "g1t usage".to_owned());
839 assert!(draft.contains(&("pending_invoice_items_behavior", "exclude".to_owned())));
840 // Taxed by Stripe Tax, every line at g1t's tax code, excluding tax.
841 assert!(draft.contains(&("automatic_tax[enabled]", "true".to_owned())));
842 let line = item_fields("cus_1", "in_1", "acme", "Sandbox time", 61);
843 assert!(line.contains(&("tax_code", crate::stripe::TAX_CODE.to_owned())));
844 assert!(line.contains(&("tax_behavior", "exclusive".to_owned())));
845 // Left a draft for want of an address: asked for, never charged.
846 assert!(needs_tax_location(&serde_json::json!({ "automatic_tax": { "status": "requires_location_inputs" } })));
847 assert!(!needs_tax_location(&serde_json::json!({ "automatic_tax": { "status": "complete" } })));
848 let item = item_fields("cus_1", "in_1", "acme", "Sandbox time", 1_234);
849 assert!(item.contains(&("invoice", "in_1".to_owned())));
850 assert!(item.contains(&("amount", "1234".to_owned())));
851 }
852
853 #[test]
854 fn only_the_card_saying_no_is_a_decline() {
855 let declined = r#"the card processor answered 402: {"error": {"code": "card_declined", "type": "card_error"}}"#;
856 assert!(is_decline(declined));
857 assert!(is_decline(r#"the card processor answered 400: {"error": {"type": "card_error"}}"#));
858 // Stripe down, busy or failing, or the network: tried again, nobody stopped.
859 assert!(!is_decline(r#"the card processor answered 500: {"error": {"type": "api_error"}}"#));
860 assert!(!is_decline(r#"the card processor answered 429: {"error": {"type": "rate_limit_error"}}"#));
861 assert!(!is_decline("Network connection lost."));
862 }
863
864 #[test]
865 fn only_owners_and_billing_managers_see_invoices() {
866 let user = |role: &str, org_roles: &[&str]| -> g1t_contracts::Viewer {
867 Some(
868 serde_json::from_value(serde_json::json!({
869 "id": "u_1", "username": "ana",
870 "workspaces": [{ "slug": "acme", "role": role, "org_roles": org_roles }],
871 }))
872 .unwrap(),
873 )
874 };
875 assert!(may_see_invoices(&user("owner", &[]), "acme"));
876 assert!(may_see_invoices(&user("member", &["billing_manager"]), "acme"));
877 assert!(!may_see_invoices(&user("member", &[]), "acme"));
878 assert!(!may_see_invoices(&user("member", &["security_manager"]), "acme"));
879 assert!(!may_see_invoices(&user("owner", &[]), "other"));
880 assert!(!may_see_invoices(&None, "acme"));
881 }
882
883 const DECLINED: &str = r#"the card processor answered 402: {"error": {"code": "card_declined", "type": "card_error"}}"#;
884 const NO_METHOD: &str = r#"the card processor answered 400: {"error": {"message": "This customer has no attached payment source or default payment method.", "type": "invalid_request_error"}}"#;
885
886 #[test]
887 fn only_a_paid_invoice_is_credited_and_only_a_decline_stops_work() {
888 assert_eq!(pay_outcome(Some("paid"), None), PayOutcome::Paid);
889 // Paid after all, whatever the attempt said.
890 assert_eq!(pay_outcome(Some("paid"), Some(DECLINED)), PayOutcome::Paid);
891 assert_eq!(pay_outcome(Some("open"), Some(DECLINED)), PayOutcome::Declined);
892 // Stripe did not answer: kept open, tried again, nobody stopped.
893 assert_eq!(pay_outcome(Some("open"), None), PayOutcome::Retry);
894 assert_eq!(pay_outcome(None, None), PayOutcome::Retry);
895 // Voided at Stripe meanwhile: closed, never charged.
896 assert_eq!(pay_outcome(Some("void"), Some(NO_METHOD)), PayOutcome::Void);
897 }
898
899 #[test]
900 fn a_refusal_for_want_of_a_card_stops_instead_of_retrying_for_ever() {
901 assert!(needs_card(NO_METHOD));
902 assert_eq!(pay_outcome(Some("open"), Some(NO_METHOD)), PayOutcome::NeedsCard);
903 assert_eq!(stripe_reason(NO_METHOD), "This customer has no attached payment source or default payment method.");
904 // Only 5xx, 429 and no answer are tried again.
905 for transient in [
906 r#"the card processor answered 500: {"error": {"type": "api_error"}}"#,
907 r#"the card processor answered 429: {"error": {"type": "invalid_request_error", "code": "rate_limit"}}"#,
908 "Network connection lost.",
909 ] {
910 assert!(!needs_card(transient), "{transient}");
911 assert_eq!(pay_outcome(Some("open"), Some(transient)), PayOutcome::Retry, "{transient}");
912 }
913 // A key problem (401) is g1t's, never the payer's: tried again.
914 assert!(!needs_card(r#"the card processor answered 401: {"error": {"type": "invalid_request_error"}}"#));
915 }
916
917 #[test]
918 fn an_invoice_attempted_again_is_the_same_until_one_is_paid_or_voided() {
919 let key = invoice_key("acme", "cus_1", "month", "2026-09", 40_001_500, 0, 0);
920 assert_eq!(key, "ws-invoice/acme/cus_1/month/2026-09/4000/p0");
921 assert_eq!(key, invoice_key("acme", "cus_1", "month", "2026-09", 40_000_100, 0, 0));
922 // A voided invoice is never handed back for the next.
923 assert_ne!(key, invoice_key("acme", "cus_1", "month", "2026-09", 40_001_500, 0, 1));
924 // Nor one paid earlier the same day for the same total.
925 assert_ne!(key, invoice_key("acme", "cus_1", "month", "2026-09", 40_001_500, 1, 0));
926 // Nor one made for another customer.
927 assert_ne!(key, invoice_key("acme", "cus_2", "month", "2026-09", 40_001_500, 0, 0));
928 }
929
930 fn items(micros: &[i64]) -> Vec<InvoiceItem> {
931 micros.iter().map(|&amount_micros| InvoiceItem { description: String::new(), amount_micros }).collect()
932 }
933
934 #[test]
935 fn the_card_is_charged_what_is_owed_rounded_up_to_the_cent_never_down() {
936 // $1.234567 + $2.345678 = $3.580245 owed: 359 cents, where cutting
937 // each line would have charged 357.
938 let cents = line_cents(&items(&[1_234_567, 2_345_678]));
939 assert_eq!(cents.iter().sum::<i64>(), 359);
940 assert_eq!(cents, vec![124, 235]);
941 // Whole cents stay as they are.
942 assert_eq!(line_cents(&items(&[40_000_000, 10_000_000])), vec![4_000, 1_000]);
943 // A credit line keeps its full credit; the total still rounds up.
944 // $50.004 used, $10.0025 paid in advance: $40.0015 owed, 4,001 cents.
945 let cents = line_cents(&items(&[50_004_000, -10_002_500]));
946 assert_eq!(cents.iter().sum::<i64>(), 4_001);
947 // Lines under a cent each add up to the cents they make together.
948 let cents = line_cents(&items(&[4_000, 4_000, 4_000]));
949 assert_eq!(cents.iter().sum::<i64>(), 2);
950 // Every invoice the close makes: never less than owed, never a cent more.
951 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)] {
952 let lines = invoice_lines(&used, owed);
953 let charged = line_cents(&lines).iter().sum::<i64>() * 10_000;
954 assert!(charged >= owed && charged - owed < 10_000, "{charged} for {owed}");
955 }
956 }
957}