Skip to content

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

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