Skip to content
564 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' THEN 'Sandbox time'
208 WHEN task = 'self_hosted' THEN 'Self-hosted runner time'
209 WHEN task = 'deployments' THEN 'Deployments: builds and usage past the plan'
210 WHEN task = 'security' THEN 'Security scans'
211 WHEN task = 'context' THEN 'Search embeddings'
212 WHEN task = 'storage' THEN 'Private repository storage'
213 WHEN task = 'git' THEN 'Git operations'
214 WHEN task = 'cache' THEN 'Actions cache storage'
215 WHEN task = 'domains' THEN 'Custom domains'
216 WHEN task = 'package_storage' THEN 'Package storage'
217 -- From when g1t ran agents and sold model access.
218 WHEN billed_to = 'workspace' THEN 'Runs on your own model provider'
219 WHEN reference LIKE 'run%' OR task = 'gateway' THEN 'Agents on g1t''s models'
220 ELSE 'Other usage' END AS kind,
221 -SUM(amount_micros) AS charged
222 FROM ledger WHERE workspace = ? AND kind = 'usage' AND created_at > ? AND created_at <= ?
223 GROUP BY 1 ORDER BY charged DESC",
224 )
225 .bind(&[workspace.into(), since.as_str().into(), now.as_str().into()])?
226 .all()
227 .await?
228 .results::<Used>()?
229 .into_iter()
230 .map(|u| (u.kind, u.charged.unwrap_or(0)))
231 .collect();
232 let lines = invoice_lines(&used, owed);
233 // Stripe Tax needs to know where the customer is. Without an
234 // address nothing is charged: the owners are asked for one, and the
235 // charge goes through once it is there.
236 match stripe.customer_placed(&customer).await {
237 Ok(true) => {}
238 Ok(false) => {
239 self.tax_address_needed(workspace).await?;
240 return Ok(Err(crate::tax::address_needed_message(workspace)));
241 }
242 Err(error) => return Ok(Err(crate::stripe::friendly(&error))),
243 }
244 let cents = line_cents(&lines);
245 // Charged to a card: Stripe's fee is its own line. A bank account
246 // set as the way to pay has no card fee.
247 let by_card = match stripe.default_payment_method(&customer).await {
248 Ok(method) => method.is_none_or(|m| m.kind == "card"),
249 Err(_) => true,
250 };
251 let fee_cents = if by_card { self.card_fee_on(cents.iter().sum::<i64>()).await? } else { 0 };
252 let key = format!("ws-invoice/{workspace}/{reason}/{period}/{}/{fee_cents}", owed / 10_000);
253 let description = match reason {
254 "month" => format!("g1t usage for {workspace}, {period}"),
255 _ => format!("g1t usage for {workspace}, charged as it neared its limit"),
256 };
257 // The draft first, then its lines on it: lines left pending on the
258 // customer by an attempt that failed half way would otherwise be
259 // swept into the next invoice (this one's retry with a different
260 // total, or the plan's renewal) on top of their own new lines.
261 let draft: StripeInvoice =
262 stripe.post_idempotent("/invoices", &draft_fields(&customer, workspace, reason, period, description), &key).await?;
263 for (position, (line, cents)) in lines.iter().zip(&cents).enumerate() {
264 let fields = item_fields(&customer, &draft.id, workspace, &line.description, *cents);
265 let _: Value = stripe.post_idempotent("/invoiceitems", &fields, &format!("{key}/item/{position}")).await?;
266 }
267 if fee_cents > 0 {
268 let fields = item_fields(&customer, &draft.id, workspace, crate::stripe::CARD_FEE_LINE, fee_cents);
269 let _: Value = stripe.post_idempotent("/invoiceitems", &fields, &format!("{key}/item/card_fee")).await?;
270 }
271 // A retry finds it finalized already; that is fine.
272 let finalized = stripe.post::<Value>(&format!("/invoices/{}/finalize", draft.id), &[]).await;
273 if let Err(error) = &finalized
274 && crate::stripe::is_tax_location_error(error)
275 {
276 self.tax_address_needed(workspace).await?;
277 return Ok(Err(crate::tax::address_needed_message(workspace)));
278 }
279 if let Ok(left) = stripe.get::<Value>(&format!("/invoices/{}", draft.id)).await
280 && left["status"].as_str() == Some("draft")
281 && needs_tax_location(&left)
282 {
283 self.tax_address_needed(workspace).await?;
284 return Ok(Err(crate::tax::address_needed_message(workspace)));
285 }
286 self.tax_address_given(workspace).await?;
287 // Charge the card now; a decline comes back as an error.
288 let paid = stripe.post::<StripeInvoice>(&format!("/invoices/{}/pay", draft.id), &[("off_session", "true".to_owned())]).await;
289 let invoice: StripeInvoice = stripe.get(&format!("/invoices/{}", draft.id)).await?;
290 let total = lines.iter().map(|l| l.amount_micros).sum::<i64>();
291 let fee_micros = fee_cents * 10_000;
292 let tax_micros = invoice.tax_cents() * 10_000;
293 let status = if invoice.status.as_deref() == Some("paid") { "paid" } else { "failed" };
294 // Only the card saying no is a decline, which stops work until it
295 // is paid. Stripe failing to answer, or answering busy, is g1t's
296 // problem and never stops a payer: the invoice stays as it is, and
297 // the next attempt (the same total finds the same invoice) pays it.
298 if status == "failed" && !paid.as_ref().err().is_some_and(|error| is_decline(&error.to_string())) {
299 return Ok(Err("The card processor did not finish the payment; it is tried again.".into()));
300 }
301 let mut writes = vec![self
302 .db
303 .prepare(
304 "INSERT OR REPLACE INTO workspace_invoices
305 (invoice_id, workspace, reason, period, amount_micros, status, hosted_url, pdf_url, through_at, created_at, paid_at,
306 fee_micros, tax_micros)
307 VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
308 )
309 .bind(&[
310 invoice.id.as_str().into(),
311 workspace.into(),
312 reason.into(),
313 period.into(),
314 (total as f64).into(),
315 status.into(),
316 crate::optional(invoice.hosted_invoice_url.as_deref()),
317 crate::optional(invoice.invoice_pdf.as_deref()),
318 now.as_str().into(),
319 now.as_str().into(),
320 crate::optional((status == "paid").then_some(now.as_str())),
321 (fee_micros as f64).into(),
322 (tax_micros as f64).into(),
323 ])?];
324 for (position, line) in lines.iter().enumerate() {
325 writes.push(
326 self.db
327 .prepare("INSERT OR REPLACE INTO workspace_invoice_lines (invoice_id, position, description, amount_micros) VALUES (?, ?, ?, ?)")
328 .bind(&[invoice.id.as_str().into(), (position as u32).into(), line.description.as_str().into(), (line.amount_micros as f64).into()])?,
329 );
330 }
331 self.db.batch(writes).await?;
332 if status == "paid" {
333 self.credit_invoice(workspace, &invoice, fee_cents).await?;
334 } else {
335 let error = paid.err().map_or_else(|| "the card was declined".to_owned(), |e| e.to_string().chars().take(200).collect());
336 self.mark_declined(workspace, &error).await?;
337 }
338 Ok(Ok(WorkspaceInvoice {
339 invoice_id: invoice.id,
340 workspace: workspace.to_owned(),
341 reason: reason.to_owned(),
342 period: period.to_owned(),
343 amount_micros: total,
344 status: status.to_owned(),
345 hosted_url: invoice.hosted_invoice_url,
346 pdf_url: invoice.invoice_pdf,
347 lines,
348 created_at: now,
349 fee_micros,
350 tax_micros,
351 }))
352 }
353
354 /// Enters an invoice's payment once, with the kind of card that paid:
355 /// what it paid for usage, never its tax or card fee, which are kept
356 /// apart (`tax_and_fees`).
357 async fn credit_invoice(&self, workspace: &str, invoice: &StripeInvoice, fee_cents: i64) -> Result<bool> {
358 let seen = self
359 .db
360 .prepare("SELECT id FROM ledger WHERE reference = ?")
361 .bind(&[invoice.id.as_str().into()])?
362 .first::<Value>(None)
363 .await?;
364 if seen.is_some() {
365 return Ok(false);
366 }
367 let extras = crate::tax::Extras { tax_cents: invoice.tax_cents(), fee_cents };
368 let amount = (invoice.amount_paid - extras.tax_cents - extras.fee_cents).max(0) * 10_000;
369 if amount <= 0 {
370 return Ok(false);
371 }
372 let description = if extras == crate::tax::Extras::default() {
373 format!("Paid invoice {}", invoice.id)
374 } else {
375 format!(
376 "Paid invoice {} (tax {} and card fee {} paid with it)",
377 invoice.id,
378 crate::features::cents(extras.tax_cents * 10_000),
379 crate::features::cents(extras.fee_cents * 10_000)
380 )
381 };
382 self.enter(workspace, EntryKind::TopUp, amount, &description, &invoice.id, None, None, None).await?;
383 self.record_extras(workspace, &invoice.id, invoice.payment_intent.as_deref(), extras, None).await?;
384 // Prepaid cards pay, but never raise the limit.
385 if let (Some(stripe), Some(charge)) = (&self.stripe, &invoice.charge)
386 && let Ok(charge) = stripe.get::<Value>(&format!("/charges/{charge}")).await
387 && let Some(funding) = charge["payment_method_details"]["card"]["funding"].as_str() {
388 self.db
389 .prepare("UPDATE ledger SET funding = ? WHERE reference = ?")
390 .bind(&[funding.into(), invoice.id.as_str().into()])?
391 .run()
392 .await?;
393 }
394 Ok(true)
395 }
396
397 pub(crate) async fn mark_declined(&self, workspace: &str, error: &str) -> Result<()> {
398 let now = rfc3339(now_ms());
399 self.db
400 .prepare(
401 "INSERT INTO limits (workspace, autopay_failed_at, autopay_error, updated_at) VALUES (?1, ?2, ?3, ?2)
402 ON CONFLICT (workspace) DO UPDATE SET autopay_failed_at = ?2, autopay_error = ?3, updated_at = ?2",
403 )
404 .bind(&[workspace.into(), now.as_str().into(), error.into()])?
405 .run()
406 .await?;
407 Ok(())
408 }
409
410 /// A workspace invoice paid later, on Stripe's page or by a retry.
411 pub(crate) async fn workspace_invoice_paid(&self, invoice_id: &str) -> Result<Option<String>> {
412 #[derive(Deserialize)]
413 struct Row {
414 workspace: String,
415 #[serde(default)]
416 fee_micros: i64,
417 }
418 let Some(row) = self
419 .db
420 .prepare("SELECT workspace, fee_micros FROM workspace_invoices WHERE invoice_id = ?")
421 .bind(&[invoice_id.into()])?
422 .first::<Row>(None)
423 .await?
424 else {
425 return Ok(None);
426 };
427 let Some(stripe) = &self.stripe else { return Ok(None) };
428 let invoice: StripeInvoice = stripe.get(&format!("/invoices/{invoice_id}")).await?;
429 self.db
430 .prepare("UPDATE workspace_invoices SET status = 'paid', paid_at = ?, tax_micros = ? WHERE invoice_id = ?")
431 .bind(&[rfc3339(now_ms()).into(), ((invoice.tax_cents() * 10_000) as f64).into(), invoice_id.into()])?
432 .run()
433 .await?;
434 let credited = self.credit_invoice(&row.workspace, &invoice, row.fee_micros / 10_000).await?;
435 Ok(Some(format!(
436 "invoice {invoice_id} for {} paid{}",
437 row.workspace,
438 if credited { "" } else { " (already credited)" }
439 )))
440 }
441
442 pub(crate) async fn workspace_invoices(&self, workspace: &str) -> Result<Vec<WorkspaceInvoice>> {
443 let rows = self
444 .db
445 .prepare("SELECT * FROM workspace_invoices WHERE workspace = ? ORDER BY created_at DESC LIMIT 36")
446 .bind(&[workspace.into()])?
447 .all()
448 .await?
449 .results::<InvoiceRow>()?;
450 let mut invoices = vec![];
451 for row in rows {
452 let lines = self
453 .db
454 .prepare("SELECT description, amount_micros FROM workspace_invoice_lines WHERE invoice_id = ? ORDER BY position")
455 .bind(&[row.invoice_id.as_str().into()])?
456 .all()
457 .await?
458 .results::<LineRow>()?
459 .into_iter()
460 .map(|l| InvoiceItem { description: l.description, amount_micros: l.amount_micros })
461 .collect();
462 invoices.push(WorkspaceInvoice {
463 invoice_id: row.invoice_id,
464 workspace: row.workspace,
465 reason: row.reason,
466 period: row.period,
467 amount_micros: row.amount_micros,
468 status: row.status,
469 hosted_url: row.hosted_url,
470 pdf_url: row.pdf_url,
471 lines,
472 created_at: row.created_at,
473 fee_micros: row.fee_micros,
474 tax_micros: row.tax_micros,
475 });
476 }
477 Ok(invoices)
478 }
479
480 /// `invoices`: for the workspace's members.
481 pub(crate) async fn invoices(&self, a: InvoicesArgs) -> Result<Outcome<Vec<WorkspaceInvoice>>> {
482 let workspace = a.workspace.to_lowercase();
483 if !a.viewer.is_some_and(|viewer| viewer.is_member(&workspace)) {
484 return Ok(Outcome::fail(FailureCode::Forbidden, "Only members can see a workspace's invoices."));
485 }
486 Ok(Outcome::Ok(self.workspace_invoices(&workspace).await?))
487 }
488}
489
490#[cfg(test)]
491mod tests {
492 use super::*;
493
494 #[test]
495 fn an_invoice_adds_up_to_what_is_owed() {
496 let used = vec![("Agents on g1t's models".to_owned(), 40_000_000), ("Sandbox time".to_owned(), 10_000_000)];
497 // $10 of credit was paid in advance.
498 let lines = invoice_lines(&used, 40_000_000);
499 assert_eq!(lines.last().unwrap().description, "Paid in advance");
500 assert_eq!(lines.iter().map(|l| l.amount_micros).sum::<i64>(), 40_000_000);
501 // $5 was left unpaid from before.
502 let lines = invoice_lines(&used, 55_000_000);
503 assert_eq!(lines.last().unwrap().description, "Unpaid from earlier");
504 assert_eq!(lines.iter().map(|l| l.amount_micros).sum::<i64>(), 55_000_000);
505 // Exactly what was used.
506 assert_eq!(invoice_lines(&used, 50_000_000).len(), 2);
507 }
508
509 #[test]
510 fn an_invoice_holds_only_its_own_lines() {
511 let draft = draft_fields("cus_1", "acme", "month", "2026-09", "g1t usage".to_owned());
512 assert!(draft.contains(&("pending_invoice_items_behavior", "exclude".to_owned())));
513 // Taxed by Stripe Tax, every line at g1t's tax code, excluding tax.
514 assert!(draft.contains(&("automatic_tax[enabled]", "true".to_owned())));
515 let line = item_fields("cus_1", "in_1", "acme", crate::stripe::CARD_FEE_LINE, 61);
516 assert!(line.contains(&("tax_code", crate::stripe::TAX_CODE.to_owned())));
517 assert!(line.contains(&("tax_behavior", "exclusive".to_owned())));
518 // Left a draft for want of an address: asked for, never charged.
519 assert!(needs_tax_location(&serde_json::json!({ "automatic_tax": { "status": "requires_location_inputs" } })));
520 assert!(!needs_tax_location(&serde_json::json!({ "automatic_tax": { "status": "complete" } })));
521 let item = item_fields("cus_1", "in_1", "acme", "Sandbox time", 1_234);
522 assert!(item.contains(&("invoice", "in_1".to_owned())));
523 assert!(item.contains(&("amount", "1234".to_owned())));
524 }
525
526 #[test]
527 fn only_the_card_saying_no_is_a_decline() {
528 let declined = r#"the card processor answered 402: {"error": {"code": "card_declined", "type": "card_error"}}"#;
529 assert!(is_decline(declined));
530 assert!(is_decline(r#"the card processor answered 400: {"error": {"type": "card_error"}}"#));
531 // Stripe down, busy or failing, or the network: tried again, nobody stopped.
532 assert!(!is_decline(r#"the card processor answered 500: {"error": {"type": "api_error"}}"#));
533 assert!(!is_decline(r#"the card processor answered 429: {"error": {"type": "rate_limit_error"}}"#));
534 assert!(!is_decline("Network connection lost."));
535 }
536
537 fn items(micros: &[i64]) -> Vec<InvoiceItem> {
538 micros.iter().map(|&amount_micros| InvoiceItem { description: String::new(), amount_micros }).collect()
539 }
540
541 #[test]
542 fn the_card_is_charged_what_is_owed_rounded_up_to_the_cent_never_down() {
543 // $1.234567 + $2.345678 = $3.580245 owed: 359 cents, where cutting
544 // each line would have charged 357.
545 let cents = line_cents(&items(&[1_234_567, 2_345_678]));
546 assert_eq!(cents.iter().sum::<i64>(), 359);
547 assert_eq!(cents, vec![124, 235]);
548 // Whole cents stay as they are.
549 assert_eq!(line_cents(&items(&[40_000_000, 10_000_000])), vec![4_000, 1_000]);
550 // A credit line keeps its full credit; the total still rounds up.
551 // $50.004 used, $10.0025 paid in advance: $40.0015 owed, 4,001 cents.
552 let cents = line_cents(&items(&[50_004_000, -10_002_500]));
553 assert_eq!(cents.iter().sum::<i64>(), 4_001);
554 // Lines under a cent each add up to the cents they make together.
555 let cents = line_cents(&items(&[4_000, 4_000, 4_000]));
556 assert_eq!(cents.iter().sum::<i64>(), 2);
557 // Every invoice the close makes: never less than owed, never a cent more.
558 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)] {
559 let lines = invoice_lines(&used, owed);
560 let charged = line_cents(&lines).iter().sum::<i64>() * 10_000;
561 assert!(charged >= owed && charged - owed < 10_000, "{charged} for {owed}");
562 }
563 }
564}