Skip to content

g1t/services/billing/src/accounts.rs

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