Skip to content

armgit / dub

Public Imported from GitHub
0

The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.

add support for embed data

Steven Teyb34b071153cf
diff --git a/apps/web/app/api/analytics/client/route.ts b/apps/web/app/api/analytics/client/route.ts
deleted file mode 100644
index 4a75223ff6..0000000000
--- a/apps/web/app/api/analytics/client/route.ts
+++ /dev/null
@@ -1,50 +0,0 @@
-import { getAnalytics } from "@/lib/analytics/get-analytics";
-import { calculateEarnings } from "@/lib/api/sales/calculate-earnings";
-import { withEmbedToken } from "@/lib/embed/auth";
-import { analyticsQuerySchema } from "@/lib/zod/schemas/analytics";
-import { NextResponse } from "next/server";
-
-// GET /api/analytics/client - get analytics for the current link
-export const GET = withEmbedToken(async ({ link, searchParams, program }) => {
- const parsedParams = analyticsQuerySchema
- .pick({
- event: true,
- start: true,
- end: true,
- interval: true,
- groupBy: true,
- timezone: true,
- })
- .parse(searchParams);
-
- const response = await getAnalytics({
- ...parsedParams,
- linkId: link.id,
- });
-
- let data;
-
- if (response instanceof Array) {
- data = response.map((item) => {
- return {
- ...item,
- earnings: calculateEarnings({
- program,
- sales: item.sales ?? 0,
- saleAmount: item.saleAmount ?? 0,
- }),
- };
- });
- } else {
- data = {
- ...response,
- earnings: calculateEarnings({
- program,
- sales: response.sales,
- saleAmount: response.saleAmount,
- }),
- };
- }
-
- return NextResponse.json(data);
-});
diff --git a/apps/web/app/api/embed/analytics/route.ts b/apps/web/app/api/embed/analytics/route.ts
index c134280e18..a41bb5f6d7 100644
--- a/apps/web/app/api/embed/analytics/route.ts
+++ b/apps/web/app/api/embed/analytics/route.ts
@@ -3,12 +3,13 @@ import { withEmbedToken } from "@/lib/embed/auth";
import { NextResponse } from "next/server";
// GET /api/embed/analytics – get timeseries analytics for a link from an embed token
-export const GET = withEmbedToken(async ({ link }) => {
+export const GET = withEmbedToken(async ({ programId, tenantId }) => {
const analytics = await getAnalytics({
event: "composite",
groupBy: "timeseries",
- linkId: link.id,
interval: "1y",
+ programId,
+ tenantId,
});
return NextResponse.json(analytics);
diff --git a/apps/web/app/api/embed/sales/route.ts b/apps/web/app/api/embed/sales/route.ts
index 7ea7b25dd9..fc1b17614a 100644
--- a/apps/web/app/api/embed/sales/route.ts
+++ b/apps/web/app/api/embed/sales/route.ts
@@ -6,36 +6,39 @@ import { prisma } from "@dub/prisma";
import { NextResponse } from "next/server";
// GET /api/embed/sales – get sales for a link from an embed token
-export const GET = withEmbedToken(async ({ link, searchParams }) => {
- const { page } = z
- .object({ page: z.coerce.number().optional().default(1) })
- .parse(searchParams);
+export const GET = withEmbedToken(
+ async ({ programId, partnerId, searchParams }) => {
+ const { page } = z
+ .object({ page: z.coerce.number().optional().default(1) })
+ .parse(searchParams);
- const sales = await prisma.sale.findMany({
- where: {
- linkId: link.id,
- },
- select: {
- id: true,
- amount: true,
- earnings: true,
- currency: true,
- status: true,
- createdAt: true,
- updatedAt: true,
- customer: {
- select: {
- email: true,
- avatar: true,
+ const sales = await prisma.sale.findMany({
+ where: {
+ programId,
+ partnerId,
+ },
+ select: {
+ id: true,
+ amount: true,
+ earnings: true,
+ currency: true,
+ status: true,
+ createdAt: true,
+ updatedAt: true,
+ customer: {
+ select: {
+ email: true,
+ avatar: true,
+ },
},
},
- },
- take: SALES_PAGE_SIZE,
- skip: (page - 1) * SALES_PAGE_SIZE,
- orderBy: {
- createdAt: "desc",
- },
- });
+ take: SALES_PAGE_SIZE,
+ skip: (page - 1) * SALES_PAGE_SIZE,
+ orderBy: {
+ createdAt: "desc",
+ },
+ });
- return NextResponse.json(z.array(PartnerSaleResponseSchema).parse(sales));
-});
+ return NextResponse.json(z.array(PartnerSaleResponseSchema).parse(sales));
+ },
+);
diff --git a/apps/web/app/api/embed/token/route.ts b/apps/web/app/api/embed/token/route.ts
index cabd97f5f6..149e7bff87 100644
--- a/apps/web/app/api/embed/token/route.ts
+++ b/apps/web/app/api/embed/token/route.ts
@@ -2,6 +2,6 @@ import { withEmbedToken } from "@/lib/embed/auth";
import { NextResponse } from "next/server";
// GET /api/embed/token - get the embed token for the given link
-export const GET = withEmbedToken(async ({ linkToken }) => {
- return NextResponse.json(linkToken);
+export const GET = withEmbedToken(async ({ embedToken }) => {
+ return NextResponse.json(embedToken);
});
diff --git a/apps/web/app/api/events/client/route.ts b/apps/web/app/api/events/client/route.ts
deleted file mode 100644
index 3c54b57b35..0000000000
--- a/apps/web/app/api/events/client/route.ts
+++ /dev/null
@@ -1,42 +0,0 @@
-import { getEvents } from "@/lib/analytics/get-events";
-import { calculateEarnings } from "@/lib/api/sales/calculate-earnings";
-import { withEmbedToken } from "@/lib/embed/auth";
-import { eventsQuerySchema } from "@/lib/zod/schemas/analytics";
-import { NextResponse } from "next/server";
-
-// GET /api/events/client - get events for the current link
-export const GET = withEmbedToken(async ({ searchParams, program, link }) => {
- const parsedParams = eventsQuerySchema
- .omit({
- linkId: true,
- externalId: true,
- domain: true,
- root: true,
- key: true,
- tagId: true,
- })
- .parse(searchParams);
-
- // TODO:
- // Replace with sales data
-
- const response = await getEvents({
- ...parsedParams,
- linkId: link.id,
- });
-
- return NextResponse.json(
- response.map((item: any) => {
- return {
- ...item,
- ...(parsedParams.event === "sales" && {
- earnings: calculateEarnings({
- program,
- sales: item.sales ?? 0,
- saleAmount: item.sale?.amount ?? 0,
- }),
- }),
- };
- }),
- );
-});
diff --git a/apps/web/app/api/tokens/embed/route.ts b/apps/web/app/api/tokens/embed/route.ts
index ec44dc422b..04aeb591b4 100644
--- a/apps/web/app/api/tokens/embed/route.ts
+++ b/apps/web/app/api/tokens/embed/route.ts
@@ -1,4 +1,4 @@
-import { getLinkOrThrow } from "@/lib/api/links/get-link-or-throw";
+import { DubApiError } from "@/lib/api/errors";
import { parseRequestBody } from "@/lib/api/utils";
import { withWorkspace } from "@/lib/auth";
import { embedToken } from "@/lib/embed/embed-token";
@@ -6,18 +6,42 @@ import {
createEmbedTokenSchema,
EmbedTokenSchema,
} from "@/lib/zod/schemas/token";
+import { prisma } from "@dub/prisma";
import { NextResponse } from "next/server";
// POST /api/tokens/embed - create a new embed token for the given link
export const POST = withWorkspace(
async ({ workspace, req }) => {
- const { linkId } = createEmbedTokenSchema.parse(
+ const { programId, tenantId } = createEmbedTokenSchema.parse(
await parseRequestBody(req),
);
- await getLinkOrThrow({ linkId, workspaceId: workspace.id });
+ const programEnrollment = await prisma.programEnrollment.findUnique({
+ where: {
+ tenantId_programId: {
+ tenantId,
+ programId,
+ },
+ },
+ include: {
+ program: true,
+ },
+ });
+
+ if (
+ !programEnrollment ||
+ programEnrollment.program.workspaceId !== workspace.id
+ ) {
+ throw new DubApiError({
+ message: `Tenant ${tenantId} not enrolled in this workspace's program ${programId}.`,
+ code: "not_found",
+ });
+ }
- const response = await embedToken.create(linkId);
+ const response = await embedToken.create({
+ tenantId,
+ programId,
+ });
return NextResponse.json(EmbedTokenSchema.parse(response), {
status: 201,
diff --git a/apps/web/app/api/user/embed-tokens/route.ts b/apps/web/app/api/user/embed-tokens/route.ts
index 543777d57c..c17980bdbc 100644
--- a/apps/web/app/api/user/embed-tokens/route.ts
+++ b/apps/web/app/api/user/embed-tokens/route.ts
@@ -1,17 +1,23 @@
import { withSession } from "@/lib/auth";
-import { dub } from "@/lib/dub";
+import { API_DOMAIN } from "@dub/utils";
import { NextResponse } from "next/server";
export const GET = withSession(async ({ session }) => {
- const referralLinkId = session.user.referralLinkId;
+ // const { publicToken } = await dub.embedTokens.create({
+ // tenantId: session.user.id,
+ // });
- if (!referralLinkId) {
- return NextResponse.json({ publicToken: null }, { status: 200 });
- }
-
- const { publicToken } = await dub.embedTokens.create({
- linkId: referralLinkId,
- });
+ const { publicToken } = await fetch(`${API_DOMAIN}/tokens/embed`, {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ Authorization: `Bearer ${process.env.DUB_API_KEY}`,
+ },
+ body: JSON.stringify({
+ programId: "prog_d8pl69xXCv4AoHNT281pHQdo",
+ tenantId: session.user.id,
+ }),
+ }).then((res) => res.json());
return NextResponse.json({ publicToken });
});
diff --git a/apps/web/app/app.dub.co/embed/inline/page-client.tsx b/apps/web/app/app.dub.co/embed/inline/page-client.tsx
index 01319d6d7c..7b48265503 100644
--- a/apps/web/app/app.dub.co/embed/inline/page-client.tsx
+++ b/apps/web/app/app.dub.co/embed/inline/page-client.tsx
@@ -26,17 +26,23 @@ import { EmbedSales } from "./sales";
export function EmbedInlinePageClient({
program,
- link,
+ links,
discount,
payouts,
+ stats,
}: {
program: Program;
- link: Link;
+ links: Link[];
discount?: DiscountProps | null;
payouts: {
status: PayoutStatus;
amount: number;
}[];
+ stats: {
+ clicks: number;
+ leads: number;
+ sales: number;
+ };
}) {
const [copied, copyToClipboard] = useCopyToClipboard();
@@ -70,7 +76,7 @@ export function EmbedInlinePageClient({
<input
type="text"
readOnly
- value={getPrettyUrl(link.shortLink)}
+ value={getPrettyUrl(links[0].shortLink)}
className="xs:w-auto h-10 w-full rounded-md border border-neutral-300 px-3 text-sm focus:border-neutral-500 focus:outline-none focus:ring-neutral-500 lg:min-w-64 xl:min-w-72"
/>
<Button
@@ -96,7 +102,7 @@ export function EmbedInlinePageClient({
}
text={copied ? "Copied link" : "Copy link"}
className="xs:w-fit"
- onClick={() => copyToClipboard(link.shortLink)}
+ onClick={() => copyToClipboard(links[0].shortLink)}
/>
</div>
<a
@@ -110,9 +116,9 @@ export function EmbedInlinePageClient({
</div>
<div className="mt-4 grid gap-2 sm:h-32 sm:grid-cols-3">
<EmbedActivity
- clicks={link.clicks}
- leads={link.leads}
- sales={link.sales}
+ clicks={stats.clicks}
+ leads={stats.leads}
+ sales={stats.sales}
/>
<EmbedPayouts payouts={payouts} />
</div>
@@ -133,9 +139,9 @@ export function EmbedInlinePageClient({
<div className="my-4">
<AnimatePresence mode="wait">
{selectedTab === "Quickstart" ? (
- <EmbedQuickstart program={program} link={link} />
+ <EmbedQuickstart program={program} link={links[0]} />
) : selectedTab === "Sales" ? (
- <EmbedSales salesCount={link.sales} />
+ <EmbedSales salesCount={stats.sales} />
) : selectedTab === "Leaderboard" ? (
<EmbedLeaderboard />
) : selectedTab === "FAQ" ? (
diff --git a/apps/web/app/app.dub.co/embed/inline/page.tsx b/apps/web/app/app.dub.co/embed/inline/page.tsx
index d86924bb5f..ef5586e3d2 100644
--- a/apps/web/app/app.dub.co/embed/inline/page.tsx
+++ b/apps/web/app/app.dub.co/embed/inline/page.tsx
@@ -8,14 +8,7 @@ export default async function EmbedInlinePage({
}) {
const { token } = searchParams;
- const { link, program, discount, payouts } = await getEmbedData(token);
+ const embedData = await getEmbedData(token);
- return (
- <EmbedInlinePageClient
- program={program}
- link={link}
- discount={discount}
- payouts={payouts}
- />
- );
+ return <EmbedInlinePageClient {...embedData} />;
}
diff --git a/apps/web/app/app.dub.co/embed/utils.ts b/apps/web/app/app.dub.co/embed/utils.ts
index 2506be65fe..8d94dcb7a8 100644
--- a/apps/web/app/app.dub.co/embed/utils.ts
+++ b/apps/web/app/app.dub.co/embed/utils.ts
@@ -4,32 +4,31 @@ import { prisma } from "@dub/prisma";
import { notFound } from "next/navigation";
export const getEmbedData = async (token: string) => {
- const linkId = await embedToken.get(token);
+ const { programId, tenantId } = (await embedToken.get(token)) ?? {};
- if (!linkId) {
+ if (!programId || !tenantId) {
notFound();
}
- const referralLink = await prisma.link.findUnique({
+ const programEnrollment = await prisma.programEnrollment.findUniqueOrThrow({
where: {
- id: linkId,
+ tenantId_programId: {
+ tenantId,
+ programId,
+ },
},
include: {
+ links: true,
program: true,
- programEnrollment: {
- select: {
- partnerId: true,
- discount: true,
- },
- },
+ discount: true,
},
});
- if (!referralLink?.program || !referralLink?.programEnrollment) {
+ if (!programEnrollment) {
notFound();
}
- const { program, programEnrollment, ...link } = referralLink;
+ const { program, links } = programEnrollment;
const payouts = await prisma.payout.groupBy({
by: ["status"],
@@ -44,7 +43,7 @@ export const getEmbedData = async (token: string) => {
return {
program,
- link,
+ links,
discount: programEnrollment.discount
? DiscountSchema.parse(programEnrollment.discount)
: null,
@@ -52,5 +51,10 @@ export const getEmbedData = async (token: string) => {
status: payout.status,
amount: payout._sum.amount ?? 0,
})),
+ stats: {
+ clicks: links.reduce((acc, link) => acc + link.clicks, 0),
+ leads: links.reduce((acc, link) => acc + link.leads, 0),
+ sales: links.reduce((acc, link) => acc + link.sales, 0),
+ },
};
};
diff --git a/apps/web/lib/embed/auth.ts b/apps/web/lib/embed/auth.ts
index c2ac7b8831..e38b4ba59d 100644
--- a/apps/web/lib/embed/auth.ts
+++ b/apps/web/lib/embed/auth.ts
@@ -1,7 +1,7 @@
import { DubApiError, handleAndReturnErrorResponse } from "@/lib/api/errors";
import { ratelimit } from "@/lib/upstash";
import { prisma } from "@dub/prisma";
-import { Link, Program, Project } from "@dub/prisma/client";
+import { Link, Program } from "@dub/prisma/client";
import { getSearchParams } from "@dub/utils";
import { AxiomRequest, withAxiom } from "next-axiom";
import { cookies } from "next/headers";
@@ -13,18 +13,22 @@ interface WithEmbedTokenHandler {
req,
params,
searchParams,
- workspace,
- link,
program,
- linkToken,
+ programId,
+ partnerId,
+ tenantId,
+ links,
+ embedToken,
}: {
req: Request;
params: Record<string, string>;
searchParams: Record<string, string>;
- workspace: Project;
- link: Link;
program: Program;
- linkToken: string;
+ programId: string;
+ partnerId: string;
+ tenantId: string;
+ links: Link[];
+ embedToken: string;
}): Promise<Response>;
}
@@ -37,8 +41,6 @@ export const withEmbedToken = (handler: WithEmbedTokenHandler) => {
let headers = {};
try {
- let link: Link | undefined = undefined;
-
const rateLimit = 60;
const searchParams = getSearchParams(req.url);
@@ -54,12 +56,13 @@ export const withEmbedToken = (handler: WithEmbedTokenHandler) => {
});
}
- const linkId = await embedToken.get(tokenFromCookie);
+ const { programId, tenantId } =
+ (await embedToken.get(tokenFromCookie)) ?? {};
- if (!linkId) {
+ if (!programId || !tenantId) {
throw new DubApiError({
code: "unauthorized",
- message: "Link token not found or expired.",
+ message: "Invalid embed public token.",
});
}
@@ -82,41 +85,30 @@ export const withEmbedToken = (handler: WithEmbedTokenHandler) => {
});
}
- link = await prisma.link.findUniqueOrThrow({
- where: {
- id: linkId,
- },
- });
-
- if (!link.trackConversion) {
- throw new DubApiError({
- code: "forbidden",
- message: "Conversion tracking is not enabled for this link.",
- });
- }
-
- const [workspace, program] = await Promise.all([
- prisma.project.findUniqueOrThrow({
+ const programEnrollment =
+ await prisma.programEnrollment.findUniqueOrThrow({
where: {
- id: link.projectId!,
+ tenantId_programId: {
+ tenantId,
+ programId,
+ },
},
- }),
-
- prisma.program.findFirstOrThrow({
- where: {
- workspaceId: link.projectId!,
+ include: {
+ links: true,
+ program: true,
},
- }),
- ]);
+ });
return await handler({
req,
params,
searchParams,
- workspace,
- link,
- program,
- linkToken: tokenFromCookie,
+ program: programEnrollment.program,
+ programId,
+ partnerId: programEnrollment.partnerId,
+ tenantId,
+ links: programEnrollment.links,
+ embedToken: tokenFromCookie,
});
} catch (error) {
req.log.error(error);
diff --git a/apps/web/lib/embed/embed-token.ts b/apps/web/lib/embed/embed-token.ts
index c9cec0e2d1..b8dca27b2d 100644
--- a/apps/web/lib/embed/embed-token.ts
+++ b/apps/web/lib/embed/embed-token.ts
@@ -7,13 +7,19 @@ import {
} from "./constants";
class EmbedToken {
- async create(linkId: string) {
+ async create({
+ programId,
+ tenantId,
+ }: {
+ programId: string;
+ tenantId: string;
+ }) {
const publicToken = createId({
prefix: EMBED_PUBLIC_TOKEN_PREFIX,
length: EMBED_PUBLIC_TOKEN_LENGTH,
});
- await redis.set(publicToken, linkId, {
+ await redis.set(publicToken, JSON.stringify({ programId, tenantId }), {
ex: EMBED_PUBLIC_TOKEN_EXPIRY,
nx: true,
});
@@ -25,7 +31,7 @@ class EmbedToken {
}
async get(token: string) {
- return await redis.get<string>(token);
+ return await redis.get<{ programId: string; tenantId: string }>(token);
}
}
diff --git a/apps/web/lib/zod/schemas/token.ts b/apps/web/lib/zod/schemas/token.ts
index e2bf4459dd..c7208dee7f 100644
--- a/apps/web/lib/zod/schemas/token.ts
+++ b/apps/web/lib/zod/schemas/token.ts
@@ -42,7 +42,8 @@ export const tokenSchema = z.object({
});
export const createEmbedTokenSchema = z.object({
- linkId: z.string().min(1),
+ programId: z.string().min(1),
+ tenantId: z.string().min(1),
});
export const EmbedTokenSchema = z.object({
diff --git a/packages/embeds/core/src/constants.ts b/packages/embeds/core/src/constants.ts
index 4c948e1f76..796938da0d 100644
--- a/packages/embeds/core/src/constants.ts
+++ b/packages/embeds/core/src/constants.ts
@@ -1,2 +1,2 @@
-export const EMBED_URL = "https://app.dub.co/embed/inline";
+export const EMBED_URL = "http://localhost:8888/embed/inline";
export const DUB_CONTAINER_ID = "dub-embed-container";
diff --git a/packages/embeds/core/src/core.ts b/packages/embeds/core/src/core.ts
index 50c4297c02..492a248e7b 100644
--- a/packages/embeds/core/src/core.ts
+++ b/packages/embeds/core/src/core.ts
@@ -5,7 +5,7 @@ import { DubEmbedOptions, DubInitResult, IframeMessage } from "./types";
const CONTAINER_STYLES = {
position: "relative",
maxWidth: "1024px",
- height: "1000px",
+ height: "1020px",
margin: "0 auto",
};