lookup-user.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410
  1. import { Database, and, eq, sql } from "../src/drizzle/index.js"
  2. import { AuthTable } from "../src/schema/auth.sql.js"
  3. import { UserTable } from "../src/schema/user.sql.js"
  4. import {
  5. BillingTable,
  6. PaymentTable,
  7. SubscriptionTable,
  8. BlackPlans,
  9. UsageTable,
  10. LiteTable,
  11. } from "../src/schema/billing.sql.js"
  12. import { WorkspaceTable } from "../src/schema/workspace.sql.js"
  13. import { KeyTable } from "../src/schema/key.sql.js"
  14. import { BlackData } from "../src/black.js"
  15. import { centsToMicroCents } from "../src/util/price.js"
  16. import { getWeekBounds } from "../src/util/date.js"
  17. import { ModelTable } from "../src/schema/model.sql.js"
  18. // get input from command line
  19. const identifier = process.argv[2]
  20. if (!identifier) {
  21. console.error("Usage: bun lookup-user.ts <email|workspaceID|apiKey>")
  22. process.exit(1)
  23. }
  24. // loop up by workspace ID
  25. if (identifier.startsWith("wrk_")) {
  26. await printWorkspace(identifier)
  27. }
  28. // lookup by API key ID
  29. else if (identifier.startsWith("key_")) {
  30. const key = await Database.use((tx) =>
  31. tx
  32. .select()
  33. .from(KeyTable)
  34. .where(eq(KeyTable.id, identifier))
  35. .then((rows) => rows[0]),
  36. )
  37. if (!key) {
  38. console.error("API key not found")
  39. process.exit(1)
  40. }
  41. await printWorkspace(key.workspaceID)
  42. }
  43. // lookup by API key value
  44. else if (identifier.startsWith("sk-")) {
  45. const key = await Database.use((tx) =>
  46. tx
  47. .select()
  48. .from(KeyTable)
  49. .where(eq(KeyTable.key, identifier))
  50. .then((rows) => rows[0]),
  51. )
  52. if (!key) {
  53. console.error("API key not found")
  54. process.exit(1)
  55. }
  56. await printWorkspace(key.workspaceID)
  57. }
  58. // lookup by email
  59. else {
  60. const authData = await Database.use(async (tx) =>
  61. tx.select().from(AuthTable).where(eq(AuthTable.subject, identifier)),
  62. )
  63. if (authData.length === 0) {
  64. console.error("Email not found")
  65. process.exit(1)
  66. }
  67. if (authData.length > 1) console.warn("Multiple users found for email", identifier)
  68. // Get all auth records for email
  69. const accountID = authData[0].accountID
  70. await printTable("Auth", (tx) => tx.select().from(AuthTable).where(eq(AuthTable.accountID, accountID)))
  71. // Get all workspaces for this account
  72. const users = await printTable("Workspaces", (tx) =>
  73. tx
  74. .select({
  75. userID: UserTable.id,
  76. workspaceID: UserTable.workspaceID,
  77. workspaceName: WorkspaceTable.name,
  78. role: UserTable.role,
  79. black: SubscriptionTable.timeCreated,
  80. lite: LiteTable.timeCreated,
  81. })
  82. .from(UserTable)
  83. .rightJoin(WorkspaceTable, eq(WorkspaceTable.id, UserTable.workspaceID))
  84. .leftJoin(SubscriptionTable, eq(SubscriptionTable.userID, UserTable.id))
  85. .leftJoin(LiteTable, eq(LiteTable.userID, UserTable.id))
  86. .where(eq(UserTable.accountID, accountID))
  87. .then((rows) =>
  88. rows.map((row) => ({
  89. userID: row.userID,
  90. workspaceID: row.workspaceID,
  91. workspaceName: row.workspaceName,
  92. role: row.role,
  93. black: formatDate(row.black),
  94. lite: formatDate(row.lite),
  95. })),
  96. ),
  97. )
  98. for (const user of users) {
  99. await printWorkspace(user.workspaceID)
  100. }
  101. }
  102. async function printWorkspace(workspaceID: string) {
  103. const workspace = await Database.use((tx) =>
  104. tx
  105. .select()
  106. .from(WorkspaceTable)
  107. .where(eq(WorkspaceTable.id, workspaceID))
  108. .then((rows) => rows[0]),
  109. )
  110. printHeader(`Workspace "${workspace.name}" (${workspace.id})`)
  111. await printTable("Users", (tx) =>
  112. tx
  113. .select({
  114. authEmail: AuthTable.subject,
  115. inviteEmail: UserTable.email,
  116. role: UserTable.role,
  117. timeSeen: UserTable.timeSeen,
  118. monthlyLimit: UserTable.monthlyLimit,
  119. monthlyUsage: UserTable.monthlyUsage,
  120. timeDeleted: UserTable.timeDeleted,
  121. fixedUsage: SubscriptionTable.fixedUsage,
  122. rollingUsage: SubscriptionTable.rollingUsage,
  123. timeFixedUpdated: SubscriptionTable.timeFixedUpdated,
  124. timeRollingUpdated: SubscriptionTable.timeRollingUpdated,
  125. timeSubscriptionCreated: SubscriptionTable.timeCreated,
  126. subscription: BillingTable.subscription,
  127. })
  128. .from(UserTable)
  129. .innerJoin(BillingTable, eq(BillingTable.workspaceID, workspace.id))
  130. .leftJoin(AuthTable, and(eq(UserTable.accountID, AuthTable.accountID), eq(AuthTable.provider, "email")))
  131. .leftJoin(SubscriptionTable, eq(SubscriptionTable.userID, UserTable.id))
  132. .where(eq(UserTable.workspaceID, workspace.id))
  133. .then((rows) =>
  134. rows.map((row) => {
  135. const subStatus = getSubscriptionStatus(row)
  136. return {
  137. email: (row.timeDeleted ? "❌ " : "") + (row.authEmail ?? row.inviteEmail),
  138. role: row.role,
  139. timeSeen: formatDate(row.timeSeen),
  140. monthly: formatMonthlyUsage(row.monthlyUsage, row.monthlyLimit),
  141. subscribed: formatDate(row.timeSubscriptionCreated),
  142. subWeekly: subStatus.weekly,
  143. subRolling: subStatus.rolling,
  144. rateLimited: subStatus.rateLimited,
  145. retryIn: subStatus.retryIn,
  146. }
  147. }),
  148. ),
  149. )
  150. await printTable("Billing", (tx) =>
  151. tx
  152. .select({
  153. balance: BillingTable.balance,
  154. customerID: BillingTable.customerID,
  155. reload: BillingTable.reload,
  156. blackSubscriptionID: BillingTable.subscriptionID,
  157. blackSubscription: {
  158. plan: BillingTable.subscriptionPlan,
  159. booked: BillingTable.timeSubscriptionBooked,
  160. enrichment: BillingTable.subscription,
  161. },
  162. timeBlackSubscriptionSelected: BillingTable.timeSubscriptionSelected,
  163. liteSubscriptionID: BillingTable.liteSubscriptionID,
  164. })
  165. .from(BillingTable)
  166. .where(eq(BillingTable.workspaceID, workspace.id))
  167. .then(
  168. (rows) =>
  169. rows.map((row) => ({
  170. balance: `$${(row.balance / 100000000).toFixed(2)}`,
  171. reload: row.reload ? "yes" : "no",
  172. customerID: row.customerID,
  173. GO: row.liteSubscriptionID,
  174. Black: row.blackSubscriptionID
  175. ? [
  176. `Black ${row.blackSubscription.enrichment!.plan}`,
  177. row.blackSubscription.enrichment!.seats > 1
  178. ? `X ${row.blackSubscription.enrichment!.seats} seats`
  179. : "",
  180. row.blackSubscription.enrichment!.coupon
  181. ? `(coupon: ${row.blackSubscription.enrichment!.coupon})`
  182. : "",
  183. `(ref: ${row.blackSubscriptionID})`,
  184. ].join(" ")
  185. : row.blackSubscription.booked
  186. ? `Waitlist ${row.blackSubscription.plan} plan${row.timeBlackSubscriptionSelected ? " (selected)" : ""}`
  187. : undefined,
  188. }))[0],
  189. ),
  190. )
  191. await printTable("Payments", (tx) =>
  192. tx
  193. .select({
  194. amount: PaymentTable.amount,
  195. paymentID: PaymentTable.paymentID,
  196. invoiceID: PaymentTable.invoiceID,
  197. customerID: PaymentTable.customerID,
  198. timeCreated: PaymentTable.timeCreated,
  199. timeRefunded: PaymentTable.timeRefunded,
  200. })
  201. .from(PaymentTable)
  202. .where(eq(PaymentTable.workspaceID, workspace.id))
  203. .orderBy(sql`${PaymentTable.timeCreated} DESC`)
  204. .limit(100)
  205. .then((rows) =>
  206. rows.map((row) => ({
  207. ...row,
  208. amount: `$${(row.amount / 100000000).toFixed(2)}`,
  209. paymentID: row.paymentID
  210. ? `https://dashboard.stripe.com/acct_1RszBH2StuRr0lbX/payments/${row.paymentID}`
  211. : null,
  212. })),
  213. ),
  214. )
  215. await printTable("28-Day Usage", (tx) =>
  216. tx
  217. .select({
  218. date: sql<string>`DATE(${UsageTable.timeCreated})`.as("date"),
  219. requests: sql<number>`COUNT(*)`.as("requests"),
  220. inputTokens: sql<number>`SUM(${UsageTable.inputTokens})`.as("input_tokens"),
  221. outputTokens: sql<number>`SUM(${UsageTable.outputTokens})`.as("output_tokens"),
  222. reasoningTokens: sql<number>`SUM(${UsageTable.reasoningTokens})`.as("reasoning_tokens"),
  223. cacheReadTokens: sql<number>`SUM(${UsageTable.cacheReadTokens})`.as("cache_read_tokens"),
  224. cacheWrite5mTokens: sql<number>`SUM(${UsageTable.cacheWrite5mTokens})`.as("cache_write_5m_tokens"),
  225. cacheWrite1hTokens: sql<number>`SUM(${UsageTable.cacheWrite1hTokens})`.as("cache_write_1h_tokens"),
  226. cost: sql<number>`SUM(${UsageTable.cost})`.as("cost"),
  227. })
  228. .from(UsageTable)
  229. .where(
  230. and(
  231. eq(UsageTable.workspaceID, workspace.id),
  232. sql`${UsageTable.timeCreated} >= DATE_SUB(NOW(), INTERVAL 28 DAY)`,
  233. ),
  234. )
  235. .groupBy(sql`DATE(${UsageTable.timeCreated})`)
  236. .orderBy(sql`DATE(${UsageTable.timeCreated}) DESC`)
  237. .then((rows) => {
  238. const totalCost = rows.reduce((sum, r) => sum + Number(r.cost), 0)
  239. const mapped = rows.map((row) => ({
  240. ...row,
  241. cost: `$${(Number(row.cost) / 100000000).toFixed(2)}`,
  242. }))
  243. if (mapped.length > 0) {
  244. mapped.push({
  245. date: "TOTAL",
  246. requests: null as any,
  247. inputTokens: null as any,
  248. outputTokens: null as any,
  249. reasoningTokens: null as any,
  250. cacheReadTokens: null as any,
  251. cacheWrite5mTokens: null as any,
  252. cacheWrite1hTokens: null as any,
  253. cost: `$${(totalCost / 100000000).toFixed(2)}`,
  254. })
  255. }
  256. return mapped
  257. }),
  258. )
  259. /*
  260. await printTable("Usage", (tx) =>
  261. tx
  262. .select({
  263. model: UsageTable.model,
  264. provider: UsageTable.provider,
  265. inputTokens: UsageTable.inputTokens,
  266. outputTokens: UsageTable.outputTokens,
  267. reasoningTokens: UsageTable.reasoningTokens,
  268. cacheReadTokens: UsageTable.cacheReadTokens,
  269. cacheWrite5mTokens: UsageTable.cacheWrite5mTokens,
  270. cacheWrite1hTokens: UsageTable.cacheWrite1hTokens,
  271. cost: UsageTable.cost,
  272. timeCreated: UsageTable.timeCreated,
  273. })
  274. .from(UsageTable)
  275. .where(eq(UsageTable.workspaceID, workspace.id))
  276. .orderBy(sql`${UsageTable.timeCreated} DESC`)
  277. .limit(10)
  278. .then((rows) =>
  279. rows.map((row) => ({
  280. ...row,
  281. cost: `$${(row.cost / 100000000).toFixed(2)}`,
  282. })),
  283. ),
  284. )
  285. await printTable("Disabled Models", (tx) =>
  286. tx
  287. .select({
  288. model: ModelTable.model,
  289. timeCreated: ModelTable.timeCreated,
  290. })
  291. .from(ModelTable)
  292. .where(eq(ModelTable.workspaceID, workspace.id))
  293. .orderBy(sql`${ModelTable.timeCreated} DESC`)
  294. .then((rows) =>
  295. rows.map((row) => ({
  296. model: row.model,
  297. timeCreated: formatDate(row.timeCreated),
  298. })),
  299. ),
  300. )
  301. */
  302. }
  303. function formatMicroCents(value: number | null | undefined) {
  304. if (value === null || value === undefined) return null
  305. return `$${(value / 100000000).toFixed(2)}`
  306. }
  307. function formatDate(value: Date | null | undefined) {
  308. if (!value) return null
  309. return value.toISOString().split("T")[0]
  310. }
  311. function formatMonthlyUsage(usage: number | null | undefined, limit: number | null | undefined) {
  312. const usageText = formatMicroCents(usage) ?? "$0.00"
  313. if (limit === null || limit === undefined) return `${usageText} / no limit`
  314. return `${usageText} / $${limit.toFixed(2)}`
  315. }
  316. function formatRetryTime(seconds: number) {
  317. const days = Math.floor(seconds / 86400)
  318. if (days >= 1) return `${days} day${days > 1 ? "s" : ""}`
  319. const hours = Math.floor(seconds / 3600)
  320. const minutes = Math.ceil((seconds % 3600) / 60)
  321. if (hours >= 1) return `${hours}hr ${minutes}min`
  322. return `${minutes}min`
  323. }
  324. function getSubscriptionStatus(row: {
  325. subscription: {
  326. plan: (typeof BlackPlans)[number]
  327. } | null
  328. timeSubscriptionCreated: Date | null
  329. fixedUsage: number | null
  330. rollingUsage: number | null
  331. timeFixedUpdated: Date | null
  332. timeRollingUpdated: Date | null
  333. }) {
  334. if (!row.timeSubscriptionCreated || !row.subscription) {
  335. return { weekly: null, rolling: null, rateLimited: null, retryIn: null }
  336. }
  337. const black = BlackData.getLimits({ plan: row.subscription.plan })
  338. const now = new Date()
  339. const week = getWeekBounds(now)
  340. const fixedLimit = black.fixedLimit ? centsToMicroCents(black.fixedLimit * 100) : null
  341. const rollingLimit = black.rollingLimit ? centsToMicroCents(black.rollingLimit * 100) : null
  342. const rollingWindowMs = (black.rollingWindow ?? 5) * 3600 * 1000
  343. // Calculate current weekly usage (reset if outside current week)
  344. const currentWeekly =
  345. row.fixedUsage && row.timeFixedUpdated && row.timeFixedUpdated >= week.start ? row.fixedUsage : 0
  346. // Calculate current rolling usage
  347. const windowStart = new Date(now.getTime() - rollingWindowMs)
  348. const currentRolling =
  349. row.rollingUsage && row.timeRollingUpdated && row.timeRollingUpdated >= windowStart ? row.rollingUsage : 0
  350. // Check rate limiting
  351. const isWeeklyLimited = fixedLimit !== null && currentWeekly >= fixedLimit
  352. const isRollingLimited = rollingLimit !== null && currentRolling >= rollingLimit
  353. let retryIn: string | null = null
  354. if (isWeeklyLimited) {
  355. const retryAfter = Math.ceil((week.end.getTime() - now.getTime()) / 1000)
  356. retryIn = formatRetryTime(retryAfter)
  357. } else if (isRollingLimited && row.timeRollingUpdated) {
  358. const retryAfter = Math.ceil((row.timeRollingUpdated.getTime() + rollingWindowMs - now.getTime()) / 1000)
  359. retryIn = formatRetryTime(retryAfter)
  360. }
  361. return {
  362. weekly: fixedLimit !== null ? `${formatMicroCents(currentWeekly)} / $${black.fixedLimit}` : null,
  363. rolling: rollingLimit !== null ? `${formatMicroCents(currentRolling)} / $${black.rollingLimit}` : null,
  364. rateLimited: isWeeklyLimited || isRollingLimited ? "yes" : "no",
  365. retryIn,
  366. }
  367. }
  368. function printHeader(title: string) {
  369. console.log()
  370. console.log("─".repeat(title.length))
  371. console.log(`${title}`)
  372. console.log("─".repeat(title.length))
  373. }
  374. function printTable(title: string, callback: (tx: Database.TxOrDb) => Promise<any>): Promise<any> {
  375. return Database.use(async (tx) => {
  376. const data = await callback(tx)
  377. console.log(`\n== ${title} ==`)
  378. if (data.length === 0) {
  379. console.log("(no data)")
  380. } else {
  381. console.table(data)
  382. }
  383. return data
  384. })
  385. }