Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,8 @@ APPLE_CLIENT_ID=
NEXT_PUBLIC_POSTHOG_KEY=
NEXT_PUBLIC_POSTHOG_HOST=https://app.posthog.com
GA_MEASUREMENT_ID=
OPENAI_ADS_PIXEL_ID=
OPENAI_ADS_CONVERSIONS_API_KEY=

# Optional runtime branding
COMPANY_NAME=Knowhere AI
Expand Down
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,8 @@ Optional:
| --- | --- |
| `NEXT_PUBLIC_POSTHOG_KEY`, `NEXT_PUBLIC_POSTHOG_HOST` | PostHog analytics. |
| `GA_MEASUREMENT_ID` | Google Analytics measurement ID. |
| `OPENAI_ADS_PIXEL_ID` | OpenAI Ads Measurement Pixel ID. Set to `JDvSf6KLL8Y3e8QJhCmFF3` for the current pixel. |
| `OPENAI_ADS_CONVERSIONS_API_KEY` | Optional OpenAI Ads Conversions API key for server-side conversion delivery. |
| `BILLING_ENABLED` | Set to `true` only when the API billing endpoints and payment configuration are available. Defaults to disabled for open-source self-hosted deployments. |
| `PASSWORD_LOGIN_ENABLED` | Set to `true` to show the login page's password-login button. Defaults to hidden. |
| `AUTH_COOKIE_DOMAIN` | Optional Better Auth parent cookie domain for cross-subdomain sessions. Leave unset for host-only cookies. |
Expand Down
2 changes: 1 addition & 1 deletion app/(dashboard)/billing/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import { Button } from "@components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@components/ui/card";
import { Skeleton } from "@components/ui/skeleton";
import { useCredits } from "@hooks/use-credits";
import { trackPaymentRedirectFromSearchParams } from "@lib/posthog-checkout";
import { trackPaymentRedirectFromSearchParams } from "@lib/analytics/payment-redirect";
import type { Subscription } from "@server/external-api/subscriptions";
import { CheckCircle2, CreditCard, XCircle } from "lucide-react";
import Link from "next/link";
Expand Down
8 changes: 6 additions & 2 deletions app/(landing)/_components/hero-playground.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import {
trackLandingInteraction,
} from "@app/(landing)/_components/landing-tracked-link";
import { Dialog, DialogContent, DialogTitle } from "@components/ui/dialog";
import { mirrorPlaygroundParseStarted } from "@lib/google-analytics";
import { trackAnalyticsEvent } from "@lib/analytics";
import { cn } from "@lib/utils";
import * as ScrollAreaPrimitive from "@radix-ui/react-scroll-area";
import {
Expand Down Expand Up @@ -1663,7 +1663,11 @@ export const HeroPlayground = () => {
file_name: sample.cardLabel,
sample_id: sampleId,
});
mirrorPlaygroundParseStarted(sample.cardLabel);
trackAnalyticsEvent({
fileName: sample.cardLabel,
name: "playground.parse_started",
timestamp: new Date().toISOString(),
});

setActiveSampleId(sampleId);
setParsedSampleId(sampleId);
Expand Down
39 changes: 39 additions & 0 deletions app/api/acquisition-attribution/bind/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import { ACQUISITION_ATTRIBUTION_COOKIE_NAME } from "@lib/acquisition-attribution/core";
import { auth } from "@lib/auth";
import { bindAcquisitionSessionToUser } from "@server/acquisition-attribution";
import { cookies } from "next/headers";
import { NextResponse } from "next/server";
import { z } from "zod";

const bindRequestSchema = z.object({
userId: z.string().min(1),
});

export async function POST(request: Request): Promise<Response> {
const sessionData = await auth.api.getSession({ headers: request.headers });
if (!sessionData?.user?.id) {
return NextResponse.json({ message: "Authentication required" }, { status: 401 });
}

const requestBody = await request.json().catch(() => null);
const parsedRequest = bindRequestSchema.safeParse(requestBody);
if (!parsedRequest.success) {
return NextResponse.json({ message: "Invalid acquisition bind payload" }, { status: 400 });
}

if (parsedRequest.data.userId !== sessionData.user.id) {
return NextResponse.json(
{ message: "Cannot bind attribution to another user" },
{ status: 403 }
);
}

const cookieStore = await cookies();
const sessionId = cookieStore.get(ACQUISITION_ATTRIBUTION_COOKIE_NAME)?.value ?? null;
const result = await bindAcquisitionSessionToUser({
sessionId,
userId: sessionData.user.id,
});

return NextResponse.json(result);
}
43 changes: 43 additions & 0 deletions app/api/acquisition-attribution/session/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import {
ACQUISITION_ATTRIBUTION_COOKIE_NAME,
ACQUISITION_ATTRIBUTION_TTL_SECONDS,
} from "@lib/acquisition-attribution/core";
import { captureAcquisitionSession } from "@server/acquisition-attribution";
import { cookies } from "next/headers";
import { NextResponse } from "next/server";
import { z } from "zod";

const captureRequestSchema = z.object({
landingUrl: z.url(),
referrer: z.string().optional(),
});

export async function POST(request: Request): Promise<Response> {
const requestBody = await request.json().catch(() => null);
const parsedRequest = captureRequestSchema.safeParse(requestBody);

if (!parsedRequest.success) {
return NextResponse.json({ message: "Invalid acquisition payload" }, { status: 400 });
}

const cookieStore = await cookies();
const existingSessionId = cookieStore.get(ACQUISITION_ATTRIBUTION_COOKIE_NAME)?.value ?? null;
const result = await captureAcquisitionSession({
existingSessionId,
landingUrl: parsedRequest.data.landingUrl,
referrer: parsedRequest.data.referrer,
});
const response = NextResponse.json(result);

if (result.sessionId) {
response.cookies.set(ACQUISITION_ATTRIBUTION_COOKIE_NAME, result.sessionId, {
httpOnly: true,
maxAge: ACQUISITION_ATTRIBUTION_TTL_SECONDS,
path: "/",
sameSite: "lax",
secure: new URL(request.url).protocol === "https:",
});
}

return response;
}
59 changes: 59 additions & 0 deletions app/api/openai-ads/conversions/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
import { sendOpenAIAdsConversionEvent } from "@server/openai-ads-conversions";
import { NextResponse } from "next/server";
import { z } from "zod";

const openAIAdsEventNameSchema = z.enum([
"checkout_started",
"lead_created",
"order_created",
"registration_completed",
"subscription_created",
]);

const openAIAdsConversionDataSchema = z.discriminatedUnion("type", [
z
.object({
type: z.literal("customer_action"),
})
.strict(),
z
.object({
amount: z.number().int().nonnegative().optional(),
currency: z.literal("USD").optional(),
type: z.literal("contents"),
})
.strict(),
z
.object({
amount: z.number().int().nonnegative().optional(),
currency: z.literal("USD").optional(),
plan_id: z.string().min(1).optional(),
type: z.literal("plan_enrollment"),
})
.strict(),
]);

const openAIAdsConversionRequestSchema = z.object({
data: openAIAdsConversionDataSchema,
eventId: z.string().min(1),
eventName: openAIAdsEventNameSchema,
sourceUrl: z.url().optional(),
timestamp: z.iso.datetime(),
});

export async function POST(request: Request): Promise<Response> {
const requestBody = await request.json().catch(() => null);
const parsedRequest = openAIAdsConversionRequestSchema.safeParse(requestBody);

if (!parsedRequest.success) {
return NextResponse.json({ message: "Invalid OpenAI Ads conversion payload" }, { status: 400 });
}

try {
const result = await sendOpenAIAdsConversionEvent(parsedRequest.data);
return NextResponse.json(result, { status: 202 });
} catch (error: unknown) {
console.error("[openai-ads] failed to send conversion event", error);
return NextResponse.json({ message: "OpenAI Ads conversion delivery failed" }, { status: 502 });
}
}
35 changes: 25 additions & 10 deletions app/layout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,8 @@ import "./globals.css";
import { ThemeProvider } from "@components/theme-provider";
import { appMetadata } from "@lib/app-metadata";
import { getDefaultConfig } from "@lib/config";
import { AnalyticsProvider } from "@providers/analytics-provider";
import { ConfigProvider } from "@providers/config-provider";
import { GoogleAnalyticsProvider } from "@providers/google-analytics-provider";
import PostHogProvider from "@providers/posthog-provider";
import { Providers } from "@providers/providers";
import { NextIntlClientProvider } from "next-intl";
import { getMessages } from "next-intl/server";
Expand Down Expand Up @@ -36,23 +35,22 @@ export default async function RootLayout({ children }: { children: React.ReactNo
// 在服务端读取环境变量(运行时配置,不带NEXT_PUBLIC_前缀)
const appConfig = getDefaultConfig();
const gaMeasurementId = appConfig.gaMeasurementId;
const openAIAdsPixelId = appConfig.openAIAdsPixelId;

// 获取翻译消息
const messages = await getMessages();

return (
<html lang={locale} suppressHydrationWarning>
<body className={"font-sans antialiased"}>
<body className={`${geistSans.variable} ${anuphan.variable} font-sans antialiased`}>
<NextIntlClientProvider messages={messages} locale={locale}>
<ConfigProvider config={appConfig}>
<ThemeProvider attribute="class" enableSystem={true} disableTransitionOnChange>
<GoogleAnalyticsProvider>
<PostHogProvider>
<Providers>
<div className="min-h-dvh">{children}</div>
</Providers>
</PostHogProvider>
</GoogleAnalyticsProvider>
<AnalyticsProvider>
<Providers>
<div className="min-h-dvh">{children}</div>
</Providers>
</AnalyticsProvider>
</ThemeProvider>
</ConfigProvider>
</NextIntlClientProvider>
Expand All @@ -72,6 +70,23 @@ export default async function RootLayout({ children }: { children: React.ReactNo
</Script>
</>
) : null}
{openAIAdsPixelId ? (
<>
<Script id="openai-ads-pixel-init" strategy="afterInteractive">
{`
window.oaiq = window.oaiq || function () {
(window.oaiq.q = window.oaiq.q || []).push(arguments);
};
window.oaiq("init", { pixelId: ${JSON.stringify(openAIAdsPixelId)} });
`}
</Script>
<Script
async={true}
src="https://bzrcdn.openai.com/sdk/oaiq.min.js"
strategy="afterInteractive"
/>
</>
) : null}
</body>
</html>
);
Expand Down
21 changes: 21 additions & 0 deletions drizzle/0008_noisy_chimera.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
CREATE TABLE "marketing_attribution_sessions" (
"session_id" text PRIMARY KEY NOT NULL,
"source" text NOT NULL,
"channel" text NOT NULL,
"utm_source" text,
"utm_medium" text,
"utm_campaign" text,
"utm_content" text,
"utm_term" text,
"oppref" text,
"landing_path" text NOT NULL,
"referrer_host" text,
"captured_at" timestamp with time zone DEFAULT now() NOT NULL,
"bound_user_id" text,
"bound_at" timestamp with time zone
);
--> statement-breakpoint
ALTER TABLE "marketing_attribution_sessions" ADD CONSTRAINT "marketing_attribution_sessions_bound_user_id_user_id_fk" FOREIGN KEY ("bound_user_id") REFERENCES "public"."user"("id") ON DELETE set null ON UPDATE no action;--> statement-breakpoint
CREATE INDEX "marketingAttributionSession_boundUserId_idx" ON "marketing_attribution_sessions" USING btree ("bound_user_id");--> statement-breakpoint
CREATE INDEX "marketingAttributionSession_capturedAt_idx" ON "marketing_attribution_sessions" USING btree ("captured_at");--> statement-breakpoint
CREATE INDEX "marketingAttributionSession_sourceCampaign_idx" ON "marketing_attribution_sessions" USING btree ("source","utm_campaign");
Loading
Loading