lookup-user.ts 11 KB

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