lookup-user.ts 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275
  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. .rightJoin(WorkspaceTable, eq(WorkspaceTable.id, UserTable.workspaceID))
  41. .leftJoin(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. subscriptionID: BillingTable.subscriptionID,
  108. subscriptionCouponID: BillingTable.subscriptionCouponID,
  109. })
  110. .from(BillingTable)
  111. .where(eq(BillingTable.workspaceID, workspace.id))
  112. .then(
  113. (rows) =>
  114. rows.map((row) => ({
  115. ...row,
  116. balance: `$${(row.balance / 100000000).toFixed(2)}`,
  117. }))[0],
  118. ),
  119. )
  120. await printTable("Payments", (tx) =>
  121. tx
  122. .select({
  123. amount: PaymentTable.amount,
  124. paymentID: PaymentTable.paymentID,
  125. invoiceID: PaymentTable.invoiceID,
  126. timeCreated: PaymentTable.timeCreated,
  127. timeRefunded: PaymentTable.timeRefunded,
  128. })
  129. .from(PaymentTable)
  130. .where(eq(PaymentTable.workspaceID, workspace.id))
  131. .orderBy(sql`${PaymentTable.timeCreated} DESC`)
  132. .limit(100)
  133. .then((rows) =>
  134. rows.map((row) => ({
  135. ...row,
  136. amount: `$${(row.amount / 100000000).toFixed(2)}`,
  137. paymentID: row.paymentID
  138. ? `https://dashboard.stripe.com/acct_1RszBH2StuRr0lbX/payments/${row.paymentID}`
  139. : null,
  140. })),
  141. ),
  142. )
  143. /*
  144. await printTable("Usage", (tx) =>
  145. tx
  146. .select({
  147. model: UsageTable.model,
  148. provider: UsageTable.provider,
  149. inputTokens: UsageTable.inputTokens,
  150. outputTokens: UsageTable.outputTokens,
  151. reasoningTokens: UsageTable.reasoningTokens,
  152. cacheReadTokens: UsageTable.cacheReadTokens,
  153. cacheWrite5mTokens: UsageTable.cacheWrite5mTokens,
  154. cacheWrite1hTokens: UsageTable.cacheWrite1hTokens,
  155. cost: UsageTable.cost,
  156. timeCreated: UsageTable.timeCreated,
  157. })
  158. .from(UsageTable)
  159. .where(eq(UsageTable.workspaceID, workspace.id))
  160. .orderBy(sql`${UsageTable.timeCreated} DESC`)
  161. .limit(10)
  162. .then((rows) =>
  163. rows.map((row) => ({
  164. ...row,
  165. cost: `$${(row.cost / 100000000).toFixed(2)}`,
  166. })),
  167. ),
  168. )
  169. */
  170. }
  171. function formatMicroCents(value: number | null | undefined) {
  172. if (value === null || value === undefined) return null
  173. return `$${(value / 100000000).toFixed(2)}`
  174. }
  175. function formatDate(value: Date | null | undefined) {
  176. if (!value) return null
  177. return value.toISOString().split("T")[0]
  178. }
  179. function formatMonthlyUsage(usage: number | null | undefined, limit: number | null | undefined) {
  180. const usageText = formatMicroCents(usage) ?? "$0.00"
  181. if (limit === null || limit === undefined) return `${usageText} / no limit`
  182. return `${usageText} / $${limit.toFixed(2)}`
  183. }
  184. function formatRetryTime(seconds: number) {
  185. const days = Math.floor(seconds / 86400)
  186. if (days >= 1) return `${days} day${days > 1 ? "s" : ""}`
  187. const hours = Math.floor(seconds / 3600)
  188. const minutes = Math.ceil((seconds % 3600) / 60)
  189. if (hours >= 1) return `${hours}hr ${minutes}min`
  190. return `${minutes}min`
  191. }
  192. function getSubscriptionStatus(row: {
  193. timeSubscriptionCreated: Date | null
  194. fixedUsage: number | null
  195. rollingUsage: number | null
  196. timeFixedUpdated: Date | null
  197. timeRollingUpdated: Date | null
  198. }) {
  199. if (!row.timeSubscriptionCreated) {
  200. return { weekly: null, rolling: null, rateLimited: null, retryIn: null }
  201. }
  202. const black = BlackData.get()
  203. const now = new Date()
  204. const week = getWeekBounds(now)
  205. const fixedLimit = black.fixedLimit ? centsToMicroCents(black.fixedLimit * 100) : null
  206. const rollingLimit = black.rollingLimit ? centsToMicroCents(black.rollingLimit * 100) : null
  207. const rollingWindowMs = (black.rollingWindow ?? 5) * 3600 * 1000
  208. // Calculate current weekly usage (reset if outside current week)
  209. const currentWeekly =
  210. row.fixedUsage && row.timeFixedUpdated && row.timeFixedUpdated >= week.start ? row.fixedUsage : 0
  211. // Calculate current rolling usage
  212. const windowStart = new Date(now.getTime() - rollingWindowMs)
  213. const currentRolling =
  214. row.rollingUsage && row.timeRollingUpdated && row.timeRollingUpdated >= windowStart ? row.rollingUsage : 0
  215. // Check rate limiting
  216. const isWeeklyLimited = fixedLimit !== null && currentWeekly >= fixedLimit
  217. const isRollingLimited = rollingLimit !== null && currentRolling >= rollingLimit
  218. let retryIn: string | null = null
  219. if (isWeeklyLimited) {
  220. const retryAfter = Math.ceil((week.end.getTime() - now.getTime()) / 1000)
  221. retryIn = formatRetryTime(retryAfter)
  222. } else if (isRollingLimited && row.timeRollingUpdated) {
  223. const retryAfter = Math.ceil((row.timeRollingUpdated.getTime() + rollingWindowMs - now.getTime()) / 1000)
  224. retryIn = formatRetryTime(retryAfter)
  225. }
  226. return {
  227. weekly: fixedLimit !== null ? `${formatMicroCents(currentWeekly)} / $${black.fixedLimit}` : null,
  228. rolling: rollingLimit !== null ? `${formatMicroCents(currentRolling)} / $${black.rollingLimit}` : null,
  229. rateLimited: isWeeklyLimited || isRollingLimited ? "yes" : "no",
  230. retryIn,
  231. }
  232. }
  233. function printHeader(title: string) {
  234. console.log()
  235. console.log("─".repeat(title.length))
  236. console.log(`${title}`)
  237. console.log("─".repeat(title.length))
  238. }
  239. function printTable(title: string, callback: (tx: Database.TxOrDb) => Promise<any>): Promise<any> {
  240. return Database.use(async (tx) => {
  241. const data = await callback(tx)
  242. console.log(`\n== ${title} ==`)
  243. if (data.length === 0) {
  244. console.log("(no data)")
  245. } else {
  246. console.table(data)
  247. }
  248. return data
  249. })
  250. }