diff --git a/packages/console/app/src/routes/stripe/webhook.ts b/packages/console/app/src/routes/stripe/webhook.ts index f1fa73c9..54dc4eb2 100644 --- a/packages/console/app/src/routes/stripe/webhook.ts +++ b/packages/console/app/src/routes/stripe/webhook.ts @@ -53,7 +53,8 @@ export async function POST(input: APIEvent) { await Actor.provide("system", { workspaceID }, async () => { const customer = await Billing.get() - if (customer?.customerID && customer.customerID !== customerID) throw new Error("Customer ID mismatch") + if (customer?.customerID && customer.customerID !== customerID) + throw new Error("Customer ID mismatch") // set customer metadata if (!customer?.customerID) { @@ -69,7 +70,18 @@ export async function POST(input: APIEvent) { expand: ["payment_method"], }) const paymentMethod = paymentIntent.payment_method - if (!paymentMethod || typeof paymentMethod === "string") throw new Error("Payment method not expanded") + if (!paymentMethod || typeof paymentMethod === "string") + throw new Error("Payment method not expanded") + + const oldBillingInfo = await Database.use((tx) => + tx + .select({ + customerID: BillingTable.customerID, + }) + .from(BillingTable) + .where(eq(BillingTable.workspaceID, workspaceID)) + .then((rows) => rows[0]), + ) await Database.transaction(async (tx) => { await tx @@ -80,9 +92,16 @@ export async function POST(input: APIEvent) { paymentMethodID: paymentMethod.id, paymentMethodLast4: paymentMethod.card?.last4 ?? null, paymentMethodType: paymentMethod.type, - reload: true, - reloadError: null, - timeReloadError: null, + // enable reload if first time enabling billing + ...(oldBillingInfo?.customerID + ? {} + : { + reload: true, + reloadTrigger: Billing.CHARGE_THRESHOLD_DOLLAR, + reloadAmount: Billing.CHARGE_AMOUNT_DOLLAR, + reloadError: null, + timeReloadError: null, + }), }) .where(eq(BillingTable.workspaceID, workspaceID)) await tx.insert(PaymentTable).values({ @@ -119,7 +138,12 @@ export async function POST(input: APIEvent) { .set({ timeRefunded: new Date(body.created * 1000), }) - .where(and(eq(PaymentTable.paymentID, paymentIntentID), eq(PaymentTable.workspaceID, workspaceID))) + .where( + and( + eq(PaymentTable.paymentID, paymentIntentID), + eq(PaymentTable.workspaceID, workspaceID), + ), + ) await tx .update(BillingTable) diff --git a/packages/console/app/src/routes/workspace/[id]/billing/billing-section.tsx b/packages/console/app/src/routes/workspace/[id]/billing/billing-section.tsx index 7cbf29ad..c0723136 100644 --- a/packages/console/app/src/routes/workspace/[id]/billing/billing-section.tsx +++ b/packages/console/app/src/routes/workspace/[id]/billing/billing-section.tsx @@ -93,7 +93,7 @@ export function BillingSection() { Current Balance - +
- +