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.

Refactor click payout processing and earnings tracking

Kiran K4f9e374aebf9
diff --git a/apps/web/app/api/cron/payouts/clicks/route.ts b/apps/web/app/api/cron/payouts/clicks/route.ts
index 056177b6d4..c1a0f8db6a 100644
--- a/apps/web/app/api/cron/payouts/clicks/route.ts
+++ b/apps/web/app/api/cron/payouts/clicks/route.ts
@@ -1,83 +1,168 @@
-import { getAnalytics } from "@/lib/analytics/get-analytics";
import { handleAndReturnErrorResponse } from "@/lib/api/errors";
+import { createId } from "@/lib/api/utils";
import { verifyVercelSignature } from "@/lib/cron/verify-vercel";
import { prisma } from "@dub/prisma";
-import { EventType, Prisma } from "@prisma/client";
+import { Payout } from "@dub/prisma/client";
import { NextResponse } from "next/server";
export const dynamic = "force-dynamic";
-/*
- This route is used aggregate clicks events on daily basis for Program links
- Runs once every day at 00:00 (0 0 * * *)
-*/
-
-// GET /cron/payouts/clicks
+// This route is used to calculate payouts for clicks.
+// Runs once every day at 00:00 (0 0 * * *)
+// GET /api/cron/payouts/clicks
export async function GET(req: Request) {
try {
await verifyVercelSignature(req);
- const links = await prisma.link.findMany({
+ let clicks = await prisma.earnings.groupBy({
+ by: ["programId", "partnerId"],
where: {
- programId: {
- not: null,
- },
- partnerId: {
- not: null,
- },
- clicks: {
- gt: 0,
- },
+ type: "click",
+ status: "pending",
+ payoutId: null,
},
- select: {
- id: true,
- programId: true,
- partnerId: true,
+ _sum: {
+ quantity: true,
},
- take: 10,
});
- if (!links.length) {
+ if (!clicks.length) {
return NextResponse.json({
- message: "No program links found. Skipping...",
+ message: "No pending clicks found. Skipping...",
});
}
- // Find the start of the today and end current time
- // TODO: Fix this
- const start = new Date();
- start.setHours(0, 0, 0, 0);
- const end = new Date();
-
- // TODO:
- // Use queue to process clicks
- const clicksData: Prisma.EarningsUncheckedCreateInput[] = await Promise.all(
- links.map(async ({ id: linkId, programId, partnerId }) => {
- const { clicks } = await getAnalytics({
- start,
- end,
- linkId,
- groupBy: "count",
- event: "clicks",
- });
-
- return {
- linkId,
- quantity: clicks,
- programId: programId!,
- partnerId: partnerId!,
- type: EventType.click,
- amount: 0,
- };
- }),
- );
+ for (const { programId, partnerId } of clicks) {
+ const payout = await createClickPayout({
+ programId,
+ partnerId,
+ });
- await prisma.earnings.createMany({
- data: clicksData,
- });
+ console.log({
+ programId,
+ payout,
+ });
+ }
- return NextResponse.json(clicksData);
+ return NextResponse.json({
+ message: "Clicks payout created.",
+ });
} catch (error) {
return handleAndReturnErrorResponse(error);
}
}
+
+const createClickPayout = async ({
+ programId,
+ partnerId,
+}: {
+ programId: string;
+ partnerId: string;
+}) => {
+ const earnings = await prisma.$transaction(async (tx) => {
+ const earnings = await tx.earnings.findMany({
+ where: {
+ programId,
+ partnerId,
+ payoutId: null,
+ type: "click",
+ status: "pending",
+ },
+ select: {
+ id: true,
+ createdAt: true,
+ earnings: true,
+ quantity: true,
+ },
+ orderBy: {
+ createdAt: "asc",
+ },
+ });
+
+ if (!earnings.length) {
+ return;
+ }
+
+ // earliest click date
+ const periodStart = earnings[0].createdAt;
+
+ // end of the month of the latest click
+ let periodEnd = earnings[earnings.length - 1].createdAt;
+ periodEnd = new Date(periodEnd.getFullYear(), periodEnd.getMonth() + 1);
+
+ const totalQuantity = earnings.reduce(
+ (total, click) => total + click.quantity,
+ 0,
+ );
+
+ const totalAmount = earnings.reduce(
+ (total, click) => total + click.earnings,
+ 0,
+ );
+
+ let payout: Payout | null = null;
+
+ // check if the partner has another pending payout
+ const existingPayout = await tx.payout.findFirst({
+ where: {
+ programId,
+ partnerId,
+ status: "pending",
+ type: "clicks",
+ },
+ });
+
+ if (existingPayout) {
+ payout = await tx.payout.update({
+ where: {
+ id: existingPayout.id,
+ },
+ data: {
+ amount: {
+ increment: totalAmount,
+ },
+ quantity: {
+ increment: totalQuantity,
+ },
+ periodEnd,
+ description: existingPayout.description ?? "Dub Partners payout",
+ },
+ });
+ } else {
+ payout = await tx.payout.create({
+ data: {
+ id: createId({ prefix: "po_" }),
+ programId,
+ partnerId,
+ periodStart,
+ periodEnd,
+ amount: totalAmount,
+ quantity: totalQuantity,
+ description: "Dub Partners payout",
+ type: "clicks",
+ },
+ });
+ }
+
+ console.info("Payout created", payout);
+
+ if (!payout) {
+ throw new Error("Payout not created.");
+ }
+
+ // update the sales records
+ await tx.earnings.updateMany({
+ where: {
+ id: {
+ in: earnings.map(({ id }) => id),
+ },
+ },
+ data: {
+ status: "processed",
+ payoutId: payout.id,
+ },
+ });
+
+ return payout;
+ });
+};
diff --git a/apps/web/app/api/cron/process-clicks/route.ts b/apps/web/app/api/cron/process-clicks/route.ts
new file mode 100644
index 0000000000..bbfe9a3994
--- /dev/null
+++ b/apps/web/app/api/cron/process-clicks/route.ts
@@ -0,0 +1,80 @@
+import { getAnalytics } from "@/lib/analytics/get-analytics";
+import { handleAndReturnErrorResponse } from "@/lib/api/errors";
+import { verifyVercelSignature } from "@/lib/cron/verify-vercel";
+import { prisma } from "@dub/prisma";
+import { EventType, Prisma } from "@prisma/client";
+import { NextResponse } from "next/server";
+
+export const dynamic = "force-dynamic";
+
+// This route is used aggregate clicks events on daily basis for Program links
+// Runs once every day at 00:00 (0 0 * * *)
+// GET /api/cron/process-clicks
+export async function GET(req: Request) {
+ try {
+ await verifyVercelSignature(req);
+
+ const links = await prisma.link.findMany({
+ where: {
+ programId: {
+ not: null,
+ },
+ partnerId: {
+ not: null,
+ },
+ clicks: {
+ gt: 0,
+ },
+ },
+ select: {
+ id: true,
+ programId: true,
+ partnerId: true,
+ },
+ take: 10,
+ });
+
+ if (!links.length) {
+ return NextResponse.json({
+ message: "No program links found. Skipping...",
+ });
+ }
+
+ // Find the start of the today and end current time
+ // TODO: Fix this
+ const start = new Date();
+ start.setHours(0, 0, 0, 0);
+ const end = new Date();
+
+ // TODO:
+ // Use queue to process clicks
+ const clicksData: Prisma.EarningsUncheckedCreateInput[] = await Promise.all(
+ links.map(async ({ id: linkId, programId, partnerId }) => {
+ const { clicks } = await getAnalytics({
+ start,
+ end,
+ linkId,
+ groupBy: "count",
+ event: "clicks",
+ });
+
+ return {
+ linkId,
+ quantity: clicks,
+ programId: programId!,
+ partnerId: partnerId!,
+ type: EventType.click,
+ amount: 0,
+ };
+ }),
+ );
+
+ await prisma.earnings.createMany({
+ data: clicksData,
+ });
+
+ return NextResponse.json(clicksData);
+ } catch (error) {
+ return handleAndReturnErrorResponse(error);
+ }
+}
diff --git a/apps/web/app/partners.dub.co/(dashboard)/programs/[programSlug]/earnings/earnings-table.tsx b/apps/web/app/partners.dub.co/(dashboard)/programs/[programSlug]/earnings/earnings-table.tsx
index 35bf1c3abe..881627eb75 100644
--- a/apps/web/app/partners.dub.co/(dashboard)/programs/[programSlug]/earnings/earnings-table.tsx
+++ b/apps/web/app/partners.dub.co/(dashboard)/programs/[programSlug]/earnings/earnings-table.tsx
@@ -52,7 +52,7 @@ export function EarningsTablePartner({ limit }: { limit?: number }) {
const { table, ...tableProps } = useTable({
data: earnings?.slice(0, limit) || [],
loading: isLoading,
- error: error ? "Failed to fetch earnings events." : undefined,
+ error: error ? "Failed to fetch earnings." : undefined,
columns: [
{
id: "createdAt",
@@ -68,9 +68,8 @@ export function EarningsTablePartner({ limit }: { limit?: number }) {
id: "customer",
header: "Customer",
accessorKey: "customer",
- cell: ({ row }) => {
- return row.original.customer.email;
- },
+ cell: ({ row }) =>
+ row.original.customer ? row.original.customer.email : "-",
},
{
id: "type",
@@ -82,25 +81,23 @@ export function EarningsTablePartner({ limit }: { limit?: number }) {
id: "saleAmount",
header: "Sale Amount",
accessorKey: "sale",
- cell: ({ row }) => {
- return row.original.amount
+ cell: ({ row }) =>
+ row.original.amount
? currencyFormatter(row.original.amount / 100, {
minimumFractionDigits: 2,
maximumFractionDigits: 2,
})
- : "-";
- },
+ : "-",
},
{
id: "earnings",
header: "Earnings",
accessorKey: "earnings",
- cell: ({ row }) => {
- return currencyFormatter(row.original.earnings / 100, {
+ cell: ({ row }) =>
+ currencyFormatter(row.original.earnings / 100, {
minimumFractionDigits: 2,
maximumFractionDigits: 2,
- });
- },
+ }),
},
{
header: "Status",
diff --git a/apps/web/app/partners.dub.co/(dashboard)/programs/[programSlug]/earnings/page.tsx b/apps/web/app/partners.dub.co/(dashboard)/programs/[programSlug]/earnings/page.tsx
index 1cc7edc663..ba0a8c6026 100644
--- a/apps/web/app/partners.dub.co/(dashboard)/programs/[programSlug]/earnings/page.tsx
+++ b/apps/web/app/partners.dub.co/(dashboard)/programs/[programSlug]/earnings/page.tsx
@@ -2,9 +2,9 @@ import { PageContent } from "@/ui/layout/page-content";
import { MaxWidthWrapper } from "@dub/ui";
import { EarningsTablePartner } from "./earnings-table";
-export default function ProgramSales() {
+export default function ProgramEarning() {
return (
- <PageContent title="Sales" hideReferButton>
+ <PageContent title="Earnings" hideReferButton>
<MaxWidthWrapper>
<EarningsTablePartner />
</MaxWidthWrapper>
diff --git a/apps/web/lib/zod/schemas/partners.ts b/apps/web/lib/zod/schemas/partners.ts
index 8b59b0b0bb..f7be9ce193 100644
--- a/apps/web/lib/zod/schemas/partners.ts
+++ b/apps/web/lib/zod/schemas/partners.ts
@@ -147,12 +147,14 @@ export const PartnerEarningsSchema = SaleResponseSchema.omit({
}).merge(
z.object({
type: z.string(),
- customer: z.object({
- email: z
- .string()
- .transform((email) => email.replace(/(?<=^.).+(?=.@)/, "********")),
- avatar: z.string().nullable(),
- }),
+ customer: z
+ .object({
+ email: z
+ .string()
+ .transform((email) => email.replace(/(?<=^.).+(?=.@)/, "********")),
+ avatar: z.string().nullable(),
+ })
+ .nullable(),
}),
);
diff --git a/apps/web/lib/zod/schemas/payouts.ts b/apps/web/lib/zod/schemas/payouts.ts
index c77470bec3..62c32dbc41 100644
--- a/apps/web/lib/zod/schemas/payouts.ts
+++ b/apps/web/lib/zod/schemas/payouts.ts
@@ -78,6 +78,7 @@ export const PayoutResponseSchema = PayoutSchema.merge(
export const PartnerPayoutResponseSchema = PayoutResponseSchema.omit({
partner: true,
+ _count: true,
}).merge(
z.object({
program: ProgramSchema.pick({