referral.ts 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424
  1. import { z } from "zod"
  2. import { and, asc, eq, inArray, isNull, sql, Database } from "./drizzle"
  3. import { Actor } from "./actor"
  4. import { Identifier } from "./identifier"
  5. import { LiteTable, PaymentTable } from "./schema/billing.sql"
  6. import { ReferralCodeTable, ReferralRewardTable, ReferralTable } from "./schema/referral.sql"
  7. import { AuthTable } from "./schema/auth.sql"
  8. import { UserTable } from "./schema/user.sql"
  9. import { WorkspaceTable } from "./schema/workspace.sql"
  10. import { centsToMicroCents, microCentsToCents } from "./util/price"
  11. import { fn } from "./util/fn"
  12. import { Billing } from "./billing"
  13. import { LiteData } from "./lite"
  14. import { Subscription } from "./subscription"
  15. import { ulid } from "ulid"
  16. export namespace Referral {
  17. export const REWARD_AMOUNT = centsToMicroCents(500)
  18. export const CODE_LENGTH = 10
  19. export function normalizeCode(code?: string | null) {
  20. return code
  21. ?.toUpperCase()
  22. .replace(/[^A-Z0-9]/g, "")
  23. .slice(0, CODE_LENGTH)
  24. }
  25. function generateCode() {
  26. return ulid().slice(-CODE_LENGTH).toUpperCase()
  27. }
  28. async function ensureCode(workspaceID = Actor.workspace()) {
  29. return Database.use(async (db) => {
  30. const existing = await db
  31. .select({ code: ReferralCodeTable.code })
  32. .from(ReferralCodeTable)
  33. .where(eq(ReferralCodeTable.workspaceID, workspaceID))
  34. .then((rows) => rows[0])
  35. if (existing) return { code: existing.code }
  36. await db.insert(ReferralCodeTable).ignore().values({
  37. workspaceID,
  38. code: generateCode(),
  39. })
  40. const created = await db
  41. .select({ code: ReferralCodeTable.code })
  42. .from(ReferralCodeTable)
  43. .where(eq(ReferralCodeTable.workspaceID, workspaceID))
  44. .then((rows) => rows[0])
  45. if (created) return { code: created.code }
  46. throw new Error("Failed to generate referral code")
  47. })
  48. }
  49. export const summary = fn(z.void(), async () => {
  50. const workspaceID = Actor.workspace()
  51. const accountID = Actor.account()
  52. const code = await ensureCode(workspaceID)
  53. const rows = await Database.use(async (tx) => {
  54. const [rewards, invites, inviteeReferral, inviteeRewards] = await Promise.all([
  55. tx
  56. .select({
  57. referralID: ReferralRewardTable.referralID,
  58. workspaceID: ReferralRewardTable.workspaceID,
  59. referralWorkspaceID: ReferralTable.workspaceID,
  60. inviteeEmail: AuthTable.subject,
  61. amount: ReferralRewardTable.amount,
  62. timeCreated: ReferralRewardTable.timeCreated,
  63. timeApplied: ReferralRewardTable.timeApplied,
  64. })
  65. .from(ReferralRewardTable)
  66. .innerJoin(ReferralTable, eq(ReferralTable.id, ReferralRewardTable.referralID))
  67. .innerJoin(
  68. AuthTable,
  69. and(eq(AuthTable.accountID, ReferralTable.inviteeAccountID), eq(AuthTable.provider, "email")),
  70. )
  71. .where(
  72. and(
  73. eq(ReferralRewardTable.workspaceID, workspaceID),
  74. isNull(ReferralRewardTable.timeDeleted),
  75. isNull(ReferralTable.timeDeleted),
  76. ),
  77. ),
  78. tx
  79. .select({ id: ReferralTable.id, inviteeEmail: AuthTable.subject, timeCreated: ReferralTable.timeCreated })
  80. .from(ReferralTable)
  81. .innerJoin(
  82. AuthTable,
  83. and(eq(AuthTable.accountID, ReferralTable.inviteeAccountID), eq(AuthTable.provider, "email")),
  84. )
  85. .where(and(eq(ReferralTable.workspaceID, workspaceID), isNull(ReferralTable.timeDeleted))),
  86. tx
  87. .select({ id: ReferralTable.id, inviterEmail: AuthTable.subject, timeCreated: ReferralTable.timeCreated })
  88. .from(ReferralTable)
  89. .leftJoin(
  90. UserTable,
  91. and(
  92. eq(UserTable.workspaceID, ReferralTable.workspaceID),
  93. eq(UserTable.role, "admin"),
  94. isNull(UserTable.timeDeleted),
  95. ),
  96. )
  97. .leftJoin(AuthTable, and(eq(AuthTable.accountID, UserTable.accountID), eq(AuthTable.provider, "email")))
  98. .where(and(eq(ReferralTable.inviteeAccountID, accountID), isNull(ReferralTable.timeDeleted)))
  99. .orderBy(asc(UserTable.timeCreated))
  100. .then((rows) => rows.find((row) => row.inviterEmail) ?? rows[0]),
  101. tx
  102. .select({ referralID: ReferralRewardTable.referralID })
  103. .from(ReferralRewardTable)
  104. .innerJoin(ReferralTable, eq(ReferralTable.id, ReferralRewardTable.referralID))
  105. .where(
  106. and(
  107. eq(ReferralTable.inviteeAccountID, accountID),
  108. isNull(ReferralRewardTable.timeDeleted),
  109. isNull(ReferralTable.timeDeleted),
  110. ),
  111. ),
  112. ])
  113. return { inviteeReferral, inviteeRewards, invites, rewards }
  114. })
  115. const rewardReferralIDs = new Set(rows.rewards.map((reward) => reward.referralID))
  116. const inviteeRewardReferralIDs = new Set(rows.inviteeRewards.map((reward) => reward.referralID))
  117. const rewards = rows.rewards.map((reward) => {
  118. const source = reward.workspaceID === reward.referralWorkspaceID ? ("inviter" as const) : ("invitee" as const)
  119. return {
  120. id: reward.referralID,
  121. source,
  122. status: reward.timeApplied ? ("applied" as const) : ("available" as const),
  123. email: source === "invitee" ? (rows.inviteeReferral?.inviterEmail ?? null) : reward.inviteeEmail,
  124. amount: microCentsToCents(reward.amount),
  125. timeCreated: reward.timeCreated,
  126. timeApplied: reward.timeApplied,
  127. }
  128. })
  129. const pending = [
  130. ...rows.invites
  131. .filter((referral) => !rewardReferralIDs.has(referral.id))
  132. .map((referral) => ({
  133. id: `${referral.id}:inviter`,
  134. source: "inviter" as const,
  135. status: "pending" as const,
  136. email: referral.inviteeEmail,
  137. amount: microCentsToCents(REWARD_AMOUNT),
  138. timeCreated: referral.timeCreated,
  139. timeApplied: null,
  140. })),
  141. ...(rows.inviteeReferral && !inviteeRewardReferralIDs.has(rows.inviteeReferral.id)
  142. ? [
  143. {
  144. id: `${rows.inviteeReferral.id}:invitee`,
  145. source: "invitee" as const,
  146. status: "pending" as const,
  147. email: rows.inviteeReferral.inviterEmail,
  148. amount: microCentsToCents(REWARD_AMOUNT),
  149. timeCreated: rows.inviteeReferral.timeCreated,
  150. timeApplied: null,
  151. },
  152. ]
  153. : []),
  154. ]
  155. const allRewards = [...pending, ...rewards].sort(
  156. (a, b) => new Date(b.timeCreated).getTime() - new Date(a.timeCreated).getTime(),
  157. )
  158. return {
  159. referralCode: code.code,
  160. hasReferral: allRewards.length > 0,
  161. rewardAmount: microCentsToCents(REWARD_AMOUNT),
  162. rewards: allRewards,
  163. }
  164. })
  165. export const applyReward = fn(z.object({ referralID: z.string() }), async (input) => {
  166. const workspaceID = Actor.workspace()
  167. return Database.transaction(async (tx) => {
  168. const reward = await tx
  169. .select({ amount: ReferralRewardTable.amount, timeApplied: ReferralRewardTable.timeApplied })
  170. .from(ReferralRewardTable)
  171. .where(
  172. and(
  173. eq(ReferralRewardTable.workspaceID, workspaceID),
  174. eq(ReferralRewardTable.referralID, input.referralID),
  175. isNull(ReferralRewardTable.timeDeleted),
  176. ),
  177. )
  178. .then((rows) => rows[0])
  179. if (!reward) throw new Error("Referral reward not found")
  180. if (reward.timeApplied) throw new Error("Referral reward already applied")
  181. const update = await tx
  182. .update(ReferralRewardTable)
  183. .set({
  184. timeApplied: sql`now()`,
  185. })
  186. .where(
  187. and(
  188. eq(ReferralRewardTable.workspaceID, workspaceID),
  189. eq(ReferralRewardTable.referralID, input.referralID),
  190. isNull(ReferralRewardTable.timeApplied),
  191. isNull(ReferralRewardTable.timeDeleted),
  192. ),
  193. )
  194. if (update.rowsAffected === 0) throw new Error("Referral reward already applied")
  195. await Billing.subtractLiteUsage(workspaceID, reward.amount)
  196. return { amount: microCentsToCents(reward.amount) }
  197. })
  198. })
  199. export const usagePreview = fn(z.object({ referralID: z.string() }), async (input) => {
  200. const row = await Database.use((tx) =>
  201. tx
  202. .select({
  203. rewardAmount: ReferralRewardTable.amount,
  204. rollingUsage: LiteTable.rollingUsage,
  205. weeklyUsage: LiteTable.weeklyUsage,
  206. monthlyUsage: LiteTable.monthlyUsage,
  207. timeRollingUpdated: LiteTable.timeRollingUpdated,
  208. timeWeeklyUpdated: LiteTable.timeWeeklyUpdated,
  209. timeMonthlyUpdated: LiteTable.timeMonthlyUpdated,
  210. timeCreated: LiteTable.timeCreated,
  211. })
  212. .from(ReferralRewardTable)
  213. .innerJoin(LiteTable, eq(LiteTable.workspaceID, ReferralRewardTable.workspaceID))
  214. .where(
  215. and(
  216. eq(ReferralRewardTable.workspaceID, Actor.workspace()),
  217. eq(ReferralRewardTable.referralID, input.referralID),
  218. isNull(ReferralRewardTable.timeApplied),
  219. isNull(ReferralRewardTable.timeDeleted),
  220. isNull(LiteTable.timeDeleted),
  221. ),
  222. )
  223. .then((rows) => rows[0]),
  224. )
  225. if (!row) return null
  226. const limits = LiteData.getLimits()
  227. return {
  228. rollingUsage: usagePreviewItem(
  229. Subscription.analyzeRollingUsage({
  230. limit: limits.rollingLimit,
  231. window: limits.rollingWindow,
  232. usage: row.rollingUsage ?? 0,
  233. timeUpdated: row.timeRollingUpdated ?? new Date(),
  234. }),
  235. Subscription.analyzeRollingUsage({
  236. limit: limits.rollingLimit,
  237. window: limits.rollingWindow,
  238. usage: Math.max(0, (row.rollingUsage ?? 0) - row.rewardAmount),
  239. timeUpdated: row.timeRollingUpdated ?? new Date(),
  240. }),
  241. ),
  242. weeklyUsage: usagePreviewItem(
  243. Subscription.analyzeWeeklyUsage({
  244. limit: limits.weeklyLimit,
  245. usage: row.weeklyUsage ?? 0,
  246. timeUpdated: row.timeWeeklyUpdated ?? new Date(),
  247. }),
  248. Subscription.analyzeWeeklyUsage({
  249. limit: limits.weeklyLimit,
  250. usage: Math.max(0, (row.weeklyUsage ?? 0) - row.rewardAmount),
  251. timeUpdated: row.timeWeeklyUpdated ?? new Date(),
  252. }),
  253. ),
  254. monthlyUsage: usagePreviewItem(
  255. Subscription.analyzeMonthlyUsage({
  256. limit: limits.monthlyLimit,
  257. usage: row.monthlyUsage ?? 0,
  258. timeUpdated: row.timeMonthlyUpdated ?? new Date(),
  259. timeSubscribed: row.timeCreated,
  260. }),
  261. Subscription.analyzeMonthlyUsage({
  262. limit: limits.monthlyLimit,
  263. usage: Math.max(0, (row.monthlyUsage ?? 0) - row.rewardAmount),
  264. timeUpdated: row.timeMonthlyUpdated ?? new Date(),
  265. timeSubscribed: row.timeCreated,
  266. }),
  267. ),
  268. }
  269. })
  270. export async function createFromAccount(input: { accountID: string; referralCode?: string }) {
  271. const referralCode = normalizeCode(input.referralCode)
  272. if (!referralCode) return
  273. return Database.transaction(async (tx) => {
  274. const code = await tx
  275. .select({ workspaceID: ReferralCodeTable.workspaceID })
  276. .from(ReferralCodeTable)
  277. .innerJoin(WorkspaceTable, eq(WorkspaceTable.id, ReferralCodeTable.workspaceID))
  278. .where(and(eq(ReferralCodeTable.code, referralCode), isNull(WorkspaceTable.timeDeleted)))
  279. .then((rows) => rows[0])
  280. if (!code) throw new Error("Referral code invalid")
  281. const existingReferral = await tx
  282. .select({ id: ReferralTable.id })
  283. .from(ReferralTable)
  284. .where(and(eq(ReferralTable.inviteeAccountID, input.accountID), isNull(ReferralTable.timeDeleted)))
  285. .then((rows) => rows[0])
  286. if (existingReferral) throw new Error("Referral already redeemed")
  287. const selfReferral = await tx
  288. .select({ id: UserTable.id })
  289. .from(UserTable)
  290. .where(
  291. and(
  292. eq(UserTable.workspaceID, code.workspaceID),
  293. eq(UserTable.accountID, input.accountID),
  294. isNull(UserTable.timeDeleted),
  295. ),
  296. )
  297. .then((rows) => rows[0])
  298. if (selfReferral) throw new Error("Self-referral is not allowed")
  299. const workspaceIDs = await tx
  300. .select({ workspaceID: UserTable.workspaceID })
  301. .from(UserTable)
  302. .where(and(eq(UserTable.accountID, input.accountID), isNull(UserTable.timeDeleted)))
  303. .then((rows) => rows.map((row) => row.workspaceID))
  304. if (workspaceIDs.length === 0) return
  305. const activeLite = await tx
  306. .select({ id: LiteTable.id })
  307. .from(LiteTable)
  308. .where(and(inArray(LiteTable.workspaceID, workspaceIDs), isNull(LiteTable.timeDeleted)))
  309. .then((rows) => rows[0])
  310. if (activeLite) return
  311. const litePayment = await tx
  312. .select({ id: PaymentTable.id })
  313. .from(PaymentTable)
  314. .where(
  315. and(
  316. inArray(PaymentTable.workspaceID, workspaceIDs),
  317. isNull(PaymentTable.timeDeleted),
  318. sql`JSON_UNQUOTE(JSON_EXTRACT(${PaymentTable.enrichment}, '$.type')) = 'lite'`,
  319. ),
  320. )
  321. .then((rows) => rows[0])
  322. if (litePayment) return
  323. const referralID = Identifier.create("referral")
  324. await tx.insert(ReferralTable).ignore().values({
  325. workspaceID: code.workspaceID,
  326. id: referralID,
  327. inviteeAccountID: input.accountID,
  328. })
  329. const referral = await tx
  330. .select({ id: ReferralTable.id, workspaceID: ReferralTable.workspaceID })
  331. .from(ReferralTable)
  332. .where(and(eq(ReferralTable.inviteeAccountID, input.accountID), isNull(ReferralTable.timeDeleted)))
  333. .then((rows) => rows[0])
  334. if (!referral) throw new Error("Referral not created")
  335. if (referral.id !== referralID) throw new Error("Referral already redeemed")
  336. })
  337. }
  338. export async function completeFromLiteSubscription(input: { workspaceID: string; userID: string }) {
  339. return Database.transaction(async (tx) => {
  340. const invitee = await tx
  341. .select({ accountID: UserTable.accountID })
  342. .from(UserTable)
  343. .where(
  344. and(
  345. eq(UserTable.workspaceID, input.workspaceID),
  346. eq(UserTable.id, input.userID),
  347. isNull(UserTable.timeDeleted),
  348. ),
  349. )
  350. .then((rows) => rows[0])
  351. if (!invitee?.accountID) throw new Error("Referral invitee account missing")
  352. const referral = await tx
  353. .select({ id: ReferralTable.id, workspaceID: ReferralTable.workspaceID })
  354. .from(ReferralTable)
  355. .where(and(eq(ReferralTable.inviteeAccountID, invitee.accountID), isNull(ReferralTable.timeDeleted)))
  356. .then((rows) => rows[0])
  357. if (!referral) return
  358. await tx.insert(ReferralRewardTable).ignore().values({
  359. workspaceID: referral.workspaceID,
  360. referralID: referral.id,
  361. amount: REWARD_AMOUNT,
  362. })
  363. const existingInviteeReward = await tx
  364. .select({ workspaceID: ReferralRewardTable.workspaceID })
  365. .from(ReferralRewardTable)
  366. .where(
  367. and(
  368. eq(ReferralRewardTable.referralID, referral.id),
  369. sql`${ReferralRewardTable.workspaceID} <> ${referral.workspaceID}`,
  370. isNull(ReferralRewardTable.timeDeleted),
  371. ),
  372. )
  373. .then((rows) => rows[0])
  374. if (existingInviteeReward) return
  375. await tx.insert(ReferralRewardTable).ignore().values({
  376. workspaceID: input.workspaceID,
  377. referralID: referral.id,
  378. amount: REWARD_AMOUNT,
  379. })
  380. })
  381. }
  382. function usagePreviewItem(
  383. before: { usagePercent: number; resetInSec: number },
  384. after: { usagePercent: number; resetInSec: number },
  385. ) {
  386. return {
  387. beforePercent: before.usagePercent,
  388. afterPercent: after.usagePercent,
  389. resetInSec: after.resetInSec,
  390. }
  391. }
  392. }