lookup-user.ts 9.8 KB

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