lookup-user.ts 9.2 KB

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