Pick any line to see why it is the way it is: the commit, the pull request and issue it came from, and what the agent was thinking.
| Paid features: a workspace turns on Deployments with a monthly plan | 1 | //! The card processor, behind the calls billing needs: start a payment |
| Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look | 2 | //! page, save and verify a card, ask whether a payment was made, and start, |
| 3 | //! read or end the monthly plan. Stripe speaks form-encoded requests and | |
| 4 | //! JSON answers. | |
| 5 | //! | |
| 6 | //! Every Stripe object billing needs beyond customers and their payments | |
| 7 | //! (the plan's product, the billing page's settings) is made the first time | |
| 8 | //! it is needed, and found again by its `metadata[g1t]` after that. | |
| Usage, Billing settings and prepaid AI credit; fixes from the UX audit | 9 | //! |
| 10 | //! Every request names the API version it is written for | |
| 11 | //! (`STRIPE_VERSION`). Without it Stripe answers at the account's default, | |
| 12 | //! which for an account made today is a newer version than this code reads: | |
| 13 | //! invoices no longer carry `subscription`, charges no longer carry | |
| 14 | //! `invoice`, and parameters this code sends can be refused. A failure is | |
| 15 | //! never shown raw: `friendly` turns it into a sentence for the page. | |
| Agents as a team: lifecycle, merge queue, billing and a new shell | 16 | |
| 17 | use serde::Deserialize; | |
| 18 | use worker::{Error, Fetch, Headers, Method, Request, RequestInit, Result}; | |
| 19 | ||
| 20 | const API: &str = "https://api.stripe.com/v1"; | |
| 21 | ||
| Usage, Billing settings and prepaid AI credit; fixes from the UX audit | 22 | /// The Stripe API version billing is written against. Changing it is a |
| 23 | /// code change: read Stripe's upgrade notes for every field billing reads. | |
| 24 | pub(crate) const STRIPE_VERSION: &str = "2025-02-24.acacia"; | |
| 25 | ||
| Merge Stripe Tax, the card fee on card payments, and one free workspace per person | 26 | /// Stripe Tax's code for what g1t sells, on every product, price and |
| 27 | /// invoice line: software as a service, for business use. A card fee line | |
| 28 | /// carries it too, since a fee for paying for a sale is taxed as the sale. | |
| 29 | pub(crate) const TAX_CODE: &str = "txcd_10103001"; | |
| 30 | ||
| 31 | /// What every payment page (payment or subscription mode) asks of Stripe | |
| 32 | /// Tax: tax worked out on top of the price shown, from a billing address | |
| 33 | /// it always collects, with the buyer's tax ID if they have one. With a | |
| 34 | /// customer already, what was entered is saved on it, so invoices and | |
| 35 | /// off-session charges later find the address too. Checkout refuses | |
| 36 | /// `automatic_tax` for a customer with no address unless it may save one | |
| 37 | /// (`customer_update[address]`), and `tax_id_collection` unless it may save | |
| 38 | /// the name (`customer_update[name]`). | |
| 39 | pub(crate) fn checkout_tax_fields(customer: Option<&str>) -> Vec<(&'static str, String)> { | |
| 40 | let mut fields = vec![ | |
| 41 | ("automatic_tax[enabled]", "true".to_owned()), | |
| 42 | ("billing_address_collection", "required".to_owned()), | |
| 43 | ("tax_id_collection[enabled]", "true".to_owned()), | |
| 44 | ]; | |
| 45 | if customer.is_some() { | |
| 46 | fields.extend([("customer_update[address]", "auto".to_owned()), ("customer_update[name]", "auto".to_owned())]); | |
| 47 | } | |
| 48 | fields | |
| 49 | } | |
| 50 | ||
| 51 | /// Whether Stripe refused because it could not tell where the customer is | |
| 52 | /// for tax: no address, or not enough of one. | |
| 53 | pub(crate) fn is_tax_location_error(error: &Error) -> bool { | |
| 54 | let text = error.to_string(); | |
| 55 | text.contains("customer_tax_location_invalid") || text.contains("requires_location_inputs") | |
| 56 | } | |
| 57 | ||
| 58 | /// Whether an address is enough for Stripe Tax to place the customer: a | |
| 59 | /// country, and in the United States a postal code (in Canada a postal | |
| 60 | /// code or a province). | |
| 61 | pub(crate) fn address_places_customer(address: &serde_json::Value) -> bool { | |
| 62 | let text = |key: &str| address[key].as_str().map(str::trim).unwrap_or_default().to_owned(); | |
| 63 | match text("country").to_uppercase().as_str() { | |
| 64 | "" => false, | |
| 65 | "US" => !text("postal_code").is_empty(), | |
| 66 | "CA" => !text("postal_code").is_empty() || !text("state").is_empty(), | |
| 67 | _ => true, | |
| 68 | } | |
| 69 | } | |
| 70 | ||
| Usage, Billing settings and prepaid AI credit; fixes from the UX audit | 71 | /// What a Stripe failure says, for the person on the page: Stripe's own |
| 72 | /// message when it gave one (never the request or any key), else that it | |
| 73 | /// could not be reached. | |
| 74 | pub(crate) fn friendly(error: &Error) -> String { | |
| 75 | let text = error.to_string(); | |
| 76 | let message = text | |
| 77 | .split_once(": ") | |
| 78 | .and_then(|(_, body)| serde_json::from_str::<serde_json::Value>(body).ok()) | |
| 79 | .and_then(|body| body["error"]["message"].as_str().map(str::to_owned)); | |
| 80 | match message { | |
| 81 | Some(message) => format!("Stripe refused it: {}", message.trim_end_matches('.').to_owned() + "."), | |
| 82 | None if text.contains("the card processor answered") => "Stripe refused it. Try again in a minute; if it keeps happening, write to support@g1t.sh.".to_owned(), | |
| 83 | None => "Stripe could not be reached. Try again in a minute.".to_owned(), | |
| 84 | } | |
| 85 | } | |
| 86 | ||
| 87 | /// Whether Stripe declined a card (as opposed to refusing the request). | |
| 88 | pub(crate) fn is_card_error(error: &Error) -> bool { | |
| 89 | let text = error.to_string(); | |
| 90 | text.contains("\"card_error\"") || text.contains("authentication_required") | |
| 91 | } | |
| 92 | ||
| Agents as a team: lifecycle, merge queue, billing and a new shell | 93 | pub struct Stripe { |
| 94 | key: String, | |
| 95 | } | |
| 96 | ||
| 97 | /// A payment page, and the payment made through it. | |
| 98 | #[derive(Deserialize)] | |
| 99 | pub struct Session { | |
| 100 | pub id: String, | |
| 101 | /// Where to send the person. Absent once the page has been used. | |
| 102 | pub url: Option<String>, | |
| 103 | /// `paid` once the money has been taken. | |
| 104 | pub payment_status: String, | |
| Merge Stripe Tax, the card fee on card payments, and one free workspace per person | 105 | /// What was paid, in cents, tax included. |
| Agents as a team: lifecycle, merge queue, billing and a new shell | 106 | pub amount_total: Option<u32>, |
| Merge Stripe Tax, the card fee on card payments, and one free workspace per person | 107 | /// What the lines came to before tax, in cents. |
| 108 | #[serde(default)] | |
| 109 | pub amount_subtotal: Option<u32>, | |
| 110 | /// The tax Stripe added (`amount_tax`), among other totals. | |
| 111 | #[serde(default)] | |
| 112 | pub total_details: Option<TotalDetails>, | |
| 113 | /// For a payment page: the payment that took the money. | |
| 114 | #[serde(default)] | |
| 115 | pub payment_intent: Option<String>, | |
| Agents as a team: lifecycle, merge queue, billing and a new shell | 116 | pub customer: Option<String>, |
| Paid features: a workspace turns on Deployments with a monthly plan | 117 | /// For a plan's page: the subscription it started. |
| 118 | #[serde(default)] | |
| 119 | pub subscription: Option<String>, | |
| Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look | 120 | /// For a card check's page: the setup that saved and verified the card. |
| 121 | #[serde(default)] | |
| 122 | pub setup_intent: Option<String>, | |
| 123 | } | |
| 124 | ||
| Merge Stripe Tax, the card fee on card payments, and one free workspace per person | 125 | #[derive(Default, Deserialize)] |
| 126 | pub struct TotalDetails { | |
| 127 | #[serde(default)] | |
| 128 | pub amount_tax: i64, | |
| 129 | } | |
| 130 | ||
| 131 | impl Session { | |
| 132 | /// The tax Stripe added on the page, in cents. | |
| 133 | pub fn tax_cents(&self) -> i64 { | |
| 134 | self.total_details.as_ref().map_or(0, |t| t.amount_tax.max(0)) | |
| 135 | } | |
| 136 | ||
| 137 | /// What the page's lines came to before tax, in cents: the total less | |
| 138 | /// the tax when Stripe gives no subtotal. | |
| 139 | pub fn before_tax_cents(&self) -> i64 { | |
| 140 | match self.amount_subtotal { | |
| 141 | Some(subtotal) => i64::from(subtotal), | |
| 142 | None => (i64::from(self.amount_total.unwrap_or(0)) - self.tax_cents()).max(0), | |
| 143 | } | |
| 144 | } | |
| 145 | } | |
| 146 | ||
| Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look | 147 | /// A card saved and verified: what a card check found. |
| 148 | #[derive(Debug, Deserialize)] | |
| 149 | pub struct CheckedCard { | |
| 150 | pub payment_method: String, | |
| 151 | pub fingerprint: Option<String>, | |
| 152 | pub brand: Option<String>, | |
| 153 | pub last4: Option<String>, | |
| 154 | /// `credit`, `debit`, `prepaid` or `unknown`. | |
| 155 | pub funding: Option<String>, | |
| 156 | pub country: Option<String>, | |
| Merge Stripe Tax, the card fee on card payments, and one free workspace per person | 157 | /// The billing address entered with the card, as Stripe keeps it. |
| 158 | #[serde(default)] | |
| 159 | pub address: Option<serde_json::Value>, | |
| Agents as a team: lifecycle, merge queue, billing and a new shell | 160 | } |
| 161 | ||
| Billing on Stripe's pages, month-end charges, warnings; sudo by workspace | 162 | /// g1t's settings for Stripe's hosted billing page. |
| 163 | #[derive(Debug, Deserialize)] | |
| 164 | pub struct PortalConfiguration { | |
| 165 | pub id: String, | |
| 166 | #[serde(default)] | |
| 167 | pub login_page: Option<LoginPage>, | |
| 168 | #[serde(default)] | |
| 169 | pub metadata: Option<std::collections::HashMap<String, String>>, | |
| 170 | } | |
| 171 | ||
| 172 | #[derive(Debug, Deserialize)] | |
| 173 | pub struct LoginPage { | |
| 174 | pub url: Option<String>, | |
| 175 | } | |
| 176 | ||
| Paid features: a workspace turns on Deployments with a monthly plan | 177 | /// A monthly plan. |
| 178 | #[derive(Deserialize)] | |
| 179 | pub struct StripeSubscription { | |
| 180 | pub id: String, | |
| 181 | /// `active`, `trialing`, `past_due`, `unpaid`, `canceled`, `incomplete`… | |
| 182 | pub status: String, | |
| 183 | #[serde(default)] | |
| 184 | pub cancel_at_period_end: bool, | |
| 185 | /// Unix seconds. Older API versions carry it here… | |
| 186 | #[serde(default)] | |
| 187 | pub current_period_end: Option<i64>, | |
| 188 | /// …newer ones on each item. | |
| 189 | #[serde(default)] | |
| 190 | pub items: Option<Items>, | |
| 191 | } | |
| 192 | ||
| 193 | #[derive(Deserialize)] | |
| 194 | pub struct Items { | |
| 195 | pub data: Vec<Item>, | |
| 196 | } | |
| 197 | ||
| 198 | #[derive(Deserialize)] | |
| 199 | pub struct Item { | |
| 200 | #[serde(default)] | |
| 201 | pub current_period_end: Option<i64>, | |
| 202 | } | |
| 203 | ||
| 204 | impl StripeSubscription { | |
| 205 | /// When the period paid for ends, in Unix seconds. | |
| 206 | pub fn period_end(&self) -> Option<i64> { | |
| 207 | self.current_period_end.or_else(|| { | |
| 208 | self.items | |
| 209 | .as_ref() | |
| 210 | .and_then(|items| items.data.iter().filter_map(|item| item.current_period_end).max()) | |
| 211 | }) | |
| 212 | } | |
| 213 | } | |
| 214 | ||
| Agents as a team: lifecycle, merge queue, billing and a new shell | 215 | /// Percent-encodes a form value. |
| 216 | fn encode(value: &str) -> String { | |
| 217 | let mut encoded = String::with_capacity(value.len()); | |
| 218 | for byte in value.bytes() { | |
| 219 | match byte { | |
| 220 | b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => { | |
| 221 | encoded.push(byte as char); | |
| 222 | } | |
| 223 | _ => encoded.push_str(&format!("%{byte:02X}")), | |
| 224 | } | |
| 225 | } | |
| 226 | encoded | |
| 227 | } | |
| 228 | ||
| 229 | /// `name=value` pairs as a form body. | |
| 230 | pub(crate) fn form(fields: &[(&str, String)]) -> String { | |
| 231 | fields | |
| 232 | .iter() | |
| 233 | .map(|(name, value)| format!("{}={}", encode(name), encode(value))) | |
| 234 | .collect::<Vec<_>>() | |
| 235 | .join("&") | |
| 236 | } | |
| 237 | ||
| Billing: credits with a kind and expiry, discounts instead of comped, and safer charging | 238 | /// The idempotency key for starting a plan on a saved card: the same |
| 239 | /// workspace, plan and card within the same ten minutes is one subscription, | |
| 240 | /// however many times it is asked for (a double click, two tabs), so a | |
| 241 | /// workspace is never billed twice for one plan. A different card is a new | |
| 242 | /// attempt, as Stripe refuses a key reused with other fields. | |
| 243 | pub(crate) fn plan_key(workspace: &str, feature: &str, payment_method: &str, now_ms: u64) -> String { | |
| 244 | format!("plan/{workspace}/{feature}/{payment_method}/{}", now_ms / 600_000) | |
| 245 | } | |
| 246 | ||
| Agents as a team: lifecycle, merge queue, billing and a new shell | 247 | impl Stripe { |
| 248 | pub fn new(key: String) -> Self { | |
| 249 | Stripe { key } | |
| 250 | } | |
| 251 | ||
| 252 | /// Whether the key is for real cards, not Stripe's test mode. | |
| 253 | pub fn live(&self) -> bool { | |
| 254 | is_live(&self.key) | |
| 255 | } | |
| 256 | ||
| Stripe webhooks, enterprise invoices, and sudo for both | 257 | /// A GET of any Stripe resource, for the webhook handlers. |
| 258 | pub(crate) async fn get<T: for<'a> Deserialize<'a>>(&self, path: &str) -> Result<T> { | |
| 259 | self.call(Method::Get, path, None).await | |
| 260 | } | |
| 261 | ||
| Usage, Billing settings and prepaid AI credit; fixes from the UX audit | 262 | /// A DELETE of any Stripe resource. |
| 263 | pub(crate) async fn delete<T: for<'a> Deserialize<'a>>(&self, path: &str) -> Result<T> { | |
| 264 | self.call(Method::Delete, path, None).await | |
| 265 | } | |
| 266 | ||
| Stripe webhooks, enterprise invoices, and sudo for both | 267 | /// A form POST to any Stripe resource. |
| 268 | pub(crate) async fn post<T: for<'a> Deserialize<'a>>(&self, path: &str, fields: &[(&str, String)]) -> Result<T> { | |
| 269 | self.call(Method::Post, path, Some(form(fields))).await | |
| 270 | } | |
| 271 | ||
| Two limits, real invoices, trust that grows by itself, sales signals | 272 | /// A form POST that Stripe does at most once for `key`, however often |
| 273 | /// it is sent. | |
| 274 | pub(crate) async fn post_idempotent<T: for<'a> Deserialize<'a>>( | |
| 275 | &self, | |
| 276 | path: &str, | |
| 277 | fields: &[(&str, String)], | |
| 278 | key: &str, | |
| 279 | ) -> Result<T> { | |
| 280 | self.send(Method::Post, path, Some(form(fields)), Some(key)).await | |
| 281 | } | |
| 282 | ||
| Agents as a team: lifecycle, merge queue, billing and a new shell | 283 | async fn call<T: for<'a> Deserialize<'a>>( |
| 284 | &self, | |
| 285 | method: Method, | |
| 286 | path: &str, | |
| 287 | body: Option<String>, | |
| 288 | ) -> Result<T> { | |
| Billing accounts, terms and enterprises; g1t is no longer free | 289 | self.send(method, path, body, None).await |
| 290 | } | |
| 291 | ||
| 292 | async fn send<T: for<'a> Deserialize<'a>>( | |
| 293 | &self, | |
| 294 | method: Method, | |
| 295 | path: &str, | |
| 296 | body: Option<String>, | |
| 297 | idempotency_key: Option<&str>, | |
| 298 | ) -> Result<T> { | |
| Agents as a team: lifecycle, merge queue, billing and a new shell | 299 | let headers = Headers::new(); |
| 300 | headers.set("authorization", &format!("Bearer {}", self.key))?; | |
| Usage, Billing settings and prepaid AI credit; fixes from the UX audit | 301 | headers.set("stripe-version", STRIPE_VERSION)?; |
| Billing accounts, terms and enterprises; g1t is no longer free | 302 | if let Some(key) = idempotency_key { |
| 303 | headers.set("idempotency-key", key)?; | |
| 304 | } | |
| Agents as a team: lifecycle, merge queue, billing and a new shell | 305 | if body.is_some() { |
| 306 | headers.set("content-type", "application/x-www-form-urlencoded")?; | |
| 307 | } | |
| 308 | let mut init = RequestInit::new(); | |
| 309 | init.with_method(method).with_headers(headers); | |
| 310 | if let Some(body) = body { | |
| 311 | init.with_body(Some(body.into())); | |
| 312 | } | |
| 313 | let request = Request::new_with_init(&format!("{API}{path}"), &init)?; | |
| 314 | let mut response = Fetch::Request(request).send().await?; | |
| 315 | if response.status_code() != 200 { | |
| 316 | return Err(Error::RustError(format!( | |
| 317 | "the card processor answered {}: {}", | |
| 318 | response.status_code(), | |
| 319 | response.text().await.unwrap_or_default() | |
| 320 | ))); | |
| 321 | } | |
| 322 | response.json().await | |
| Billing accounts, terms and enterprises; g1t is no longer free | 323 | } |
| 324 | ||
| Billing on Stripe's pages, month-end charges, warnings; sudo by workspace | 325 | /// A customer for a workspace that has none yet. |
| 326 | pub async fn create_customer(&self, workspace: &str) -> Result<String> { | |
| 327 | #[derive(Deserialize)] | |
| 328 | struct Customer { | |
| 329 | id: String, | |
| 330 | } | |
| 331 | let fields = [ | |
| 332 | ("name", workspace.to_owned()), | |
| 333 | ("metadata[workspace]", workspace.to_owned()), | |
| 334 | ]; | |
| 335 | let customer: Customer = self.call(Method::Post, "/customers", Some(form(&fields))).await?; | |
| 336 | Ok(customer.id) | |
| 337 | } | |
| 338 | ||
| 339 | /// A session on Stripe's hosted billing page (the customer portal) for | |
| 340 | /// the customer, coming back to `return_url`. | |
| 341 | pub async fn portal_session(&self, customer: &str, return_url: &str) -> Result<String> { | |
| 342 | #[derive(Deserialize)] | |
| 343 | struct Portal { | |
| 344 | url: String, | |
| 345 | } | |
| 346 | let configuration = self.portal_configuration().await?; | |
| 347 | let fields = [ | |
| 348 | ("customer", customer.to_owned()), | |
| 349 | ("return_url", return_url.to_owned()), | |
| 350 | ("configuration", configuration.id), | |
| 351 | ]; | |
| 352 | let portal: Portal = self.call(Method::Post, "/billing_portal/sessions", Some(form(&fields))).await?; | |
| 353 | Ok(portal.url) | |
| 354 | } | |
| 355 | ||
| 356 | /// g1t's billing page settings at Stripe, made the first time they are | |
| 357 | /// needed: cards, invoices, billing details, and a sign-in page. | |
| 358 | pub async fn portal_configuration(&self) -> Result<PortalConfiguration> { | |
| 359 | #[derive(Deserialize)] | |
| 360 | struct List { | |
| 361 | data: Vec<PortalConfiguration>, | |
| 362 | } | |
| 363 | let list: List = self | |
| 364 | .call(Method::Get, "/billing_portal/configurations?active=true&limit=20", None) | |
| 365 | .await?; | |
| 366 | if let Some(existing) = list | |
| 367 | .data | |
| 368 | .into_iter() | |
| 369 | .find(|c| c.metadata.as_ref().and_then(|m| m.get("g1t")).is_some()) | |
| 370 | { | |
| 371 | return Ok(existing); | |
| 372 | } | |
| 373 | let fields = [ | |
| 374 | ("business_profile[headline]", "g1t billing: your card, invoices and billing details".to_owned()), | |
| 375 | ("features[payment_method_update][enabled]", "true".to_owned()), | |
| 376 | ("features[invoice_history][enabled]", "true".to_owned()), | |
| 377 | ("features[customer_update][enabled]", "true".to_owned()), | |
| 378 | ("features[customer_update][allowed_updates][0]", "email".to_owned()), | |
| 379 | ("features[customer_update][allowed_updates][1]", "address".to_owned()), | |
| 380 | ("features[customer_update][allowed_updates][2]", "name".to_owned()), | |
| 381 | ("features[customer_update][allowed_updates][3]", "tax_id".to_owned()), | |
| 382 | ("login_page[enabled]", "true".to_owned()), | |
| 383 | ("metadata[g1t]", "billing".to_owned()), | |
| 384 | ]; | |
| 385 | self.call(Method::Post, "/billing_portal/configurations", Some(form(&fields))).await | |
| 386 | } | |
| 387 | ||
| 388 | /// The customer's email at Stripe, if they gave one. | |
| 389 | pub async fn customer_email(&self, customer: &str) -> Result<Option<String>> { | |
| 390 | #[derive(Deserialize)] | |
| 391 | struct Customer { | |
| 392 | email: Option<String>, | |
| 393 | } | |
| 394 | let found: Customer = self.call(Method::Get, &format!("/customers/{}", encode(customer)), None).await?; | |
| 395 | Ok(found.email) | |
| 396 | } | |
| 397 | ||
| Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look | 398 | /// Starts a page on which `amount_cents` is paid in advance: by card, |
| 399 | /// with 3-D Secure asked for wherever the card supports it, the card | |
| 400 | /// kept for later charges; or, with `bank_transfer` and a customer, by | |
| 401 | /// bank transfer to the account details Stripe gives, counted when the | |
| 402 | /// money arrives. | |
| Agents as a team: lifecycle, merge queue, billing and a new shell | 403 | pub async fn start_checkout( |
| 404 | &self, | |
| 405 | workspace: &str, | |
| 406 | amount_cents: u32, | |
| Merge Stripe Tax, the card fee on card payments, and one free workspace per person | 407 | fee_cents: u32, |
| Agents as a team: lifecycle, merge queue, billing and a new shell | 408 | customer: Option<&str>, |
| 409 | return_url: &str, | |
| Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look | 410 | bank_transfer: bool, |
| Agents as a team: lifecycle, merge queue, billing and a new shell | 411 | ) -> Result<Session> { |
| Merge Stripe Tax, the card fee on card payments, and one free workspace per person | 412 | let fields = prepay_fields(workspace, amount_cents, fee_cents, customer, return_url, bank_transfer); |
| 413 | let key = page_key( | |
| 414 | "prepay", | |
| 415 | workspace, | |
| 416 | &format!("{amount_cents}/{fee_cents}/{bank_transfer}/{}", customer.unwrap_or("new")), | |
| 417 | g1t_kit::now_ms(), | |
| 418 | ); | |
| Usage, Billing settings and prepaid AI credit; fixes from the UX audit | 419 | self.send(Method::Post, "/checkout/sessions", Some(form(&fields)), Some(&key)).await |
| Agents as a team: lifecycle, merge queue, billing and a new shell | 420 | } |
| 421 | ||
| Merge Stripe Tax, the card fee on card payments, and one free workspace per person | 422 | /// Starts a page on which a feature's monthly plan is paid for by card, |
| 423 | /// with the card fee as a monthly line of its own. | |
| 424 | #[allow(clippy::too_many_arguments)] | |
| Paid features: a workspace turns on Deployments with a monthly plan | 425 | pub async fn start_subscription( |
| 426 | &self, | |
| 427 | workspace: &str, | |
| 428 | feature: &str, | |
| 429 | title: &str, | |
| 430 | monthly_cents: u32, | |
| Merge Stripe Tax, the card fee on card payments, and one free workspace per person | 431 | fee_cents: u32, |
| Paid features: a workspace turns on Deployments with a monthly plan | 432 | customer: Option<&str>, |
| 433 | return_url: &str, | |
| 434 | ) -> Result<Session> { | |
| Merge Stripe Tax, the card fee on card payments, and one free workspace per person | 435 | let fields = subscription_fields(workspace, feature, title, monthly_cents, fee_cents, customer, return_url); |
| 436 | let key = page_key( | |
| 437 | "plan", | |
| 438 | workspace, | |
| 439 | &format!("{feature}/{monthly_cents}/{fee_cents}/{}", customer.unwrap_or("new")), | |
| 440 | g1t_kit::now_ms(), | |
| 441 | ); | |
| Usage, Billing settings and prepaid AI credit; fixes from the UX audit | 442 | self.send(Method::Post, "/checkout/sessions", Some(form(&fields)), Some(&key)).await |
| Paid features: a workspace turns on Deployments with a monthly plan | 443 | } |
| 444 | ||
| Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look | 445 | /// Starts a page that saves and verifies a card, with 3-D Secure asked |
| 446 | /// for wherever the card supports it. Nothing is charged: the card's | |
| 447 | /// bank sees at most a $0 or $1 authorization that is never captured. | |
| 448 | pub async fn start_card_check(&self, workspace: &str, customer: &str, return_url: &str) -> Result<Session> { | |
| Usage, Billing settings and prepaid AI credit; fixes from the UX audit | 449 | let fields = card_check_fields(workspace, customer, return_url); |
| 450 | let key = page_key("card_check", workspace, customer, g1t_kit::now_ms()); | |
| 451 | self.send(Method::Post, "/checkout/sessions", Some(form(&fields)), Some(&key)).await | |
| 452 | } | |
| 453 | ||
| 454 | /// Starts a page on which AI credit is bought: one payment by card, the | |
| 455 | /// card fee as its own line, the card kept for auto-reload. | |
| 456 | pub async fn start_credit_checkout(&self, purchase: &CreditPurchase<'_>) -> Result<Session> { | |
| 457 | let fields = credit_fields(purchase); | |
| 458 | let key = page_key( | |
| 459 | "ai_credit", | |
| 460 | purchase.workspace, | |
| 461 | &format!("{}/{}/{}", purchase.credit_cents, purchase.fee_cents, purchase.customer.unwrap_or("new")), | |
| 462 | g1t_kit::now_ms(), | |
| 463 | ); | |
| 464 | self.send(Method::Post, "/checkout/sessions", Some(form(&fields)), Some(&key)).await | |
| 465 | } | |
| 466 | ||
| 467 | /// The customer's default payment method: the one its invoices are | |
| 468 | /// charged to, else its newest card. None when it has none. | |
| 469 | pub async fn default_payment_method(&self, customer: &str) -> Result<Option<SavedMethod>> { | |
| 470 | let found: serde_json::Value = self | |
| 471 | .call( | |
| 472 | Method::Get, | |
| 473 | &format!("/customers/{}?expand[]=invoice_settings.default_payment_method", encode(customer)), | |
| 474 | None, | |
| 475 | ) | |
| 476 | .await?; | |
| 477 | if let Some(method) = SavedMethod::from_json(&found["invoice_settings"]["default_payment_method"]) { | |
| 478 | return Ok(Some(method)); | |
| 479 | } | |
| 480 | let list: serde_json::Value = self | |
| 481 | .call(Method::Get, &format!("/payment_methods?customer={}&type=card&limit=1", encode(customer)), None) | |
| 482 | .await?; | |
| 483 | Ok(list["data"].as_array().and_then(|data| data.first()).and_then(SavedMethod::from_json)) | |
| 484 | } | |
| 485 | ||
| 486 | /// The customer as Stripe keeps it, with its tax ids. | |
| 487 | pub async fn customer(&self, customer: &str) -> Result<serde_json::Value> { | |
| 488 | self.call(Method::Get, &format!("/customers/{}?expand[]=tax_ids", encode(customer)), None).await | |
| 489 | } | |
| 490 | ||
| 491 | /// The customer's invoices, newest first. | |
| 492 | pub async fn invoices(&self, customer: &str) -> Result<Vec<serde_json::Value>> { | |
| 493 | let list: serde_json::Value = self.call(Method::Get, &format!("/invoices?customer={}&limit=24", encode(customer)), None).await?; | |
| 494 | Ok(list["data"].as_array().cloned().unwrap_or_default()) | |
| 495 | } | |
| 496 | ||
| 497 | /// Charges a saved payment method now, with nobody there: auto-reload. | |
| 498 | /// Done at most once for `key`, however often it is sent. | |
| 499 | pub async fn charge_saved(&self, charge: &SavedCharge<'_>) -> Result<serde_json::Value> { | |
| 500 | self.send(Method::Post, "/payment_intents", Some(form(&saved_charge_fields(charge))), Some(charge.key)).await | |
| 501 | } | |
| Merge Stripe Tax, the card fee on card payments, and one free workspace per person | 502 | |
| 503 | /// Stripe Tax's figure for an off-session charge, which no Checkout | |
| 504 | /// page or invoice works out: the credit and the card fee, each at | |
| 505 | /// g1t's tax code and excluding tax, for the customer's saved address. | |
| 506 | /// A customer Stripe cannot place fails with | |
| 507 | /// `customer_tax_location_invalid` (`is_tax_location_error`). | |
| 508 | pub async fn tax_calculation(&self, charge: &SavedCharge<'_>) -> Result<TaxCalculation> { | |
| 509 | let key = format!("{}/tax", charge.key); | |
| 510 | self.send(Method::Post, "/tax/calculations", Some(form(&tax_calculation_fields(charge))), Some(&key)).await | |
| 511 | } | |
| 512 | ||
| 513 | /// Records a calculation as a tax transaction once its payment went | |
| 514 | /// through, so Stripe Tax reports and files it; `reference` is the | |
| 515 | /// PaymentIntent. Its id, for reversing it on a refund. | |
| 516 | pub async fn record_tax(&self, calculation: &str, reference: &str) -> Result<String> { | |
| 517 | #[derive(Deserialize)] | |
| 518 | struct Transaction { | |
| 519 | id: String, | |
| 520 | } | |
| 521 | let fields = [("calculation", calculation.to_owned()), ("reference", reference.to_owned())]; | |
| 522 | let made: Transaction = self | |
| 523 | .send(Method::Post, "/tax/transactions/create_from_calculation", Some(form(&fields)), Some(&format!("tax/{reference}"))) | |
| 524 | .await?; | |
| 525 | Ok(made.id) | |
| 526 | } | |
| 527 | ||
| 528 | /// Reverses a tax transaction in part for a refund: `refunded_cents` of | |
| 529 | /// the payment, tax included, taken back across all of it. | |
| 530 | pub async fn reverse_tax(&self, transaction: &str, reference: &str, refunded_cents: i64) -> Result<()> { | |
| 531 | let _: serde_json::Value = self | |
| 532 | .send( | |
| 533 | Method::Post, | |
| 534 | "/tax/transactions/create_reversal", | |
| 535 | Some(form(&reversal_fields(transaction, reference, refunded_cents))), | |
| 536 | Some(&format!("tax-reversal/{reference}")), | |
| 537 | ) | |
| 538 | .await?; | |
| 539 | Ok(()) | |
| 540 | } | |
| 541 | ||
| 542 | /// Copies the billing address entered with a card onto the customer | |
| 543 | /// when the customer has none Stripe Tax can use, so later invoices and | |
| 544 | /// charges can be taxed. Never replaces an address an owner gave. | |
| 545 | pub async fn fill_address(&self, customer: &str, address: &serde_json::Value) -> Result<bool> { | |
| 546 | if !address_places_customer(address) { | |
| 547 | return Ok(false); | |
| 548 | } | |
| 549 | let found = self.customer(customer).await?; | |
| 550 | if address_places_customer(&found["address"]) { | |
| 551 | return Ok(false); | |
| 552 | } | |
| 553 | let _: serde_json::Value = self.post(&format!("/customers/{}", encode(customer)), &address_fields(address)).await?; | |
| 554 | Ok(true) | |
| 555 | } | |
| 556 | ||
| 557 | /// Whether the customer's address is enough for Stripe Tax. | |
| 558 | pub async fn customer_placed(&self, customer: &str) -> Result<bool> { | |
| 559 | let found = self.customer(customer).await?; | |
| 560 | Ok(address_places_customer(&found["address"]) || address_places_customer(&found["shipping"]["address"])) | |
| 561 | } | |
| 562 | } | |
| 563 | ||
| 564 | /// Stripe Tax's answer for an off-session charge. | |
| 565 | #[derive(Debug, Deserialize)] | |
| 566 | pub struct TaxCalculation { | |
| 567 | pub id: String, | |
| 568 | /// The tax on top, in cents. | |
| 569 | #[serde(default)] | |
| 570 | pub tax_amount_exclusive: i64, | |
| 571 | } | |
| 572 | ||
| 573 | /// A customer's address from an address Stripe gave. | |
| 574 | pub(crate) fn address_fields(address: &serde_json::Value) -> Vec<(&'static str, String)> { | |
| 575 | let text = |key: &str| address[key].as_str().unwrap_or_default().to_owned(); | |
| 576 | vec![ | |
| 577 | ("address[line1]", text("line1")), | |
| 578 | ("address[line2]", text("line2")), | |
| 579 | ("address[city]", text("city")), | |
| 580 | ("address[state]", text("state")), | |
| 581 | ("address[postal_code]", text("postal_code")), | |
| 582 | ("address[country]", text("country")), | |
| 583 | ] | |
| 584 | } | |
| 585 | ||
| 586 | /// A tax calculation's fields: the credit and the card fee as lines at | |
| 587 | /// g1t's tax code, prices excluding tax. | |
| 588 | pub(crate) fn tax_calculation_fields(c: &SavedCharge<'_>) -> Vec<(&'static str, String)> { | |
| 589 | let mut fields = vec![ | |
| 590 | ("currency", "usd".to_owned()), | |
| 591 | ("customer", c.customer.to_owned()), | |
| 592 | ("line_items[0][amount]", c.credit_cents.to_string()), | |
| 593 | ("line_items[0][reference]", "ai_credit".to_owned()), | |
| 594 | ("line_items[0][tax_code]", TAX_CODE.to_owned()), | |
| 595 | ("line_items[0][tax_behavior]", "exclusive".to_owned()), | |
| 596 | ]; | |
| 597 | if c.fee_cents > 0 { | |
| 598 | fields.extend([ | |
| 599 | ("line_items[1][amount]", c.fee_cents.to_string()), | |
| 600 | ("line_items[1][reference]", "card_fee".to_owned()), | |
| 601 | ("line_items[1][tax_code]", TAX_CODE.to_owned()), | |
| 602 | ("line_items[1][tax_behavior]", "exclusive".to_owned()), | |
| 603 | ]); | |
| 604 | } | |
| 605 | fields | |
| Usage, Billing settings and prepaid AI credit; fixes from the UX audit | 606 | } |
| 607 | ||
| Merge Stripe Tax, the card fee on card payments, and one free workspace per person | 608 | /// A refund's tax reversal: a part of the payment, as a negative amount. |
| 609 | pub(crate) fn reversal_fields(transaction: &str, reference: &str, refunded_cents: i64) -> Vec<(&'static str, String)> { | |
| 610 | vec![ | |
| 611 | ("mode", "partial".to_owned()), | |
| 612 | ("original_transaction", transaction.to_owned()), | |
| 613 | ("reference", reference.to_owned()), | |
| 614 | ("flat_amount", (-refunded_cents.abs()).to_string()), | |
| 615 | ] | |
| 616 | } | |
| 617 | ||
| Usage, Billing settings and prepaid AI credit; fixes from the UX audit | 618 | /// An AI credit purchase, as its payment page needs it. |
| 619 | pub struct CreditPurchase<'a> { | |
| 620 | pub workspace: &'a str, | |
| 621 | pub credit_cents: u32, | |
| 622 | pub fee_cents: u32, | |
| 623 | pub customer: Option<&'a str>, | |
| 624 | pub return_url: &'a str, | |
| 625 | } | |
| 626 | ||
| 627 | /// A charge to a saved card with nobody there. | |
| 628 | pub struct SavedCharge<'a> { | |
| 629 | pub workspace: &'a str, | |
| 630 | pub customer: &'a str, | |
| 631 | pub payment_method: &'a str, | |
| 632 | pub credit_cents: u32, | |
| 633 | pub fee_cents: u32, | |
| Merge Stripe Tax, the card fee on card payments, and one free workspace per person | 634 | /// Tax on top, from `tax_calculation`. |
| 635 | pub tax_cents: u32, | |
| 636 | /// The calculation the tax came from, kept on the payment. | |
| 637 | pub tax_calculation: Option<&'a str>, | |
| Usage, Billing settings and prepaid AI credit; fixes from the UX audit | 638 | pub key: &'a str, |
| 639 | } | |
| 640 | ||
| 641 | /// A saved way to pay, as far as it is safe to show. | |
| 642 | #[derive(Clone, Debug, PartialEq)] | |
| 643 | pub struct SavedMethod { | |
| 644 | pub id: String, | |
| 645 | pub kind: String, | |
| 646 | pub brand: Option<String>, | |
| 647 | pub last4: Option<String>, | |
| 648 | pub exp_month: Option<u32>, | |
| 649 | pub exp_year: Option<u32>, | |
| 650 | } | |
| 651 | ||
| 652 | impl SavedMethod { | |
| 653 | fn from_json(method: &serde_json::Value) -> Option<SavedMethod> { | |
| 654 | let id = method["id"].as_str()?.to_owned(); | |
| 655 | let kind = method["type"].as_str().unwrap_or("card").to_owned(); | |
| 656 | let details = &method[kind.as_str()]; | |
| 657 | Some(SavedMethod { | |
| 658 | id, | |
| 659 | brand: details["brand"].as_str().or_else(|| details["bank_name"].as_str()).map(str::to_owned), | |
| 660 | last4: details["last4"].as_str().map(str::to_owned), | |
| 661 | exp_month: details["exp_month"].as_u64().map(|m| m as u32), | |
| 662 | exp_year: details["exp_year"].as_u64().map(|y| y as u32), | |
| 663 | kind, | |
| 664 | }) | |
| 665 | } | |
| 666 | } | |
| 667 | ||
| 668 | /// The idempotency key for a payment page: the same workspace, purpose and | |
| 669 | /// details within ten minutes is one page, however often it is asked for (a | |
| 670 | /// double click, two tabs). | |
| 671 | pub(crate) fn page_key(purpose: &str, workspace: &str, details: &str, now_ms: u64) -> String { | |
| 672 | format!("page/{purpose}/{workspace}/{details}/{}", now_ms / 600_000) | |
| 673 | } | |
| 674 | ||
| 675 | /// Where Stripe sends the person back, with the page's id under `name`. | |
| 676 | fn back_to(return_url: &str, name: &str) -> String { | |
| 677 | let separator = if return_url.contains('?') { '&' } else { '?' }; | |
| 678 | // Stripe fills in the page's id. | |
| 679 | format!("{return_url}{separator}{name}={{CHECKOUT_SESSION_ID}}") | |
| 680 | } | |
| 681 | ||
| Merge Stripe Tax, the card fee on card payments, and one free workspace per person | 682 | /// The name of the card fee's line everywhere it appears: Checkout pages, |
| 683 | /// subscriptions and invoices. Revenue figures find it by this name. | |
| 684 | pub(crate) const CARD_FEE_LINE: &str = "Card processing fee"; | |
| 685 | ||
| 686 | /// The form keys of one line on a payment page, for the first two lines | |
| 687 | /// (what is bought, and the card fee). | |
| 688 | const LINE_KEYS: [[&str; 8]; 2] = [ | |
| 689 | [ | |
| 690 | "line_items[0][quantity]", | |
| 691 | "line_items[0][price_data][currency]", | |
| 692 | "line_items[0][price_data][unit_amount]", | |
| 693 | "line_items[0][price_data][tax_behavior]", | |
| 694 | "line_items[0][price_data][product_data][name]", | |
| 695 | "line_items[0][price_data][product_data][tax_code]", | |
| 696 | "line_items[0][price_data][product_data][description]", | |
| 697 | "line_items[0][price_data][recurring][interval]", | |
| 698 | ], | |
| 699 | [ | |
| 700 | "line_items[1][quantity]", | |
| 701 | "line_items[1][price_data][currency]", | |
| 702 | "line_items[1][price_data][unit_amount]", | |
| 703 | "line_items[1][price_data][tax_behavior]", | |
| 704 | "line_items[1][price_data][product_data][name]", | |
| 705 | "line_items[1][price_data][product_data][tax_code]", | |
| 706 | "line_items[1][price_data][product_data][description]", | |
| 707 | "line_items[1][price_data][recurring][interval]", | |
| 708 | ], | |
| 709 | ]; | |
| 710 | ||
| 711 | /// One line on a payment page at g1t's tax code, its price excluding tax; | |
| 712 | /// monthly when `monthly`. | |
| 713 | fn page_line(index: usize, cents: u32, name: String, description: Option<String>, monthly: bool) -> Vec<(&'static str, String)> { | |
| 714 | let keys = LINE_KEYS[index.min(1)]; | |
| 715 | let mut fields = vec![ | |
| 716 | (keys[0], "1".to_owned()), | |
| 717 | (keys[1], "usd".to_owned()), | |
| 718 | (keys[2], cents.to_string()), | |
| 719 | (keys[3], "exclusive".to_owned()), | |
| 720 | (keys[4], name), | |
| 721 | (keys[5], TAX_CODE.to_owned()), | |
| 722 | ]; | |
| 723 | if let Some(description) = description { | |
| 724 | fields.push((keys[6], description)); | |
| 725 | } | |
| 726 | if monthly { | |
| 727 | fields.push((keys[7], "month".to_owned())); | |
| 728 | } | |
| 729 | fields | |
| 730 | } | |
| 731 | ||
| 732 | /// The card fee's line on a payment page, when there is a fee. | |
| 733 | fn fee_line(fee_cents: u32, monthly: bool) -> Vec<(&'static str, String)> { | |
| 734 | if fee_cents == 0 { | |
| 735 | return vec![]; | |
| 736 | } | |
| 737 | page_line(1, fee_cents, CARD_FEE_LINE.to_owned(), Some("Stripe's fee for taking the payment by card, passed on at cost".to_owned()), monthly) | |
| 738 | } | |
| 739 | ||
| 740 | /// A prepayment page's fields. By card, the card fee is its own line; by | |
| 741 | /// bank transfer there is none. | |
| Usage, Billing settings and prepaid AI credit; fixes from the UX audit | 742 | pub(crate) fn prepay_fields( |
| 743 | workspace: &str, | |
| 744 | amount_cents: u32, | |
| Merge Stripe Tax, the card fee on card payments, and one free workspace per person | 745 | fee_cents: u32, |
| Usage, Billing settings and prepaid AI credit; fixes from the UX audit | 746 | customer: Option<&str>, |
| 747 | return_url: &str, | |
| 748 | bank_transfer: bool, | |
| 749 | ) -> Vec<(&'static str, String)> { | |
| 750 | let mut fields = vec![("mode", "payment".to_owned())]; | |
| 751 | if bank_transfer { | |
| 752 | fields.extend([ | |
| 753 | ("payment_method_types[0]", "customer_balance".to_owned()), | |
| 754 | ("payment_method_options[customer_balance][funding_type]", "bank_transfer".to_owned()), | |
| 755 | ("payment_method_options[customer_balance][bank_transfer][type]", "us_bank_transfer".to_owned()), | |
| 756 | ]); | |
| 757 | } else { | |
| 758 | fields.extend([ | |
| Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look | 759 | ("payment_method_types[0]", "card".to_owned()), |
| 760 | ("payment_method_options[card][request_three_d_secure]", "any".to_owned()), | |
| Usage, Billing settings and prepaid AI credit; fixes from the UX audit | 761 | ("payment_intent_data[setup_future_usage]", "off_session".to_owned()), |
| 762 | ]); | |
| 763 | } | |
| 764 | fields.extend([ | |
| 765 | ("success_url", back_to(return_url, "session")), | |
| 766 | ("cancel_url", return_url.to_owned()), | |
| 767 | ("client_reference_id", workspace.to_owned()), | |
| 768 | ("metadata[workspace]", workspace.to_owned()), | |
| 769 | ]); | |
| Merge Stripe Tax, the card fee on card payments, and one free workspace per person | 770 | fields.extend(page_line(0, amount_cents, format!("g1t usage paid in advance for {workspace}"), None, false)); |
| 771 | if !bank_transfer { | |
| 772 | fields.extend(fee_line(fee_cents, false)); | |
| 773 | } | |
| 774 | fields.extend(checkout_tax_fields(customer)); | |
| Usage, Billing settings and prepaid AI credit; fixes from the UX audit | 775 | match customer { |
| 776 | Some(customer) => fields.push(("customer", customer.to_owned())), | |
| 777 | None => fields.push(("customer_creation", "always".to_owned())), | |
| 778 | } | |
| 779 | fields | |
| 780 | } | |
| 781 | ||
| Merge Stripe Tax, the card fee on card payments, and one free workspace per person | 782 | /// A plan's page's fields: the plan, and the card fee as a monthly line of |
| 783 | /// its own. In subscription mode Stripe makes the customer itself when | |
| 784 | /// there is none; `customer_creation` is for payment mode only. The | |
| 785 | /// subscription it starts keeps `automatic_tax`, so every renewal is taxed. | |
| Usage, Billing settings and prepaid AI credit; fixes from the UX audit | 786 | pub(crate) fn subscription_fields( |
| 787 | workspace: &str, | |
| 788 | feature: &str, | |
| 789 | title: &str, | |
| 790 | monthly_cents: u32, | |
| Merge Stripe Tax, the card fee on card payments, and one free workspace per person | 791 | fee_cents: u32, |
| Usage, Billing settings and prepaid AI credit; fixes from the UX audit | 792 | customer: Option<&str>, |
| 793 | return_url: &str, | |
| 794 | ) -> Vec<(&'static str, String)> { | |
| 795 | let mut fields = vec![ | |
| 796 | ("mode", "subscription".to_owned()), | |
| 797 | ("payment_method_types[0]", "card".to_owned()), | |
| 798 | ("success_url", back_to(return_url, "session")), | |
| 799 | ("cancel_url", return_url.to_owned()), | |
| 800 | ("client_reference_id", workspace.to_owned()), | |
| 801 | ("metadata[workspace]", workspace.to_owned()), | |
| 802 | ("metadata[feature]", feature.to_owned()), | |
| 803 | ("subscription_data[metadata][workspace]", workspace.to_owned()), | |
| 804 | ("subscription_data[metadata][feature]", feature.to_owned()), | |
| 805 | ]; | |
| Merge Stripe Tax, the card fee on card payments, and one free workspace per person | 806 | fields.extend(page_line(0, monthly_cents, format!("g1t {title} for {workspace}"), None, true)); |
| 807 | fields.extend(fee_line(fee_cents, true)); | |
| 808 | fields.extend(checkout_tax_fields(customer)); | |
| Usage, Billing settings and prepaid AI credit; fixes from the UX audit | 809 | if let Some(customer) = customer { |
| 810 | fields.push(("customer", customer.to_owned())); | |
| 811 | } | |
| 812 | fields | |
| 813 | } | |
| 814 | ||
| Merge Stripe Tax, the card fee on card payments, and one free workspace per person | 815 | /// A card check's page's fields: setup mode, nothing charged, so nothing |
| 816 | /// to tax. Setup mode takes no line items and no amount. The billing | |
| 817 | /// address is asked for all the same, and copied onto the customer once | |
| 818 | /// the card is checked (`fill_address`), so the plan and invoices that | |
| 819 | /// follow can be taxed. | |
| Usage, Billing settings and prepaid AI credit; fixes from the UX audit | 820 | pub(crate) fn card_check_fields(workspace: &str, customer: &str, return_url: &str) -> Vec<(&'static str, String)> { |
| 821 | vec![ | |
| 822 | ("mode", "setup".to_owned()), | |
| 823 | ("customer", customer.to_owned()), | |
| 824 | ("payment_method_types[0]", "card".to_owned()), | |
| 825 | ("payment_method_options[card][request_three_d_secure]", "any".to_owned()), | |
| Merge Stripe Tax, the card fee on card payments, and one free workspace per person | 826 | ("billing_address_collection", "required".to_owned()), |
| Usage, Billing settings and prepaid AI credit; fixes from the UX audit | 827 | ("success_url", back_to(return_url, "card_check")), |
| 828 | ("cancel_url", return_url.to_owned()), | |
| 829 | ("client_reference_id", workspace.to_owned()), | |
| 830 | ("metadata[workspace]", workspace.to_owned()), | |
| 831 | ("metadata[purpose]", "card_check".to_owned()), | |
| 832 | ("setup_intent_data[metadata][workspace]", workspace.to_owned()), | |
| 833 | ("setup_intent_data[description]", format!("Card check for g1t workspace {workspace}; never charged")), | |
| 834 | ] | |
| 835 | } | |
| 836 | ||
| 837 | /// An AI credit page's fields: the credit, and the card fee as its own | |
| 838 | /// line when there is one. | |
| 839 | pub(crate) fn credit_fields(p: &CreditPurchase<'_>) -> Vec<(&'static str, String)> { | |
| 840 | let mut fields = vec![ | |
| 841 | ("mode", "payment".to_owned()), | |
| 842 | ("payment_method_types[0]", "card".to_owned()), | |
| 843 | ("payment_method_options[card][request_three_d_secure]", "any".to_owned()), | |
| 844 | // Kept for auto-reload, which charges it with nobody there. | |
| 845 | ("payment_intent_data[setup_future_usage]", "off_session".to_owned()), | |
| 846 | ("payment_intent_data[description]", format!("g1t AI credit for {}", p.workspace)), | |
| 847 | ("payment_intent_data[metadata][workspace]", p.workspace.to_owned()), | |
| 848 | ("payment_intent_data[metadata][purpose]", "ai_credit".to_owned()), | |
| 849 | ("success_url", back_to(p.return_url, "ai_credit")), | |
| 850 | ("cancel_url", p.return_url.to_owned()), | |
| 851 | ("client_reference_id", p.workspace.to_owned()), | |
| 852 | ("metadata[workspace]", p.workspace.to_owned()), | |
| 853 | ("metadata[purpose]", "ai_credit".to_owned()), | |
| 854 | ]; | |
| Merge Stripe Tax, the card fee on card payments, and one free workspace per person | 855 | fields.extend(page_line( |
| 856 | 0, | |
| 857 | p.credit_cents, | |
| 858 | "g1t AI credit".to_owned(), | |
| 859 | Some(format!("Prepaid credit for Agent and AI Gateway usage in {}; expires a year after purchase", p.workspace)), | |
| 860 | false, | |
| 861 | )); | |
| 862 | fields.extend(fee_line(p.fee_cents, false)); | |
| 863 | fields.extend(checkout_tax_fields(p.customer)); | |
| Usage, Billing settings and prepaid AI credit; fixes from the UX audit | 864 | match p.customer { |
| 865 | Some(customer) => fields.push(("customer", customer.to_owned())), | |
| 866 | None => fields.push(("customer_creation", "always".to_owned())), | |
| Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look | 867 | } |
| Usage, Billing settings and prepaid AI credit; fixes from the UX audit | 868 | fields |
| 869 | } | |
| Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look | 870 | |
| Merge Stripe Tax, the card fee on card payments, and one free workspace per person | 871 | /// An off-session charge's fields: the credit, the card fee and the tax |
| 872 | /// Stripe Tax worked out for them, in one payment. | |
| Usage, Billing settings and prepaid AI credit; fixes from the UX audit | 873 | pub(crate) fn saved_charge_fields(c: &SavedCharge<'_>) -> Vec<(&'static str, String)> { |
| Merge Stripe Tax, the card fee on card payments, and one free workspace per person | 874 | let mut fields = vec![ |
| 875 | ("amount", (c.credit_cents + c.fee_cents + c.tax_cents).to_string()), | |
| Usage, Billing settings and prepaid AI credit; fixes from the UX audit | 876 | ("currency", "usd".to_owned()), |
| 877 | ("customer", c.customer.to_owned()), | |
| 878 | ("payment_method", c.payment_method.to_owned()), | |
| 879 | ("off_session", "true".to_owned()), | |
| 880 | ("confirm", "true".to_owned()), | |
| 881 | ("description", format!("g1t AI credit auto-reload for {}", c.workspace)), | |
| 882 | ("metadata[workspace]", c.workspace.to_owned()), | |
| 883 | ("metadata[purpose]", "ai_reload".to_owned()), | |
| 884 | ("metadata[credit_cents]", c.credit_cents.to_string()), | |
| 885 | ("metadata[fee_cents]", c.fee_cents.to_string()), | |
| Merge Stripe Tax, the card fee on card payments, and one free workspace per person | 886 | ("metadata[tax_cents]", c.tax_cents.to_string()), |
| 887 | ]; | |
| 888 | if let Some(calculation) = c.tax_calculation { | |
| 889 | fields.push(("metadata[tax_calculation]", calculation.to_owned())); | |
| 890 | } | |
| 891 | fields | |
| 892 | } | |
| 893 | ||
| 894 | /// A Stripe invoice's tax settings, for every invoice g1t makes: worked out | |
| 895 | /// by Stripe Tax. | |
| 896 | pub(crate) fn invoice_tax_fields() -> Vec<(&'static str, String)> { | |
| 897 | vec![("automatic_tax[enabled]", "true".to_owned())] | |
| 898 | } | |
| 899 | ||
| 900 | /// An invoice item's tax settings: g1t's tax code, the amount excluding tax. | |
| 901 | pub(crate) fn item_tax_fields() -> Vec<(&'static str, String)> { | |
| 902 | vec![("tax_behavior", "exclusive".to_owned()), ("tax_code", TAX_CODE.to_owned())] | |
| 903 | } | |
| 904 | ||
| 905 | /// What a paid Stripe invoice comes to, as billing counts it: the tax | |
| 906 | /// (`tax`, in this API version), the card fee (its lines, by name), and | |
| 907 | /// what is left for what was sold, all in cents. | |
| 908 | #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] | |
| 909 | pub(crate) struct InvoiceSplit { | |
| 910 | pub tax_cents: i64, | |
| 911 | pub fee_cents: i64, | |
| 912 | pub net_cents: i64, | |
| 913 | } | |
| 914 | ||
| 915 | /// A plan started on a saved card, as its subscription needs it. | |
| 916 | pub(crate) struct SavedPlan<'a> { | |
| 917 | pub workspace: &'a str, | |
| 918 | pub feature: &'a str, | |
| 919 | pub title: &'a str, | |
| 920 | pub monthly_cents: u32, | |
| 921 | pub fee_cents: u32, | |
| 922 | pub customer: &'a str, | |
| 923 | pub payment_method: &'a str, | |
| Usage, Billing settings and prepaid AI credit; fixes from the UX audit | 924 | } |
| 925 | ||
| Merge Stripe Tax, the card fee on card payments, and one free workspace per person | 926 | /// A subscription's fields, started on a saved card: the plan, the card |
| 927 | /// fee as a monthly item when there is one, each excluding tax, and Stripe | |
| 928 | /// Tax on. | |
| 929 | pub(crate) fn saved_subscription_fields(p: &SavedPlan<'_>, product: &str, fee_product: Option<&str>) -> Vec<(&'static str, String)> { | |
| 930 | let mut fields = vec![ | |
| 931 | ("customer", p.customer.to_owned()), | |
| 932 | ("default_payment_method", p.payment_method.to_owned()), | |
| 933 | ("payment_behavior", "error_if_incomplete".to_owned()), | |
| 934 | ("automatic_tax[enabled]", "true".to_owned()), | |
| 935 | ("items[0][price_data][currency]", "usd".to_owned()), | |
| 936 | ("items[0][price_data][product]", product.to_owned()), | |
| 937 | ("items[0][price_data][unit_amount]", p.monthly_cents.to_string()), | |
| 938 | ("items[0][price_data][recurring][interval]", "month".to_owned()), | |
| 939 | ("items[0][price_data][tax_behavior]", "exclusive".to_owned()), | |
| 940 | ("metadata[workspace]", p.workspace.to_owned()), | |
| 941 | ("metadata[feature]", p.feature.to_owned()), | |
| 942 | ("description", format!("{} plan for {}", p.title, p.workspace)), | |
| 943 | ]; | |
| 944 | if let (Some(fee_product), true) = (fee_product, p.fee_cents > 0) { | |
| 945 | fields.extend([ | |
| 946 | ("items[1][price_data][currency]", "usd".to_owned()), | |
| 947 | ("items[1][price_data][product]", fee_product.to_owned()), | |
| 948 | ("items[1][price_data][unit_amount]", p.fee_cents.to_string()), | |
| 949 | ("items[1][price_data][recurring][interval]", "month".to_owned()), | |
| 950 | ("items[1][price_data][tax_behavior]", "exclusive".to_owned()), | |
| 951 | ]); | |
| 952 | } | |
| 953 | fields | |
| 954 | } | |
| 955 | ||
| 956 | pub(crate) fn invoice_split(invoice: &serde_json::Value, amount_paid: i64) -> InvoiceSplit { | |
| 957 | let tax_cents = invoice["tax"].as_i64().unwrap_or(0).max(0); | |
| 958 | let fee_cents: i64 = invoice["lines"]["data"] | |
| 959 | .as_array() | |
| 960 | .map(|lines| { | |
| 961 | lines | |
| 962 | .iter() | |
| 963 | .filter(|line| line["description"].as_str().is_some_and(|d| d.contains(CARD_FEE_LINE))) | |
| 964 | .map(|line| line["amount"].as_i64().unwrap_or(0)) | |
| 965 | .sum() | |
| 966 | }) | |
| 967 | .unwrap_or(0); | |
| 968 | let fee_cents = fee_cents.max(0); | |
| 969 | InvoiceSplit { tax_cents, fee_cents, net_cents: (amount_paid - tax_cents - fee_cents).max(0) } | |
| 970 | } | |
| 971 | ||
| Usage, Billing settings and prepaid AI credit; fixes from the UX audit | 972 | impl Stripe { |
| Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look | 973 | /// What a card check's setup found, once it succeeded. |
| 974 | pub async fn checked_card(&self, setup_intent: &str) -> Result<Option<CheckedCard>> { | |
| 975 | #[derive(Deserialize)] | |
| 976 | struct Setup { | |
| 977 | status: String, | |
| 978 | payment_method: Option<String>, | |
| 979 | } | |
| 980 | #[derive(Deserialize)] | |
| 981 | struct Card { | |
| 982 | fingerprint: Option<String>, | |
| 983 | brand: Option<String>, | |
| 984 | last4: Option<String>, | |
| 985 | funding: Option<String>, | |
| 986 | country: Option<String>, | |
| 987 | } | |
| 988 | #[derive(Deserialize)] | |
| Merge Stripe Tax, the card fee on card payments, and one free workspace per person | 989 | struct Billing { |
| 990 | #[serde(default)] | |
| 991 | address: Option<serde_json::Value>, | |
| 992 | } | |
| 993 | #[derive(Deserialize)] | |
| Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look | 994 | struct PaymentMethod { |
| 995 | card: Option<Card>, | |
| Merge Stripe Tax, the card fee on card payments, and one free workspace per person | 996 | #[serde(default)] |
| 997 | billing_details: Option<Billing>, | |
| Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look | 998 | } |
| 999 | let setup: Setup = self.call(Method::Get, &format!("/setup_intents/{}", encode(setup_intent)), None).await?; | |
| 1000 | let (true, Some(method)) = (setup.status == "succeeded", setup.payment_method) else { return Ok(None) }; | |
| 1001 | let found: PaymentMethod = self.call(Method::Get, &format!("/payment_methods/{}", encode(&method)), None).await?; | |
| 1002 | let card = found.card; | |
| Merge Stripe Tax, the card fee on card payments, and one free workspace per person | 1003 | let address = found.billing_details.and_then(|b| b.address).filter(|a| a.is_object()); |
| Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look | 1004 | Ok(Some(CheckedCard { |
| Merge Stripe Tax, the card fee on card payments, and one free workspace per person | 1005 | address, |
| Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look | 1006 | payment_method: method, |
| 1007 | fingerprint: card.as_ref().and_then(|c| c.fingerprint.clone()), | |
| 1008 | brand: card.as_ref().and_then(|c| c.brand.clone()), | |
| 1009 | last4: card.as_ref().and_then(|c| c.last4.clone()), | |
| 1010 | funding: card.as_ref().and_then(|c| c.funding.clone()), | |
| 1011 | country: card.as_ref().and_then(|c| c.country.clone()), | |
| 1012 | })) | |
| 1013 | } | |
| 1014 | ||
| 1015 | /// Makes `payment_method` the card the customer's invoices are charged to. | |
| 1016 | pub async fn set_default_card(&self, customer: &str, payment_method: &str) -> Result<()> { | |
| 1017 | let _: serde_json::Value = self | |
| 1018 | .call( | |
| 1019 | Method::Post, | |
| 1020 | &format!("/customers/{}", encode(customer)), | |
| 1021 | Some(form(&[("invoice_settings[default_payment_method]", payment_method.to_owned())])), | |
| 1022 | ) | |
| 1023 | .await?; | |
| 1024 | Ok(()) | |
| 1025 | } | |
| 1026 | ||
| Merge Stripe Tax, the card fee on card payments, and one free workspace per person | 1027 | /// One of g1t's products at Stripe, tagged `metadata[g1t]` (the plan's |
| 1028 | /// is `plan`, the card fee's `card_fee`), made the first time it is | |
| 1029 | /// needed, with g1t's tax code. One made before Stripe Tax was on is | |
| 1030 | /// given the code when it is found. | |
| 1031 | async fn product(&self, tag: &str, name: &str) -> Result<String> { | |
| Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look | 1032 | #[derive(Deserialize)] |
| 1033 | struct Product { | |
| 1034 | id: String, | |
| 1035 | #[serde(default)] | |
| 1036 | metadata: Option<std::collections::HashMap<String, String>>, | |
| Merge Stripe Tax, the card fee on card payments, and one free workspace per person | 1037 | #[serde(default)] |
| 1038 | tax_code: Option<serde_json::Value>, | |
| Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look | 1039 | } |
| 1040 | #[derive(Deserialize)] | |
| 1041 | struct List { | |
| 1042 | data: Vec<Product>, | |
| 1043 | } | |
| 1044 | let list: List = self.call(Method::Get, "/products?active=true&limit=100", None).await?; | |
| Merge Stripe Tax, the card fee on card payments, and one free workspace per person | 1045 | let ours = |p: &Product| p.metadata.as_ref().and_then(|m| m.get("g1t")).map(String::as_str) == Some(tag); |
| Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look | 1046 | if let Some(found) = list.data.into_iter().find(ours) { |
| Merge Stripe Tax, the card fee on card payments, and one free workspace per person | 1047 | let coded = found.tax_code.as_ref().is_some_and(|code| code.as_str() == Some(TAX_CODE) || code["id"].as_str() == Some(TAX_CODE)); |
| 1048 | if !coded { | |
| 1049 | let _: serde_json::Value = self | |
| 1050 | .call(Method::Post, &format!("/products/{}", encode(&found.id)), Some(form(&[("tax_code", TAX_CODE.to_owned())]))) | |
| 1051 | .await?; | |
| 1052 | } | |
| Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look | 1053 | return Ok(found.id); |
| 1054 | } | |
| 1055 | let created: Product = self | |
| 1056 | .call( | |
| 1057 | Method::Post, | |
| 1058 | "/products", | |
| Merge Stripe Tax, the card fee on card payments, and one free workspace per person | 1059 | Some(form(&[("name", name.to_owned()), ("metadata[g1t]", tag.to_owned()), ("tax_code", TAX_CODE.to_owned())])), |
| Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look | 1060 | ) |
| 1061 | .await?; | |
| 1062 | Ok(created.id) | |
| 1063 | } | |
| 1064 | ||
| Merge Stripe Tax, the card fee on card payments, and one free workspace per person | 1065 | /// Starts the monthly plan on a saved card, at once, with tax worked |
| 1066 | /// out by Stripe Tax on every invoice and the card fee as a monthly item | |
| 1067 | /// of its own. Fails rather than leaving it half-started when the card's | |
| 1068 | /// bank wants the person again, or when Stripe Tax cannot place the | |
| 1069 | /// customer (no billing address yet); the caller then sends them to | |
| 1070 | /// Stripe's page, which asks for the address. | |
| 1071 | #[allow(clippy::too_many_arguments)] | |
| Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look | 1072 | pub async fn subscribe_with_card( |
| 1073 | &self, | |
| 1074 | workspace: &str, | |
| 1075 | feature: &str, | |
| 1076 | title: &str, | |
| 1077 | monthly_cents: u32, | |
| Merge Stripe Tax, the card fee on card payments, and one free workspace per person | 1078 | fee_cents: u32, |
| Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look | 1079 | customer: &str, |
| 1080 | payment_method: &str, | |
| 1081 | ) -> Result<StripeSubscription> { | |
| Merge Stripe Tax, the card fee on card payments, and one free workspace per person | 1082 | let product = self.product(feature, &format!("{title} plan")).await?; |
| 1083 | let fee_product = if fee_cents > 0 { Some(self.product("card_fee", CARD_FEE_LINE).await?) } else { None }; | |
| 1084 | let plan = SavedPlan { workspace, feature, title, monthly_cents, fee_cents, customer, payment_method }; | |
| 1085 | let fields = saved_subscription_fields(&plan, &product, fee_product.as_deref()); | |
| 1086 | let key = plan_key(workspace, feature, &format!("{payment_method}/{monthly_cents}/{fee_cents}"), g1t_kit::now_ms()); | |
| Billing: credits with a kind and expiry, discounts instead of comped, and safer charging | 1087 | self.send(Method::Post, "/subscriptions", Some(form(&fields)), Some(&key)).await |
| Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look | 1088 | } |
| 1089 | ||
| Merge Stripe Tax, the card fee on card payments, and one free workspace per person | 1090 | |
| Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look | 1091 | /// Ends a subscription now: one that never started properly. |
| 1092 | pub async fn cancel_now(&self, id: &str) -> Result<StripeSubscription> { | |
| 1093 | self.call(Method::Delete, &format!("/subscriptions/{}", encode(id)), None).await | |
| 1094 | } | |
| 1095 | ||
| Paid features: a workspace turns on Deployments with a monthly plan | 1096 | pub async fn subscription(&self, id: &str) -> Result<StripeSubscription> { |
| 1097 | self.call(Method::Get, &format!("/subscriptions/{}", encode(id)), None) | |
| 1098 | .await | |
| 1099 | } | |
| 1100 | ||
| 1101 | /// Ends a plan when its period does (`cancel` true), or takes that back. | |
| 1102 | pub async fn cancel_at_period_end(&self, id: &str, cancel: bool) -> Result<StripeSubscription> { | |
| 1103 | self.call( | |
| 1104 | Method::Post, | |
| 1105 | &format!("/subscriptions/{}", encode(id)), | |
| 1106 | Some(form(&[("cancel_at_period_end", cancel.to_string())])), | |
| 1107 | ) | |
| 1108 | .await | |
| 1109 | } | |
| 1110 | ||
| Agents as a team: lifecycle, merge queue, billing and a new shell | 1111 | pub async fn session(&self, id: &str) -> Result<Session> { |
| 1112 | self.call( | |
| 1113 | Method::Get, | |
| 1114 | &format!("/checkout/sessions/{}", encode(id)), | |
| 1115 | None, | |
| 1116 | ) | |
| 1117 | .await | |
| 1118 | } | |
| 1119 | } | |
| 1120 | ||
| Project dependencies: addresses, preview stacks, Affects, and agents who know | 1121 | /// Whether the processor said an id it was given does not exist, as when |
| 1122 | /// g1t moves to another Stripe account and ids saved from the old one stay | |
| 1123 | /// behind. | |
| 1124 | pub(crate) fn is_missing(error: &Error) -> bool { | |
| 1125 | error.to_string().contains("resource_missing") | |
| 1126 | } | |
| 1127 | ||
| Agents as a team: lifecycle, merge queue, billing and a new shell | 1128 | pub(crate) fn is_live(key: &str) -> bool { |
| 1129 | key.starts_with("sk_live_") || key.starts_with("rk_live_") | |
| 1130 | } | |
| 1131 | ||
| 1132 | #[cfg(test)] | |
| 1133 | mod tests { | |
| 1134 | use super::*; | |
| 1135 | ||
| 1136 | #[test] | |
| Billing: credits with a kind and expiry, discounts instead of comped, and safer charging | 1137 | fn asking_twice_for_a_plan_starts_one() { |
| 1138 | let at = 1_791_000_000_000; | |
| 1139 | assert_eq!(plan_key("acme", "plan", "pm_1", at), plan_key("acme", "plan", "pm_1", at + 1_000)); | |
| 1140 | assert_ne!(plan_key("acme", "plan", "pm_1", at), plan_key("acme", "plan", "pm_2", at)); | |
| 1141 | assert_ne!(plan_key("acme", "plan", "pm_1", at), plan_key("other", "plan", "pm_1", at)); | |
| 1142 | } | |
| 1143 | ||
| 1144 | #[test] | |
| Agents as a team: lifecycle, merge queue, billing and a new shell | 1145 | fn form_values_are_percent_encoded() { |
| 1146 | assert_eq!( | |
| 1147 | form(&[ | |
| 1148 | ( | |
| 1149 | "success_url", | |
| 1150 | "https://g1t.sh/a/-/billing?session={ID}".to_owned() | |
| 1151 | ), | |
| 1152 | ("line_items[0][quantity]", "1".to_owned()), | |
| 1153 | ]), | |
| 1154 | "success_url=https%3A%2F%2Fg1t.sh%2Fa%2F-%2Fbilling%3Fsession%3D%7BID%7D&line_items%5B0%5D%5Bquantity%5D=1" | |
| 1155 | ); | |
| 1156 | } | |
| 1157 | ||
| 1158 | #[test] | |
| 1159 | fn test_keys_are_not_live() { | |
| 1160 | assert!(is_live("sk_live_abc")); | |
| 1161 | assert!(!is_live("sk_test_abc")); | |
| 1162 | assert!(!is_live("")); | |
| 1163 | } | |
| Usage, Billing settings and prepaid AI credit; fixes from the UX audit | 1164 | |
| 1165 | fn has(fields: &[(&str, String)], name: &str) -> Option<String> { | |
| 1166 | fields.iter().find(|(n, _)| *n == name).map(|(_, v)| v.clone()) | |
| 1167 | } | |
| 1168 | ||
| 1169 | #[test] | |
| 1170 | fn every_request_names_the_api_version_it_is_written_for() { | |
| 1171 | // Without it a new Stripe account answers at its newest version, and | |
| 1172 | // invoices, charges and pages read differently from what billing | |
| 1173 | // expects. | |
| 1174 | assert!(STRIPE_VERSION.starts_with("2025-02-24")); | |
| 1175 | let source = include_str!("stripe.rs"); | |
| 1176 | assert!(source.contains(concat!("headers.set(\"stripe-", "version\", STRIPE_VERSION)"))); | |
| 1177 | } | |
| 1178 | ||
| 1179 | #[test] | |
| 1180 | fn the_plans_page_is_a_subscription_without_payment_mode_fields() { | |
| 1181 | let url = "https://g1t.sh/acme/-/billing?plan=plan"; | |
| 1182 | for customer in [None, Some("cus_1")] { | |
| Merge Stripe Tax, the card fee on card payments, and one free workspace per person | 1183 | let fields = subscription_fields("acme", "plan", "g1t", 2_000, 92, customer, url); |
| Usage, Billing settings and prepaid AI credit; fixes from the UX audit | 1184 | assert_eq!(has(&fields, "mode").as_deref(), Some("subscription")); |
| 1185 | // customer_creation is for payment mode; Stripe refuses it here. | |
| 1186 | assert!(has(&fields, "customer_creation").is_none()); | |
| 1187 | assert!(has(&fields, "payment_intent_data[setup_future_usage]").is_none()); | |
| 1188 | assert_eq!(has(&fields, "customer").as_deref(), customer); | |
| 1189 | assert_eq!(has(&fields, "success_url").unwrap(), "https://g1t.sh/acme/-/billing?plan=plan&session={CHECKOUT_SESSION_ID}"); | |
| 1190 | assert_eq!(has(&fields, "line_items[0][price_data][recurring][interval]").as_deref(), Some("month")); | |
| Merge Stripe Tax, the card fee on card payments, and one free workspace per person | 1191 | // The card fee is a monthly line of its own. |
| 1192 | assert_eq!(has(&fields, "line_items[1][price_data][unit_amount]").as_deref(), Some("92")); | |
| 1193 | assert_eq!(has(&fields, "line_items[1][price_data][recurring][interval]").as_deref(), Some("month")); | |
| 1194 | assert_eq!(has(&fields, "line_items[1][price_data][product_data][name]").as_deref(), Some(CARD_FEE_LINE)); | |
| Usage, Billing settings and prepaid AI credit; fixes from the UX audit | 1195 | } |
| Merge Stripe Tax, the card fee on card payments, and one free workspace per person | 1196 | let fields = subscription_fields("acme", "plan", "g1t", 2_000, 0, None, url); |
| 1197 | assert!(has(&fields, "line_items[1][quantity]").is_none()); | |
| 1198 | } | |
| 1199 | ||
| 1200 | /// Every field a page must carry for Stripe Tax: tax on top of the | |
| 1201 | /// price, an address always asked for, the buyer's tax ID, and each | |
| 1202 | /// line at g1t's tax code, excluding tax. With a customer, what is | |
| 1203 | /// entered is saved on it (Checkout refuses `automatic_tax` and | |
| 1204 | /// `tax_id_collection` for a customer otherwise). | |
| 1205 | fn assert_taxed_page(fields: &[(&str, String)], customer: Option<&str>, lines: usize) { | |
| 1206 | assert_eq!(has(fields, "automatic_tax[enabled]").as_deref(), Some("true")); | |
| 1207 | assert_eq!(has(fields, "billing_address_collection").as_deref(), Some("required")); | |
| 1208 | assert_eq!(has(fields, "tax_id_collection[enabled]").as_deref(), Some("true")); | |
| 1209 | let saved = if customer.is_some() { Some("auto") } else { None }; | |
| 1210 | assert_eq!(has(fields, "customer_update[address]").as_deref(), saved); | |
| 1211 | assert_eq!(has(fields, "customer_update[name]").as_deref(), saved); | |
| 1212 | for (line, keys) in LINE_KEYS.iter().enumerate().take(lines) { | |
| 1213 | assert_eq!(has(fields, keys[3]).as_deref(), Some("exclusive"), "line {line}"); | |
| 1214 | assert_eq!(has(fields, keys[5]).as_deref(), Some(TAX_CODE), "line {line}"); | |
| 1215 | } | |
| 1216 | // No key twice: Stripe takes the last, silently. | |
| 1217 | let mut names: Vec<&str> = fields.iter().map(|(n, _)| *n).collect(); | |
| 1218 | names.sort_unstable(); | |
| 1219 | let count = names.len(); | |
| 1220 | names.dedup(); | |
| 1221 | assert_eq!(names.len(), count); | |
| 1222 | } | |
| 1223 | ||
| 1224 | #[test] | |
| 1225 | fn every_payment_page_is_taxed_by_stripe_tax() { | |
| 1226 | let url = "https://g1t.sh/acme/-/billing"; | |
| 1227 | for customer in [None, Some("cus_1")] { | |
| 1228 | // The plan and Security and quality. | |
| 1229 | assert_taxed_page(&subscription_fields("acme", "plan", "g1t", 2_000, 92, customer, url), customer, 2); | |
| 1230 | assert_taxed_page(&subscription_fields("acme", "security", "Security and quality", 1_000, 61, customer, url), customer, 2); | |
| 1231 | // Prepaying by card, with its fee, and by bank transfer, without. | |
| 1232 | assert_taxed_page(&prepay_fields("acme", 5_000, 185, customer, url, false), customer, 2); | |
| 1233 | assert_taxed_page(&prepay_fields("acme", 100_000, 0, customer, url, true), customer, 1); | |
| 1234 | // AI credit. | |
| 1235 | let purchase = CreditPurchase { workspace: "acme", credit_cents: 2_500, fee_cents: 106, customer, return_url: url }; | |
| 1236 | assert_taxed_page(&credit_fields(&purchase), customer, 2); | |
| 1237 | } | |
| 1238 | // tax_id_collection and customer_update are for payment and | |
| 1239 | // subscription mode; a card check charges nothing, so it is not | |
| 1240 | // taxed, but it asks for the address the plan will be taxed at. | |
| 1241 | let check = card_check_fields("acme", "cus_1", url); | |
| 1242 | assert!(has(&check, "automatic_tax[enabled]").is_none()); | |
| 1243 | assert_eq!(has(&check, "billing_address_collection").as_deref(), Some("required")); | |
| 1244 | } | |
| 1245 | ||
| 1246 | #[test] | |
| 1247 | fn a_bank_transfer_has_no_card_fee() { | |
| 1248 | let fields = prepay_fields("acme", 100_000, 3_100, Some("cus_1"), "https://g1t.sh/acme/-/billing", true); | |
| 1249 | assert!(has(&fields, "line_items[1][quantity]").is_none()); | |
| 1250 | let fields = prepay_fields("acme", 5_000, 185, None, "https://g1t.sh/acme/-/billing", false); | |
| 1251 | assert_eq!(has(&fields, "line_items[1][price_data][unit_amount]").as_deref(), Some("185")); | |
| 1252 | assert_eq!(has(&fields, "line_items[1][price_data][product_data][name]").as_deref(), Some(CARD_FEE_LINE)); | |
| 1253 | } | |
| 1254 | ||
| 1255 | #[test] | |
| 1256 | fn a_plan_on_a_saved_card_is_taxed_with_its_card_fee() { | |
| 1257 | let plan = SavedPlan { workspace: "acme", feature: "plan", title: "g1t", monthly_cents: 2_000, fee_cents: 92, customer: "cus_1", payment_method: "pm_1" }; | |
| 1258 | let fields = saved_subscription_fields(&plan, "prod_plan", Some("prod_fee")); | |
| 1259 | assert_eq!(has(&fields, "automatic_tax[enabled]").as_deref(), Some("true")); | |
| 1260 | assert_eq!(has(&fields, "items[0][price_data][tax_behavior]").as_deref(), Some("exclusive")); | |
| 1261 | assert_eq!(has(&fields, "items[1][price_data][product]").as_deref(), Some("prod_fee")); | |
| 1262 | assert_eq!(has(&fields, "items[1][price_data][unit_amount]").as_deref(), Some("92")); | |
| 1263 | assert_eq!(has(&fields, "items[1][price_data][tax_behavior]").as_deref(), Some("exclusive")); | |
| 1264 | let fields = saved_subscription_fields(&SavedPlan { fee_cents: 0, ..plan }, "prod_plan", None); | |
| 1265 | assert!(has(&fields, "items[1][price_data][product]").is_none()); | |
| Usage, Billing settings and prepaid AI credit; fixes from the UX audit | 1266 | } |
| 1267 | ||
| 1268 | #[test] | |
| Merge Stripe Tax, the card fee on card payments, and one free workspace per person | 1269 | fn invoices_and_their_lines_are_taxed() { |
| 1270 | assert_eq!(has(&invoice_tax_fields(), "automatic_tax[enabled]").as_deref(), Some("true")); | |
| 1271 | let item = item_tax_fields(); | |
| 1272 | assert_eq!(has(&item, "tax_behavior").as_deref(), Some("exclusive")); | |
| 1273 | assert_eq!(has(&item, "tax_code").as_deref(), Some(TAX_CODE)); | |
| 1274 | } | |
| 1275 | ||
| 1276 | #[test] | |
| 1277 | fn an_off_session_charge_is_its_credit_fee_and_tax() { | |
| 1278 | let charge = SavedCharge { | |
| 1279 | workspace: "acme", | |
| 1280 | customer: "cus_1", | |
| 1281 | payment_method: "pm_1", | |
| 1282 | credit_cents: 1_600, | |
| 1283 | fee_cents: 78, | |
| 1284 | tax_cents: 134, | |
| 1285 | tax_calculation: Some("taxcalc_1"), | |
| 1286 | key: "reload/acme/2026-10/1", | |
| 1287 | }; | |
| 1288 | let calculation = tax_calculation_fields(&charge); | |
| 1289 | assert_eq!(has(&calculation, "customer").as_deref(), Some("cus_1")); | |
| 1290 | assert_eq!(has(&calculation, "line_items[0][amount]").as_deref(), Some("1600")); | |
| 1291 | assert_eq!(has(&calculation, "line_items[0][tax_behavior]").as_deref(), Some("exclusive")); | |
| 1292 | assert_eq!(has(&calculation, "line_items[0][tax_code]").as_deref(), Some(TAX_CODE)); | |
| 1293 | assert_eq!(has(&calculation, "line_items[1][amount]").as_deref(), Some("78")); | |
| 1294 | assert_eq!(has(&calculation, "line_items[1][tax_code]").as_deref(), Some(TAX_CODE)); | |
| 1295 | let fields = saved_charge_fields(&charge); | |
| 1296 | assert_eq!(has(&fields, "amount").as_deref(), Some("1812")); | |
| 1297 | assert_eq!(has(&fields, "metadata[tax_calculation]").as_deref(), Some("taxcalc_1")); | |
| 1298 | let reversal = reversal_fields("tax_1", "pi_1/re_1", 500); | |
| 1299 | assert_eq!(has(&reversal, "flat_amount").as_deref(), Some("-500")); | |
| 1300 | assert_eq!(has(&reversal, "mode").as_deref(), Some("partial")); | |
| 1301 | } | |
| 1302 | ||
| 1303 | #[test] | |
| 1304 | fn a_paid_invoice_splits_into_tax_card_fee_and_what_was_sold() { | |
| 1305 | let invoice = serde_json::json!({ | |
| 1306 | "tax": 180, | |
| 1307 | "lines": { "data": [ | |
| 1308 | { "description": "1 × g1t plan (at $20.00 / month)", "amount": 2000 }, | |
| 1309 | { "description": "1 × Card processing fee (at $0.92 / month)", "amount": 92 }, | |
| 1310 | ] } | |
| 1311 | }); | |
| 1312 | assert_eq!(invoice_split(&invoice, 2_272), InvoiceSplit { tax_cents: 180, fee_cents: 92, net_cents: 2_000 }); | |
| 1313 | // Before Stripe Tax: no tax, no fee, all of it sold. | |
| 1314 | assert_eq!(invoice_split(&serde_json::json!({ "tax": null }), 2_000).net_cents, 2_000); | |
| 1315 | // A page's tax and what came before it. | |
| 1316 | let session: Session = serde_json::from_value(serde_json::json!({ | |
| 1317 | "id": "cs_1", "payment_status": "paid", "amount_total": 5_585, "amount_subtotal": 5_185, | |
| 1318 | "total_details": { "amount_tax": 400 }, "customer": "cus_1", "payment_intent": "pi_1" | |
| 1319 | })) | |
| 1320 | .unwrap(); | |
| 1321 | assert_eq!((session.tax_cents(), session.before_tax_cents()), (400, 5_185)); | |
| 1322 | } | |
| 1323 | ||
| 1324 | #[test] | |
| 1325 | fn an_address_places_a_customer_for_tax() { | |
| 1326 | use serde_json::json; | |
| 1327 | assert!(address_places_customer(&json!({ "country": "DE" }))); | |
| 1328 | assert!(address_places_customer(&json!({ "country": "US", "postal_code": "94107" }))); | |
| 1329 | assert!(!address_places_customer(&json!({ "country": "US", "postal_code": "" }))); | |
| 1330 | assert!(address_places_customer(&json!({ "country": "CA", "state": "ON" }))); | |
| 1331 | assert!(!address_places_customer(&json!({ "country": "" }))); | |
| 1332 | assert!(!address_places_customer(&serde_json::Value::Null)); | |
| 1333 | let error = Error::RustError(r#"the card processor answered 400: {"error":{"code":"customer_tax_location_invalid","message":"x"}}"#.into()); | |
| 1334 | assert!(is_tax_location_error(&error)); | |
| 1335 | } | |
| 1336 | ||
| 1337 | #[test] | |
| Usage, Billing settings and prepaid AI credit; fixes from the UX audit | 1338 | fn a_card_check_is_a_setup_page_with_no_amount() { |
| 1339 | let fields = card_check_fields("acme", "cus_1", "https://g1t.sh/acme/-/billing"); | |
| 1340 | assert_eq!(has(&fields, "mode").as_deref(), Some("setup")); | |
| 1341 | assert!(fields.iter().all(|(n, _)| !n.starts_with("line_items"))); | |
| 1342 | assert_eq!(has(&fields, "success_url").unwrap(), "https://g1t.sh/acme/-/billing?card_check={CHECKOUT_SESSION_ID}"); | |
| 1343 | assert_eq!(has(&fields, "customer").as_deref(), Some("cus_1")); | |
| 1344 | } | |
| 1345 | ||
| 1346 | #[test] | |
| 1347 | fn an_ai_credit_page_has_the_card_fee_as_its_own_line() { | |
| 1348 | let purchase = CreditPurchase { workspace: "acme", credit_cents: 2_500, fee_cents: 106, customer: None, return_url: "https://g1t.sh/acme/-/billing" }; | |
| 1349 | let fields = credit_fields(&purchase); | |
| 1350 | assert_eq!(has(&fields, "mode").as_deref(), Some("payment")); | |
| 1351 | assert_eq!(has(&fields, "line_items[0][price_data][unit_amount]").as_deref(), Some("2500")); | |
| 1352 | assert_eq!(has(&fields, "line_items[1][price_data][unit_amount]").as_deref(), Some("106")); | |
| 1353 | assert_eq!(has(&fields, "line_items[1][price_data][product_data][name]").as_deref(), Some("Card processing fee")); | |
| 1354 | assert_eq!(has(&fields, "customer_creation").as_deref(), Some("always")); | |
| 1355 | assert_eq!(has(&fields, "payment_intent_data[setup_future_usage]").as_deref(), Some("off_session")); | |
| 1356 | assert_eq!(has(&fields, "success_url").unwrap(), "https://g1t.sh/acme/-/billing?ai_credit={CHECKOUT_SESSION_ID}"); | |
| 1357 | // No fee: no second line. | |
| 1358 | let fields = credit_fields(&CreditPurchase { fee_cents: 0, customer: Some("cus_1"), ..purchase }); | |
| 1359 | assert!(has(&fields, "line_items[1][quantity]").is_none()); | |
| 1360 | assert!(has(&fields, "customer_creation").is_none()); | |
| 1361 | } | |
| 1362 | ||
| 1363 | #[test] | |
| 1364 | fn an_auto_reload_is_one_off_session_charge() { | |
| Merge Stripe Tax, the card fee on card payments, and one free workspace per person | 1365 | let charge = SavedCharge { |
| 1366 | workspace: "acme", | |
| 1367 | customer: "cus_1", | |
| 1368 | payment_method: "pm_1", | |
| 1369 | credit_cents: 1_600, | |
| 1370 | fee_cents: 78, | |
| 1371 | tax_cents: 0, | |
| 1372 | tax_calculation: None, | |
| 1373 | key: "reload/acme/2026-10/1", | |
| 1374 | }; | |
| Usage, Billing settings and prepaid AI credit; fixes from the UX audit | 1375 | let fields = saved_charge_fields(&charge); |
| 1376 | assert_eq!(has(&fields, "amount").as_deref(), Some("1678")); | |
| 1377 | assert_eq!(has(&fields, "off_session").as_deref(), Some("true")); | |
| 1378 | assert_eq!(has(&fields, "confirm").as_deref(), Some("true")); | |
| 1379 | } | |
| 1380 | ||
| 1381 | #[test] | |
| 1382 | fn a_page_asked_for_twice_is_one_page() { | |
| 1383 | let at = 1_791_000_000_000; | |
| 1384 | assert_eq!(page_key("plan", "acme", "plan/2000", at), page_key("plan", "acme", "plan/2000", at + 60_000)); | |
| 1385 | assert_ne!(page_key("plan", "acme", "plan/2000", at), page_key("ai_credit", "acme", "plan/2000", at)); | |
| 1386 | } | |
| 1387 | ||
| 1388 | #[test] | |
| 1389 | fn a_stripe_failure_reads_as_a_sentence_never_raw() { | |
| 1390 | let refused = Error::RustError( | |
| 1391 | r#"the card processor answered 400: {"error":{"message":"You may only specify one of these parameters: customer, customer_creation.","type":"invalid_request_error"}}"#.into(), | |
| 1392 | ); | |
| 1393 | assert_eq!(friendly(&refused), "Stripe refused it: You may only specify one of these parameters: customer, customer_creation."); | |
| 1394 | assert!(!friendly(&refused).contains("invalid_request_error")); | |
| 1395 | let odd = Error::RustError("the card processor answered 502: <html>".into()); | |
| 1396 | assert!(friendly(&odd).starts_with("Stripe refused it. Try again")); | |
| 1397 | let down = Error::RustError("network connection lost".into()); | |
| 1398 | assert_eq!(friendly(&down), "Stripe could not be reached. Try again in a minute."); | |
| 1399 | let declined = Error::RustError(r#"the card processor answered 402: {"error":{"type":"card_error","code":"card_declined","message":"Your card was declined."}}"#.into()); | |
| 1400 | assert!(is_card_error(&declined) && !is_card_error(&refused)); | |
| 1401 | } | |
| Agents as a team: lifecycle, merge queue, billing and a new shell | 1402 | } |
This file's history is long; its oldest lines are credited to the oldest commit read.