lookup-user.ts 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260
  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 { BillingTable, PaymentTable, SubscriptionTable, UsageTable } from "../src/schema/billing.sql.js"
  5. import { WorkspaceTable } from "../src/schema/workspace.sql.js"
  6. import { BlackData } from "../src/black.js"
  7. import { centsToMicroCents } from "../src/util/price.js"
  8. import { getWeekBounds } from "../src/util/date.js"
  9. // get input from command line
  10. const identifier = process.argv[2]
  11. if (!identifier) {
  12. console.error("Usage: bun lookup-user.ts <email|workspaceID>")
  13. process.exit(1)
  14. }
  15. if (identifier.startsWith("wrk_")) {
  16. await printWorkspace(identifier)
  17. } else {
  18. const authData = await Database.use(async (tx) =>
  19. tx.select().from(AuthTable).where(eq(AuthTable.subject, identifier)),
  20. )
  21. if (authData.length === 0) {
  22. console.error("Email not found")
  23. process.exit(1)
  24. }
  25. if (authData.length > 1) console.warn("Multiple users found for email", identifier)
  26. // Get all auth records for email
  27. const accountID = authData[0].accountID
  28. await printTable("Auth", (tx) => tx.select().from(AuthTable).where(eq(AuthTable.accountID, accountID)))
  29. // Get all workspaces for this account
  30. const users = await printTable("Workspaces", (tx) =>
  31. tx
  32. .select({
  33. userID: UserTable.id,
  34. workspaceID: UserTable.workspaceID,
  35. workspaceName: WorkspaceTable.name,
  36. role: UserTable.role,
  37. })
  38. .from(UserTable)
  39. .innerJoin(WorkspaceTable, eq(WorkspaceTable.id, UserTable.workspaceID))
  40. .where(eq(UserTable.accountID, accountID)),
  41. )
  42. // Get all payments for these workspaces
  43. await Promise.all(users.map((u: { workspaceID: string }) => printWorkspace(u.workspaceID)))
  44. }
  45. async function printWorkspace(workspaceID: string) {
  46. const workspace = await Database.use((tx) =>
  47. tx
  48. .select()
  49. .from(WorkspaceTable)
  50. .where(eq(WorkspaceTable.id, workspaceID))
  51. .then((rows) => rows[0]),
  52. )
  53. printHeader(`Workspace "${workspace.name}" (${workspace.id})`)
  54. await printTable("Users", (tx) =>
  55. tx
  56. .select({
  57. authEmail: AuthTable.subject,
  58. inviteEmail: UserTable.email,
  59. role: UserTable.role,
  60. timeSeen: UserTable.timeSeen,
  61. monthlyLimit: UserTable.monthlyLimit,
  62. monthlyUsage: UserTable.monthlyUsage,
  63. timeDeleted: UserTable.timeDeleted,
  64. fixedUsage: SubscriptionTable.fixedUsage,
  65. rollingUsage: SubscriptionTable.rollingUsage,
  66. timeFixedUpdated: SubscriptionTable.timeFixedUpdated,
  67. timeRollingUpdated: SubscriptionTable.timeRollingUpdated,
  68. timeSubscriptionCreated: SubscriptionTable.timeCreated,
  69. })
  70. .from(UserTable)
  71. .leftJoin(AuthTable, and(eq(UserTable.accountID, AuthTable.accountID), eq(AuthTable.provider, "email")))
  72. .leftJoin(SubscriptionTable, eq(SubscriptionTable.userID, UserTable.id))
  73. .where(eq(UserTable.workspaceID, workspace.id))
  74. .then((rows) =>
  75. rows.map((row) => {
  76. const subStatus = getSubscriptionStatus(row)
  77. return {
  78. email: (row.timeDeleted ? "❌ " : "") + (row.authEmail ?? row.inviteEmail),
  79. role: row.role,
  80. timeSeen: formatDate(row.timeSeen),
  81. monthly: formatMonthlyUsage(row.monthlyUsage, row.monthlyLimit),
  82. subscribed: formatDate(row.timeSubscriptionCreated),
  83. subWeekly: subStatus.weekly,
  84. subRolling: subStatus.rolling,
  85. rateLimited: subStatus.rateLimited,
  86. retryIn: subStatus.retryIn,
  87. }
  88. }),
  89. ),
  90. )
  91. await printTable("Billing", (tx) =>
  92. tx
  93. .select({
  94. balance: BillingTable.balance,
  95. customerID: BillingTable.customerID,
  96. })
  97. .from(BillingTable)
  98. .where(eq(BillingTable.workspaceID, workspace.id))
  99. .then(
  100. (rows) =>
  101. rows.map((row) => ({
  102. ...row,
  103. balance: `$${(row.balance / 100000000).toFixed(2)}`,
  104. }))[0],
  105. ),
  106. )
  107. await printTable("Payments", (tx) =>
  108. tx
  109. .select({
  110. amount: PaymentTable.amount,
  111. paymentID: PaymentTable.paymentID,
  112. invoiceID: PaymentTable.invoiceID,
  113. timeCreated: PaymentTable.timeCreated,
  114. timeRefunded: PaymentTable.timeRefunded,
  115. })
  116. .from(PaymentTable)
  117. .where(eq(PaymentTable.workspaceID, workspace.id))
  118. .orderBy(sql`${PaymentTable.timeCreated} DESC`)
  119. .limit(100)
  120. .then((rows) =>
  121. rows.map((row) => ({
  122. ...row,
  123. amount: `$${(row.amount / 100000000).toFixed(2)}`,
  124. paymentID: row.paymentID
  125. ? `https://dashboard.stripe.com/acct_1RszBH2StuRr0lbX/payments/${row.paymentID}`
  126. : null,
  127. })),
  128. ),
  129. )
  130. await printTable("Usage", (tx) =>
  131. tx
  132. .select({
  133. model: UsageTable.model,
  134. provider: UsageTable.provider,
  135. inputTokens: UsageTable.inputTokens,
  136. outputTokens: UsageTable.outputTokens,
  137. reasoningTokens: UsageTable.reasoningTokens,
  138. cacheReadTokens: UsageTable.cacheReadTokens,
  139. cacheWrite5mTokens: UsageTable.cacheWrite5mTokens,
  140. cacheWrite1hTokens: UsageTable.cacheWrite1hTokens,
  141. cost: UsageTable.cost,
  142. timeCreated: UsageTable.timeCreated,
  143. })
  144. .from(UsageTable)
  145. .where(eq(UsageTable.workspaceID, workspace.id))
  146. .orderBy(sql`${UsageTable.timeCreated} DESC`)
  147. .limit(10)
  148. .then((rows) =>
  149. rows.map((row) => ({
  150. ...row,
  151. cost: `$${(row.cost / 100000000).toFixed(2)}`,
  152. })),
  153. ),
  154. )
  155. }
  156. function formatMicroCents(value: number | null | undefined) {
  157. if (value === null || value === undefined) return null
  158. return `$${(value / 100000000).toFixed(2)}`
  159. }
  160. function formatDate(value: Date | null | undefined) {
  161. if (!value) return null
  162. return value.toISOString().split("T")[0]
  163. }
  164. function formatMonthlyUsage(usage: number | null | undefined, limit: number | null | undefined) {
  165. const usageText = formatMicroCents(usage) ?? "$0.00"
  166. if (limit === null || limit === undefined) return `${usageText} / no limit`
  167. return `${usageText} / $${limit.toFixed(2)}`
  168. }
  169. function formatRetryTime(seconds: number) {
  170. const days = Math.floor(seconds / 86400)
  171. if (days >= 1) return `${days} day${days > 1 ? "s" : ""}`
  172. const hours = Math.floor(seconds / 3600)
  173. const minutes = Math.ceil((seconds % 3600) / 60)
  174. if (hours >= 1) return `${hours}hr ${minutes}min`
  175. return `${minutes}min`
  176. }
  177. function getSubscriptionStatus(row: {
  178. timeSubscriptionCreated: Date | null
  179. fixedUsage: number | null
  180. rollingUsage: number | null
  181. timeFixedUpdated: Date | null
  182. timeRollingUpdated: Date | null
  183. }) {
  184. if (!row.timeSubscriptionCreated) {
  185. return { weekly: null, rolling: null, rateLimited: null, retryIn: null }
  186. }
  187. const black = BlackData.get()
  188. const now = new Date()
  189. const week = getWeekBounds(now)
  190. const fixedLimit = black.fixedLimit ? centsToMicroCents(black.fixedLimit * 100) : null
  191. const rollingLimit = black.rollingLimit ? centsToMicroCents(black.rollingLimit * 100) : null
  192. const rollingWindowMs = (black.rollingWindow ?? 5) * 3600 * 1000
  193. // Calculate current weekly usage (reset if outside current week)
  194. const currentWeekly =
  195. row.fixedUsage && row.timeFixedUpdated && row.timeFixedUpdated >= week.start ? row.fixedUsage : 0
  196. // Calculate current rolling usage
  197. const windowStart = new Date(now.getTime() - rollingWindowMs)
  198. const currentRolling =
  199. row.rollingUsage && row.timeRollingUpdated && row.timeRollingUpdated >= windowStart ? row.rollingUsage : 0
  200. // Check rate limiting
  201. const isWeeklyLimited = fixedLimit !== null && currentWeekly >= fixedLimit
  202. const isRollingLimited = rollingLimit !== null && currentRolling >= rollingLimit
  203. let retryIn: string | null = null
  204. if (isWeeklyLimited) {
  205. const retryAfter = Math.ceil((week.end.getTime() - now.getTime()) / 1000)
  206. retryIn = formatRetryTime(retryAfter)
  207. } else if (isRollingLimited && row.timeRollingUpdated) {
  208. const retryAfter = Math.ceil((row.timeRollingUpdated.getTime() + rollingWindowMs - now.getTime()) / 1000)
  209. retryIn = formatRetryTime(retryAfter)
  210. }
  211. return {
  212. weekly: fixedLimit !== null ? `${formatMicroCents(currentWeekly)} / $${black.fixedLimit}` : null,
  213. rolling: rollingLimit !== null ? `${formatMicroCents(currentRolling)} / $${black.rollingLimit}` : null,
  214. rateLimited: isWeeklyLimited || isRollingLimited ? "yes" : "no",
  215. retryIn,
  216. }
  217. }
  218. function printHeader(title: string) {
  219. console.log()
  220. console.log("─".repeat(title.length))
  221. console.log(`${title}`)
  222. console.log("─".repeat(title.length))
  223. }
  224. function printTable(title: string, callback: (tx: Database.TxOrDb) => Promise<any>): Promise<any> {
  225. return Database.use(async (tx) => {
  226. const data = await callback(tx)
  227. console.log(`\n== ${title} ==`)
  228. if (data.length === 0) {
  229. console.log("(no data)")
  230. } else {
  231. console.table(data)
  232. }
  233. return data
  234. })
  235. }