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.

add modal

Kiran K7bc5cd7d3e27
diff --git a/apps/web/lib/actions/partners/set-partnerstack-token.ts b/apps/web/lib/actions/partners/set-partnerstack-token.ts
new file mode 100644
index 0000000000..0eb395c7af
--- /dev/null
+++ b/apps/web/lib/actions/partners/set-partnerstack-token.ts
@@ -0,0 +1,47 @@
+"use server";
+
+import { PartnerStackApi } from "@/lib/partnerstack/api";
+import { partnerstackImporter } from "@/lib/partnerstack/importer";
+import { z } from "zod";
+import { authActionClient } from "../safe-action";
+
+const schema = z.object({
+ workspaceId: z.string(),
+ partnerstackProgramId: z.string().describe("PartnerStack program ID to import."),
+ token: z.string(),
+});
+
+export const setPartnerStackTokenAction = authActionClient
+ .schema(schema)
+ .action(async ({ parsedInput, ctx }) => {
+ const { workspace, user } = ctx;
+ const { token, partnerstackProgramId } = parsedInput;
+
+ if (!workspace.partnersEnabled) {
+ throw new Error("You are not allowed to perform this action.");
+ }
+
+ const partnerstackApi = new PartnerStackApi({ token });
+
+ try {
+ // Test the API connection by attempting to fetch program info
+ // Note: PartnerStack doesn't return detailed program info, so we'll just validate the token
+ await partnerstackApi.testConnection();
+ } catch (error) {
+ throw new Error(
+ error instanceof Error
+ ? error.message
+ : "Invalid PartnerStack token or program ID.",
+ );
+ }
+
+ await partnerstackImporter.setCredentials(workspace.id, {
+ userId: user.id,
+ token,
+ partnerstackProgramId,
+ });
+
+ return {
+ success: true,
+ };
+ });
\ No newline at end of file
diff --git a/apps/web/lib/actions/partners/start-partnerstack-import.ts b/apps/web/lib/actions/partners/start-partnerstack-import.ts
new file mode 100644
index 0000000000..e7c82e333d
--- /dev/null
+++ b/apps/web/lib/actions/partners/start-partnerstack-import.ts
@@ -0,0 +1,45 @@
+"use server";
+
+import { getDefaultProgramIdOrThrow } from "@/lib/api/programs/get-default-program-id-or-throw";
+import { getProgramOrThrow } from "@/lib/api/programs/get-program-or-throw";
+import { partnerstackImporter } from "@/lib/partnerstack/importer";
+import { authActionClient } from "../safe-action";
+import { z } from "zod";
+
+const schema = z.object({
+ workspaceId: z.string(),
+});
+
+export const startPartnerStackImportAction = authActionClient
+ .schema(schema)
+ .action(async ({ ctx }) => {
+ const { workspace } = ctx;
+
+ 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 credentials = await partnerstackImporter.getCredentials(workspace.id);
+
+ if (!credentials) {
+ throw new Error(
+ "PartnerStack credentials not found. Please restart the import process.",
+ );
+ }
+
+ await partnerstackImporter.queue({
+ action: "import-affiliates",
+ programId,
+ });
+ });
\ No newline at end of file
diff --git a/apps/web/lib/partners/constants.ts b/apps/web/lib/partners/constants.ts
index f7c1c88047..26286e40cc 100644
--- a/apps/web/lib/partners/constants.ts
+++ b/apps/web/lib/partners/constants.ts
@@ -78,4 +78,10 @@ export const PROGRAM_IMPORT_SOURCES = [
image: "https://assets.dub.co/misc/icons/tolt.svg",
helpUrl: "https://dub.co/help/article/migrating-from-tolt",
},
+ {
+ id: "partnerstack",
+ value: "PartnerStack",
+ image: "https://assets.dub.co/misc/icons/partnerstack.svg",
+ helpUrl: "https://dub.co/help/article/migrating-from-partnerstack",
+ },
] as const;
diff --git a/apps/web/lib/partnerstack/api.ts b/apps/web/lib/partnerstack/api.ts
index e69de29bb2..0c609d4128 100644
--- a/apps/web/lib/partnerstack/api.ts
+++ b/apps/web/lib/partnerstack/api.ts
@@ -0,0 +1,39 @@
+const PAGE_LIMIT = 100;
+
+export class PartnerStackApi {
+ private readonly baseUrl = "https://api.partnerstack.com/api/v2";
+ private readonly token: string;
+
+ constructor({ token }: { token: string }) {
+ this.token = token;
+ }
+
+ private async fetch<T>(url: string): Promise<T> {
+ const response = await fetch(url, {
+ headers: {
+ Authorization: `Bearer ${this.token}`,
+ },
+ });
+
+ if (!response.ok) {
+ const error = await response.json();
+
+ console.error("PartnerStack API Error:", error);
+
+ throw new Error(error.message || "Unknown error from PartnerStack API.");
+ }
+
+ return await response.json();
+ }
+
+ async testConnection(): Promise<boolean> {
+ try {
+ // Test the API connection by making a simple request
+ // We'll use a basic endpoint to validate the token
+ await this.fetch(`${this.baseUrl}/test`);
+ return true;
+ } catch (error) {
+ throw new Error("Invalid PartnerStack API token.");
+ }
+ }
+}
diff --git a/apps/web/lib/partnerstack/importer.ts b/apps/web/lib/partnerstack/importer.ts
index e69de29bb2..833c1ea0e2 100644
--- a/apps/web/lib/partnerstack/importer.ts
+++ b/apps/web/lib/partnerstack/importer.ts
@@ -0,0 +1,90 @@
+import { qstash } from "@/lib/cron";
+import { redis } from "@/lib/upstash";
+import { APP_DOMAIN_WITH_NGROK } from "@dub/utils";
+import { z } from "zod";
+import { PartnerStackConfig } from "./types";
+
+export const MAX_BATCHES = 5;
+export const CACHE_EXPIRY = 60 * 60 * 24;
+export const CACHE_KEY_PREFIX = "partnerstack:import";
+export const PARTNER_IDS_KEY_PREFIX = "partnerstack:import:partnerIds";
+
+export const importSteps = z.enum([
+ "import-affiliates",
+ "import-links",
+ "import-referrals",
+ "import-commissions",
+ "update-stripe-customers", // update the customers with their stripe customer ID
+ "cleanup-partners", // remove partners with 0 leads
+]);
+
+class PartnerStackImporter {
+ async setCredentials(workspaceId: string, payload: PartnerStackConfig) {
+ await redis.set(`${CACHE_KEY_PREFIX}:${workspaceId}`, payload, {
+ ex: CACHE_EXPIRY,
+ });
+ }
+
+ async getCredentials(workspaceId: string) {
+ const config = await redis.get<PartnerStackConfig>(
+ `${CACHE_KEY_PREFIX}:${workspaceId}`,
+ );
+
+ if (!config) {
+ throw new Error("PartnerStack configuration not found.");
+ }
+
+ return config;
+ }
+
+ async deleteCredentials(workspaceId: string) {
+ return await redis.del(`${CACHE_KEY_PREFIX}:${workspaceId}`);
+ }
+
+ async queue(body: {
+ action: z.infer<typeof importSteps>;
+ programId: string;
+ startingAfter?: string;
+ }) {
+ return await qstash.publishJSON({
+ url: `${APP_DOMAIN_WITH_NGROK}/api/cron/import/partnerstack`,
+ body,
+ });
+ }
+
+ async addPartners({
+ programId,
+ partnerIds,
+ }: {
+ programId: string;
+ partnerIds: string[];
+ }) {
+ if (!partnerIds || partnerIds.length === 0) {
+ return;
+ }
+
+ await redis.lpush(`${PARTNER_IDS_KEY_PREFIX}:${programId}`, ...partnerIds);
+ }
+
+ async scanPartnerIds({
+ programId,
+ start,
+ end,
+ }: {
+ programId: string;
+ start: number;
+ end: number;
+ }) {
+ return await redis.lrange(
+ `${PARTNER_IDS_KEY_PREFIX}:${programId}`,
+ start,
+ end,
+ );
+ }
+
+ async deletePartnerIds(programId: string) {
+ return await redis.del(`${PARTNER_IDS_KEY_PREFIX}:${programId}`);
+ }
+}
+
+export const partnerstackImporter = new PartnerStackImporter();
diff --git a/apps/web/lib/partnerstack/types.ts b/apps/web/lib/partnerstack/types.ts
index e69de29bb2..83bc015500 100644
--- a/apps/web/lib/partnerstack/types.ts
+++ b/apps/web/lib/partnerstack/types.ts
@@ -0,0 +1,53 @@
+import { z } from "zod";
+
+export interface PartnerStackConfig {
+ token: string;
+ userId: string;
+ partnerstackProgramId: string;
+}
+
+export interface PartnerStackListResponse<T> {
+ success: true;
+ total_count: number;
+ data: T[];
+}
+
+// Basic types - these will be expanded as we implement the API
+export interface PartnerStackAffiliate {
+ id: string;
+ email: string;
+ first_name: string;
+ last_name: string;
+ company_name?: string;
+ country_code?: string;
+ profile_type?: string;
+ created_at: string;
+}
+
+export interface PartnerStackLink {
+ id: string;
+ tracking_url: string;
+ token: string;
+ partner_id: string;
+ created_at: string;
+}
+
+export interface PartnerStackReferral {
+ id: string;
+ email: string;
+ first_name: string;
+ last_name: string;
+ company_name?: string;
+ partner_id: string;
+ created_at: string;
+}
+
+export interface PartnerStackCommission {
+ id: string;
+ amount: number;
+ commission_amount: number;
+ status: string;
+ partner_id: string;
+ customer_id: string;
+ created_at: string;
+}
diff --git a/apps/web/ui/modals/import-partnerstack-modal.tsx b/apps/web/ui/modals/import-partnerstack-modal.tsx
new file mode 100644
index 0000000000..5a045475a4
--- /dev/null
+++ b/apps/web/ui/modals/import-partnerstack-modal.tsx
@@ -0,0 +1,231 @@
+import { setPartnerStackTokenAction } from "@/lib/actions/partners/set-partnerstack-token";
+import { startPartnerStackImportAction } from "@/lib/actions/partners/start-partnerstack-import";
+import useWorkspace from "@/lib/swr/use-workspace";
+import { Button, Logo, Modal, useMediaQuery, useRouterStuff } from "@dub/ui";
+import { ArrowRight } from "lucide-react";
+import { useAction } from "next-safe-action/hooks";
+import { useRouter, useSearchParams } from "next/navigation";
+import {
+ Dispatch,
+ SetStateAction,
+ useCallback,
+ useEffect,
+ useState,
+} from "react";
+import { toast } from "sonner";
+
+function ImportPartnerStackModal({
+ showImportPartnerStackModal,
+ setShowImportPartnerStackModal,
+}: {
+ showImportPartnerStackModal: boolean;
+ setShowImportPartnerStackModal: Dispatch<SetStateAction<boolean>>;
+}) {
+ const searchParams = useSearchParams();
+ const { queryParams } = useRouterStuff();
+
+ useEffect(() => {
+ if (searchParams?.get("import") === "partnerstack") {
+ setShowImportPartnerStackModal(true);
+ } else {
+ setShowImportPartnerStackModal(false);
+ }
+ }, [searchParams]);
+
+ return (
+ <Modal
+ showModal={showImportPartnerStackModal}
+ setShowModal={setShowImportPartnerStackModal}
+ onClose={() =>
+ queryParams({
+ del: "import",
+ })
+ }
+ >
+ <div className="flex flex-col items-center justify-center space-y-3 border-b border-neutral-200 px-4 py-8 sm:px-16">
+ <div className="flex items-center space-x-3 py-4">
+ <img
+ src="https://assets.dub.co/misc/icons/partnerstack.svg"
+ alt="PartnerStack logo"
+ className="h-10 w-10 rounded-full"
+ />
+ <ArrowRight className="h-5 w-5 text-neutral-600" />
+ <Logo />
+ </div>
+ <h3 className="text-lg font-medium">Import Your PartnerStack Program</h3>
+ <p className="text-center text-sm text-neutral-500">
+ Import your existing PartnerStack program into{" "}
+ {process.env.NEXT_PUBLIC_APP_NAME} with just a few clicks.
+ </p>
+ </div>
+
+ <div className="flex flex-col space-y-6 bg-neutral-50 px-4 py-8 text-left sm:px-16">
+ <TokenForm
+ onClose={() => {
+ setShowImportPartnerStackModal(false);
+ queryParams({
+ del: "import",
+ });
+ }}
+ />
+ </div>
+ </Modal>
+ );
+}
+
+function TokenForm({
+ onClose,
+}: {
+ onClose: () => void;
+}) {
+ const { isMobile } = useMediaQuery();
+ const router = useRouter();
+ const { id: workspaceId, slug } = useWorkspace();
+
+ const [token, setToken] = useState("");
+ const [programId, setProgramId] = useState("");
+
+ const { executeAsync: setTokenAsync, isPending: isSettingToken } = useAction(
+ setPartnerStackTokenAction,
+ {
+ onError: ({ error }) => {
+ toast.error(error.serverError);
+ },
+ },
+ );
+
+ const { executeAsync: startImportAsync, isPending: isStartingImport } =
+ useAction(startPartnerStackImportAction, {
+ onSuccess: () => {
+ onClose();
+ toast.success(
+ "Successfully added program to import queue! We will send you an email when your program has been fully imported.",
+ );
+ router.push(`/${slug}/program/partners`);
+ },
+ onError: ({ error }) => {
+ toast.error(error.serverError);
+ },
+ });
+
+ const onSubmit = async (e: React.FormEvent) => {
+ e.preventDefault();
+
+ if (!workspaceId || !token || !programId) {
+ return;
+ }
+
+ try {
+ // First set the token
+ await setTokenAsync({
+ workspaceId,
+ partnerstackProgramId: programId,
+ token,
+ });
+
+ // Then start the import
+ await startImportAsync({
+ workspaceId,
+ });
+ } catch (error) {
+ // Error handling is done in the action callbacks
+ console.error("Import error:", error);
+ }
+ };
+
+ const isLoading = isSettingToken || isStartingImport;
+
+ return (
+ <form onSubmit={onSubmit} className="flex flex-col space-y-4">
+ <div>
+ <label
+ htmlFor="token"
+ className="block text-sm font-medium text-neutral-700"
+ >
+ PartnerStack API Key
+ </label>
+ <input
+ type="password"
+ id="token"
+ value={token}
+ autoFocus={!isMobile}
+ onChange={(e) => setToken(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"
+ target="_blank"
+ rel="noopener noreferrer"
+ className="text-blue-500 hover:text-blue-600"
+ >
+ API settings
+ </a>
+ </p>
+ </div>
+
+ <div>
+ <label
+ htmlFor="programId"
+ className="block text-sm font-medium text-neutral-700"
+ >
+ PartnerStack Program ID
+ </label>
+ <input
+ type="text"
+ id="programId"
+ value={programId}
+ onChange={(e) => setProgramId(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 program ID in your{" "}
+ <a
+ href="https://app.partnerstack.com/programs"
+ target="_blank"
+ rel="noopener noreferrer"
+ className="text-blue-500 hover:text-blue-600"
+ >
+ Programs page
+ </a>
+ </p>
+ </div>
+
+ <Button
+ text={
+ isLoading
+ ? isSettingToken
+ ? "Validating credentials..."
+ : "Starting import..."
+ : "Start Import"
+ }
+ loading={isLoading}
+ disabled={!token || !programId || isLoading}
+ />
+ </form>
+ );
+}
+
+export function useImportPartnerStackModal() {
+ const [showImportPartnerStackModal, setShowImportPartnerStackModal] =
+ useState(false);
+
+ const ImportPartnerStackModalCallback = useCallback(
+ () => (
+ <ImportPartnerStackModal
+ showImportPartnerStackModal={showImportPartnerStackModal}
+ setShowImportPartnerStackModal={setShowImportPartnerStackModal}
+ />
+ ),
+ [showImportPartnerStackModal],
+ );
+
+ return {
+ showImportPartnerStackModal,
+ setShowImportPartnerStackModal,
+ ImportPartnerStackModal: ImportPartnerStackModalCallback,
+ };
+}
\ No newline at end of file
diff --git a/apps/web/ui/modals/modal-provider.tsx b/apps/web/ui/modals/modal-provider.tsx
index 3558d0e7b2..9af6053697 100644
--- a/apps/web/ui/modals/modal-provider.tsx
+++ b/apps/web/ui/modals/modal-provider.tsx
@@ -26,6 +26,7 @@ import {
import { toast } from "sonner";
import { useAddEditTagModal } from "./add-edit-tag-modal";
import { useImportRebrandlyModal } from "./import-rebrandly-modal";
+import { useImportPartnerStackModal } from "./import-partnerstack-modal";
import { useImportRewardfulModal } from "./import-rewardful-modal";
import { useImportToltModal } from "./import-tolt-modal";
import { useLinkBuilder } from "./link-builder";
@@ -42,6 +43,7 @@ export const ModalContext = createContext<{
setShowImportShortModal: Dispatch<SetStateAction<boolean>>;
setShowImportRebrandlyModal: Dispatch<SetStateAction<boolean>>;
setShowImportCsvModal: Dispatch<SetStateAction<boolean>>;
+ setShowImportPartnerStackModal: Dispatch<SetStateAction<boolean>>;
setShowImportRewardfulModal: Dispatch<SetStateAction<boolean>>;
setShowImportToltModal: Dispatch<SetStateAction<boolean>>;
}>({
@@ -53,6 +55,7 @@ export const ModalContext = createContext<{
setShowImportShortModal: () => {},
setShowImportRebrandlyModal: () => {},
setShowImportCsvModal: () => {},
+ setShowImportPartnerStackModal: () => {},
setShowImportRewardfulModal: () => {},
setShowImportToltModal: () => {},
});
@@ -106,6 +109,8 @@ function ModalProviderClient({ children }: { children: ReactNode }) {
const { setShowUpgradedModal, UpgradedModal } = useUpgradedModal();
const { setShowProgramWelcomeModal, ProgramWelcomeModal } =
useProgramWelcomeModal();
+ const { setShowImportPartnerStackModal, ImportPartnerStackModal } =
+ useImportPartnerStackModal();
const { setShowImportRewardfulModal, ImportRewardfulModal } =
useImportRewardfulModal();
const { setShowImportToltModal, ImportToltModal } = useImportToltModal();
@@ -199,6 +204,7 @@ function ModalProviderClient({ children }: { children: ReactNode }) {
setShowImportShortModal,
setShowImportRebrandlyModal,
setShowImportCsvModal,
+ setShowImportPartnerStackModal,
setShowImportRewardfulModal,
setShowImportToltModal,
}}
@@ -212,6 +218,7 @@ function ModalProviderClient({ children }: { children: ReactNode }) {
<ImportShortModal />
<ImportRebrandlyModal />
<ImportCsvModal />
+ <ImportPartnerStackModal />
<ImportRewardfulModal />
<ImportToltModal />
<WelcomeModal />