Skip to content

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

839 linesCodeBlameRaw
1//! Who pays for a workspace, and on what terms.
2//!
3//! Every workspace is paid for by a billing account. By default that is
4//! its own (`ws_<slug>`), on standard terms, and needs no row. g1t staff
5//! can change that in sudo.g1t.sh:
6//!
7//! - **Terms.** Comped (nothing charged, usage still recorded with its
8//! cost; for g1t's own workspaces and partners), or custom (a discount,
9//! a ceiling of its own, or both), optionally until a date.
10//! - **Enterprises.** One account paying for several workspaces, as GitHub
11//! Enterprise does: their usage and payments count together against one
12//! limit, on one set of terms.
13//! - **Credits**: promotional, goodwill or refunds (see `grants`).
14//!
15//! Every change names who made it and is kept in `admin_actions`.
16
17use g1t_contracts::billing::{
18 AccountDetail, AccountKind, AccountSummary, AdminAccountArgs, AdminAccountsArgs, AdminAction, AdminAttachArgs,
19 AdminCreateEnterpriseArgs, AdminSetAllowancesArgs, AdminSetTermsArgs, Allowances, BillingAccount, LedgerEntry, Terms,
20 TermsKind, WorkspaceFigures,
21};
22use g1t_contracts::time::rfc3339;
23use g1t_contracts::{FailureCode, Outcome, new_id};
24use g1t_kit::now_ms;
25use serde::Deserialize;
26use worker::Result;
27use worker::wasm_bindgen::JsValue;
28
29use crate::{Billing, LedgerRow, optional};
30
31pub(crate) const FEE_WAIVER_SUBSCRIPTIONS: &str = "SELECT subscription_id FROM subscriptions WHERE workspace = ? AND status <> 'canceled' LIMIT 1";
32
33#[derive(Deserialize)]
34struct AccountRow {
35 id: String,
36 kind: String,
37 name: String,
38 terms_kind: String,
39 discount_percent: u32,
40 ceiling_micros: Option<i64>,
41 note: String,
42 terms_until: Option<String>,
43 terms_set_by: Option<String>,
44 terms_set_at: Option<String>,
45 created_at: String,
46 #[serde(default)]
47 billing_email: Option<String>,
48 #[serde(default)]
49 team_granted: Option<i64>,
50 #[serde(default)]
51 oss_repo_micros: Option<i64>,
52 #[serde(default)]
53 trial_micros: Option<i64>,
54 #[serde(default)]
55 max_concurrent_agents: Option<u32>,
56 #[serde(default)]
57 audit_retention_days: Option<u32>,
58 #[serde(default)]
59 hold: Option<String>,
60}
61
62impl AccountRow {
63 fn allowances(&self) -> Allowances {
64 Allowances {
65 // The column is named for the plan's old name.
66 plan: self.team_granted.unwrap_or(0) != 0,
67 oss_repo_micros: self.oss_repo_micros,
68 trial_micros: self.trial_micros,
69 max_concurrent_agents: self.max_concurrent_agents,
70 audit_retention_days: self.audit_retention_days,
71 hold: self.hold.clone().filter(|h| !h.trim().is_empty()),
72 }
73 }
74}
75
76impl AccountRow {
77 fn terms(&self) -> Terms {
78 let expired = self.terms_until.as_deref().is_some_and(|until| until < rfc3339(now_ms()).as_str());
79 if expired {
80 return Terms::standard();
81 }
82 Terms {
83 kind: match self.terms_kind.as_str() {
84 "comped" => TermsKind::Comped,
85 "custom" => TermsKind::Custom,
86 _ => TermsKind::Standard,
87 },
88 discount_percent: self.discount_percent,
89 ceiling_micros: self.ceiling_micros,
90 note: self.note.clone(),
91 until: self.terms_until.clone(),
92 set_by: self.terms_set_by.clone(),
93 set_at: self.terms_set_at.clone(),
94 }
95 }
96}
97
98#[derive(Deserialize)]
99struct Member {
100 workspace: String,
101}
102
103#[derive(Deserialize)]
104struct ActionRow {
105 id: String,
106 account: String,
107 action: String,
108 detail: String,
109 by: String,
110 created_at: String,
111}
112
113/// `ws_<slug>`: a workspace's own account.
114pub(crate) fn own_account(workspace: &str) -> String {
115 format!("ws_{}", workspace.to_lowercase())
116}
117
118fn kind_text(kind: TermsKind) -> &'static str {
119 match kind {
120 TermsKind::Standard => "standard",
121 TermsKind::Comped => "comped",
122 TermsKind::Custom => "custom",
123 }
124}
125
126fn describe(terms: &Terms) -> String {
127 let mut text = match terms.kind {
128 TermsKind::Standard => "standard".to_owned(),
129 TermsKind::Comped | TermsKind::Custom => {
130 let mut parts = vec![];
131 if let Some(label) = terms.discount_label() {
132 parts.push(label);
133 }
134 if let Some(ceiling) = terms.ceiling_micros {
135 let what = if terms.full_discount() { "monthly budget" } else { "ceiling" };
136 parts.push(format!("{what} {}", crate::features::dollars(ceiling)));
137 }
138 if parts.is_empty() { "custom (no changes)".to_owned() } else { parts.join(", ") }
139 }
140 };
141 if let Some(until) = &terms.until {
142 text.push_str(&format!(" until {}", &until[..until.len().min(10)]));
143 }
144 if !terms.note.is_empty() {
145 text.push_str(&format!(": {}", terms.note));
146 }
147 text
148}
149
150impl Billing {
151 /// Local terms never cancel or discount an existing Stripe subscription.
152 /// Refuse a fee waiver until those subscriptions are actually ended, so
153 /// sudo cannot promise no charge while Stripe continues charging monthly.
154 async fn fee_waiver_conflict(&self, account: &BillingAccount) -> Result<bool> {
155 for workspace in &account.workspaces {
156 if self.db.prepare(FEE_WAIVER_SUBSCRIPTIONS)
157 .bind(&[workspace.as_str().into()])?.first::<serde_json::Value>(None).await?.is_some() {
158 return Ok(true);
159 }
160 }
161 Ok(false)
162 }
163
164 async fn account_row(&self, id: &str) -> Result<Option<AccountRow>> {
165 self.db
166 .prepare("SELECT * FROM billing_accounts WHERE id = ?")
167 .bind(&[id.into()])?
168 .first::<AccountRow>(None)
169 .await
170 }
171
172 async fn members(&self, account: &str) -> Result<Vec<String>> {
173 Ok(self
174 .db
175 .prepare("SELECT workspace FROM account_members WHERE account_id = ? ORDER BY workspace")
176 .bind(&[account.into()])?
177 .all()
178 .await?
179 .results::<Member>()?
180 .into_iter()
181 .map(|m| m.workspace)
182 .collect())
183 }
184
185 fn to_account(&self, row: &AccountRow, workspaces: Vec<String>) -> BillingAccount {
186 BillingAccount {
187 id: row.id.clone(),
188 kind: if row.kind == "enterprise" { AccountKind::Enterprise } else { AccountKind::Workspace },
189 name: row.name.clone(),
190 terms: row.terms(),
191 workspaces,
192 created_at: row.created_at.clone(),
193 billing_email: row.billing_email.clone(),
194 invoices: vec![],
195 allowances: row.allowances(),
196 }
197 }
198
199 /// The account that pays for a workspace.
200 pub(crate) async fn account_of(&self, workspace: &str) -> Result<BillingAccount> {
201 let workspace = workspace.to_lowercase();
202 #[derive(Deserialize)]
203 struct Link {
204 account_id: String,
205 }
206 let linked = self
207 .db
208 .prepare("SELECT account_id FROM account_members WHERE workspace = ?")
209 .bind(&[workspace.as_str().into()])?
210 .first::<Link>(None)
211 .await?;
212 if let Some(link) = linked
213 && let Some(row) = self.account_row(&link.account_id).await? {
214 let members = self.members(&row.id).await?;
215 return Ok(self.to_account(&row, members));
216 }
217 let id = own_account(&workspace);
218 Ok(match self.account_row(&id).await? {
219 Some(row) => self.to_account(&row, vec![workspace]),
220 None => BillingAccount {
221 id,
222 kind: AccountKind::Workspace,
223 name: workspace.clone(),
224 terms: Terms::standard(),
225 workspaces: vec![workspace],
226 created_at: String::new(),
227 billing_email: None,
228 invoices: vec![],
229 allowances: Allowances::default(),
230 },
231 })
232 }
233
234 /// The terms a workspace is charged on.
235 pub(crate) async fn terms_of(&self, workspace: &str) -> Result<Terms> {
236 Ok(self.account_of(workspace).await?.terms)
237 }
238
239 /// An enterprise, with its invoices.
240 pub(crate) async fn enterprise(&self, id: &str) -> Result<Option<BillingAccount>> {
241 let Some(row) = self.account_row(id).await?.filter(|row| row.kind == "enterprise") else {
242 return Ok(None);
243 };
244 let members = self.members(&row.id).await?;
245 let mut account = self.to_account(&row, members);
246 account.invoices = self.enterprise_invoices(&row.id).await?;
247 Ok(Some(account))
248 }
249
250 /// An account by id, or the account of a workspace by its slug.
251 pub(crate) async fn find_account(&self, id: &str) -> Result<Option<BillingAccount>> {
252 let id = id.trim().to_lowercase();
253 if id.starts_with("ent_") {
254 return self.enterprise(&id).await;
255 }
256 let slug = id.strip_prefix("ws_").unwrap_or(&id);
257 if slug.is_empty() {
258 return Ok(None);
259 }
260 Ok(Some(self.account_of(slug).await?))
261 }
262
263 pub(crate) async fn audit(&self, account: &str, action: &str, detail: &str, by: &str) -> Result<()> {
264 self.audit_at(account, action, detail, by, now_ms()).await
265 }
266
267 /// `audit`, at a given instant: a testing reset's entry carries the
268 /// same `created_at` as the `reset_costs` it kept.
269 pub(crate) async fn audit_at(&self, account: &str, action: &str, detail: &str, by: &str, at_ms: u64) -> Result<()> {
270 self.db
271 .prepare("INSERT INTO admin_actions (id, account, action, detail, by, created_at) VALUES (?, ?, ?, ?, ?, ?)")
272 .bind(&[
273 new_id("adm", at_ms).into(),
274 account.into(),
275 action.into(),
276 detail.into(),
277 by.into(),
278 rfc3339(at_ms).into(),
279 ])?
280 .run()
281 .await?;
282 Ok(())
283 }
284
285 /// Where an account stands this month.
286 async fn summary(&self, account: BillingAccount) -> Result<AccountSummary> {
287 let first = account.workspaces.first().cloned().unwrap_or_else(|| account.name.clone());
288 let limit = self.limit_of(&first).await?;
289 #[derive(Deserialize)]
290 struct Totals {
291 workspace: String,
292 charged: Option<i64>,
293 cost: Option<i64>,
294 }
295 #[derive(Deserialize)]
296 struct Paid {
297 workspace: String,
298 paid: Option<i64>,
299 }
300 let marks = vec!["?"; account.workspaces.len().max(1)].join(", ");
301 let mut values: Vec<JsValue> = account.workspaces.iter().map(|w| JsValue::from(w.as_str())).collect();
302 if values.is_empty() {
303 values.push(JsValue::from(""));
304 }
305 let month_start = format!("{}-01", &rfc3339(now_ms())[..7]);
306 let mut with_month = values.clone();
307 with_month.push(month_start.as_str().into());
308 let totals = self
309 .db
310 .prepare(format!(
311 "SELECT workspace, -SUM(amount_micros) AS charged,
312 SUM(CASE WHEN COALESCE(billed_to, 'g1t') = 'g1t' THEN cost_micros ELSE 0 END) AS cost
313 FROM ledger WHERE kind = 'usage' AND workspace IN ({marks}) AND created_at >= ? GROUP BY workspace"
314 ))
315 .bind(&with_month)?
316 .all()
317 .await?
318 .results::<Totals>()?;
319 let paid = self
320 .db
321 .prepare(format!(
322 "SELECT workspace, SUM(amount_micros) AS paid FROM ledger
323 WHERE kind = 'top_up' AND workspace IN ({marks}) GROUP BY workspace"
324 ))
325 .bind(&values)?
326 .all()
327 .await?
328 .results::<Paid>()?;
329 // Each workspace's share, in the account's order; the account's
330 // figures are their sum.
331 let mut by_workspace: Vec<WorkspaceFigures> = vec![];
332 for workspace in &account.workspaces {
333 figures_for(&mut by_workspace, workspace);
334 }
335 for t in &totals {
336 let f = figures_for(&mut by_workspace, &t.workspace);
337 f.charged_micros += t.charged.unwrap_or(0);
338 f.cost_micros += t.cost.unwrap_or(0);
339 }
340 for p in &paid {
341 figures_for(&mut by_workspace, &p.workspace).paid_micros += p.paid.unwrap_or(0);
342 }
343 let months = self.months_for(&account.workspaces, 6).await?;
344 Ok(AccountSummary {
345 months,
346 charged_micros: by_workspace.iter().map(|f| f.charged_micros).sum(),
347 cost_micros: by_workspace.iter().map(|f| f.cost_micros).sum(),
348 paid_micros: by_workspace.iter().map(|f| f.paid_micros).sum(),
349 by_workspace,
350 account,
351 limit,
352 })
353 }
354
355 // --- Staff ------------------------------------------------------------
356
357 pub(crate) async fn admin_accounts(&self, a: AdminAccountsArgs) -> Result<Vec<AccountSummary>> {
358 // Exactly the workspaces asked for, such as one page of sudo's list.
359 if let Some(workspaces) = &a.workspaces {
360 let mut seen = std::collections::HashSet::new();
361 let mut summaries = vec![];
362 for slug in workspaces.iter().take(200) {
363 let account = self.account_of(slug).await?;
364 if seen.insert(account.id.clone()) {
365 summaries.push(self.summary(account).await?);
366 }
367 }
368 return Ok(summaries);
369 }
370 // Every workspace that has used or paid for anything, and every
371 // account with terms of its own.
372 #[derive(Deserialize)]
373 struct Slug {
374 workspace: String,
375 }
376 let mut slugs: Vec<String> = self
377 .db
378 .prepare(
379 "SELECT DISTINCT workspace FROM ledger
380 UNION SELECT workspace FROM accounts
381 UNION SELECT substr(id, 4) FROM billing_accounts WHERE kind = 'workspace'",
382 )
383 .all()
384 .await?
385 .results::<Slug>()?
386 .into_iter()
387 .map(|s| s.workspace)
388 .collect();
389 if let Some(query) = a.query.as_deref().map(str::trim).filter(|q| !q.is_empty()) {
390 let query = query.to_lowercase();
391 slugs.retain(|slug| slug.contains(&query));
392 }
393 let mut seen = std::collections::HashSet::new();
394 let mut summaries = vec![];
395 for slug in slugs.into_iter().take(200) {
396 let account = self.account_of(&slug).await?;
397 if !seen.insert(account.id.clone()) {
398 continue;
399 }
400 summaries.push(self.summary(account).await?);
401 }
402 // Enterprises with no usage yet.
403 #[derive(Deserialize)]
404 struct Id {
405 id: String,
406 }
407 let enterprises = self
408 .db
409 .prepare("SELECT id FROM billing_accounts WHERE kind = 'enterprise'")
410 .all()
411 .await?
412 .results::<Id>()?;
413 for Id { id } in enterprises {
414 if seen.contains(&id) {
415 continue;
416 }
417 if let Some(account) = self.find_account(&id).await?
418 && a.query.as_deref().is_none_or(|q| account.name.to_lowercase().contains(&q.to_lowercase())) {
419 seen.insert(id);
420 summaries.push(self.summary(account).await?);
421 }
422 }
423 summaries.sort_by_key(|x| std::cmp::Reverse(x.limit.exposure_micros));
424 Ok(summaries)
425 }
426
427 pub(crate) async fn admin_account(&self, a: AdminAccountArgs) -> Result<Outcome<AccountDetail>> {
428 let Some(account) = self.find_account(&a.id).await? else {
429 return Ok(Outcome::fail(FailureCode::NotFound, "No such account."));
430 };
431 let mut workspaces = vec![];
432 for workspace in &account.workspaces {
433 workspaces.push(self.limit_of(workspace).await?);
434 }
435 let marks = vec!["?"; account.workspaces.len().max(1)].join(", ");
436 let mut values: Vec<JsValue> = account.workspaces.iter().map(|w| JsValue::from(w.as_str())).collect();
437 if values.is_empty() {
438 values.push(JsValue::from(""));
439 }
440 let ledger = self
441 .db
442 .prepare(format!("SELECT * FROM ledger WHERE workspace IN ({marks}) ORDER BY id DESC LIMIT 100"))
443 .bind(&values)?
444 .all()
445 .await?
446 .results::<LedgerRow>()?
447 .into_iter()
448 .map(LedgerEntry::from)
449 .collect();
450 let audit = self
451 .db
452 .prepare("SELECT * FROM admin_actions WHERE account = ? ORDER BY created_at DESC LIMIT 50")
453 .bind(&[account.id.as_str().into()])?
454 .all()
455 .await?
456 .results::<ActionRow>()?
457 .into_iter()
458 .map(|row| AdminAction {
459 id: row.id,
460 account: row.account,
461 action: row.action,
462 detail: row.detail,
463 by: row.by,
464 created_at: row.created_at,
465 })
466 .collect();
467 Ok(Outcome::Ok(AccountDetail { summary: self.summary(account).await?, workspaces, ledger, audit }))
468 }
469
470 pub(crate) async fn admin_set_terms(&self, mut a: AdminSetTermsArgs) -> Result<Outcome<BillingAccount>> {
471 a.terms = normalized(a.terms);
472 if a.by.trim().is_empty() {
473 return Ok(Outcome::fail(FailureCode::Invalid, "Say who is making the change."));
474 }
475 if a.terms.kind != TermsKind::Standard && a.terms.note.trim().is_empty() {
476 return Ok(Outcome::fail(FailureCode::Invalid, "Say why, in the note."));
477 }
478 if a.terms.discount_percent > 100 || a.terms.ceiling_micros.is_some_and(|c| c < 0) {
479 return Ok(Outcome::fail(FailureCode::Invalid, "A discount is 0 to 100%, and a ceiling is not negative."));
480 }
481 let Some(account) = self.find_account(&a.id).await? else {
482 return Ok(Outcome::fail(FailureCode::NotFound, "No such account."));
483 };
484 if a.terms.full_discount() && self.fee_waiver_conflict(&account).await? {
485 return Ok(Outcome::fail(FailureCode::Conflict,
486 "An existing Stripe subscription can still charge its monthly fee. End that subscription before granting a full discount; changing usage terms does not cancel it."));
487 }
488 let now = rfc3339(now_ms());
489 // A workspace's own account gets a row the first time its terms change.
490 self.db
491 .prepare(
492 "INSERT INTO billing_accounts (id, kind, name, terms_kind, discount_percent, ceiling_micros, note,
493 terms_until, terms_set_by, terms_set_at, created_by, created_at)
494 VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?9, ?10)
495 ON CONFLICT (id) DO UPDATE SET terms_kind = ?4, discount_percent = ?5, ceiling_micros = ?6,
496 note = ?7, terms_until = ?8, terms_set_by = ?9, terms_set_at = ?10",
497 )
498 .bind(&[
499 account.id.as_str().into(),
500 if account.kind == AccountKind::Enterprise { "enterprise" } else { "workspace" }.into(),
501 account.name.as_str().into(),
502 kind_text(a.terms.kind).into(),
503 a.terms.discount_percent.into(),
504 a.terms.ceiling_micros.map_or(JsValue::NULL, |c| (c as f64).into()),
505 a.terms.note.trim().into(),
506 optional(a.terms.until.as_deref()),
507 a.by.as_str().into(),
508 now.as_str().into(),
509 ])?
510 .run()
511 .await?;
512 self.audit(&account.id, "terms", &format!("{} → {}", describe(&account.terms), describe(&a.terms)), &a.by)
513 .await?;
514 Ok(Outcome::Ok(self.find_account(&account.id).await?.unwrap_or(account)))
515 }
516
517 /// The plan without its price, the plan's caps, a hold on new compute,
518 /// and the account's share of g1t's pools.
519 pub(crate) async fn admin_set_allowances(&self, a: AdminSetAllowancesArgs) -> Result<Outcome<BillingAccount>> {
520 if a.by.trim().is_empty() || a.note.trim().is_empty() {
521 return Ok(Outcome::fail(FailureCode::Invalid, "Say who is making the change, and why, in the note."));
522 }
523 let money = |m: Option<i64>| m.is_none_or(|m| (0..=1_000 * g1t_contracts::billing::MICROS_PER_DOLLAR).contains(&m));
524 if !money(a.allowances.oss_repo_micros) || !money(a.allowances.trial_micros) {
525 return Ok(Outcome::fail(FailureCode::Invalid, "A pool share or trial is between $0 and $1,000."));
526 }
527 if a.allowances.max_concurrent_agents.is_some_and(|n| n == 0 || n > 1_000) {
528 return Ok(Outcome::fail(FailureCode::Invalid, "Agents at once is between 1 and 1,000."));
529 }
530 if let Some(why) = crate::retention::invalid_days(&self.plans, a.allowances.audit_retention_days) {
531 return Ok(Outcome::fail(FailureCode::Invalid, why));
532 }
533 let Some(account) = self.find_account(&a.id).await? else {
534 return Ok(Outcome::fail(FailureCode::NotFound, "No such account."));
535 };
536 if a.allowances.plan && self.fee_waiver_conflict(&account).await? {
537 return Ok(Outcome::fail(FailureCode::Conflict,
538 "An existing Stripe subscription can still charge its monthly fee. End that subscription before granting the plan without its price."));
539 }
540 let now = rfc3339(now_ms());
541 let opt = |m: Option<i64>| m.map_or(JsValue::NULL, |m| (m as f64).into());
542 // A workspace's own account gets a row the first time anything is set.
543 self.db
544 .prepare(
545 "INSERT INTO billing_accounts (id, kind, name, terms_kind, discount_percent, note, created_by, created_at,
546 team_granted, oss_repo_micros, trial_micros, max_concurrent_agents, hold, audit_retention_days)
547 VALUES (?1, ?2, ?3, 'standard', 0, '', ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11)
548 ON CONFLICT (id) DO UPDATE SET team_granted = ?6, oss_repo_micros = ?7, trial_micros = ?8,
549 max_concurrent_agents = ?9, hold = ?10, audit_retention_days = ?11",
550 )
551 .bind(&[
552 account.id.as_str().into(),
553 if account.kind == AccountKind::Enterprise { "enterprise" } else { "workspace" }.into(),
554 account.name.as_str().into(),
555 a.by.as_str().into(),
556 now.as_str().into(),
557 u32::from(a.allowances.plan).into(),
558 opt(a.allowances.oss_repo_micros),
559 opt(a.allowances.trial_micros),
560 a.allowances.max_concurrent_agents.map_or(JsValue::NULL, JsValue::from),
561 optional(a.allowances.hold.as_deref().map(str::trim).filter(|h| !h.is_empty())),
562 a.allowances.audit_retention_days.map_or(JsValue::NULL, JsValue::from),
563 ])?
564 .run()
565 .await?;
566 // A trial amount from staff replaces each workspace's grant, outside
567 // the monthly pool; what was used stays used.
568 if let Some(amount) = a.allowances.trial_micros {
569 for workspace in &account.workspaces {
570 self.db
571 .prepare(
572 "INSERT INTO trial_grants (workspace, month, granted_micros, used_micros, created_at)
573 VALUES (?1, 'staff', ?2, 0, ?3)
574 ON CONFLICT (workspace) DO UPDATE SET month = 'staff', granted_micros = ?2",
575 )
576 .bind(&[workspace.as_str().into(), (amount as f64).into(), now.as_str().into()])?
577 .run()
578 .await?;
579 }
580 }
581 self.audit(
582 &account.id,
583 "allowances",
584 &format!("{} → {}: {}", describe_allowances(&account.allowances), describe_allowances(&a.allowances), a.note.trim()),
585 &a.by,
586 )
587 .await?;
588 Ok(Outcome::Ok(self.find_account(&account.id).await?.unwrap_or(account)))
589 }
590
591 pub(crate) async fn admin_create_enterprise(&self, a: AdminCreateEnterpriseArgs) -> Result<Outcome<BillingAccount>> {
592 let name = a.name.trim();
593 if name.is_empty() || a.by.trim().is_empty() {
594 return Ok(Outcome::fail(FailureCode::Invalid, "An enterprise needs a name, and who is making it."));
595 }
596 let now = now_ms();
597 let id = new_id("ent", now).to_lowercase();
598 self.db
599 .prepare(
600 "INSERT INTO billing_accounts (id, kind, name, terms_kind, discount_percent, note, created_by, created_at)
601 VALUES (?, 'enterprise', ?, 'standard', 0, '', ?, ?)",
602 )
603 .bind(&[id.as_str().into(), name.into(), a.by.as_str().into(), rfc3339(now).into()])?
604 .run()
605 .await?;
606 self.audit(&id, "create", &format!("Enterprise {name}"), &a.by).await?;
607 for workspace in &a.workspaces {
608 let workspace = workspace.trim().to_lowercase();
609 if !workspace.is_empty() {
610 self.attach(&workspace, Some(&id), &a.by).await?;
611 }
612 }
613 Ok(match self.find_account(&id).await? {
614 Some(account) => Outcome::Ok(account),
615 None => Outcome::fail(FailureCode::NotFound, "The enterprise was not saved."),
616 })
617 }
618
619 async fn attach(&self, workspace: &str, account: Option<&str>, by: &str) -> Result<()> {
620 let before = self.account_of(workspace).await?;
621 match account {
622 Some(account) => {
623 self.db
624 .prepare(
625 "INSERT INTO account_members (workspace, account_id, added_by, added_at) VALUES (?1, ?2, ?3, ?4)
626 ON CONFLICT (workspace) DO UPDATE SET account_id = ?2, added_by = ?3, added_at = ?4",
627 )
628 .bind(&[workspace.into(), account.into(), by.into(), rfc3339(now_ms()).into()])?
629 .run()
630 .await?;
631 self.audit(account, "attach", &format!("{workspace} joined, from {}", before.name), by).await?;
632 }
633 None => {
634 self.db
635 .prepare("DELETE FROM account_members WHERE workspace = ?")
636 .bind(&[workspace.into()])?
637 .run()
638 .await?;
639 self.audit(&before.id, "detach", &format!("{workspace} left, back to paying for itself"), by).await?;
640 }
641 }
642 Ok(())
643 }
644
645 pub(crate) async fn admin_attach(&self, a: AdminAttachArgs) -> Result<Outcome<BillingAccount>> {
646 let workspace = a.workspace.trim().to_lowercase();
647 if workspace.is_empty() || a.by.trim().is_empty() {
648 return Ok(Outcome::fail(FailureCode::Invalid, "Name the workspace, and who is making the change."));
649 }
650 if let Some(account) = &a.account {
651 match self.account_row(account).await? {
652 Some(row) if row.kind == "enterprise" => {}
653 _ => return Ok(Outcome::fail(FailureCode::NotFound, "Workspaces can only join an enterprise.")),
654 }
655 }
656 self.attach(&workspace, a.account.as_deref(), &a.by).await?;
657 Ok(Outcome::Ok(self.account_of(&workspace).await?))
658 }
659
660 pub(crate) async fn admin_billing_link(
661 &self,
662 a: g1t_contracts::billing::AdminBillingLinkArgs,
663 ) -> Result<Outcome<g1t_contracts::billing::BillingLink>> {
664 let workspace = a.workspace.trim().to_lowercase();
665 if workspace.is_empty() || a.by.trim().is_empty() {
666 return Ok(Outcome::fail(FailureCode::Invalid, "Name the workspace, and who is asking."));
667 }
668 let Some(stripe) = &self.stripe else {
669 return Ok(Outcome::fail(FailureCode::Conflict, "Payments are not set up on this g1t."));
670 };
671 let customer = match self.customer_for(&workspace).await {
672 Ok(customer) => customer,
673 Err(error) => return Ok(Outcome::fail(FailureCode::Conflict, crate::stripe::friendly(&error))),
674 };
675 let link = async {
676 let configuration = stripe.portal_configuration().await?;
677 let portal_url = stripe.portal_session(&customer, "https://g1t.sh/").await?;
678 let customer_email = stripe.customer_email(&customer).await.ok().flatten();
679 Ok::<_, worker::Error>(g1t_contracts::billing::BillingLink {
680 portal_url,
681 login_url: configuration.login_page.and_then(|page| page.url),
682 customer_email,
683 expires_note: "The one-time link works for a short while and only once; the sign-in page does not expire."
684 .to_owned(),
685 })
686 }
687 .await;
688 match link {
689 Ok(link) => {
690 let account = self.account_of(&workspace).await?;
691 self.audit(&account.id, "billing_link", &format!("Stripe billing link for {workspace}"), &a.by).await?;
692 Ok(Outcome::Ok(link))
693 }
694 Err(error) => Ok(Outcome::fail(FailureCode::Conflict, crate::stripe::friendly(&error))),
695 }
696 }
697}
698
699/// Terms as billing keeps them: "comped" is a 100% discount, and custom
700/// terms with nothing in them are standard.
701fn normalized(mut terms: Terms) -> Terms {
702 if terms.kind == TermsKind::Comped {
703 terms.kind = TermsKind::Custom;
704 terms.discount_percent = 100;
705 }
706 if terms.kind == TermsKind::Custom && terms.discount_percent == 0 && terms.ceiling_micros.is_none() {
707 terms.kind = TermsKind::Standard;
708 }
709 if terms.kind == TermsKind::Standard {
710 terms.discount_percent = 0;
711 terms.ceiling_micros = None;
712 }
713 terms
714}
715
716/// Allowances as the audit log reads them.
717fn describe_allowances(a: &Allowances) -> String {
718 let mut parts = vec![if a.plan { "plan given" } else { "plan not given" }.to_owned()];
719 if let Some(m) = a.oss_repo_micros {
720 parts.push(format!("open-source share {} a repository", crate::features::dollars(m)));
721 }
722 if let Some(m) = a.trial_micros {
723 parts.push(format!("trial {}", crate::features::dollars(m)));
724 }
725 if let Some(n) = a.max_concurrent_agents {
726 parts.push(format!("{n} agents at once"));
727 }
728 if let Some(days) = a.audit_retention_days {
729 parts.push(format!("audit log {days} days"));
730 }
731 if let Some(hold) = &a.hold {
732 parts.push(format!("hold: {hold}"));
733 }
734 parts.join(", ")
735}
736
737/// A workspace's figures in `list`, added at the end the first time.
738fn figures_for<'a>(list: &'a mut Vec<WorkspaceFigures>, workspace: &str) -> &'a mut WorkspaceFigures {
739 let i = match list.iter().position(|f| f.workspace == workspace) {
740 Some(i) => i,
741 None => {
742 list.push(WorkspaceFigures { workspace: workspace.to_owned(), ..Default::default() });
743 list.len() - 1
744 }
745 };
746 &mut list[i]
747}
748
749#[cfg(test)]
750mod tests {
751 use super::*;
752
753 fn terms(kind: TermsKind, discount: u32) -> Terms {
754 Terms { kind, discount_percent: discount, ..Terms::standard() }
755 }
756
757 #[test]
758 fn terms_shape_every_charge() {
759 assert_eq!(terms(TermsKind::Standard, 0).apply(1_000), 1_000);
760 assert_eq!(terms(TermsKind::Comped, 0).apply(1_000), 0);
761 assert_eq!(terms(TermsKind::Custom, 25).apply(1_000), 750);
762 assert_eq!(terms(TermsKind::Custom, 250).apply(1_000), 0);
763 }
764
765 #[test]
766 fn a_discount_below_cost_plus_the_margin_is_counted_as_given() {
767 // $1 of model cost at 20%: $1.20 is the floor of what a sale is worth.
768 let base = crate::margin_on(1_000_000, 20);
769 assert_eq!(base, 1_200_000);
770 // Standard: all of it sold, nothing given.
771 assert_eq!(terms(TermsKind::Standard, 0).discounted(base), (1_200_000, 0));
772 // 30% off: charged $0.84, under cost; the $0.36 below the floor is
773 // given, so charged plus given is never under cost plus the margin.
774 let (charged, given) = terms(TermsKind::Custom, 30).discounted(base);
775 assert_eq!((charged, given), (840_000, 360_000));
776 assert_eq!(charged + given, base);
777 // Over 100% is everything given, never a negative charge.
778 assert_eq!(terms(TermsKind::Custom, 250).discounted(base), (0, base));
779 // A 100% discount (and "comped", from before discounts) charges
780 // nothing and records the whole price as the discount, so the
781 // statement shows what the workspace would pay.
782 assert_eq!(terms(TermsKind::Custom, 100).discounted(base), (0, base));
783 assert_eq!(terms(TermsKind::Comped, 0).discounted(base), (0, base));
784 assert!(terms(TermsKind::Comped, 0).full_discount() && terms(TermsKind::Custom, 100).full_discount());
785 assert!(!terms(TermsKind::Custom, 99).full_discount() && !Terms::standard().full_discount());
786 // Every discount: charged plus given is the whole charge.
787 for percent in 0..=100 {
788 let (charged, given) = terms(TermsKind::Custom, percent).discounted(base);
789 assert_eq!(charged + given, base, "{percent}% off");
790 }
791 }
792
793 #[test]
794 fn terms_read_plainly_in_the_audit_log() {
795 let custom = Terms { ceiling_micros: Some(50_000_000), note: "Design partner".into(), ..terms(TermsKind::Custom, 20) };
796 assert_eq!(describe(&custom), "20% off, ceiling $50.00: Design partner");
797 assert_eq!(describe(&Terms::standard()), "standard");
798 let flagon = Terms { ceiling_micros: Some(150_000_000), note: "g1t's own".into(), ..terms(TermsKind::Custom, 100) };
799 assert_eq!(describe(&flagon), "100% discount, monthly budget $150.00: g1t's own");
800 }
801
802 #[test]
803 fn comped_terms_are_kept_as_a_100_percent_discount() {
804 let comped = normalized(Terms { note: "Partner".into(), ..terms(TermsKind::Comped, 0) });
805 assert_eq!((comped.kind, comped.discount_percent), (TermsKind::Custom, 100));
806 // Nothing in custom terms is standard, and standard keeps nothing.
807 assert_eq!(normalized(terms(TermsKind::Custom, 0)).kind, TermsKind::Standard);
808 let standard = normalized(Terms { ceiling_micros: Some(1), ..terms(TermsKind::Standard, 30) });
809 assert_eq!((standard.discount_percent, standard.ceiling_micros), (0, None));
810 }
811
812 #[test]
813 fn allowances_read_plainly_in_the_audit_log() {
814 assert_eq!(describe_allowances(&Allowances::default()), "plan not given");
815 let given = Allowances {
816 plan: true,
817 oss_repo_micros: Some(5_000_000),
818 trial_micros: Some(2_000_000),
819 max_concurrent_agents: Some(4),
820 audit_retention_days: Some(365),
821 hold: Some("mining".into()),
822 };
823 assert_eq!(
824 describe_allowances(&given),
825 "plan given, open-source share $5.00 a repository, trial $2.00, 4 agents at once, audit log 365 days, hold: mining"
826 );
827 }
828
829 #[test]
830 fn each_workspace_gets_one_share() {
831 let mut list = vec![];
832 figures_for(&mut list, "acme").charged_micros += 5;
833 figures_for(&mut list, "beta").cost_micros += 2;
834 figures_for(&mut list, "acme").charged_micros += 7;
835 assert_eq!(list.len(), 2);
836 assert_eq!(list[0], WorkspaceFigures { workspace: "acme".into(), charged_micros: 12, ..Default::default() });
837 assert_eq!(list[1].cost_micros, 2);
838 }
839}