11import { Stripe } from "stripe"
2- import { and , Database , eq , sql } from "./drizzle"
2+ import { and , Database , eq , isNull , sql } from "./drizzle"
33import {
44 BillingTable ,
55 CouponTable ,
@@ -176,6 +176,16 @@ export namespace Billing {
176176 )
177177 }
178178
179+ export const hasCoupon = async ( email : string , type : ( typeof CouponType ) [ number ] ) => {
180+ return await Database . use ( ( tx ) =>
181+ tx
182+ . select ( )
183+ . from ( CouponTable )
184+ . where ( and ( eq ( CouponTable . email , email ) , eq ( CouponTable . type , type ) , isNull ( CouponTable . timeRedeemed ) ) )
185+ . then ( ( rows ) => rows . length > 0 ) ,
186+ )
187+ }
188+
179189 export const setMonthlyLimit = fn ( z . number ( ) , async ( input ) => {
180190 return await Database . use ( ( tx ) =>
181191 tx
@@ -274,16 +284,19 @@ export namespace Billing {
274284 const user = Actor . assert ( "user" )
275285 const { successUrl, cancelUrl, method } = input
276286
277- const email = await User . getAuthEmail ( user . properties . userID )
287+ const email = ( await User . getAuthEmail ( user . properties . userID ) ) !
278288 const billing = await Billing . get ( )
279289
280290 if ( billing . subscriptionID ) throw new Error ( "Already subscribed to Black" )
281291 if ( billing . liteSubscriptionID ) throw new Error ( "Already subscribed to Lite" )
282292
293+ const coupon = ( await Billing . hasCoupon ( email , "GOFREEMONTH" ) )
294+ ? LiteData . firstMonth100Coupon
295+ : LiteData . firstMonth50Coupon
283296 const createSession = ( ) =>
284297 Billing . stripe ( ) . checkout . sessions . create ( {
285298 mode : "subscription" ,
286- discounts : [ { coupon : LiteData . firstMonthCoupon ( email ! ) } ] ,
299+ discounts : [ { coupon } ] ,
287300 ...( billing . customerID
288301 ? {
289302 customer : billing . customerID ,
@@ -293,7 +306,7 @@ export namespace Billing {
293306 } ,
294307 }
295308 : {
296- customer_email : email ! ,
309+ customer_email : email ,
297310 } ) ,
298311 ...( ( ) => {
299312 if ( method === "alipay" ) {
@@ -341,6 +354,8 @@ export namespace Billing {
341354 metadata : {
342355 workspaceID : Actor . workspace ( ) ,
343356 userID : user . properties . userID ,
357+ userEmail : email ,
358+ coupon,
344359 type : "lite" ,
345360 } ,
346361 } ,
0 commit comments