-
Notifications
You must be signed in to change notification settings - Fork 2.8k
FirstPromoter migration tool #2816
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
25 commits
Select commit
Hold shift + click to select a range
3519eb0
FirstPromoter importer
devkiran 703351e
add import modal
devkiran 54f3059
Merge branch 'main' into first-promoter
devkiran 2c18ee3
Merge branch 'main' into first-promoter
devkiran 413b7ae
fix import campaigns
devkiran f18fd9e
fix import-partners
devkiran 4df8fd3
fix import-customers
devkiran 7d9206d
fix import-customers
devkiran 643a8c2
fix import-commissions
devkiran 988ef31
format
devkiran c30a009
fix build
devkiran 559eb19
Update program-onboarding.ts
devkiran 8a05b04
Update import-firstpromoter-modal.tsx
devkiran 25c76ff
Update api.ts
devkiran f4abaeb
Update import-campaigns.ts
devkiran 5778ecd
Update import-partners.ts
devkiran e4dce2b
Update update-stripe-customers.ts
devkiran 8c98497
Merge branch 'main' into first-promoter
steven-tey efca13b
leadEventName: "Signup (auto lead tracking)"
steven-tey 2130dad
Merge branch 'main' into first-promoter
devkiran 8036c4e
Merge branch 'main' into first-promoter
steven-tey f963435
Merge branch 'main' into first-promoter
steven-tey 277fbc8
Merge branch 'main' into first-promoter
devkiran dbeb683
Merge branch 'main' into first-promoter
devkiran ea81a21
Merge branch 'main' into first-promoter
steven-tey File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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); | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
60 changes: 60 additions & 0 deletions
60
apps/web/lib/actions/partners/start-firstpromoter-import.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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(), | ||
| }); | ||
|
|
||
| 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, | ||
| }); | ||
| }); | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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(); | ||
devkiran marked this conversation as resolved.
Show resolved
Hide resolved
devkiran marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
| 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); | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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); | ||
devkiran marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
devkiran marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| 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, | ||
devkiran marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| }); | ||
| } | ||
|
|
||
| currentPage++; | ||
| processedBatches++; | ||
| } | ||
|
|
||
| await firstPromoterImporter.queue({ | ||
| ...payload, | ||
| action: hasMore ? "import-campaigns" : "import-partners", | ||
| page: hasMore ? currentPage : undefined, | ||
| }); | ||
| } | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
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:
Also applies to: 20-21
🤖 Prompt for AI Agents