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.

syncTotalCommissions

Steven Tey6ff6a891f6d7
diff --git a/apps/web/lib/api/partners/backfill-link-commissions.ts b/apps/web/lib/api/partners/backfill-link-commissions.ts
index ff3244fe87..05b41ece1f 100644
--- a/apps/web/lib/api/partners/backfill-link-commissions.ts
+++ b/apps/web/lib/api/partners/backfill-link-commissions.ts
@@ -5,6 +5,7 @@ import { determinePartnerReward } from "@/lib/partners/determine-partner-reward"
import { SaleEvent } from "@/lib/types";
import { prisma } from "@dub/prisma";
import { EventType } from "@dub/prisma/client";
+import { syncTotalCommissions } from "./sync-total-commissions";
export const backfillLinkCommissions = async (link: {
id: string;
@@ -63,8 +64,15 @@ export const backfillLinkCommissions = async (link: {
}),
}));
- return await prisma.commission.createMany({
+ // create commissions
+ await prisma.commission.createMany({
data,
skipDuplicates: true,
});
+
+ // sync total commissions for the partner in the program
+ await syncTotalCommissions({
+ partnerId: link.partnerId,
+ programId: link.programId,
+ });
};
diff --git a/apps/web/lib/api/partners/sync-total-commissions.ts b/apps/web/lib/api/partners/sync-total-commissions.ts
new file mode 100644
index 0000000000..e98f75c91f
--- /dev/null
+++ b/apps/web/lib/api/partners/sync-total-commissions.ts
@@ -0,0 +1,33 @@
+import { prisma } from "@dub/prisma";
+
+// syncs the total commissions for a partner in a program
+export const syncTotalCommissions = async ({
+ partnerId,
+ programId,
+}: {
+ partnerId: string;
+ programId: string;
+}) => {
+ const totalCommissions = await prisma.commission.aggregate({
+ where: {
+ earnings: {
+ gt: 0,
+ },
+ programId,
+ partnerId,
+ },
+ _sum: { earnings: true },
+ });
+
+ return await prisma.programEnrollment.update({
+ where: {
+ partnerId_programId: {
+ partnerId,
+ programId,
+ },
+ },
+ data: {
+ totalCommissions: totalCommissions._sum.earnings || 0,
+ },
+ });
+};
diff --git a/apps/web/lib/rewardful/import-commissions.ts b/apps/web/lib/rewardful/import-commissions.ts
index c65d9b97dd..886109c5e2 100644
--- a/apps/web/lib/rewardful/import-commissions.ts
+++ b/apps/web/lib/rewardful/import-commissions.ts
@@ -4,6 +4,7 @@ import { prisma } from "@dub/prisma";
import { nanoid } from "@dub/utils";
import { CommissionStatus, Program } from "@prisma/client";
import { createId } from "../api/create-id";
+import { syncTotalCommissions } from "../api/partners/sync-total-commissions";
import { getLeadEvent } from "../tinybird";
import { recordSaleWithTimestamp } from "../tinybird/record-sale";
import { clickEventSchemaTB } from "../zod/schemas/clicks";
@@ -268,4 +269,9 @@ async function createCommission({
},
}),
]);
+
+ await syncTotalCommissions({
+ partnerId: customerFound.link.partnerId,
+ programId: program.id,
+ });
}