lookup.ts 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479
  1. "use server"
  2. import { Database, and, eq, isNull, sql } from "@opencode-ai/console-core/drizzle/index.js"
  3. import { AuthTable } from "@opencode-ai/console-core/schema/auth.sql.js"
  4. import { UserTable } from "@opencode-ai/console-core/schema/user.sql.js"
  5. import {
  6. BillingTable,
  7. PaymentTable,
  8. SubscriptionTable,
  9. BlackPlans,
  10. UsageTable,
  11. LiteTable,
  12. } from "@opencode-ai/console-core/schema/billing.sql.js"
  13. import { WorkspaceTable } from "@opencode-ai/console-core/schema/workspace.sql.js"
  14. import { KeyTable } from "@opencode-ai/console-core/schema/key.sql.js"
  15. import { ModelTable } from "@opencode-ai/console-core/schema/model.sql.js"
  16. import { BlackData } from "@opencode-ai/console-core/black.js"
  17. import { LiteData } from "@opencode-ai/console-core/lite.js"
  18. import { Subscription } from "@opencode-ai/console-core/subscription.js"
  19. import { centsToMicroCents } from "@opencode-ai/console-core/util/price.js"
  20. import { getWeekBounds } from "@opencode-ai/console-core/util/date.js"
  21. export type LookupResult = {
  22. identifier: string
  23. auth?: Record<string, unknown>[]
  24. accountWorkspaces?: Record<string, unknown>[]
  25. workspaces: WorkspaceSection[]
  26. }
  27. export type WorkspaceSection = {
  28. workspaceID: string
  29. title: string
  30. users: Record<string, unknown>[]
  31. billing: Record<string, unknown> | null
  32. go: Record<string, unknown>[]
  33. payments: Record<string, unknown>[]
  34. usage: Record<string, unknown>[]
  35. disabledModels: Record<string, unknown>[]
  36. }
  37. export async function lookup(identifier: string): Promise<LookupResult> {
  38. if (!identifier) throw new Error("Identifier is required")
  39. if (identifier.startsWith("wrk_")) {
  40. const workspace = await loadWorkspace(identifier)
  41. return { identifier, workspaces: [workspace] }
  42. }
  43. if (identifier.startsWith("key_")) {
  44. const key = await Database.use((tx) =>
  45. tx
  46. .select()
  47. .from(KeyTable)
  48. .where(eq(KeyTable.id, identifier))
  49. .then((rows) => rows[0]),
  50. )
  51. if (!key) throw new Error("API key not found")
  52. const workspace = await loadWorkspace(key.workspaceID)
  53. return { identifier, workspaces: [workspace] }
  54. }
  55. if (identifier.startsWith("sk-")) {
  56. const key = await Database.use((tx) =>
  57. tx
  58. .select()
  59. .from(KeyTable)
  60. .where(eq(KeyTable.key, identifier))
  61. .then((rows) => rows[0]),
  62. )
  63. if (!key) throw new Error("API key not found")
  64. const workspace = await loadWorkspace(key.workspaceID)
  65. return { identifier, workspaces: [workspace] }
  66. }
  67. // Treat as email
  68. const authData = await Database.use((tx) => tx.select().from(AuthTable).where(eq(AuthTable.subject, identifier)))
  69. if (authData.length === 0) throw new Error("Email not found")
  70. const accountID = authData[0].accountID
  71. const auth = await Database.use((tx) => tx.select().from(AuthTable).where(eq(AuthTable.accountID, accountID)))
  72. const accountWorkspaces = await Database.use((tx) =>
  73. tx
  74. .select({
  75. userID: UserTable.id,
  76. workspaceID: UserTable.workspaceID,
  77. workspaceName: WorkspaceTable.name,
  78. balance: BillingTable.balance,
  79. role: UserTable.role,
  80. black: SubscriptionTable.timeCreated,
  81. lite: LiteTable.timeCreated,
  82. })
  83. .from(UserTable)
  84. .rightJoin(WorkspaceTable, eq(WorkspaceTable.id, UserTable.workspaceID))
  85. .leftJoin(BillingTable, eq(BillingTable.workspaceID, WorkspaceTable.id))
  86. .leftJoin(SubscriptionTable, eq(SubscriptionTable.userID, UserTable.id))
  87. .leftJoin(LiteTable, eq(LiteTable.userID, UserTable.id))
  88. .where(eq(UserTable.accountID, accountID))
  89. .then((rows) =>
  90. rows.map((row) => ({
  91. workspaceName: row.workspaceID
  92. ? { __link: `#workspace-${row.workspaceID}`, label: row.workspaceName }
  93. : row.workspaceName,
  94. userID: row.userID,
  95. workspaceID: row.workspaceID,
  96. balance: formatMicroCents(row.balance) ?? "$0.00",
  97. role: row.role,
  98. black: formatDate(row.black),
  99. lite: formatDate(row.lite),
  100. })),
  101. ),
  102. )
  103. const workspaces: WorkspaceSection[] = []
  104. for (const w of accountWorkspaces) {
  105. if (!w.workspaceID) continue
  106. workspaces.push(await loadWorkspace(w.workspaceID))
  107. }
  108. return {
  109. identifier,
  110. auth: auth.map((row) => ({
  111. provider: row.provider,
  112. subject: row.subject,
  113. accountID: row.accountID,
  114. })),
  115. accountWorkspaces,
  116. workspaces,
  117. }
  118. }
  119. async function loadWorkspace(workspaceID: string): Promise<WorkspaceSection> {
  120. const workspace = await Database.use((tx) =>
  121. tx
  122. .select()
  123. .from(WorkspaceTable)
  124. .where(eq(WorkspaceTable.id, workspaceID))
  125. .then((rows) => rows[0]),
  126. )
  127. if (!workspace) throw new Error(`Workspace ${workspaceID} not found`)
  128. const users = await Database.use((tx) =>
  129. tx
  130. .select({
  131. authEmail: AuthTable.subject,
  132. inviteEmail: UserTable.email,
  133. role: UserTable.role,
  134. timeSeen: UserTable.timeSeen,
  135. monthlyLimit: UserTable.monthlyLimit,
  136. monthlyUsage: UserTable.monthlyUsage,
  137. timeDeleted: UserTable.timeDeleted,
  138. fixedUsage: SubscriptionTable.fixedUsage,
  139. rollingUsage: SubscriptionTable.rollingUsage,
  140. timeFixedUpdated: SubscriptionTable.timeFixedUpdated,
  141. timeRollingUpdated: SubscriptionTable.timeRollingUpdated,
  142. timeSubscriptionCreated: SubscriptionTable.timeCreated,
  143. subscription: BillingTable.subscription,
  144. })
  145. .from(UserTable)
  146. .innerJoin(BillingTable, eq(BillingTable.workspaceID, workspace.id))
  147. .leftJoin(AuthTable, and(eq(UserTable.accountID, AuthTable.accountID), eq(AuthTable.provider, "email")))
  148. .leftJoin(SubscriptionTable, eq(SubscriptionTable.userID, UserTable.id))
  149. .where(eq(UserTable.workspaceID, workspace.id))
  150. .then((rows) =>
  151. rows.map((row) => {
  152. const subStatus = getSubscriptionStatus(row)
  153. return {
  154. email: (row.timeDeleted ? "[deleted] " : "") + (row.authEmail ?? row.inviteEmail),
  155. role: row.role,
  156. timeSeen: formatDate(row.timeSeen),
  157. monthly: formatMonthlyUsage(row.monthlyUsage, row.monthlyLimit),
  158. subscribed: formatDate(row.timeSubscriptionCreated),
  159. subWeekly: subStatus.weekly,
  160. subRolling: subStatus.rolling,
  161. rateLimited: subStatus.rateLimited,
  162. retryIn: subStatus.retryIn,
  163. }
  164. }),
  165. ),
  166. )
  167. const billing = await Database.use((tx) =>
  168. tx
  169. .select({
  170. balance: BillingTable.balance,
  171. customerID: BillingTable.customerID,
  172. reload: BillingTable.reload,
  173. blackSubscriptionID: BillingTable.subscriptionID,
  174. blackSubscription: {
  175. plan: BillingTable.subscriptionPlan,
  176. booked: BillingTable.timeSubscriptionBooked,
  177. enrichment: BillingTable.subscription,
  178. },
  179. timeBlackSubscriptionSelected: BillingTable.timeSubscriptionSelected,
  180. liteSubscriptionID: BillingTable.liteSubscriptionID,
  181. })
  182. .from(BillingTable)
  183. .where(eq(BillingTable.workspaceID, workspace.id))
  184. .then(
  185. (rows) =>
  186. rows.map((row) => ({
  187. balance: `$${(row.balance / 100000000).toFixed(2)}`,
  188. reload: row.reload ? "yes" : "no",
  189. customerID: row.customerID,
  190. GO: row.liteSubscriptionID,
  191. Black: row.blackSubscriptionID
  192. ? [
  193. `Black ${row.blackSubscription.enrichment!.plan}`,
  194. row.blackSubscription.enrichment!.seats > 1
  195. ? `X ${row.blackSubscription.enrichment!.seats} seats`
  196. : "",
  197. row.blackSubscription.enrichment!.coupon
  198. ? `(coupon: ${row.blackSubscription.enrichment!.coupon})`
  199. : "",
  200. `(ref: ${row.blackSubscriptionID})`,
  201. ].join(" ")
  202. : row.blackSubscription.booked
  203. ? `Waitlist ${row.blackSubscription.plan} plan${row.timeBlackSubscriptionSelected ? " (selected)" : ""}`
  204. : undefined,
  205. }))[0] ?? null,
  206. ),
  207. )
  208. const liteLimits = LiteData.getLimits()
  209. const go = await Database.use((tx) =>
  210. tx
  211. .select({
  212. userID: LiteTable.userID,
  213. userEmail: UserTable.email,
  214. authEmail: AuthTable.subject,
  215. rollingUsage: LiteTable.rollingUsage,
  216. weeklyUsage: LiteTable.weeklyUsage,
  217. monthlyUsage: LiteTable.monthlyUsage,
  218. timeRollingUpdated: LiteTable.timeRollingUpdated,
  219. timeWeeklyUpdated: LiteTable.timeWeeklyUpdated,
  220. timeMonthlyUpdated: LiteTable.timeMonthlyUpdated,
  221. timeCreated: LiteTable.timeCreated,
  222. useBalance: BillingTable.lite,
  223. })
  224. .from(LiteTable)
  225. .innerJoin(BillingTable, eq(BillingTable.workspaceID, LiteTable.workspaceID))
  226. .leftJoin(UserTable, eq(UserTable.id, LiteTable.userID))
  227. .leftJoin(AuthTable, and(eq(UserTable.accountID, AuthTable.accountID), eq(AuthTable.provider, "email")))
  228. .where(and(eq(LiteTable.workspaceID, workspace.id), isNull(LiteTable.timeDeleted)))
  229. .then((rows) =>
  230. rows.map((row) => {
  231. const rolling = Subscription.analyzeRollingUsage({
  232. limit: liteLimits.rollingLimit,
  233. window: liteLimits.rollingWindow,
  234. usage: row.rollingUsage ?? 0,
  235. timeUpdated: row.timeRollingUpdated ?? new Date(),
  236. })
  237. const weekly = Subscription.analyzeWeeklyUsage({
  238. limit: liteLimits.weeklyLimit,
  239. usage: row.weeklyUsage ?? 0,
  240. timeUpdated: row.timeWeeklyUpdated ?? new Date(),
  241. })
  242. const monthly = Subscription.analyzeMonthlyUsage({
  243. limit: liteLimits.monthlyLimit,
  244. usage: row.monthlyUsage ?? 0,
  245. timeUpdated: row.timeMonthlyUpdated ?? new Date(),
  246. timeSubscribed: row.timeCreated,
  247. })
  248. return {
  249. email: row.authEmail ?? row.userEmail ?? row.userID,
  250. subscribed: formatDate(row.timeCreated),
  251. useBalance: row.useBalance?.useBalance ? "yes" : "no",
  252. rolling: formatLiteUsage(rolling),
  253. weekly: formatLiteUsage(weekly),
  254. monthly: formatLiteUsage(monthly),
  255. }
  256. }),
  257. ),
  258. )
  259. const payments = await Database.use((tx) =>
  260. tx
  261. .select({
  262. amount: PaymentTable.amount,
  263. paymentID: PaymentTable.paymentID,
  264. invoiceID: PaymentTable.invoiceID,
  265. customerID: PaymentTable.customerID,
  266. timeCreated: PaymentTable.timeCreated,
  267. timeRefunded: PaymentTable.timeRefunded,
  268. })
  269. .from(PaymentTable)
  270. .where(eq(PaymentTable.workspaceID, workspace.id))
  271. .orderBy(sql`${PaymentTable.timeCreated} DESC`)
  272. .limit(100)
  273. .then((rows) =>
  274. rows.map((row) => ({
  275. amount: `$${(row.amount / 100000000).toFixed(2)}`,
  276. paymentID: row.paymentID
  277. ? `https://dashboard.stripe.com/acct_1RszBH2StuRr0lbX/payments/${row.paymentID}`
  278. : null,
  279. invoiceID: row.invoiceID,
  280. customerID: row.customerID,
  281. timeCreated: formatDate(row.timeCreated),
  282. timeRefunded: formatDate(row.timeRefunded),
  283. })),
  284. ),
  285. )
  286. const planExpr = sql`JSON_UNQUOTE(JSON_EXTRACT(${UsageTable.enrichment}, '$.plan'))`
  287. const usage = await Database.use((tx) =>
  288. tx
  289. .select({
  290. date: sql<string>`DATE(${UsageTable.timeCreated})`.as("date"),
  291. freeRequests: sql<number>`SUM(CASE WHEN ${UsageTable.cost} = 0 THEN 1 ELSE 0 END)`.as("free_requests"),
  292. goRequests: sql<number>`SUM(CASE WHEN ${planExpr} = 'lite' THEN 1 ELSE 0 END)`.as("go_requests"),
  293. goCost: sql<number>`SUM(CASE WHEN ${planExpr} = 'lite' THEN ${UsageTable.cost} ELSE 0 END)`.as("go_cost"),
  294. apiRequests: sql<number>`SUM(CASE WHEN ${planExpr} IS NULL AND ${UsageTable.cost} > 0 THEN 1 ELSE 0 END)`.as(
  295. "api_requests",
  296. ),
  297. apiCost:
  298. sql<number>`SUM(CASE WHEN ${planExpr} IS NULL AND ${UsageTable.cost} > 0 THEN ${UsageTable.cost} ELSE 0 END)`.as(
  299. "api_cost",
  300. ),
  301. })
  302. .from(UsageTable)
  303. .where(
  304. and(
  305. eq(UsageTable.workspaceID, workspace.id),
  306. sql`${UsageTable.timeCreated} >= DATE_SUB(NOW(), INTERVAL 28 DAY)`,
  307. ),
  308. )
  309. .groupBy(sql`DATE(${UsageTable.timeCreated})`)
  310. .orderBy(sql`DATE(${UsageTable.timeCreated}) DESC`)
  311. .then((rows) => {
  312. const totals = rows.reduce(
  313. (acc, r) => ({
  314. freeRequests: acc.freeRequests + Number(r.freeRequests),
  315. goRequests: acc.goRequests + Number(r.goRequests),
  316. goCost: acc.goCost + Number(r.goCost),
  317. apiRequests: acc.apiRequests + Number(r.apiRequests),
  318. apiCost: acc.apiCost + Number(r.apiCost),
  319. }),
  320. { freeRequests: 0, goRequests: 0, goCost: 0, apiRequests: 0, apiCost: 0 },
  321. )
  322. const mapped: Record<string, unknown>[] = rows.map((row) => ({
  323. date: row.date,
  324. freeRequests: Number(row.freeRequests),
  325. goRequests: Number(row.goRequests),
  326. goCost: formatMicroCents(Number(row.goCost)) ?? "$0.00",
  327. apiRequests: Number(row.apiRequests),
  328. apiCost: formatMicroCents(Number(row.apiCost)) ?? "$0.00",
  329. }))
  330. if (mapped.length > 0) {
  331. mapped.push({
  332. date: "TOTAL",
  333. freeRequests: totals.freeRequests,
  334. goRequests: totals.goRequests,
  335. goCost: formatMicroCents(totals.goCost) ?? "$0.00",
  336. apiRequests: totals.apiRequests,
  337. apiCost: formatMicroCents(totals.apiCost) ?? "$0.00",
  338. })
  339. }
  340. return mapped
  341. }),
  342. )
  343. const disabledModels = await Database.use((tx) =>
  344. tx
  345. .select({
  346. model: ModelTable.model,
  347. timeCreated: ModelTable.timeCreated,
  348. })
  349. .from(ModelTable)
  350. .where(eq(ModelTable.workspaceID, workspace.id))
  351. .orderBy(sql`${ModelTable.timeCreated} DESC`)
  352. .then((rows) =>
  353. rows.map((row) => ({
  354. model: row.model,
  355. timeCreated: formatDate(row.timeCreated),
  356. })),
  357. ),
  358. )
  359. return {
  360. workspaceID: workspace.id,
  361. title: `Workspace "${workspace.name}" (${workspace.id})`,
  362. users,
  363. billing,
  364. go,
  365. payments,
  366. usage,
  367. disabledModels,
  368. }
  369. }
  370. function formatLiteUsage(usage: { status: "ok" | "rate-limited"; usagePercent: number; resetInSec: number }) {
  371. const reset = formatResetTime(usage.resetInSec)
  372. const status = usage.status === "rate-limited" ? " [limited]" : ""
  373. return `${usage.usagePercent}% (resets in ${reset})${status}`
  374. }
  375. function formatResetTime(seconds: number) {
  376. if (seconds <= 0) return "now"
  377. const days = Math.floor(seconds / 86400)
  378. if (days >= 1) return `${days}d`
  379. const hours = Math.floor(seconds / 3600)
  380. if (hours >= 1) {
  381. const minutes = Math.floor((seconds % 3600) / 60)
  382. return minutes > 0 ? `${hours}h ${minutes}m` : `${hours}h`
  383. }
  384. const minutes = Math.max(1, Math.ceil(seconds / 60))
  385. return `${minutes}m`
  386. }
  387. function formatMicroCents(value: number | null | undefined) {
  388. if (value === null || value === undefined) return null
  389. return `$${(value / 100000000).toFixed(2)}`
  390. }
  391. function formatDate(value: Date | null | undefined) {
  392. if (!value) return null
  393. return value.toISOString().split("T")[0]
  394. }
  395. function formatMonthlyUsage(usage: number | null | undefined, limit: number | null | undefined) {
  396. const usageText = formatMicroCents(usage) ?? "$0.00"
  397. if (limit === null || limit === undefined) return `${usageText} / no limit`
  398. return `${usageText} / $${limit.toFixed(2)}`
  399. }
  400. function formatRetryTime(seconds: number) {
  401. const days = Math.floor(seconds / 86400)
  402. if (days >= 1) return `${days} day${days > 1 ? "s" : ""}`
  403. const hours = Math.floor(seconds / 3600)
  404. const minutes = Math.ceil((seconds % 3600) / 60)
  405. if (hours >= 1) return `${hours}hr ${minutes}min`
  406. return `${minutes}min`
  407. }
  408. function getSubscriptionStatus(row: {
  409. subscription: {
  410. plan: (typeof BlackPlans)[number]
  411. } | null
  412. timeSubscriptionCreated: Date | null
  413. fixedUsage: number | null
  414. rollingUsage: number | null
  415. timeFixedUpdated: Date | null
  416. timeRollingUpdated: Date | null
  417. }) {
  418. if (!row.timeSubscriptionCreated || !row.subscription) {
  419. return { weekly: null, rolling: null, rateLimited: null, retryIn: null }
  420. }
  421. const black = BlackData.getLimits({ plan: row.subscription.plan })
  422. const now = new Date()
  423. const week = getWeekBounds(now)
  424. const fixedLimit = black.fixedLimit ? centsToMicroCents(black.fixedLimit * 100) : null
  425. const rollingLimit = black.rollingLimit ? centsToMicroCents(black.rollingLimit * 100) : null
  426. const rollingWindowMs = (black.rollingWindow ?? 5) * 3600 * 1000
  427. const currentWeekly =
  428. row.fixedUsage && row.timeFixedUpdated && row.timeFixedUpdated >= week.start ? row.fixedUsage : 0
  429. const windowStart = new Date(now.getTime() - rollingWindowMs)
  430. const currentRolling =
  431. row.rollingUsage && row.timeRollingUpdated && row.timeRollingUpdated >= windowStart ? row.rollingUsage : 0
  432. const isWeeklyLimited = fixedLimit !== null && currentWeekly >= fixedLimit
  433. const isRollingLimited = rollingLimit !== null && currentRolling >= rollingLimit
  434. const retryIn = isWeeklyLimited
  435. ? formatRetryTime(Math.ceil((week.end.getTime() - now.getTime()) / 1000))
  436. : isRollingLimited && row.timeRollingUpdated
  437. ? formatRetryTime(Math.ceil((row.timeRollingUpdated.getTime() + rollingWindowMs - now.getTime()) / 1000))
  438. : null
  439. return {
  440. weekly: fixedLimit !== null ? `${formatMicroCents(currentWeekly)} / $${black.fixedLimit}` : null,
  441. rolling: rollingLimit !== null ? `${formatMicroCents(currentRolling)} / $${black.rollingLimit}` : null,
  442. rateLimited: isWeeklyLimited || isRollingLimited ? "yes" : "no",
  443. retryIn,
  444. }
  445. }