The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
Refactor PartnerStack import to use public and secret keys
Kiran K57f246e28bb5
diff --git a/apps/web/lib/actions/partners/start-partnerstack-import.ts b/apps/web/lib/actions/partners/start-partnerstack-import.tsindex e3e07760ea..f07c004b05 100644--- a/apps/web/lib/actions/partners/start-partnerstack-import.ts+++ b/apps/web/lib/actions/partners/start-partnerstack-import.ts@@ -9,14 +9,15 @@ import { authActionClient } from "../safe-action";const schema = z.object({workspaceId: z.string(),- token: z.string().min(1),+ publicKey: z.string().min(1),+ secretKey: z.string().min(1),});export const startPartnerStackImportAction = authActionClient.schema(schema).action(async ({ ctx, parsedInput }) => {const { workspace, user } = ctx;- const { token } = parsedInput;+ const { publicKey, secretKey } = parsedInput;const programId = getDefaultProgramIdOrThrow(workspace);@@ -34,14 +35,20 @@ export const startPartnerStackImportAction = authActionClient}const partnerStackApi = new PartnerStackApi({- token,+ publicKey,+ secretKey,});await partnerStackApi.testConnection();+ await partnerStackImporter.setCredentials(workspace.id, {+ publicKey,+ secretKey,+ });+await partnerStackImporter.queue({programId,userId: user.id,- action: "import-affiliates",+ action: "import-partners",});});diff --git a/apps/web/lib/partnerstack/api.ts b/apps/web/lib/partnerstack/api.tsindex ea08951aea..7147be77da 100644--- a/apps/web/lib/partnerstack/api.ts+++ b/apps/web/lib/partnerstack/api.ts@@ -12,20 +12,32 @@ import {PartnerStackListResponse,} from "./types";-const PAGE_LIMIT = 100;+const PAGE_LIMIT = 50;export class PartnerStackApi {private readonly baseUrl = "https://api.partnerstack.com/api/v2";- private readonly token: string;-- constructor({ token }: { token: string }) {- this.token = token;+ private readonly publicKey: string;+ private readonly secretKey: string;++ constructor({+ publicKey,+ secretKey,+ }: {+ publicKey: string;+ secretKey: string;+ }) {+ this.publicKey = publicKey;+ this.secretKey = secretKey;}private async fetch<T>(path: string): Promise<T> {+ const token = Buffer.from(`${this.publicKey}:${this.secretKey}`).toString(+ "base64",+ );+const response = await fetch(`${this.baseUrl}${path}`, {headers: {- Authorization: `Bearer ${this.token}`,+ Authorization: `Basic ${token}`,},});diff --git a/apps/web/lib/partnerstack/import-commissions.ts b/apps/web/lib/partnerstack/import-commissions.tsindex 666ae400c7..e06f753cae 100644--- a/apps/web/lib/partnerstack/import-commissions.ts+++ b/apps/web/lib/partnerstack/import-commissions.ts@@ -15,12 +15,13 @@ export async function importCommissions(payload: PartnerStackImportPayload) {},});- const { token } = await partnerStackImporter.getCredentials(+ const { publicKey, secretKey } = await partnerStackImporter.getCredentials(program.workspaceId,);const partnerStackApi = new PartnerStackApi({- token,+ publicKey,+ secretKey,});let hasMore = true;diff --git a/apps/web/lib/partnerstack/import-customers.ts b/apps/web/lib/partnerstack/import-customers.tsindex b496530235..f58bf5e8ab 100644--- a/apps/web/lib/partnerstack/import-customers.ts+++ b/apps/web/lib/partnerstack/import-customers.ts@@ -24,12 +24,13 @@ export async function importCustomers(payload: PartnerStackImportPayload) {},});- const { token } = await partnerStackImporter.getCredentials(+ const { publicKey, secretKey } = await partnerStackImporter.getCredentials(program.workspaceId,);const partnerStackApi = new PartnerStackApi({- token,+ publicKey,+ secretKey,});let hasMore = true;diff --git a/apps/web/lib/partnerstack/import-links.ts b/apps/web/lib/partnerstack/import-links.tsindex 973a82ae95..a4373701b5 100644--- a/apps/web/lib/partnerstack/import-links.ts+++ b/apps/web/lib/partnerstack/import-links.ts@@ -18,12 +18,13 @@ export async function importLinks(payload: PartnerStackImportPayload) {},});- const { token } = await partnerStackImporter.getCredentials(+ const { publicKey, secretKey } = await partnerStackImporter.getCredentials(program.workspaceId,);const partnerStackApi = new PartnerStackApi({- token,+ publicKey,+ secretKey,});let hasMore = true;@@ -89,7 +90,7 @@ export async function importLinks(payload: PartnerStackImportPayload) {await partnerStackImporter.queue({...payload,...(hasMore && { startingAfter: currentStartingAfter }),- action: hasMore ? "import-links" : "import-referrals",+ action: hasMore ? "import-links" : "import-customers",});}diff --git a/apps/web/lib/partnerstack/import-affiliates.ts b/apps/web/lib/partnerstack/import-partners.tssimilarity index 79%rename from apps/web/lib/partnerstack/import-affiliates.tsrename to apps/web/lib/partnerstack/import-partners.tsindex ed8a841630..306d82c220 100644--- a/apps/web/lib/partnerstack/import-affiliates.ts+++ b/apps/web/lib/partnerstack/import-partners.ts@@ -1,13 +1,13 @@import { prisma } from "@dub/prisma";import { Program, Reward } from "@dub/prisma/client";-import { COUNTRY_CODES } from "@dub/utils";+import { COUNTRIES } from "@dub/utils";import { createId } from "../api/create-id";import { REWARD_EVENT_COLUMN_MAPPING } from "../zod/schemas/rewards";import { PartnerStackApi } from "./api";import { MAX_BATCHES, partnerStackImporter } from "./importer";import { PartnerStackAffiliate, PartnerStackImportPayload } from "./types";-export async function importAffiliates(payload: PartnerStackImportPayload) {+export async function importPartners(payload: PartnerStackImportPayload) {const { programId, startingAfter } = payload;const program = await prisma.program.findUniqueOrThrow({@@ -23,12 +23,13 @@ export async function importAffiliates(payload: PartnerStackImportPayload) {},});- const { token } = await partnerStackImporter.getCredentials(+ const { publicKey, secretKey } = await partnerStackImporter.getCredentials(program.workspaceId,);const partnerStackApi = new PartnerStackApi({- token,+ publicKey,+ secretKey,});const saleReward = program.rewards.find((r) => r.event === "sale");@@ -50,9 +51,13 @@ export async function importAffiliates(payload: PartnerStackImportPayload) {break;}- if (affiliates.length > 0) {+ const activeAffiliates = affiliates.filter(+ (affiliate) => affiliate.stats.CUSTOMER_COUNT > 0,+ );++ if (activeAffiliates.length > 0) {await Promise.allSettled(- affiliates.map((affiliate) =>+ activeAffiliates.map((affiliate) =>createPartner({program,affiliate,@@ -60,9 +65,6 @@ export async function importAffiliates(payload: PartnerStackImportPayload) {}),),);-- // TODO:- // Remove the partners with 0 leads}await new Promise((resolve) => setTimeout(resolve, 2000));@@ -74,11 +76,10 @@ export async function importAffiliates(payload: PartnerStackImportPayload) {await partnerStackImporter.queue({...payload,...(hasMore && { startingAfter: currentStartingAfter }),- action: hasMore ? "import-affiliates" : "import-links",+ action: hasMore ? "import-partners" : "import-links",});}-// Create partnerasync function createPartner({program,affiliate,@@ -88,6 +89,12 @@ async function createPartner({affiliate: PartnerStackAffiliate;reward?: Pick<Reward, "id" | "event">;}) {+ const countryCode = affiliate.address?.country+ ? Object.keys(COUNTRIES).find(+ (key) => COUNTRIES[key] === affiliate.address?.country,+ )+ : null;+const partner = await prisma.partner.upsert({where: {email: affiliate.email,@@ -96,7 +103,7 @@ async function createPartner({id: createId({ prefix: "pn_" }),name: `${affiliate.first_name} ${affiliate.last_name}`,email: affiliate.email,- country: COUNTRY_CODES[affiliate.address.country],+ country: countryCode,},update: {// do nothing@@ -120,6 +127,4 @@ async function createPartner({status: "approved",},});-- return partner;}diff --git a/apps/web/lib/partnerstack/importer.ts b/apps/web/lib/partnerstack/importer.tsindex a8cf4759e6..e95d5ca5b0 100644--- a/apps/web/lib/partnerstack/importer.ts+++ b/apps/web/lib/partnerstack/importer.ts@@ -5,7 +5,7 @@ import { z } from "zod";import { partnerStackImportPayloadSchema } from "./schemas";import { PartnerStackConfig } from "./types";-export const MAX_BATCHES = 5;+export const MAX_BATCHES = 1;export const CACHE_EXPIRY = 60 * 60 * 24;export const CACHE_KEY_PREFIX = "partnerstack:import";diff --git a/apps/web/lib/partnerstack/types.ts b/apps/web/lib/partnerstack/types.tsindex d9d09f1245..5954ebd443 100644--- a/apps/web/lib/partnerstack/types.ts+++ b/apps/web/lib/partnerstack/types.ts@@ -8,7 +8,8 @@ import {} from "./schemas";export interface PartnerStackConfig {- token: string;+ publicKey: string;+ secretKey: string;}export interface PartnerStackListResponse<T> {diff --git a/apps/web/ui/modals/import-partnerstack-modal.tsx b/apps/web/ui/modals/import-partnerstack-modal.tsxindex 46df2c121a..8d8c836d2c 100644--- a/apps/web/ui/modals/import-partnerstack-modal.tsx+++ b/apps/web/ui/modals/import-partnerstack-modal.tsx@@ -77,7 +77,8 @@ function ImportPartnerStackModal({function TokenForm({ onClose }: { onClose: () => void }) {const router = useRouter();const { isMobile } = useMediaQuery();- const [token, setToken] = useState("");+ const [publicKey, setPublicKey] = useState("");+ const [secretKey, setSecretKey] = useState("");const { id: workspaceId, slug } = useWorkspace();const { executeAsync, isPending } = useAction(startPartnerStackImportAction, {@@ -96,13 +97,14 @@ function TokenForm({ onClose }: { onClose: () => void }) {const onSubmit = async (e: React.FormEvent) => {e.preventDefault();- if (!workspaceId || !token) {+ if (!workspaceId || !publicKey || !secretKey) {return;}await executeAsync({workspaceId,- token,+ publicKey,+ secretKey,});};@@ -110,37 +112,55 @@ function TokenForm({ onClose }: { onClose: () => void }) {<form onSubmit={onSubmit} className="flex flex-col space-y-4"><div><label- htmlFor="token"+ htmlFor="publicKey"className="block text-sm font-medium text-neutral-700">- PartnerStack API Key+ PartnerStack Public Key</label><inputtype="password"- id="token"- value={token}+ id="publicKey"+ value={publicKey}autoFocus={!isMobile}- onChange={(e) => setToken(e.target.value)}+ onChange={(e) => setPublicKey(e.target.value)}className="mt-1 block w-full rounded-md border border-neutral-200 px-3 py-2 placeholder-neutral-400 focus:border-neutral-500 focus:outline-none focus:ring-neutral-500 sm:text-sm"required/><p className="mt-1.5 text-xs text-neutral-500">You can find your PartnerStack API key in your{" "}<a- href="https://app.partnerstack.com/settings/api"+ href="https://app.partnerstack.com/settings/integrations"target="_blank"rel="noopener noreferrer"className="text-blue-500 hover:text-blue-600">- API settings+ Settings</a></p></div>+ <div>+ <label+ htmlFor="secretKey"+ className="block text-sm font-medium text-neutral-700"+ >+ PartnerStack Secret Key+ </label>+ <input+ type="password"+ id="secretKey"+ value={secretKey}+ autoFocus={!isMobile}+ onChange={(e) => setSecretKey(e.target.value)}+ className="mt-1 block w-full rounded-md border border-neutral-200 px-3 py-2 placeholder-neutral-400 focus:border-neutral-500 focus:outline-none focus:ring-neutral-500 sm:text-sm"+ required+ />+ </div>+<Buttontext={isPending ? "Starting import..." : "Start Import"}loading={isPending}- disabled={!token}+ disabled={!publicKey || !secretKey}/></form>);