|
| 1 | +import { AnalyticsEvent } from '@codebuff/common/constants/analytics-events' |
| 2 | +import db from '@codebuff/internal/db' |
| 3 | +import * as schema from '@codebuff/internal/db/schema' |
| 4 | +import { and, eq, isNull } from 'drizzle-orm' |
| 5 | +import { NextResponse } from 'next/server' |
| 6 | +import { z } from 'zod' |
| 7 | + |
| 8 | +import { requireUserFromApiKey } from '../../_helpers' |
| 9 | + |
| 10 | +import type { TrackEventFn } from '@codebuff/common/types/contracts/analytics' |
| 11 | +import type { GetUserInfoFromApiKeyFn } from '@codebuff/common/types/contracts/database' |
| 12 | +import type { |
| 13 | + Logger, |
| 14 | + LoggerWithContextFn, |
| 15 | +} from '@codebuff/common/types/contracts/logger' |
| 16 | +import type { NextRequest } from 'next/server' |
| 17 | + |
| 18 | +const bodySchema = z.object({ |
| 19 | + impUrl: z.url(), |
| 20 | + surface: z.enum(['chat', 'waiting_room']).optional(), |
| 21 | +}) |
| 22 | + |
| 23 | +export async function postAdClick(params: { |
| 24 | + req: NextRequest |
| 25 | + getUserInfoFromApiKey: GetUserInfoFromApiKeyFn |
| 26 | + logger: Logger |
| 27 | + loggerWithContext: LoggerWithContextFn |
| 28 | + trackEvent: TrackEventFn |
| 29 | +}) { |
| 30 | + const { req, getUserInfoFromApiKey, loggerWithContext, trackEvent } = params |
| 31 | + const baseLogger = params.logger |
| 32 | + |
| 33 | + let impUrl: string |
| 34 | + let surface: z.infer<typeof bodySchema>['surface'] |
| 35 | + try { |
| 36 | + const json = await req.json() |
| 37 | + const parsed = bodySchema.safeParse(json) |
| 38 | + if (!parsed.success) { |
| 39 | + return NextResponse.json( |
| 40 | + { error: 'Invalid request body', details: parsed.error.format() }, |
| 41 | + { status: 400 }, |
| 42 | + ) |
| 43 | + } |
| 44 | + impUrl = parsed.data.impUrl |
| 45 | + surface = parsed.data.surface |
| 46 | + } catch { |
| 47 | + return NextResponse.json( |
| 48 | + { error: 'Invalid JSON in request body' }, |
| 49 | + { status: 400 }, |
| 50 | + ) |
| 51 | + } |
| 52 | + |
| 53 | + const authed = await requireUserFromApiKey({ |
| 54 | + req, |
| 55 | + getUserInfoFromApiKey, |
| 56 | + logger: baseLogger, |
| 57 | + loggerWithContext, |
| 58 | + trackEvent, |
| 59 | + authErrorEvent: AnalyticsEvent.ADS_API_AUTH_ERROR, |
| 60 | + }) |
| 61 | + if (!authed.ok) return authed.response |
| 62 | + |
| 63 | + const { userId, logger } = authed.data |
| 64 | + |
| 65 | + const adRecord = await db.query.adImpression.findFirst({ |
| 66 | + where: eq(schema.adImpression.imp_url, impUrl), |
| 67 | + }) |
| 68 | + |
| 69 | + if (!adRecord || adRecord.user_id !== userId) { |
| 70 | + logger.warn( |
| 71 | + { |
| 72 | + userId, |
| 73 | + adUserId: adRecord?.user_id, |
| 74 | + impUrl, |
| 75 | + }, |
| 76 | + '[ads] Ad click not found for user', |
| 77 | + ) |
| 78 | + return NextResponse.json( |
| 79 | + { success: false, error: 'Ad not found' }, |
| 80 | + { status: 404 }, |
| 81 | + ) |
| 82 | + } |
| 83 | + |
| 84 | + trackEvent({ |
| 85 | + event: AnalyticsEvent.ADS_CLICKED, |
| 86 | + userId, |
| 87 | + properties: { |
| 88 | + ad_impression_id: adRecord.id, |
| 89 | + provider: adRecord.provider, |
| 90 | + title: adRecord.title, |
| 91 | + cta: adRecord.cta, |
| 92 | + ad_url: adRecord.url, |
| 93 | + already_clicked: Boolean(adRecord.clicked_at), |
| 94 | + impression_recorded: Boolean(adRecord.impression_fired_at), |
| 95 | + surface, |
| 96 | + }, |
| 97 | + logger, |
| 98 | + }) |
| 99 | + |
| 100 | + try { |
| 101 | + await db |
| 102 | + .update(schema.adImpression) |
| 103 | + .set({ clicked_at: new Date() }) |
| 104 | + .where( |
| 105 | + and( |
| 106 | + eq(schema.adImpression.id, adRecord.id), |
| 107 | + isNull(schema.adImpression.clicked_at), |
| 108 | + ), |
| 109 | + ) |
| 110 | + } catch (error) { |
| 111 | + logger.error( |
| 112 | + { |
| 113 | + userId, |
| 114 | + impUrl, |
| 115 | + error: |
| 116 | + error instanceof Error |
| 117 | + ? { name: error.name, message: error.message } |
| 118 | + : error, |
| 119 | + }, |
| 120 | + '[ads] Failed to update ad click record', |
| 121 | + ) |
| 122 | + } |
| 123 | + |
| 124 | + return NextResponse.json({ success: true }) |
| 125 | +} |
0 commit comments