Thanks to visit codestin.com
Credit goes to github.com

Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
25 commits
Select commit Hold shift + click to select a range
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
48 changes: 48 additions & 0 deletions apps/web/app/(ee)/api/cron/import/firstpromoter/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
import { handleAndReturnErrorResponse } from "@/lib/api/errors";
import { verifyQstashSignature } from "@/lib/cron/verify-qstash";
import { importCampaigns } from "@/lib/firstpromoter/import-campaigns";
import { importCommissions } from "@/lib/firstpromoter/import-commissions";
import { importCustomers } from "@/lib/firstpromoter/import-customers";
import { importPartners } from "@/lib/firstpromoter/import-partners";
import { firstPromoterImportPayloadSchema } from "@/lib/firstpromoter/schemas";
import { updateStripeCustomers } from "@/lib/firstpromoter/update-stripe-customers";
import { NextResponse } from "next/server";

export const dynamic = "force-dynamic";

export async function POST(req: Request) {
try {
const rawBody = await req.text();

await verifyQstashSignature({
req,
rawBody,
});

const payload = firstPromoterImportPayloadSchema.parse(JSON.parse(rawBody));

switch (payload.action) {
case "import-campaigns":
await importCampaigns(payload);
break;
case "import-partners":
await importPartners(payload);
break;
case "import-customers":
await importCustomers(payload);
break;
case "import-commissions":
await importCommissions(payload);
break;
case "update-stripe-customers":
await updateStripeCustomers(payload);
break;
default:
throw new Error(`Unknown action: ${payload.action}`);
}

return NextResponse.json("OK");
} catch (error) {
return handleAndReturnErrorResponse(error);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import { PROGRAM_IMPORT_SOURCES } from "@/lib/partners/constants";
import useWorkspace from "@/lib/swr/use-workspace";
import { useExportPartnersModal } from "@/ui/modals/export-partners-modal";
import { useImportFirstPromoterModal } from "@/ui/modals/import-firstpromoter-modal";
import { useImportPartnerStackModal } from "@/ui/modals/import-partnerstack-modal";
import { useImportRewardfulModal } from "@/ui/modals/import-rewardful-modal";
import { useImportToltModal } from "@/ui/modals/import-tolt-modal";
Expand All @@ -19,6 +20,7 @@ export function ImportExportButtons() {
const { ImportToltModal } = useImportToltModal();
const { ImportRewardfulModal } = useImportRewardfulModal();
const { ImportPartnerStackModal } = useImportPartnerStackModal();
const { ImportFirstPromoterModal } = useImportFirstPromoterModal();

const { ExportPartnersModal, setShowExportPartnersModal } =
useExportPartnersModal();
Expand All @@ -27,6 +29,7 @@ export function ImportExportButtons() {
<>
<ImportToltModal />
<ImportRewardfulModal />
<ImportFirstPromoterModal />
<ImportPartnerStackModal />
<ExportPartnersModal />
<Popover
Expand Down
60 changes: 60 additions & 0 deletions apps/web/lib/actions/partners/start-firstpromoter-import.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
"use server";

import { createId } from "@/lib/api/create-id";
import { getDefaultProgramIdOrThrow } from "@/lib/api/programs/get-default-program-id-or-throw";
import { getProgramOrThrow } from "@/lib/api/programs/get-program-or-throw";
import { FirstPromoterApi } from "@/lib/firstpromoter/api";
import { firstPromoterImporter } from "@/lib/firstpromoter/importer";
import { firstPromoterCredentialsSchema } from "@/lib/firstpromoter/schemas";
import { z } from "zod";
import { authActionClient } from "../safe-action";

const schema = firstPromoterCredentialsSchema.extend({
workspaceId: z.string(),
});
Comment on lines +12 to +14
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Validate client-sent workspaceId or drop it

workspaceId is required by the schema but unused, which can confuse callers. Either remove it from the schema or enforce it matches ctx.workspace.id.

Apply:

-const schema = firstPromoterCredentialsSchema.extend({
-  workspaceId: z.string(),
-});
+const schema = firstPromoterCredentialsSchema.extend({
+  workspaceId: z.string(),
+});
@@
-    const { apiKey, accountId } = parsedInput;
+    const { apiKey, accountId, workspaceId } = parsedInput;
+    if (workspaceId !== workspace.id) {
+      throw new Error("Workspace mismatch.");
+    }

Also applies to: 20-21

🤖 Prompt for AI Agents
In apps/web/lib/actions/partners/start-firstpromoter-import.ts around lines
12-14 (and similarly lines 20-21), the schema currently requires workspaceId but
that value is never used — either remove workspaceId from the schema or validate
it against ctx.workspace.id; to fix, choose one: (A) remove workspaceId from the
schema and callers, keeping only the fields actually used, or (B) keep
workspaceId but change validation so the parsed value is compared to
ctx.workspace.id (e.g., use a refine or an explicit post-parse check) and throw
a validation/authorization error if it doesn’t match, ensuring the handler uses
ctx.workspace.id for any operations rather than the client-supplied value.


export const startFirstPromoterImportAction = authActionClient
.schema(schema)
.action(async ({ ctx, parsedInput }) => {
const { workspace, user } = ctx;
const { apiKey, accountId } = parsedInput;

const programId = getDefaultProgramIdOrThrow(workspace);

const program = await getProgramOrThrow({
workspaceId: workspace.id,
programId,
});

if (!program.domain) {
throw new Error("Program domain is not set.");
}

if (!program.url) {
throw new Error("Program URL is not set.");
}

const firstPromoterApi = new FirstPromoterApi({ apiKey, accountId });

try {
await firstPromoterApi.testConnection();
} catch (error) {
throw new Error(
error instanceof Error
? error.message
: "Invalid FirstPromoter credentials.",
);
}

await firstPromoterImporter.setCredentials(workspace.id, {
apiKey,
accountId,
});

await firstPromoterImporter.queue({
importId: createId({ prefix: "import_" }),
action: "import-campaigns",
userId: user.id,
programId,
});
});
107 changes: 107 additions & 0 deletions apps/web/lib/firstpromoter/api.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
import { z } from "zod";
import { PAGE_LIMIT } from "./importer";
import {
firstPromoterCampaignSchema,
firstPromoterCommissionSchema,
firstPromoterCustomerSchema,
firstPromoterPartnerSchema,
} from "./schemas";

export class FirstPromoterApi {
private readonly baseUrl = "https://v2.firstpromoter.com/api/v2/company";
private readonly apiKey: string;
private readonly accountId: string;

constructor({ apiKey, accountId }: { apiKey: string; accountId: string }) {
this.apiKey = apiKey;
this.accountId = accountId;
}

private async fetch<T>(path: string): Promise<T> {
const response = await fetch(`${this.baseUrl}${path}`, {
headers: {
Authorization: `Bearer ${this.apiKey}`,
"ACCOUNT-ID": this.accountId,
},
});

if (!response.ok) {
const error = await response.json();

console.error("FirstPromoter API Error:", error);
throw new Error(error.message || "Unknown error from FirstPromoter API.");
}

return await response.json();
}

async testConnection() {
try {
await this.fetch("/promoter_campaigns?page=1&per_page=1");
return true;
} catch (error) {
throw new Error("Invalid FirstPromoter API token.");
}
}

async listCampaigns({ page }: { page?: number }) {
const searchParams = new URLSearchParams({
per_page: PAGE_LIMIT.toString(),
...(page ? { page: page.toString() } : {}),
});

const campaigns = await this.fetch(
`/promoter_campaigns?${searchParams.toString()}`,
);

return firstPromoterCampaignSchema.array().parse(campaigns);
}

async listPartners({ page }: { page?: number }) {
const searchParams = new URLSearchParams({
filters: JSON.stringify({
archived: false,
state: "accepted",
referrals_count: {
from: 1,
},
}),
per_page: PAGE_LIMIT.toString(),
...(page ? { page: page.toString() } : {}),
});

const response = await this.fetch(`/promoters?${searchParams.toString()}`);

const { data: partners } = z
.object({
data: firstPromoterPartnerSchema.array(),
})
.parse(response);

return partners;
}

async listCustomers({ page }: { page?: number }) {
const searchParams = new URLSearchParams({
per_page: PAGE_LIMIT.toString(),
...(page ? { page: page.toString() } : {}),
});

const customers = await this.fetch(`/referrals?${searchParams.toString()}`);

return firstPromoterCustomerSchema.array().parse(customers);
}

async listCommissions({ page }: { page?: number }) {
const searchParams = new URLSearchParams({
per_page: PAGE_LIMIT.toString(),
...(page ? { page: page.toString() } : {}),
});

const commissions = await this.fetch(
`/commissions?${searchParams.toString()}`,
);

return firstPromoterCommissionSchema.array().parse(commissions);
}
}
74 changes: 74 additions & 0 deletions apps/web/lib/firstpromoter/import-campaigns.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
import { RESOURCE_COLORS } from "@/ui/colors";
import { prisma } from "@dub/prisma";
import { randomValue } from "@dub/utils";
import slugify from "@sindresorhus/slugify";
import { createId } from "../api/create-id";
import { FirstPromoterApi } from "./api";
import { firstPromoterImporter, MAX_BATCHES } from "./importer";
import { FirstPromoterImportPayload } from "./types";

export async function importCampaigns(payload: FirstPromoterImportPayload) {
const { programId, page = 1 } = payload;

// Find the program and their groups
const program = await prisma.program.findUniqueOrThrow({
where: {
id: programId,
},
include: {
groups: true,
},
});

// Groups in the program
const existingGroupNames = program.groups.map((group) => group.name);

const credentials = await firstPromoterImporter.getCredentials(
program.workspaceId,
);

const firstPromoterApi = new FirstPromoterApi(credentials);

let hasMore = true;
let processedBatches = 0;
let currentPage = page;

while (processedBatches < MAX_BATCHES) {
const campaigns = await firstPromoterApi.listCampaigns({
page: currentPage,
});

if (campaigns.length === 0) {
hasMore = false;
break;
}

// Find the campaigns that don't exist in the program
// We compare the group name with the campaign name
const newCampaigns = campaigns.filter(
(campaign) => !existingGroupNames.includes(campaign.campaign.name),
);

if (newCampaigns.length > 0) {
const groups = await prisma.partnerGroup.createMany({
data: newCampaigns.map((campaign) => ({
id: createId({ prefix: "grp_" }),
programId: program.id,
slug: slugify(campaign.campaign.name),
name: campaign.campaign.name,
color: randomValue(RESOURCE_COLORS),
})),
skipDuplicates: true,
});
}

currentPage++;
processedBatches++;
}

await firstPromoterImporter.queue({
...payload,
action: hasMore ? "import-campaigns" : "import-partners",
page: hasMore ? currentPage : undefined,
});
}
Loading