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.

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