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.

g1t.sh
565 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, taxed by Stripe Tax,
70/// and holding only the lines put on it, never whatever is pending on the
71/// customer.
72fn draft_fields(customer: &str, workspace: &str, reason: &str, period: &str, description: String) -> Vec<(&'static str, String)> {
73 let mut fields = vec![
74 ("customer", customer.to_owned()),
75 ("collection_method", "charge_automatically".to_owned()),
76 ("auto_advance", "false".to_owned()),
77 ("pending_invoice_items_behavior", "exclude".to_owned()),
78 ("description", description),
79 ("metadata[g1t_workspace]", workspace.to_owned()),
80 ("metadata[reason]", reason.to_owned()),
81 ("metadata[period]", period.to_owned()),
82 ];
83 fields.extend(crate::stripe::invoice_tax_fields());
84 fields
85}
86
87/// One line, on the draft `invoice`, at g1t's tax code, excluding tax.
88fn item_fields(customer: &str, invoice: &str, workspace: &str, description: &str, cents: i64) -> Vec<(&'static str, String)> {
89 let mut fields = vec![
90 ("customer", customer.to_owned()),
91 ("invoice", invoice.to_owned()),
92 ("amount", cents.to_string()),
93 ("currency", "usd".to_owned()),
94 ("description", description.to_owned()),
95 ("metadata[workspace]", workspace.to_owned()),
96 ];
97 fields.extend(crate::stripe::item_tax_fields());
98 fields
99}
100
101/// Whether Stripe left an invoice a draft because Stripe Tax could not
102/// place the customer.
103pub(crate) fn needs_tax_location(invoice: &Value) -> bool {
104 invoice["automatic_tax"]["status"].as_str() == Some("requires_location_inputs")
105}
106
107#[derive(Deserialize)]
108struct InvoiceRow {
109 invoice_id: String,
110 workspace: String,
111 reason: String,
112 period: String,
113 amount_micros: i64,
114 status: String,
115 hosted_url: Option<String>,
116 pdf_url: Option<String>,
117 created_at: String,
118 #[serde(default)]
119 fee_micros: i64,
120 #[serde(default)]
121 tax_micros: i64,
122}
123
124#[derive(Deserialize)]
125struct LineRow {
126 description: String,
127 amount_micros: i64,
128}
129
130/// A Stripe invoice, as far as billing reads it.
131#[derive(Deserialize)]
132struct StripeInvoice {
133 id: String,
134 #[serde(default)]
135 status: Option<String>,
136 #[serde(default)]
137 hosted_invoice_url: Option<String>,
138 #[serde(default)]
139 invoice_pdf: Option<String>,
140 #[serde(default)]
141 amount_paid: i64,
142 #[serde(default)]
143 charge: Option<String>,
144 #[serde(default)]
145 payment_intent: Option<String>,
146 /// The tax Stripe added, in cents (`tax`, in this API version).
147 #[serde(default)]
148 tax: Option<i64>,
149}
150
151impl StripeInvoice {
152 fn tax_cents(&self) -> i64 {
153 self.tax.unwrap_or(0).max(0)
154 }
155}
156
157impl Billing {
158 /// Invoices the workspace for what it owes, charging its card. `Ok(Err)`
159 /// says why not, when there was nothing to do or no card.
160 pub(crate) async fn invoice_workspace(
161 &self,
162 workspace: &str,
163 reason: &str,
164 period: &str,
165 ) -> Result<std::result::Result<WorkspaceInvoice, String>> {
166 let Some(stripe) = &self.stripe else { return Ok(Err("Payments are not set up.".into())) };
167 let Some(account) = self.row(workspace).await? else { return Ok(Err("Nothing billed yet.".into())) };
168 let Some(customer) = account.customer_id else { return Ok(Err("No card on file.".into())) };
169 // AI credit left (bought before g1t stopped selling it) props up the
170 // balance but pays only for models: it is not money for anything else.
171 let owed = self.owed_with(workspace, account.balance_micros).await?;
172 // Only a month's close charges no less than the minimum
173 // (`MIN_CHARGE_MICROS`), so a payment's fee is never most of it;
174 // less carries over. A charge because a limit was reached always
175 // goes through, whatever its size, so a new workspace's limit never
176 // strands it.
177 if reason == "month" && !crate::limits::worth_charging(owed, self.plans.min_charge_micros) {
178 return Ok(Err(format!(
179 "{} is owed, under the {} minimum charge; it carries over to the next invoice.",
180 crate::features::dollars(owed),
181 crate::features::dollars(self.plans.min_charge_micros)
182 )));
183 }
184 // What was used since the last invoice, by kind.
185 #[derive(Deserialize)]
186 struct Last {
187 through_at: Option<String>,
188 }
189 let since = self
190 .db
191 .prepare("SELECT MAX(through_at) AS through_at FROM workspace_invoices WHERE workspace = ? AND status <> 'void'")
192 .bind(&[workspace.into()])?
193 .first::<Last>(None)
194 .await?
195 .and_then(|l| l.through_at)
196 .unwrap_or_default();
197 #[derive(Deserialize)]
198 struct Used {
199 kind: String,
200 charged: Option<i64>,
201 }
202 let now = rfc3339(now_ms());
203 let used: Vec<(String, i64)> = self
204 .db
205 .prepare(
206 "SELECT CASE
207 WHEN task = 'sandbox' AND machine IS NOT NULL THEN 'Runner minutes, ' || machine
208 WHEN task = 'sandbox' THEN 'Sandbox time'
209 WHEN task = 'self_hosted' THEN 'Self-hosted runner time'
210 WHEN task = 'deployments' THEN 'Deployments: builds and usage past the plan'
211 WHEN task = 'security' THEN 'Security scans'
212 WHEN task = 'context' THEN 'Search embeddings'
213 WHEN task = 'storage' THEN 'Private repository storage'
214 WHEN task = 'git' THEN 'Git operations'
215 WHEN task = 'cache' THEN 'Actions cache storage'
216 WHEN task = 'domains' THEN 'Custom domains'
217 WHEN task = 'package_storage' THEN 'Package storage'
218 -- From when g1t ran agents and sold model access.
219 WHEN billed_to = 'workspace' THEN 'Runs on your own model provider'
220 WHEN reference LIKE 'run%' OR task = 'gateway' THEN 'Agents on g1t''s models'
221 ELSE 'Other usage' END AS kind,
222 -SUM(amount_micros) AS charged
223 FROM ledger WHERE workspace = ? AND kind = 'usage' AND created_at > ? AND created_at <= ?
224 GROUP BY 1 ORDER BY charged DESC",
225 )
226 .bind(&[workspace.into(), since.as_str().into(), now.as_str().into()])?
227 .all()
228 .await?
229 .results::<Used>()?
230 .into_iter()
231 .map(|u| (u.kind, u.charged.unwrap_or(0)))
232 .collect();
233 let lines = invoice_lines(&used, owed);
234 // Stripe Tax needs to know where the customer is. Without an
235 // address nothing is charged: the owners are asked for one, and the
236 // charge goes through once it is there.
237 match stripe.customer_placed(&customer).await {
238 Ok(true) => {}
239 Ok(false) => {
240 self.tax_address_needed(workspace).await?;
241 return Ok(Err(crate::tax::address_needed_message(workspace)));
242 }
243 Err(error) => return Ok(Err(crate::stripe::friendly(&error))),
244 }
245 let cents = line_cents(&lines);
246 // Charged to a card: Stripe's fee is its own line. A bank account
247 // set as the way to pay has no card fee.
248 let by_card = match stripe.default_payment_method(&customer).await {
249 Ok(method) => method.is_none_or(|m| m.kind == "card"),
250 Err(_) => true,
251 };
252 let fee_cents = if by_card { self.card_fee_on(cents.iter().sum::<i64>()).await? } else { 0 };
253 let key = format!("ws-invoice/{workspace}/{reason}/{period}/{}/{fee_cents}", owed / 10_000);
254 let description = match reason {
255 "month" => format!("g1t usage for {workspace}, {period}"),
256 _ => format!("g1t usage for {workspace}, charged as it neared its limit"),
257 };
258 // The draft first, then its lines on it: lines left pending on the
259 // customer by an attempt that failed half way would otherwise be
260 // swept into the next invoice (this one's retry with a different
261 // total, or the plan's renewal) on top of their own new lines.
262 let draft: StripeInvoice =
263 stripe.post_idempotent("/invoices", &draft_fields(&customer, workspace, reason, period, description), &key).await?;
264 for (position, (line, cents)) in lines.iter().zip(&cents).enumerate() {
265 let fields = item_fields(&customer, &draft.id, workspace, &line.description, *cents);
266 let _: Value = stripe.post_idempotent("/invoiceitems", &fields, &format!("{key}/item/{position}")).await?;
267 }
268 if fee_cents > 0 {
269 let fields = item_fields(&customer, &draft.id, workspace, crate::stripe::CARD_FEE_LINE, fee_cents);
270 let _: Value = stripe.post_idempotent("/invoiceitems", &fields, &format!("{key}/item/card_fee")).await?;
271 }
272 // A retry finds it finalized already; that is fine.
273 let finalized = stripe.post::<Value>(&format!("/invoices/{}/finalize", draft.id), &[]).await;
274 if let Err(error) = &finalized
275 && crate::stripe::is_tax_location_error(error)
276 {
277 self.tax_address_needed(workspace).await?;
278 return Ok(Err(crate::tax::address_needed_message(workspace)));
279 }
280 if let Ok(left) = stripe.get::<Value>(&format!("/invoices/{}", draft.id)).await
281 && left["status"].as_str() == Some("draft")
282 && needs_tax_location(&left)
283 {
284 self.tax_address_needed(workspace).await?;
285 return Ok(Err(crate::tax::address_needed_message(workspace)));
286 }
287 self.tax_address_given(workspace).await?;
288 // Charge the card now; a decline comes back as an error.
289 let paid = stripe.post::<StripeInvoice>(&format!("/invoices/{}/pay", draft.id), &[("off_session", "true".to_owned())]).await;
290 let invoice: StripeInvoice = stripe.get(&format!("/invoices/{}", draft.id)).await?;
291 let total = lines.iter().map(|l| l.amount_micros).sum::<i64>();
292 let fee_micros = fee_cents * 10_000;
293 let tax_micros = invoice.tax_cents() * 10_000;
294 let status = if invoice.status.as_deref() == Some("paid") { "paid" } else { "failed" };
295 // Only the card saying no is a decline, which stops work until it
296 // is paid. Stripe failing to answer, or answering busy, is g1t's
297 // problem and never stops a payer: the invoice stays as it is, and
298 // the next attempt (the same total finds the same invoice) pays it.
299 if status == "failed" && !paid.as_ref().err().is_some_and(|error| is_decline(&error.to_string())) {
300 return Ok(Err("The card processor did not finish the payment; it is tried again.".into()));
301 }
302 let mut writes = vec![self
303 .db
304 .prepare(
305 "INSERT OR REPLACE INTO workspace_invoices
306 (invoice_id, workspace, reason, period, amount_micros, status, hosted_url, pdf_url, through_at, created_at, paid_at,
307 fee_micros, tax_micros)
308 VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
309 )
310 .bind(&[
311 invoice.id.as_str().into(),
312 workspace.into(),
313 reason.into(),
314 period.into(),
315 (total as f64).into(),
316 status.into(),
317 crate::optional(invoice.hosted_invoice_url.as_deref()),
318 crate::optional(invoice.invoice_pdf.as_deref()),
319 now.as_str().into(),
320 now.as_str().into(),
321 crate::optional((status == "paid").then_some(now.as_str())),
322 (fee_micros as f64).into(),
323 (tax_micros as f64).into(),
324 ])?];
325 for (position, line) in lines.iter().enumerate() {
326 writes.push(
327 self.db
328 .prepare("INSERT OR REPLACE INTO workspace_invoice_lines (invoice_id, position, description, amount_micros) VALUES (?, ?, ?, ?)")
329 .bind(&[invoice.id.as_str().into(), (position as u32).into(), line.description.as_str().into(), (line.amount_micros as f64).into()])?,
330 );
331 }
332 self.db.batch(writes).await?;
333 if status == "paid" {
334 self.credit_invoice(workspace, &invoice, fee_cents).await?;
335 } else {
336 let error = paid.err().map_or_else(|| "the card was declined".to_owned(), |e| e.to_string().chars().take(200).collect());
337 self.mark_declined(workspace, &error).await?;
338 }
339 Ok(Ok(WorkspaceInvoice {
340 invoice_id: invoice.id,
341 workspace: workspace.to_owned(),
342 reason: reason.to_owned(),
343 period: period.to_owned(),
344 amount_micros: total,
345 status: status.to_owned(),
346 hosted_url: invoice.hosted_invoice_url,
347 pdf_url: invoice.invoice_pdf,
348 lines,
349 created_at: now,
350 fee_micros,
351 tax_micros,
352 }))
353 }
354
355 /// Enters an invoice's payment once, with the kind of card that paid:
356 /// what it paid for usage, never its tax or card fee, which are kept
357 /// apart (`tax_and_fees`).
358 async fn credit_invoice(&self, workspace: &str, invoice: &StripeInvoice, fee_cents: i64) -> Result<bool> {
359 let seen = self
360 .db
361 .prepare("SELECT id FROM ledger WHERE reference = ?")
362 .bind(&[invoice.id.as_str().into()])?
363 .first::<Value>(None)
364 .await?;
365 if seen.is_some() {
366 return Ok(false);
367 }
368 let extras = crate::tax::Extras { tax_cents: invoice.tax_cents(), fee_cents };
369 let amount = (invoice.amount_paid - extras.tax_cents - extras.fee_cents).max(0) * 10_000;
370 if amount <= 0 {
371 return Ok(false);
372 }
373 let description = if extras == crate::tax::Extras::default() {
374 format!("Paid invoice {}", invoice.id)
375 } else {
376 format!(
377 "Paid invoice {} (tax {} and card fee {} paid with it)",
378 invoice.id,
379 crate::features::cents(extras.tax_cents * 10_000),
380 crate::features::cents(extras.fee_cents * 10_000)
381 )
382 };
383 self.enter(workspace, EntryKind::TopUp, amount, &description, &invoice.id, None, None, None).await?;
384 self.record_extras(workspace, &invoice.id, invoice.payment_intent.as_deref(), extras, None).await?;
385 // Prepaid cards pay, but never raise the limit.
386 if let (Some(stripe), Some(charge)) = (&self.stripe, &invoice.charge)
387 && let Ok(charge) = stripe.get::<Value>(&format!("/charges/{charge}")).await
388 && let Some(funding) = charge["payment_method_details"]["card"]["funding"].as_str() {
389 self.db
390 .prepare("UPDATE ledger SET funding = ? WHERE reference = ?")
391 .bind(&[funding.into(), invoice.id.as_str().into()])?
392 .run()
393 .await?;
394 }
395 Ok(true)
396 }
397
398 pub(crate) async fn mark_declined(&self, workspace: &str, error: &str) -> Result<()> {
399 let now = rfc3339(now_ms());
400 self.db
401 .prepare(
402 "INSERT INTO limits (workspace, autopay_failed_at, autopay_error, updated_at) VALUES (?1, ?2, ?3, ?2)
403 ON CONFLICT (workspace) DO UPDATE SET autopay_failed_at = ?2, autopay_error = ?3, updated_at = ?2",
404 )
405 .bind(&[workspace.into(), now.as_str().into(), error.into()])?
406 .run()
407 .await?;
408 Ok(())
409 }
410
411 /// A workspace invoice paid later, on Stripe's page or by a retry.
412 pub(crate) async fn workspace_invoice_paid(&self, invoice_id: &str) -> Result<Option<String>> {
413 #[derive(Deserialize)]
414 struct Row {
415 workspace: String,
416 #[serde(default)]
417 fee_micros: i64,
418 }
419 let Some(row) = self
420 .db
421 .prepare("SELECT workspace, fee_micros FROM workspace_invoices WHERE invoice_id = ?")
422 .bind(&[invoice_id.into()])?
423 .first::<Row>(None)
424 .await?
425 else {
426 return Ok(None);
427 };
428 let Some(stripe) = &self.stripe else { return Ok(None) };
429 let invoice: StripeInvoice = stripe.get(&format!("/invoices/{invoice_id}")).await?;
430 self.db
431 .prepare("UPDATE workspace_invoices SET status = 'paid', paid_at = ?, tax_micros = ? WHERE invoice_id = ?")
432 .bind(&[rfc3339(now_ms()).into(), ((invoice.tax_cents() * 10_000) as f64).into(), invoice_id.into()])?
433 .run()
434 .await?;
435 let credited = self.credit_invoice(&row.workspace, &invoice, row.fee_micros / 10_000).await?;
436 Ok(Some(format!(
437 "invoice {invoice_id} for {} paid{}",
438 row.workspace,
439 if credited { "" } else { " (already credited)" }
440 )))
441 }
442
443 pub(crate) async fn workspace_invoices(&self, workspace: &str) -> Result<Vec<WorkspaceInvoice>> {
444 let rows = self
445 .db
446 .prepare("SELECT * FROM workspace_invoices WHERE workspace = ? ORDER BY created_at DESC LIMIT 36")
447 .bind(&[workspace.into()])?
448 .all()
449 .await?
450 .results::<InvoiceRow>()?;
451 let mut invoices = vec![];
452 for row in rows {
453 let lines = self
454 .db
455 .prepare("SELECT description, amount_micros FROM workspace_invoice_lines WHERE invoice_id = ? ORDER BY position")
456 .bind(&[row.invoice_id.as_str().into()])?
457 .all()
458 .await?
459 .results::<LineRow>()?
460 .into_iter()
461 .map(|l| InvoiceItem { description: l.description, amount_micros: l.amount_micros })
462 .collect();
463 invoices.push(WorkspaceInvoice {
464 invoice_id: row.invoice_id,
465 workspace: row.workspace,
466 reason: row.reason,
467 period: row.period,
468 amount_micros: row.amount_micros,
469 status: row.status,
470 hosted_url: row.hosted_url,
471 pdf_url: row.pdf_url,
472 lines,
473 created_at: row.created_at,
474 fee_micros: row.fee_micros,
475 tax_micros: row.tax_micros,
476 });
477 }
478 Ok(invoices)
479 }
480
481 /// `invoices`: for the workspace's members.
482 pub(crate) async fn invoices(&self, a: InvoicesArgs) -> Result<Outcome<Vec<WorkspaceInvoice>>> {
483 let workspace = a.workspace.to_lowercase();
484 if !a.viewer.is_some_and(|viewer| viewer.is_member(&workspace)) {
485 return Ok(Outcome::fail(FailureCode::Forbidden, "Only members can see a workspace's invoices."));
486 }
487 Ok(Outcome::Ok(self.workspace_invoices(&workspace).await?))
488 }
489}
490
491#[cfg(test)]
492mod tests {
493 use super::*;
494
495 #[test]
496 fn an_invoice_adds_up_to_what_is_owed() {
497 let used = vec![("Agents on g1t's models".to_owned(), 40_000_000), ("Sandbox time".to_owned(), 10_000_000)];
498 // $10 of credit was paid in advance.
499 let lines = invoice_lines(&used, 40_000_000);
500 assert_eq!(lines.last().unwrap().description, "Paid in advance");
501 assert_eq!(lines.iter().map(|l| l.amount_micros).sum::<i64>(), 40_000_000);
502 // $5 was left unpaid from before.
503 let lines = invoice_lines(&used, 55_000_000);
504 assert_eq!(lines.last().unwrap().description, "Unpaid from earlier");
505 assert_eq!(lines.iter().map(|l| l.amount_micros).sum::<i64>(), 55_000_000);
506 // Exactly what was used.
507 assert_eq!(invoice_lines(&used, 50_000_000).len(), 2);
508 }
509
510 #[test]
511 fn an_invoice_holds_only_its_own_lines() {
512 let draft = draft_fields("cus_1", "acme", "month", "2026-09", "g1t usage".to_owned());
513 assert!(draft.contains(&("pending_invoice_items_behavior", "exclude".to_owned())));
514 // Taxed by Stripe Tax, every line at g1t's tax code, excluding tax.
515 assert!(draft.contains(&("automatic_tax[enabled]", "true".to_owned())));
516 let line = item_fields("cus_1", "in_1", "acme", crate::stripe::CARD_FEE_LINE, 61);
517 assert!(line.contains(&("tax_code", crate::stripe::TAX_CODE.to_owned())));
518 assert!(line.contains(&("tax_behavior", "exclusive".to_owned())));
519 // Left a draft for want of an address: asked for, never charged.
520 assert!(needs_tax_location(&serde_json::json!({ "automatic_tax": { "status": "requires_location_inputs" } })));
521 assert!(!needs_tax_location(&serde_json::json!({ "automatic_tax": { "status": "complete" } })));
522 let item = item_fields("cus_1", "in_1", "acme", "Sandbox time", 1_234);
523 assert!(item.contains(&("invoice", "in_1".to_owned())));
524 assert!(item.contains(&("amount", "1234".to_owned())));
525 }
526
527 #[test]
528 fn only_the_card_saying_no_is_a_decline() {
529 let declined = r#"the card processor answered 402: {"error": {"code": "card_declined", "type": "card_error"}}"#;
530 assert!(is_decline(declined));
531 assert!(is_decline(r#"the card processor answered 400: {"error": {"type": "card_error"}}"#));
532 // Stripe down, busy or failing, or the network: tried again, nobody stopped.
533 assert!(!is_decline(r#"the card processor answered 500: {"error": {"type": "api_error"}}"#));
534 assert!(!is_decline(r#"the card processor answered 429: {"error": {"type": "rate_limit_error"}}"#));
535 assert!(!is_decline("Network connection lost."));
536 }
537
538 fn items(micros: &[i64]) -> Vec<InvoiceItem> {
539 micros.iter().map(|&amount_micros| InvoiceItem { description: String::new(), amount_micros }).collect()
540 }
541
542 #[test]
543 fn the_card_is_charged_what_is_owed_rounded_up_to_the_cent_never_down() {
544 // $1.234567 + $2.345678 = $3.580245 owed: 359 cents, where cutting
545 // each line would have charged 357.
546 let cents = line_cents(&items(&[1_234_567, 2_345_678]));
547 assert_eq!(cents.iter().sum::<i64>(), 359);
548 assert_eq!(cents, vec![124, 235]);
549 // Whole cents stay as they are.
550 assert_eq!(line_cents(&items(&[40_000_000, 10_000_000])), vec![4_000, 1_000]);
551 // A credit line keeps its full credit; the total still rounds up.
552 // $50.004 used, $10.0025 paid in advance: $40.0015 owed, 4,001 cents.
553 let cents = line_cents(&items(&[50_004_000, -10_002_500]));
554 assert_eq!(cents.iter().sum::<i64>(), 4_001);
555 // Lines under a cent each add up to the cents they make together.
556 let cents = line_cents(&items(&[4_000, 4_000, 4_000]));
557 assert_eq!(cents.iter().sum::<i64>(), 2);
558 // Every invoice the close makes: never less than owed, never a cent more.
559 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)] {
560 let lines = invoice_lines(&used, owed);
561 let charged = line_cents(&lines).iter().sum::<i64>() * 10_000;
562 assert!(charged >= owed && charged - owed < 10_000, "{charged} for {owed}");
563 }
564 }
565}