billing.ts 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587
  1. import { Stripe } from "stripe"
  2. import { and, Database, eq, isNull, sql } from "./drizzle"
  3. import {
  4. BillingTable,
  5. CouponTable,
  6. CouponType,
  7. LiteTable,
  8. PaymentTable,
  9. SubscriptionTable,
  10. UsageTable,
  11. } from "./schema/billing.sql"
  12. import { Actor } from "./actor"
  13. import { fn } from "./util/fn"
  14. import { z } from "zod"
  15. import { Resource } from "@opencode-ai/console-resource"
  16. import { Identifier } from "./identifier"
  17. import { centsToMicroCents } from "./util/price"
  18. import { User } from "./user"
  19. import { BlackData } from "./black"
  20. import { LiteData } from "./lite"
  21. export namespace Billing {
  22. export const ITEM_CREDIT_NAME = "opencode credits"
  23. export const ITEM_FEE_NAME = "processing fee"
  24. export const RELOAD_AMOUNT = 20
  25. export const RELOAD_AMOUNT_MIN = 10
  26. export const RELOAD_TRIGGER = 5
  27. export const RELOAD_TRIGGER_MIN = 5
  28. export const stripe = () =>
  29. new Stripe(Resource.STRIPE_SECRET_KEY.value, {
  30. apiVersion: "2025-03-31.basil",
  31. httpClient: Stripe.createFetchHttpClient(),
  32. })
  33. export const get = async () => {
  34. return Database.use(async (tx) =>
  35. tx
  36. .select()
  37. .from(BillingTable)
  38. .where(eq(BillingTable.workspaceID, Actor.workspace()))
  39. .then((r) => r[0]),
  40. )
  41. }
  42. export const payments = async () => {
  43. return await Database.use((tx) =>
  44. tx
  45. .select()
  46. .from(PaymentTable)
  47. .where(eq(PaymentTable.workspaceID, Actor.workspace()))
  48. .orderBy(sql`${PaymentTable.timeCreated} DESC`)
  49. .limit(100),
  50. )
  51. }
  52. export const usages = async (page = 0, pageSize = 50) => {
  53. return await Database.use((tx) =>
  54. tx
  55. .select()
  56. .from(UsageTable)
  57. .where(eq(UsageTable.workspaceID, Actor.workspace()))
  58. .orderBy(sql`${UsageTable.timeCreated} DESC`)
  59. .limit(pageSize)
  60. .offset(page * pageSize),
  61. )
  62. }
  63. export const calculateFeeInCents = (x: number) => {
  64. // math: x = total - (total * 0.044 + 0.30)
  65. // math: x = total * (1-0.044) - 0.30
  66. // math: (x + 0.30) / 0.956 = total
  67. return Math.round(((x + 30) / 0.956) * 0.044 + 30)
  68. }
  69. export const reload = async () => {
  70. const billing = await Database.use((tx) =>
  71. tx
  72. .select({
  73. customerID: BillingTable.customerID,
  74. paymentMethodID: BillingTable.paymentMethodID,
  75. reloadAmount: BillingTable.reloadAmount,
  76. })
  77. .from(BillingTable)
  78. .where(eq(BillingTable.workspaceID, Actor.workspace()))
  79. .then((rows) => rows[0]),
  80. )
  81. const customerID = billing.customerID
  82. const paymentMethodID = billing.paymentMethodID
  83. const amountInCents = (billing.reloadAmount ?? Billing.RELOAD_AMOUNT) * 100
  84. try {
  85. const draft = await Billing.stripe().invoices.create({
  86. customer: customerID!,
  87. auto_advance: false,
  88. default_payment_method: paymentMethodID!,
  89. collection_method: "charge_automatically",
  90. currency: "usd",
  91. metadata: {
  92. workspaceID: Actor.workspace(),
  93. amount: amountInCents.toString(),
  94. },
  95. })
  96. await Billing.stripe().invoiceItems.create({
  97. amount: amountInCents,
  98. currency: "usd",
  99. customer: customerID!,
  100. invoice: draft.id!,
  101. description: ITEM_CREDIT_NAME,
  102. })
  103. await Billing.stripe().invoiceItems.create({
  104. amount: calculateFeeInCents(amountInCents),
  105. currency: "usd",
  106. customer: customerID!,
  107. invoice: draft.id!,
  108. description: ITEM_FEE_NAME,
  109. })
  110. await Billing.stripe().invoices.finalizeInvoice(draft.id!)
  111. await Billing.stripe().invoices.pay(draft.id!, {
  112. off_session: true,
  113. payment_method: paymentMethodID!,
  114. })
  115. } catch (e: any) {
  116. console.error(e)
  117. await Database.use((tx) =>
  118. tx
  119. .update(BillingTable)
  120. .set({
  121. reload: false,
  122. reloadError: e.message ?? "Payment failed.",
  123. timeReloadError: sql`now()`,
  124. })
  125. .where(eq(BillingTable.workspaceID, Actor.workspace())),
  126. )
  127. return
  128. }
  129. }
  130. export const grantCredit = async (workspaceID: string, dollarAmount: number) => {
  131. const amountInMicroCents = centsToMicroCents(dollarAmount * 100)
  132. await Database.transaction(async (tx) => {
  133. await tx
  134. .update(BillingTable)
  135. .set({
  136. balance: sql`${BillingTable.balance} + ${amountInMicroCents}`,
  137. })
  138. .where(eq(BillingTable.workspaceID, workspaceID))
  139. await tx.insert(PaymentTable).values({
  140. workspaceID,
  141. id: Identifier.create("payment"),
  142. amount: amountInMicroCents,
  143. enrichment: {
  144. type: "credit",
  145. },
  146. })
  147. })
  148. return amountInMicroCents
  149. }
  150. export const subtractLiteUsage = async (workspaceID: string, amountInMicroCents: number) => {
  151. await Database.transaction(async (tx) => {
  152. const lite = await tx
  153. .select({ id: LiteTable.id })
  154. .from(LiteTable)
  155. .where(and(eq(LiteTable.workspaceID, workspaceID), isNull(LiteTable.timeDeleted)))
  156. .then((rows) => rows[0])
  157. if (!lite) throw new Error("Subscribe to Go before applying referral rewards")
  158. await tx
  159. .update(LiteTable)
  160. .set({
  161. monthlyUsage: sql`GREATEST(0, COALESCE(${LiteTable.monthlyUsage}, 0) - ${amountInMicroCents})`,
  162. weeklyUsage: sql`GREATEST(0, COALESCE(${LiteTable.weeklyUsage}, 0) - ${amountInMicroCents})`,
  163. rollingUsage: sql`GREATEST(0, COALESCE(${LiteTable.rollingUsage}, 0) - ${amountInMicroCents})`,
  164. })
  165. .where(and(eq(LiteTable.workspaceID, workspaceID), isNull(LiteTable.timeDeleted)))
  166. })
  167. }
  168. export const redeemCoupon = async (email: string, type: (typeof CouponType)[number]) => {
  169. // validate coupon type
  170. await (async () => {
  171. if (type === "GO1MONTH50") return
  172. const coupon = await Database.use((tx) =>
  173. tx
  174. .select()
  175. .from(CouponTable)
  176. .where(and(eq(CouponTable.email, email), eq(CouponTable.type, type)))
  177. .then((rows) => rows[0]),
  178. )
  179. if (!coupon) throw new Error("Invalid coupon code")
  180. if (coupon.timeRedeemed) throw new Error("Coupon already redeemed")
  181. })()
  182. // handle coupon type
  183. if (type === "BUILDATHON") await grantCredit(Actor.workspace(), 500)
  184. await Database.use((tx) =>
  185. tx
  186. .insert(CouponTable)
  187. .values({ email, type, timeRedeemed: sql`now()` })
  188. .onDuplicateKeyUpdate({
  189. set: {
  190. timeRedeemed: sql`now()`,
  191. },
  192. }),
  193. )
  194. }
  195. export const setMonthlyLimit = fn(z.number(), async (input) => {
  196. return await Database.use((tx) =>
  197. tx
  198. .update(BillingTable)
  199. .set({
  200. monthlyLimit: input,
  201. })
  202. .where(eq(BillingTable.workspaceID, Actor.workspace())),
  203. )
  204. })
  205. export const generateCheckoutUrl = fn(
  206. z.object({
  207. successUrl: z.string(),
  208. cancelUrl: z.string(),
  209. amount: z.number().optional(),
  210. }),
  211. async (input) => {
  212. const user = Actor.assert("user")
  213. const { successUrl, cancelUrl, amount } = input
  214. if (amount !== undefined && amount < Billing.RELOAD_AMOUNT_MIN) {
  215. throw new Error(`Amount must be at least $${Billing.RELOAD_AMOUNT_MIN}`)
  216. }
  217. const email = await User.getAuthEmail(user.properties.userID)
  218. const customer = await Billing.get()
  219. const amountInCents = (amount ?? customer.reloadAmount ?? Billing.RELOAD_AMOUNT) * 100
  220. const session = await Billing.stripe().checkout.sessions.create({
  221. mode: "payment",
  222. billing_address_collection: "required",
  223. line_items: [
  224. {
  225. price_data: {
  226. currency: "usd",
  227. product_data: { name: ITEM_CREDIT_NAME },
  228. unit_amount: amountInCents,
  229. },
  230. quantity: 1,
  231. },
  232. {
  233. price_data: {
  234. currency: "usd",
  235. product_data: { name: ITEM_FEE_NAME },
  236. unit_amount: calculateFeeInCents(amountInCents),
  237. },
  238. quantity: 1,
  239. },
  240. ],
  241. ...(customer.customerID
  242. ? {
  243. customer: customer.customerID,
  244. customer_update: {
  245. name: "auto",
  246. address: "auto",
  247. },
  248. }
  249. : {
  250. customer_email: email!,
  251. customer_creation: "always",
  252. }),
  253. currency: "usd",
  254. invoice_creation: {
  255. enabled: true,
  256. },
  257. payment_method_options: {
  258. card: {
  259. setup_future_usage: "off_session",
  260. },
  261. link: {
  262. setup_future_usage: "off_session",
  263. },
  264. },
  265. //payment_method_data: {
  266. // allow_redisplay: "always",
  267. //},
  268. tax_id_collection: {
  269. enabled: true,
  270. },
  271. metadata: {
  272. workspaceID: Actor.workspace(),
  273. amount: amountInCents.toString(),
  274. },
  275. success_url: successUrl,
  276. cancel_url: cancelUrl,
  277. })
  278. return session.url
  279. },
  280. )
  281. export const generateLiteCheckoutUrl = fn(
  282. z.object({
  283. successUrl: z.string(),
  284. cancelUrl: z.string(),
  285. method: z.enum(["alipay", "upi"]).optional(),
  286. }),
  287. async (input) => {
  288. const user = Actor.assert("user")
  289. const { successUrl, cancelUrl, method } = input
  290. const email = (await User.getAuthEmail(user.properties.userID))!
  291. const billing = await Billing.get()
  292. if (billing.subscriptionID) throw new Error("Already subscribed to Black")
  293. if (billing.liteSubscriptionID) throw new Error("Already subscribed to Lite")
  294. const coupons = await Database.use((tx) =>
  295. tx
  296. .select({ type: CouponTable.type, timeRedeemed: CouponTable.timeRedeemed })
  297. .from(CouponTable)
  298. .where(eq(CouponTable.email, email)),
  299. )
  300. const coupon = (() => {
  301. if (coupons.some((coupon) => coupon.type === "GO12MONTHS100" && !coupon.timeRedeemed))
  302. return LiteData.twelveMonths100Coupon
  303. if (coupons.some((coupon) => coupon.type === "GO6MONTHS100" && !coupon.timeRedeemed))
  304. return LiteData.sixMonths100Coupon
  305. if (coupons.some((coupon) => coupon.type === "GO3MONTHS100" && !coupon.timeRedeemed))
  306. return LiteData.threeMonths100Coupon
  307. if (coupons.some((coupon) => coupon.type === "GOFREEMONTH" && !coupon.timeRedeemed))
  308. return LiteData.firstMonth100Coupon
  309. if (!coupons.some((coupon) => coupon.type === "GO1MONTH50")) return LiteData.firstMonth50Coupon
  310. return undefined
  311. })()
  312. const createSession = () =>
  313. Billing.stripe().checkout.sessions.create({
  314. mode: "subscription",
  315. discounts: coupon ? [{ coupon }] : undefined,
  316. ...(billing.customerID
  317. ? {
  318. customer: billing.customerID,
  319. customer_update: {
  320. name: "auto",
  321. address: "auto",
  322. },
  323. }
  324. : {
  325. customer_email: email,
  326. }),
  327. ...(() => {
  328. if (method === "alipay") {
  329. return {
  330. line_items: [{ price: LiteData.priceID(), quantity: 1 }],
  331. payment_method_types: ["alipay"],
  332. adaptive_pricing: {
  333. enabled: false,
  334. },
  335. }
  336. }
  337. if (method === "upi") {
  338. return {
  339. line_items: [
  340. {
  341. price_data: {
  342. currency: "inr",
  343. product: LiteData.productID(),
  344. recurring: {
  345. interval: "month",
  346. interval_count: 1,
  347. },
  348. unit_amount: LiteData.priceInr(),
  349. },
  350. quantity: 1,
  351. },
  352. ],
  353. payment_method_types: ["upi"] as any,
  354. adaptive_pricing: {
  355. enabled: false,
  356. },
  357. }
  358. }
  359. return {
  360. line_items: [{ price: LiteData.priceID(), quantity: 1 }],
  361. billing_address_collection: "required",
  362. }
  363. })(),
  364. tax_id_collection: {
  365. enabled: true,
  366. },
  367. success_url: successUrl,
  368. cancel_url: cancelUrl,
  369. subscription_data: {
  370. metadata: {
  371. workspaceID: Actor.workspace(),
  372. userID: user.properties.userID,
  373. userEmail: email,
  374. coupon,
  375. type: "lite",
  376. },
  377. },
  378. })
  379. try {
  380. const session = await createSession()
  381. return session.url
  382. } catch (e: any) {
  383. if (
  384. e.type !== "StripeInvalidRequestError" ||
  385. !e.message.includes("You cannot combine currencies on a single customer")
  386. )
  387. throw e
  388. // get pending payment intent
  389. const intents = await Billing.stripe().paymentIntents.search({
  390. query: `-status:'canceled' AND -status:'processing' AND -status:'succeeded' AND customer:'${billing.customerID}'`,
  391. })
  392. if (intents.data.length === 0) throw e
  393. for (const intent of intents.data) {
  394. // get checkout session
  395. const sessions = await Billing.stripe().checkout.sessions.list({
  396. customer: billing.customerID!,
  397. payment_intent: intent.id,
  398. })
  399. // delete pending payment intent
  400. await Billing.stripe().checkout.sessions.expire(sessions.data[0].id)
  401. }
  402. const session = await createSession()
  403. return session.url
  404. }
  405. },
  406. )
  407. export const generateSessionUrl = fn(
  408. z.object({
  409. returnUrl: z.string(),
  410. }),
  411. async (input) => {
  412. const { returnUrl } = input
  413. const customer = await Billing.get()
  414. if (!customer?.customerID) {
  415. throw new Error("No stripe customer ID")
  416. }
  417. const session = await Billing.stripe().billingPortal.sessions.create({
  418. customer: customer.customerID,
  419. return_url: returnUrl,
  420. })
  421. return session.url
  422. },
  423. )
  424. export const generateReceiptUrl = fn(
  425. z.object({
  426. paymentID: z.string(),
  427. }),
  428. async (input) => {
  429. const { paymentID } = input
  430. const intent = await Billing.stripe().paymentIntents.retrieve(paymentID)
  431. if (!intent.latest_charge) throw new Error("No charge found")
  432. const charge = await Billing.stripe().charges.retrieve(intent.latest_charge as string)
  433. if (!charge.receipt_url) throw new Error("No receipt URL found")
  434. return charge.receipt_url
  435. },
  436. )
  437. export const subscribeBlack = fn(
  438. z.object({
  439. seats: z.number(),
  440. coupon: z.string().optional(),
  441. }),
  442. async ({ seats, coupon }) => {
  443. const user = Actor.assert("user")
  444. const billing = await Database.use((tx) =>
  445. tx
  446. .select({
  447. customerID: BillingTable.customerID,
  448. paymentMethodID: BillingTable.paymentMethodID,
  449. subscriptionID: BillingTable.subscriptionID,
  450. subscriptionPlan: BillingTable.subscriptionPlan,
  451. timeSubscriptionSelected: BillingTable.timeSubscriptionSelected,
  452. })
  453. .from(BillingTable)
  454. .where(eq(BillingTable.workspaceID, Actor.workspace()))
  455. .then((rows) => rows[0]),
  456. )
  457. if (!billing) throw new Error("Billing record not found")
  458. if (!billing.timeSubscriptionSelected) throw new Error("Not selected for subscription")
  459. if (billing.subscriptionID) throw new Error("Already subscribed")
  460. if (!billing.customerID) throw new Error("No customer ID")
  461. if (!billing.paymentMethodID) throw new Error("No payment method")
  462. if (!billing.subscriptionPlan) throw new Error("No subscription plan")
  463. const subscription = await Billing.stripe().subscriptions.create({
  464. customer: billing.customerID,
  465. default_payment_method: billing.paymentMethodID,
  466. items: [{ price: BlackData.planToPriceID({ plan: billing.subscriptionPlan }) }],
  467. metadata: {
  468. workspaceID: Actor.workspace(),
  469. },
  470. })
  471. await Database.transaction(async (tx) => {
  472. await tx
  473. .update(BillingTable)
  474. .set({
  475. subscriptionID: subscription.id,
  476. subscription: {
  477. status: "subscribed",
  478. coupon,
  479. seats,
  480. plan: billing.subscriptionPlan!,
  481. },
  482. subscriptionPlan: null,
  483. timeSubscriptionBooked: null,
  484. timeSubscriptionSelected: null,
  485. })
  486. .where(eq(BillingTable.workspaceID, Actor.workspace()))
  487. await tx.insert(SubscriptionTable).values({
  488. workspaceID: Actor.workspace(),
  489. id: Identifier.create("subscription"),
  490. userID: user.properties.userID,
  491. })
  492. })
  493. return subscription.id
  494. },
  495. )
  496. export const unsubscribeBlack = fn(
  497. z.object({
  498. subscriptionID: z.string(),
  499. }),
  500. async ({ subscriptionID }) => {
  501. const workspaceID = await Database.use((tx) =>
  502. tx
  503. .select({ workspaceID: BillingTable.workspaceID })
  504. .from(BillingTable)
  505. .where(eq(BillingTable.subscriptionID, subscriptionID))
  506. .then((rows) => rows[0]?.workspaceID),
  507. )
  508. if (!workspaceID) throw new Error("Workspace ID not found for subscription")
  509. await Database.transaction(async (tx) => {
  510. await tx
  511. .update(BillingTable)
  512. .set({ subscriptionID: null, subscription: null })
  513. .where(eq(BillingTable.workspaceID, workspaceID))
  514. await tx.delete(SubscriptionTable).where(eq(SubscriptionTable.workspaceID, workspaceID))
  515. })
  516. },
  517. )
  518. export const unsubscribeLite = fn(
  519. z.object({
  520. subscriptionID: z.string(),
  521. }),
  522. async ({ subscriptionID }) => {
  523. const workspaceID = await Database.use((tx) =>
  524. tx
  525. .select({ workspaceID: BillingTable.workspaceID })
  526. .from(BillingTable)
  527. .where(eq(BillingTable.liteSubscriptionID, subscriptionID))
  528. .then((rows) => rows[0]?.workspaceID),
  529. )
  530. if (!workspaceID) throw new Error("Workspace ID not found for subscription")
  531. await Database.transaction(async (tx) => {
  532. await tx
  533. .update(BillingTable)
  534. .set({ liteSubscriptionID: null, lite: null })
  535. .where(eq(BillingTable.workspaceID, workspaceID))
  536. await tx.delete(LiteTable).where(eq(LiteTable.workspaceID, workspaceID))
  537. })
  538. },
  539. )
  540. }