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.

Integrate Flodesk for marketing emails

Steven Teye1189087c53e
diff --git a/apps/web/app/admin.dub.co/actions.ts b/apps/web/app/admin.dub.co/actions.ts
index eefc01b6bf..30f29c178d 100644
--- a/apps/web/app/admin.dub.co/actions.ts
+++ b/apps/web/app/admin.dub.co/actions.ts
@@ -2,6 +2,7 @@
import { deleteProject } from "@/lib/api/projects";
import { getSession, hashToken } from "@/lib/auth";
+import { unsubscribe } from "@/lib/flodesk";
import prisma from "@/lib/prisma";
import { DUB_DOMAINS, DUB_PROJECT_ID } from "@dub/utils";
import { get } from "@vercel/edge-config";
@@ -164,7 +165,7 @@ export async function banUser(data: FormData) {
},
});
- if (!user) {
+ if (!user?.email) {
return {
error: "No user found",
};
@@ -192,6 +193,7 @@ export async function banUser(data: FormData) {
cloudinary.v2.uploader.destroy(`avatars/${user.id}`, {
invalidate: true,
}),
+ unsubscribe(user.email),
fetch(
`https://api.vercel.com/v1/edge-config/${process.env.EDGE_CONFIG_ID}/items?teamId=${process.env.TEAM_ID_VERCEL}`,
{
diff --git a/apps/web/app/api/user/route.ts b/apps/web/app/api/user/route.ts
index b965f45474..06a55b0620 100644
--- a/apps/web/app/api/user/route.ts
+++ b/apps/web/app/api/user/route.ts
@@ -1,4 +1,5 @@
import { withSession } from "@/lib/auth";
+import { unsubscribe } from "@/lib/flodesk";
import prisma from "@/lib/prisma";
import { redis } from "@/lib/upstash";
import cloudinary from "cloudinary";
@@ -77,6 +78,7 @@ export const DELETE = withSession(async ({ session }) => {
cloudinary.v2.uploader.destroy(`avatars/${session?.user?.id}`, {
invalidate: true,
}),
+ unsubscribe(session.user.email),
]);
return NextResponse.json(response);
}
diff --git a/apps/web/app/api/user/subscribe/route.ts b/apps/web/app/api/user/subscribe/route.ts
index 039f72e255..a2967e256f 100644
--- a/apps/web/app/api/user/subscribe/route.ts
+++ b/apps/web/app/api/user/subscribe/route.ts
@@ -1,4 +1,5 @@
import { withSession } from "@/lib/auth";
+import { subscribe, unsubscribe } from "@/lib/flodesk";
import prisma from "@/lib/prisma";
import { NextResponse } from "next/server";
@@ -23,40 +24,48 @@ export const GET = withSession(async ({ session }) => {
return NextResponse.json(user);
});
-// POST /api/user/subscribe – subscribe a specific user
+// POST /api/user/subscribe – subscribe a specific user
export const POST = withSession(async ({ session }) => {
- const user = await prisma.user.update({
- where: {
- id: session.user.id,
- },
- data: {
- subscribed: true,
- },
- select: {
- id: true,
- name: true,
- email: true,
- subscribed: true,
- },
- });
+ const [user, _] = await Promise.all([
+ prisma.user.update({
+ where: {
+ id: session.user.id,
+ },
+ data: {
+ subscribed: true,
+ },
+ select: {
+ id: true,
+ name: true,
+ email: true,
+ subscribed: true,
+ },
+ }),
+ subscribe({ email: session.user.email, name: session.user.name }),
+ ]);
+
return NextResponse.json(user);
});
// DELETE /api/user/subscribe – unsubscribe a specific user
export const DELETE = withSession(async ({ session }) => {
- const user = await prisma.user.update({
- where: {
- id: session.user.id,
- },
- data: {
- subscribed: false,
- },
- select: {
- id: true,
- name: true,
- email: true,
- subscribed: true,
- },
- });
+ const [user, _] = await Promise.all([
+ prisma.user.update({
+ where: {
+ id: session.user.id,
+ },
+ data: {
+ subscribed: false,
+ },
+ select: {
+ id: true,
+ name: true,
+ email: true,
+ subscribed: true,
+ },
+ }),
+ unsubscribe(session.user.email),
+ ]);
+
return NextResponse.json(user);
});
diff --git a/apps/web/app/app.dub.co/(auth)/settings/unsubscribe/form.tsx b/apps/web/app/app.dub.co/(auth)/settings/unsubscribe/form.tsx
index ec84c09c59..79e92cd72c 100644
--- a/apps/web/app/app.dub.co/(auth)/settings/unsubscribe/form.tsx
+++ b/apps/web/app/app.dub.co/(auth)/settings/unsubscribe/form.tsx
@@ -4,6 +4,7 @@ import { LoadingSpinner, Logo } from "@dub/ui";
import { APP_NAME, HOME_DOMAIN } from "@dub/utils";
import Link from "next/link";
import { useEffect, useState } from "react";
+import { toast } from "sonner";
export default function UnsubscribeForm() {
const [unsubscribing, setUnsubscribing] = useState(true);
@@ -11,7 +12,12 @@ export default function UnsubscribeForm() {
useEffect(() => {
fetch("/api/user/subscribe", {
method: "DELETE",
- }).then(() => setUnsubscribing(false));
+ }).then(() => {
+ setUnsubscribing(false);
+ toast.success(
+ `You have been unsubscribed from all ${APP_NAME} marketing emails`,
+ );
+ });
}, []);
return (
diff --git a/apps/web/app/app.dub.co/(dashboard)/settings/page-client.tsx b/apps/web/app/app.dub.co/(dashboard)/settings/page-client.tsx
index 977bf991f8..96ae949b56 100644
--- a/apps/web/app/app.dub.co/(dashboard)/settings/page-client.tsx
+++ b/apps/web/app/app.dub.co/(dashboard)/settings/page-client.tsx
@@ -3,6 +3,7 @@
import DeleteAccountSection from "@/ui/account/delete-account";
import UploadAvatar from "@/ui/account/upload-avatar";
import { Form } from "@dub/ui";
+import { APP_NAME } from "@dub/utils";
import { useSession } from "next-auth/react";
import { toast } from "sonner";
@@ -13,7 +14,7 @@ export default function SettingsPageClient() {
<>
<Form
title="Your Name"
- description={`This will be your display name on ${process.env.NEXT_PUBLIC_APP_NAME}.`}
+ description={`This will be your display name on ${APP_NAME}.`}
inputAttrs={{
name: "name",
defaultValue:
@@ -42,13 +43,14 @@ export default function SettingsPageClient() {
/>
<Form
title="Your Email"
- description={`This will be the email you use to log in to ${process.env.NEXT_PUBLIC_APP_NAME} and receive notifications.`}
+ description={`This will be the email you use to log in to ${APP_NAME} and receive notifications.`}
inputAttrs={{
name: "email",
defaultValue: session?.user?.email || undefined,
placeholder: "[email protected]",
}}
helpText="Must be a valid email address."
+ // helpText={<UpdateSubscription />} TODO: enable this once we can subscribe folks programmatically
handleSubmit={(data) =>
fetch("/api/user", {
method: "PUT",
diff --git a/apps/web/lib/auth/options.ts b/apps/web/lib/auth/options.ts
index 91fe081c4d..76c0d32da0 100644
--- a/apps/web/lib/auth/options.ts
+++ b/apps/web/lib/auth/options.ts
@@ -10,6 +10,7 @@ import CredentialsProvider from "next-auth/providers/credentials";
import EmailProvider from "next-auth/providers/email";
import GithubProvider from "next-auth/providers/github";
import GoogleProvider from "next-auth/providers/google";
+import { subscribe } from "../flodesk";
const VERCEL_DEPLOYMENT = !!process.env.VERCEL_URL;
@@ -327,15 +328,18 @@ export const authOptions: NextAuthOptions = {
new Date(user.createdAt).getTime() > Date.now() - 10000 &&
process.env.NEXT_PUBLIC_IS_DUB
) {
- await sendEmail({
- subject: "Welcome to Dub.co!",
- email,
- react: WelcomeEmail({
+ await Promise.allSettled([
+ subscribe({ email, name: user.name || undefined }),
+ sendEmail({
+ subject: "Welcome to Dub.co!",
email,
- name: user.name || null,
+ react: WelcomeEmail({
+ email,
+ name: user.name || null,
+ }),
+ marketing: true,
}),
- marketing: true,
- });
+ ]);
}
}
},
diff --git a/apps/web/lib/flodesk.ts b/apps/web/lib/flodesk.ts
new file mode 100644
index 0000000000..8701aac897
--- /dev/null
+++ b/apps/web/lib/flodesk.ts
@@ -0,0 +1,33 @@
+export async function subscribe({
+ email,
+ name,
+}: {
+ email: string;
+ name?: string | null;
+}) {
+ return fetch("https://api.flodesk.com/v1/subscribers", {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ Authorization: `Basic ${process.env.FLODESK_API_KEY}`,
+ },
+ body: JSON.stringify({
+ email,
+ ...(name && {
+ custom_fields: {
+ name,
+ },
+ }),
+ }),
+ }).then((res) => res.json());
+}
+
+export async function unsubscribe(email: string) {
+ return fetch(`https://api.flodesk.com/v1/subscribers/${email}/unsubscribe`, {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ Authorization: `Basic ${process.env.FLODESK_API_KEY}`,
+ },
+ }).then((res) => res.json());
+}
diff --git a/apps/web/ui/account/update-subscription.tsx b/apps/web/ui/account/update-subscription.tsx
new file mode 100644
index 0000000000..1bb0091c3d
--- /dev/null
+++ b/apps/web/ui/account/update-subscription.tsx
@@ -0,0 +1,36 @@
+import { Switch, useOptimisticUpdate } from "@dub/ui";
+import { APP_NAME } from "@dub/utils";
+
+export default function UpdateSubscription() {
+ const { data, isLoading, update } = useOptimisticUpdate<{
+ subscribed: boolean;
+ }>("/api/user/subscribe", {
+ loading: "Updating email preferences...",
+ success: `Your ${APP_NAME} email preferences has been updated!`,
+ error: "Failed to update email preferences. Please try again.",
+ });
+
+ const subscribe = async (checked: boolean) => {
+ const method = checked ? "POST" : "DELETE";
+ const res = await fetch("/api/user/subscribe", {
+ method,
+ });
+ if (!res.ok) {
+ throw new Error("Failed to update email preferences");
+ }
+ return { subscribed: checked };
+ };
+
+ return (
+ <div className="flex items-center space-x-2">
+ <Switch
+ checked={data?.subscribed}
+ loading={isLoading}
+ fn={(checked: boolean) => {
+ update(() => subscribe(checked), { subscribed: checked });
+ }}
+ />
+ <p className="text-sm text-gray-500">Subscribed to updates</p>
+ </div>
+ );
+}
diff --git a/packages/ui/src/form.tsx b/packages/ui/src/form.tsx
index cf14ecce94..cab114c821 100644
--- a/packages/ui/src/form.tsx
+++ b/packages/ui/src/form.tsx
@@ -14,7 +14,7 @@ export function Form({
title: string;
description: string;
inputAttrs: InputHTMLAttributes<HTMLInputElement>;
- helpText?: string;
+ helpText?: string | ReactNode;
buttonText?: string;
disabledTooltip?: string | ReactNode;
handleSubmit: (data: any) => Promise<any>;
@@ -62,10 +62,14 @@ export function Form({
</div>
<div className="flex items-center justify-between space-x-4 rounded-b-lg border-t border-gray-200 bg-gray-50 p-3 sm:px-10">
- <p
- className="prose-sm prose-a:underline prose-a:underline-offset-4 hover:prose-a:text-gray-700 text-gray-500 transition-colors"
- dangerouslySetInnerHTML={{ __html: helpText || "" }}
- />
+ {typeof helpText === "string" ? (
+ <p
+ className="prose-sm prose-a:underline prose-a:underline-offset-4 hover:prose-a:text-gray-700 text-gray-500 transition-colors"
+ dangerouslySetInnerHTML={{ __html: helpText || "" }}
+ />
+ ) : (
+ helpText
+ )}
<div className="shrink-0">
<Button
text={buttonText}
diff --git a/packages/ui/src/hooks/index.ts b/packages/ui/src/hooks/index.ts
index 6cc0d98efd..208ea50bf9 100644
--- a/packages/ui/src/hooks/index.ts
+++ b/packages/ui/src/hooks/index.ts
@@ -3,6 +3,7 @@ export { default as useCurrentAnchor } from "./use-current-anchor";
export { default as useIntersectionObserver } from "./use-intersection-observer";
export { default as useLocalStorage } from "./use-local-storage";
export { default as useMediaQuery } from "./use-media-query";
+export { default as useOptimisticUpdate } from "./use-optimistic-update";
export { default as useRouterStuff } from "./use-router-stuff";
export { default as useScroll } from "./use-scroll";
export { default as useToastWithUndo } from "./use-toast-with-undo";
diff --git a/packages/ui/src/hooks/use-optimistic-update.ts b/packages/ui/src/hooks/use-optimistic-update.ts
new file mode 100644
index 0000000000..8174167da7
--- /dev/null
+++ b/packages/ui/src/hooks/use-optimistic-update.ts
@@ -0,0 +1,30 @@
+import useSWR from "swr";
+import { fetcher } from "@dub/utils";
+import { toast } from "sonner";
+
+export default function useOptimisticUpdate<T>(
+ url: string,
+ toastCopy?: { loading: string; success: string; error: string },
+) {
+ const { data, isLoading, mutate } = useSWR<T>(url, fetcher);
+
+ return {
+ data,
+ isLoading,
+ update: async (fn: (data: T) => Promise<T>, optimisticData: T) => {
+ return toast.promise(
+ mutate(fn(data as T), {
+ optimisticData,
+ rollbackOnError: true,
+ populateCache: true,
+ revalidate: true,
+ }),
+ {
+ loading: toastCopy?.loading || "Updating...",
+ success: toastCopy?.success || "Successfully updated",
+ error: toastCopy?.error || "Failed to update",
+ },
+ );
+ },
+ };
+}
diff --git a/packages/ui/src/switch.tsx b/packages/ui/src/switch.tsx
index 47e453a2f3..985f9f3075 100644
--- a/packages/ui/src/switch.tsx
+++ b/packages/ui/src/switch.tsx
@@ -11,14 +11,16 @@ export function Switch({
thumbDimensions,
thumbTranslate,
checked = true,
+ loading = false,
disabled = false,
disabledTooltip,
}: {
- fn?: Dispatch<SetStateAction<boolean>> | (() => void);
+ fn?: Dispatch<SetStateAction<boolean>> | ((checked: boolean) => void);
trackDimensions?: string;
thumbDimensions?: string;
thumbTranslate?: string;
checked?: boolean;
+ loading?: boolean;
disabled?: boolean;
disabledTooltip?: string | ReactNode;
}) {
@@ -39,22 +41,26 @@ export function Switch({
{...(fn && { onCheckedChange: fn })}
disabled={disabled}
className={cn(
- disabled
- ? "cursor-not-allowed bg-gray-300"
- : "radix-state-checked:bg-blue-500 radix-state-unchecked:bg-gray-200 cursor-pointer focus:outline-none focus-visible:ring focus-visible:ring-blue-500 focus-visible:ring-opacity-75",
+ loading
+ ? "bg-gray-200"
+ : disabled
+ ? "cursor-not-allowed bg-gray-300"
+ : "radix-state-checked:bg-blue-500 radix-state-unchecked:bg-gray-200 cursor-pointer focus:outline-none focus-visible:ring focus-visible:ring-blue-500 focus-visible:ring-opacity-75",
"relative inline-flex h-4 w-8 flex-shrink-0 rounded-full border-2 border-transparent transition-colors duration-200 ease-in-out",
trackDimensions,
)}
>
- <SwitchPrimitive.Thumb
- className={cn(
- `radix-state-checked:${thumbTranslate}`,
- "radix-state-unchecked:translate-x-0",
- `pointer-events-none h-3 w-3 translate-x-4 transform rounded-full bg-white shadow-lg ring-0 transition duration-200 ease-in-out`,
- thumbDimensions,
- thumbTranslate,
- )}
- />
+ {!loading && (
+ <SwitchPrimitive.Thumb
+ className={cn(
+ `radix-state-checked:${thumbTranslate}`,
+ "radix-state-unchecked:translate-x-0",
+ `pointer-events-none h-3 w-3 translate-x-4 transform rounded-full bg-white shadow-lg ring-0 transition duration-200 ease-in-out`,
+ thumbDimensions,
+ thumbTranslate,
+ )}
+ />
+ )}
</SwitchPrimitive.Root>
);
}