|
| 1 | +import { |
| 2 | + BadRequestException, |
| 3 | + Injectable, |
| 4 | + NotFoundException, |
| 5 | +} from '@nestjs/common'; |
| 6 | +import { db } from '@db'; |
| 7 | +import { StripeService } from '../stripe/stripe.service'; |
| 8 | + |
| 9 | +@Injectable() |
| 10 | +export class BackgroundCheckBillingService { |
| 11 | + constructor(private readonly stripeService: StripeService) {} |
| 12 | + |
| 13 | + async getStatus(organizationId: string): Promise<{ |
| 14 | + hasBilling: boolean; |
| 15 | + hasPaymentMethod: boolean; |
| 16 | + setupAt: Date | null; |
| 17 | + }> { |
| 18 | + const billing = await db.organizationBilling.findUnique({ |
| 19 | + where: { organizationId }, |
| 20 | + select: { |
| 21 | + stripeCustomerId: true, |
| 22 | + stripeBackgroundCheckPaymentMethodId: true, |
| 23 | + backgroundCheckPaymentMethodSetupAt: true, |
| 24 | + }, |
| 25 | + }); |
| 26 | + |
| 27 | + return { |
| 28 | + hasBilling: !!billing, |
| 29 | + hasPaymentMethod: !!billing?.stripeBackgroundCheckPaymentMethodId, |
| 30 | + setupAt: billing?.backgroundCheckPaymentMethodSetupAt ?? null, |
| 31 | + }; |
| 32 | + } |
| 33 | + |
| 34 | + async createSetupSession({ |
| 35 | + organizationId, |
| 36 | + successUrl, |
| 37 | + cancelUrl, |
| 38 | + }: { |
| 39 | + organizationId: string; |
| 40 | + successUrl: string; |
| 41 | + cancelUrl: string; |
| 42 | + }): Promise<{ url: string }> { |
| 43 | + this.validateRedirectUrl(successUrl); |
| 44 | + this.validateRedirectUrl(cancelUrl); |
| 45 | + |
| 46 | + const stripe = this.stripeService.getClient(); |
| 47 | + const customerId = await this.findOrCreateCustomer(organizationId); |
| 48 | + const price = await this.getBackgroundCheckPrice(); |
| 49 | + |
| 50 | + const session = await stripe.checkout.sessions.create({ |
| 51 | + mode: 'setup', |
| 52 | + customer: customerId, |
| 53 | + currency: price.currency, |
| 54 | + success_url: successUrl, |
| 55 | + cancel_url: cancelUrl, |
| 56 | + metadata: { |
| 57 | + organizationId, |
| 58 | + source: 'comp-background-check', |
| 59 | + }, |
| 60 | + }); |
| 61 | + |
| 62 | + if (!session.url) { |
| 63 | + throw new BadRequestException('Failed to create Stripe Checkout session.'); |
| 64 | + } |
| 65 | + |
| 66 | + return { url: session.url }; |
| 67 | + } |
| 68 | + |
| 69 | + async handleSetupSuccess({ |
| 70 | + organizationId, |
| 71 | + sessionId, |
| 72 | + }: { |
| 73 | + organizationId: string; |
| 74 | + sessionId: string; |
| 75 | + }): Promise<{ success: true }> { |
| 76 | + const stripe = this.stripeService.getClient(); |
| 77 | + const session = await stripe.checkout.sessions.retrieve(sessionId, { |
| 78 | + expand: ['setup_intent'], |
| 79 | + }); |
| 80 | + |
| 81 | + if (session.status !== 'complete') { |
| 82 | + throw new BadRequestException('Checkout session is not complete.'); |
| 83 | + } |
| 84 | + |
| 85 | + if (session.metadata?.organizationId && session.metadata.organizationId !== organizationId) { |
| 86 | + throw new BadRequestException('Checkout session does not belong to this organization.'); |
| 87 | + } |
| 88 | + |
| 89 | + const stripeCustomerId = this.extractStripeId(session.customer); |
| 90 | + if (!stripeCustomerId) { |
| 91 | + throw new BadRequestException('Checkout session is missing a customer.'); |
| 92 | + } |
| 93 | + |
| 94 | + await this.assertCustomerBelongsToOrganization({ |
| 95 | + organizationId, |
| 96 | + stripeCustomerId, |
| 97 | + }); |
| 98 | + |
| 99 | + const setupIntent = session.setup_intent; |
| 100 | + if (!setupIntent || typeof setupIntent === 'string') { |
| 101 | + throw new BadRequestException('Checkout session is missing a setup intent.'); |
| 102 | + } |
| 103 | + |
| 104 | + const paymentMethodId = this.extractStripeId(setupIntent.payment_method); |
| 105 | + if (!paymentMethodId) { |
| 106 | + throw new BadRequestException('Setup intent is missing a payment method.'); |
| 107 | + } |
| 108 | + |
| 109 | + await stripe.customers.update(stripeCustomerId, { |
| 110 | + invoice_settings: { |
| 111 | + default_payment_method: paymentMethodId, |
| 112 | + }, |
| 113 | + }); |
| 114 | + |
| 115 | + await db.organizationBilling.upsert({ |
| 116 | + where: { organizationId }, |
| 117 | + create: { |
| 118 | + organizationId, |
| 119 | + stripeCustomerId, |
| 120 | + stripeBackgroundCheckPaymentMethodId: paymentMethodId, |
| 121 | + backgroundCheckPaymentMethodSetupAt: new Date(), |
| 122 | + }, |
| 123 | + update: { |
| 124 | + stripeCustomerId, |
| 125 | + stripeBackgroundCheckPaymentMethodId: paymentMethodId, |
| 126 | + backgroundCheckPaymentMethodSetupAt: new Date(), |
| 127 | + }, |
| 128 | + }); |
| 129 | + |
| 130 | + return { success: true }; |
| 131 | + } |
| 132 | + |
| 133 | + async createBillingPortalSession({ |
| 134 | + organizationId, |
| 135 | + returnUrl, |
| 136 | + }: { |
| 137 | + organizationId: string; |
| 138 | + returnUrl: string; |
| 139 | + }): Promise<{ url: string }> { |
| 140 | + this.validateRedirectUrl(returnUrl); |
| 141 | + |
| 142 | + const stripe = this.stripeService.getClient(); |
| 143 | + const billing = await db.organizationBilling.findUnique({ |
| 144 | + where: { organizationId }, |
| 145 | + select: { stripeCustomerId: true }, |
| 146 | + }); |
| 147 | + |
| 148 | + if (!billing) { |
| 149 | + throw new NotFoundException('No billing record found for this organization.'); |
| 150 | + } |
| 151 | + |
| 152 | + const portalSession = await stripe.billingPortal.sessions.create({ |
| 153 | + customer: billing.stripeCustomerId, |
| 154 | + return_url: returnUrl, |
| 155 | + }); |
| 156 | + |
| 157 | + return { url: portalSession.url }; |
| 158 | + } |
| 159 | + |
| 160 | + async findOrCreateCustomer(organizationId: string): Promise<string> { |
| 161 | + const existingBilling = await db.organizationBilling.findUnique({ |
| 162 | + where: { organizationId }, |
| 163 | + select: { stripeCustomerId: true }, |
| 164 | + }); |
| 165 | + |
| 166 | + if (existingBilling) { |
| 167 | + return existingBilling.stripeCustomerId; |
| 168 | + } |
| 169 | + |
| 170 | + const organization = await db.organization.findUnique({ |
| 171 | + where: { id: organizationId }, |
| 172 | + select: { name: true }, |
| 173 | + }); |
| 174 | + |
| 175 | + if (!organization) { |
| 176 | + throw new NotFoundException('Organization not found.'); |
| 177 | + } |
| 178 | + |
| 179 | + const stripe = this.stripeService.getClient(); |
| 180 | + const customer = await stripe.customers.create({ |
| 181 | + name: organization.name, |
| 182 | + metadata: { organizationId }, |
| 183 | + }); |
| 184 | + |
| 185 | + await db.organizationBilling.create({ |
| 186 | + data: { |
| 187 | + organizationId, |
| 188 | + stripeCustomerId: customer.id, |
| 189 | + }, |
| 190 | + }); |
| 191 | + |
| 192 | + return customer.id; |
| 193 | + } |
| 194 | + |
| 195 | + async getBackgroundCheckPrice(): Promise<{ id: string; unitAmount: number; currency: string }> { |
| 196 | + const priceId = process.env.STRIPE_BACKGROUND_CHECK_PRICE_ID; |
| 197 | + if (!priceId) { |
| 198 | + throw new BadRequestException('Background check pricing is not configured. Contact support.'); |
| 199 | + } |
| 200 | + |
| 201 | + const stripe = this.stripeService.getClient(); |
| 202 | + const price = await stripe.prices.retrieve(priceId); |
| 203 | + if (price.unit_amount === null || price.unit_amount === undefined) { |
| 204 | + throw new BadRequestException('Background check pricing is not configured. Contact support.'); |
| 205 | + } |
| 206 | + |
| 207 | + return { |
| 208 | + id: price.id, |
| 209 | + unitAmount: price.unit_amount, |
| 210 | + currency: price.currency, |
| 211 | + }; |
| 212 | + } |
| 213 | + |
| 214 | + private validateRedirectUrl(url: string): void { |
| 215 | + const appUrl = |
| 216 | + process.env.NEXT_PUBLIC_APP_URL || process.env.APP_URL || process.env.BETTER_AUTH_URL; |
| 217 | + if (!appUrl) { |
| 218 | + throw new BadRequestException('App URL is not configured on the server.'); |
| 219 | + } |
| 220 | + |
| 221 | + let parsed: URL; |
| 222 | + try { |
| 223 | + parsed = new URL(url); |
| 224 | + } catch { |
| 225 | + throw new BadRequestException('Invalid redirect URL.'); |
| 226 | + } |
| 227 | + |
| 228 | + if (parsed.origin !== new URL(appUrl).origin) { |
| 229 | + throw new BadRequestException('Redirect URL must belong to the application origin.'); |
| 230 | + } |
| 231 | + } |
| 232 | + |
| 233 | + private extractStripeId(value: string | { id?: string } | null): string | null { |
| 234 | + if (!value) return null; |
| 235 | + if (typeof value === 'string') return value; |
| 236 | + return value.id ?? null; |
| 237 | + } |
| 238 | + |
| 239 | + private async assertCustomerBelongsToOrganization({ |
| 240 | + organizationId, |
| 241 | + stripeCustomerId, |
| 242 | + }: { |
| 243 | + organizationId: string; |
| 244 | + stripeCustomerId: string; |
| 245 | + }): Promise<void> { |
| 246 | + const billing = await db.organizationBilling.findUnique({ |
| 247 | + where: { organizationId }, |
| 248 | + select: { stripeCustomerId: true }, |
| 249 | + }); |
| 250 | + |
| 251 | + if (billing?.stripeCustomerId === stripeCustomerId) { |
| 252 | + return; |
| 253 | + } |
| 254 | + |
| 255 | + const stripe = this.stripeService.getClient(); |
| 256 | + const customer = await stripe.customers.retrieve(stripeCustomerId); |
| 257 | + if (customer.deleted || customer.metadata?.organizationId !== organizationId) { |
| 258 | + throw new BadRequestException('Checkout session does not belong to this organization.'); |
| 259 | + } |
| 260 | + } |
| 261 | +} |
0 commit comments