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.

update the settings values

Kiran Kcaeab3f742a3
diff --git a/apps/web/app/api/workspaces/[idOrSlug]/notification-preferences/route.ts b/apps/web/app/api/workspaces/[idOrSlug]/notification-preferences/route.ts
new file mode 100644
index 0000000000..53f3314a94
--- /dev/null
+++ b/apps/web/app/api/workspaces/[idOrSlug]/notification-preferences/route.ts
@@ -0,0 +1,21 @@
+import { withWorkspace } from "@/lib/auth";
+import { prisma } from "@/lib/prisma";
+import { NextResponse } from "next/server";
+
+// GET /api/workspaces/[idOrSlug]/notification-preferences – get notification preferences for a workspace for the current user
+export const GET = withWorkspace(async ({ workspace, session }) => {
+ const response = await prisma.notificationPreference.findFirstOrThrow({
+ select: {
+ domainConfigurationWarnings: true,
+ linkUsageSummary: true,
+ },
+ where: {
+ projectUser: {
+ userId: session.user.id,
+ projectId: workspace.id,
+ },
+ },
+ });
+
+ return NextResponse.json(response);
+});
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/settings/notifications/preferences.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/settings/notifications/preferences.tsx
index bb2b89b80d..d6dbf91b76 100644
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/settings/notifications/preferences.tsx
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/settings/notifications/preferences.tsx
@@ -1,15 +1,44 @@
-const preferences = [
+"use client";
+
+import { updateNotificationPreference } from "@/lib/actions/update-notification-preference";
+import useWorkspace from "@/lib/swr/use-workspace";
+import { LoadingSpinner } from "@dub/ui/src/icons";
+import { fetcher } from "@dub/utils";
+import { useAction } from "next-safe-action/hooks";
+import { toast } from "sonner";
+import useSWR from "swr";
+
+const notifications = [
{
- key: "links_usage_summary",
- title: "Monthly links usage summary",
+ type: "linkUsageSummary",
+ description: "Monthly links usage summary",
},
{
- key: "domain_configuration",
- title: "Domain configuration warnings",
+ type: "domainConfigurationWarnings",
+ description: "Domain configuration warnings",
},
];
+interface PreferenceProps {
+ type: string;
+ description: string;
+ enabled: boolean;
+ onChange: (value: boolean) => void;
+}
+
export const NotificationPreferences = () => {
+ const { id: workspaceId } = useWorkspace();
+ const { executeAsync } = useAction(updateNotificationPreference);
+
+ const {
+ data: preferences,
+ isLoading,
+ mutate,
+ } = useSWR<{
+ linkUsageSummary: boolean;
+ domainConfigurationWarnings: boolean;
+ }>(`/api/workspaces/${workspaceId}/notification-preferences`, fetcher);
+
return (
<>
<div className="rounded-lg border border-gray-200 bg-white">
@@ -23,22 +52,56 @@ export const NotificationPreferences = () => {
</div>
</div>
- <div className="flex flex-col gap-2 p-5 sm:p-10">
- {preferences.map((preference) => (
- <Preference key={preference.key} title={preference.title} />
- ))}
+ <div className="flex flex-col gap-3 p-5 sm:p-10">
+ {isLoading ? (
+ <LoadingSpinner />
+ ) : (
+ notifications.map((notification) => (
+ <Preference
+ {...notification}
+ enabled={preferences ? preferences[notification.type] : false}
+ key={notification.type}
+ onChange={async (value) => {
+ if (!workspaceId) return;
+
+ const response = await executeAsync({
+ workspaceId,
+ type: notification.type as any,
+ value,
+ });
+
+ if (response?.data) {
+ mutate();
+ toast.success("Notification preference saved.");
+ } else {
+ toast.error(response?.serverError?.serverError);
+ }
+ }}
+ />
+ ))
+ )}
</div>
</div>
</>
);
};
-const Preference = ({ key, title }: { key: string; title: string }) => {
+const Preference = ({
+ type,
+ description,
+ enabled,
+ onChange,
+}: PreferenceProps) => {
return (
- <div key={key}>
- <label className="flex items-center text-gray-700 font-medium">
- <input type="checkbox" />
- <span className="ml-2 text-sm">{title}</span>
+ <div key={type}>
+ <label className="flex items-center font-medium text-gray-700">
+ <input
+ type="checkbox"
+ className="h-4 w-4 border-gray-300 text-black focus:outline-none focus:ring-0"
+ onChange={(e) => onChange(e.target.checked)}
+ checked={enabled}
+ />
+ <span className="ml-2 text-sm text-gray-500">{description}</span>
</label>
</div>
);
diff --git a/apps/web/lib/actions/safe-action.ts b/apps/web/lib/actions/safe-action.ts
new file mode 100644
index 0000000000..07fd3f490e
--- /dev/null
+++ b/apps/web/lib/actions/safe-action.ts
@@ -0,0 +1,63 @@
+import { createSafeActionClient } from "next-safe-action";
+import { getSession } from "../auth";
+import { prisma } from "../prisma";
+
+export const actionClient = createSafeActionClient({
+ handleReturnedServerError: (e) => {
+ if (e instanceof Error) {
+ return {
+ serverError: e.message,
+ };
+ }
+
+ return {
+ serverError: "An unknown error occurred.",
+ };
+ },
+});
+
+export const authActionClient = actionClient.use(
+ async ({ next, clientInput }) => {
+ const session = await getSession();
+
+ if (!session?.user.id) {
+ throw new Error("Unauthorized: Login required.");
+ }
+
+ // @ts-ignore
+ let workspaceId = clientInput?.workspaceId;
+
+ if (!workspaceId) {
+ throw new Error("WorkspaceId is required.");
+ }
+
+ workspaceId = workspaceId.replace("ws_", "");
+
+ const workspace = await prisma.project.findUnique({
+ where: {
+ id: workspaceId,
+ },
+ include: {
+ users: {
+ where: {
+ userId: session.user.id,
+ },
+ select: {
+ role: true,
+ },
+ },
+ },
+ });
+
+ if (!workspace || !workspace.users) {
+ throw new Error("Workspace not found.");
+ }
+
+ return next({
+ ctx: {
+ user: session.user,
+ workspace,
+ },
+ });
+ },
+);
diff --git a/apps/web/lib/actions/update-notification-preference.ts b/apps/web/lib/actions/update-notification-preference.ts
new file mode 100644
index 0000000000..fc6b2fb98d
--- /dev/null
+++ b/apps/web/lib/actions/update-notification-preference.ts
@@ -0,0 +1,36 @@
+"use server";
+
+import { prisma } from "@/lib/prisma";
+import z from "../zod";
+import { authActionClient } from "./safe-action";
+
+const schema = z.object({
+ workspaceId: z.string(),
+ type: z.enum(["linkUsageSummary", "domainConfigurationWarnings"]),
+ value: z.boolean(),
+});
+
+export const updateNotificationPreference = authActionClient
+ .schema(schema)
+ .action(async ({ ctx, parsedInput }) => {
+ const { user, workspace } = ctx;
+ const { type, value } = parsedInput;
+
+ await prisma.projectUsers.update({
+ where: {
+ userId_projectId: {
+ userId: user.id,
+ projectId: workspace.id,
+ },
+ },
+ data: {
+ notificationPreference: {
+ update: {
+ [type]: value,
+ },
+ },
+ },
+ });
+
+ return { ok: true };
+ });
diff --git a/apps/web/package.json b/apps/web/package.json
index b8485577b6..8252d5a4f0 100644
--- a/apps/web/package.json
+++ b/apps/web/package.json
@@ -74,6 +74,7 @@
"nanoid": "^5.0.1",
"next": "14.3.0-canary.42",
"next-auth": "^4.24.4",
+ "next-safe-action": "7.1.4-experimental.1",
"node-html-parser": "^6.1.4",
"nodemailer": "^6.9.3",
"openapi-types": "^12.1.3",
@@ -128,7 +129,7 @@
"tailwindcss": "^3.4.4",
"tsx": "^3.14.0",
"turbo": "^1.10.14",
- "typescript": "^5.1.6",
+ "typescript": "^5.4.4",
"vite": "5.2.9",
"vite-tsconfig-paths": "^4.3.2",
"vitest": "1.5.0"
diff --git a/apps/web/prisma/schema/workspace.prisma b/apps/web/prisma/schema/workspace.prisma
index 89f54f95a3..6de9a0954d 100644
--- a/apps/web/prisma/schema/workspace.prisma
+++ b/apps/web/prisma/schema/workspace.prisma
@@ -24,16 +24,15 @@ model Project {
updatedAt DateTime @updatedAt
usageLastChecked DateTime @default(now())
- users ProjectUsers[]
- invites ProjectInvite[]
- sentEmails SentEmail[]
- links Link[]
- domains Domain[]
- tags Tag[]
- customers Customer[]
- defaultDomains DefaultDomains[]
- restrictedTokens RestrictedToken[]
- NotificationPreference NotificationPreference[]
+ users ProjectUsers[]
+ invites ProjectInvite[]
+ sentEmails SentEmail[]
+ links Link[]
+ domains Domain[]
+ tags Tag[]
+ customers Customer[]
+ defaultDomains DefaultDomains[]
+ restrictedTokens RestrictedToken[]
@@index(usageLastChecked(sort: Asc))
}
@@ -55,14 +54,15 @@ enum Role {
}
model ProjectUsers {
- id String @id @default(cuid())
- role Role @default(member)
- createdAt DateTime @default(now())
- updatedAt DateTime @updatedAt
- user User @relation(fields: [userId], references: [id], onDelete: Cascade)
- userId String
- project Project @relation(fields: [projectId], references: [id], onDelete: Cascade)
- projectId String
+ id String @id @default(cuid())
+ role Role @default(member)
+ createdAt DateTime @default(now())
+ updatedAt DateTime @updatedAt
+ user User @relation(fields: [userId], references: [id], onDelete: Cascade)
+ userId String
+ project Project @relation(fields: [projectId], references: [id], onDelete: Cascade)
+ projectId String
+ notificationPreference NotificationPreference?
@@unique([userId, projectId])
@@index([projectId])
@@ -80,13 +80,9 @@ model SentEmail {
model NotificationPreference {
id String @id @default(cuid())
- userId String
- projectId String
+ projectUserId String @unique
linkUsageSummary Boolean @default(true)
domainConfigurationWarnings Boolean @default(true)
- user User @relation(fields: [userId], references: [id], onDelete: Cascade)
- project Project @relation(fields: [projectId], references: [id], onDelete: Cascade)
-
- @@unique([userId, projectId])
+ projectUser ProjectUsers @relation(fields: [projectUserId], references: [id], onDelete: Cascade)
}
diff --git a/apps/web/scripts/update-notifications-preferences.ts b/apps/web/scripts/update-notifications-preferences.ts
new file mode 100644
index 0000000000..deedd7d8d3
--- /dev/null
+++ b/apps/web/scripts/update-notifications-preferences.ts
@@ -0,0 +1,38 @@
+import { prisma } from "@/lib/prisma";
+
+import "dotenv-flow/config";
+
+async function main() {
+ const workspaceUsers = await prisma.projectUsers.findMany({
+ where: {
+ user: {
+ isMachine: false,
+ },
+ },
+ select: {
+ id: true,
+ },
+ take: 500,
+ skip: 0,
+ });
+
+ if (!workspaceUsers) {
+ return;
+ }
+
+ const result = await prisma.notificationPreference.createMany({
+ data: workspaceUsers.map((workspaceUser) => {
+ return {
+ projectUserId: workspaceUser.id,
+ };
+ }),
+ });
+
+ console.log(
+ "Created notification preferences for",
+ result.count,
+ "workspace users",
+ );
+}
+
+main();
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index e78019eeda..743c021497 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -19,7 +19,7 @@ importers:
version: 3.2.5
prettier-plugin-organize-imports:
specifier: ^3.2.4
prettier-plugin-tailwindcss:
specifier: ^0.6.0
@@ -218,6 +218,9 @@ importers:
next-auth:
specifier: ^4.24.4
+ next-safe-action:
+ specifier: 7.1.4-experimental.1
node-html-parser:
specifier: ^6.1.4
version: 6.1.4
@@ -376,14 +379,14 @@ importers:
specifier: ^1.10.14
version: 1.10.14
typescript:
- specifier: ^5.1.6
- version: 5.1.6
+ specifier: ^5.4.4
+ version: 5.4.4
vite:
specifier: 5.2.9
version: 5.2.9(@types/[email protected])
vite-tsconfig-paths:
specifier: ^4.3.2
vitest:
specifier: 1.5.0
version: 1.5.0(@types/[email protected])
@@ -8801,7 +8804,7 @@ packages:
dependencies:
'@vue/compiler-ssr': 3.4.21
'@vue/shared': 3.4.21
- vue: 3.4.21([email protected])
+ vue: 3.4.21([email protected])
dev: false
@@ -9068,7 +9071,7 @@ packages:
swr: 2.2.0([email protected])
swr-store: 0.10.6
swrv: 1.0.4([email protected])
- vue: 3.4.21([email protected])
+ vue: 3.4.21([email protected])
zod: 3.22.4
zod-to-json-schema: 3.22.5([email protected])
dev: false
@@ -15230,6 +15233,21 @@ packages:
uuid: 8.3.2
dev: false
+ resolution: {integrity: sha512-6BihKPIJ/Wu7qgEGUKAUJfy5NTPO2eV1BJ/7WWpgMarHzm+6/OUkllwwndAw85YLy+khVmzHYkSCS+n0Ei7qMg==}
+ engines: {node: '>=18.17'}
+ peerDependencies:
+ next: '>= 14.0.0'
+ react: '>= 18.2.0'
+ react-dom: '>= 18.2.0'
+ zod: '>= 3.0.0'
+ dependencies:
+ next: 14.3.0-canary.42(@babel/[email protected])(@opentelemetry/[email protected])([email protected])([email protected])
+ react: 18.2.0
+ react-dom: 18.2.0([email protected])
+ zod: 3.22.4
+ dev: false
+
resolution: {integrity: sha512-u8yiAK7L+fl/U9yFmq3VOpkHlImx5wg3OoDz3qxTXhPmmMzNcPbblWgxBf5d6Z+aik8BEn27L31k/tXCRzwFxA==}
engines: {node: '>=18.17.0'}
@@ -16135,7 +16153,7 @@ packages:
resolution: {integrity: sha512-vkcDPrRZo1QZLbn5RLGPpg/WmIQ65qoWWhcGKf/b5eplkkarX0m9z8ppCat4mlOqUsWpyNuYgO3VRyrYHSzX5g==}
engines: {node: '>= 0.8.0'}
resolution: {integrity: sha512-6m8WBhIp0dfwu0SkgfOxJqh+HpdyfqSSLfKKRZSFbDuEQXDDndb8fTpRWkUrX/uBenkex3MgnVk0J3b3Y5byog==}
peerDependencies:
'@volar/vue-language-plugin-pug': ^1.0.4
@@ -16149,7 +16167,7 @@ packages:
optional: true
dependencies:
prettier: 3.2.5
- typescript: 5.2.2
+ typescript: 5.5.3
dev: true
@@ -16205,7 +16223,7 @@ packages:
optional: true
dependencies:
prettier: 3.2.5
- prettier-plugin-organize-imports: 3.2.4([email protected])([email protected])
+ prettier-plugin-organize-imports: 3.2.4([email protected])([email protected])
dev: true
@@ -18192,7 +18210,7 @@ packages:
peerDependencies:
vue: '>=3.2.26 < 4'
dependencies:
- vue: 3.4.21([email protected])
+ vue: 3.4.21([email protected])
dev: false
@@ -18543,7 +18561,7 @@ packages:
yargs-parser: 20.2.9
dev: true
resolution: {integrity: sha512-4t0noZX9t6GcPTfBAbIbbIU4pfpCwh0ueq3S4O/5qXI1VwK1outmxhe9dOiEWqMz3MW2LKgDTpqWV+37IWuVbA==}
engines: {node: ^18 || >=20}
hasBin: true
@@ -18553,7 +18571,7 @@ packages:
typescript:
optional: true
dependencies:
- typescript: 5.1.6
+ typescript: 5.4.4
dev: true
@@ -18961,8 +18979,13 @@ packages:
engines: {node: '>=14.17'}
hasBin: true
- resolution: {integrity: sha512-mI4WrpHsbCIcwT9cF4FZvr80QUeKvsUsUvKDoR+X/7XHQH98xYD8YHZg7ANtz2GtZt/CBq2QJ0thkGJMHfqc1w==}
+ resolution: {integrity: sha512-dGE2Vv8cpVvw28v8HCPqyb08EzbBURxDpuhJvTrusShUfGnhHBafDsLdS1EhhxyL6BJQE+2cT3dDPAv+MQ6oLw==}
+ engines: {node: '>=14.17'}
+ hasBin: true
+
+ resolution: {integrity: sha512-/hreyEujaB0w76zKo6717l3L0o/qEUtRgdvUBvlkhoWeOVMjMuHNHk0BRBzikzuGDqNmPQbg5ifMEqsHLiIUcQ==}
engines: {node: '>=14.17'}
hasBin: true
dev: true
@@ -19314,7 +19337,7 @@ packages:
- terser
dev: true
resolution: {integrity: sha512-0Vd/a6po6Q+86rPlntHye7F31zA2URZMbH8M3saAZ/xR9QoGN/L21bxEGfXdWmFdNkqPpRdxFT7nmNe12e9/uA==}
peerDependencies:
vite: '*'
@@ -19324,7 +19347,7 @@ packages:
dependencies:
debug: 4.3.4
globrex: 0.1.2
- tsconfck: 3.0.3([email protected])
+ tsconfck: 3.0.3([email protected])
vite: 5.2.9(@types/[email protected])
transitivePeerDependencies:
- supports-color
@@ -19435,7 +19458,7 @@ packages:
resolution: {integrity: sha512-AFbieoL7a5LMqcnOF04ji+rpXadgOXnZsxQr//r83kLPr7biP7am3g9zbaZIaBGwBRWeSvoMD4mgPdX3e4NWBg==}
dev: false
resolution: {integrity: sha512-5hjyV/jLEIKD/jYl4cavMcnzKwjMKohureP8ejn3hhEjwhWIhWeuzL2kJAjzl/WyVsgPY56Sy4Z40C3lVshxXA==}
peerDependencies:
typescript: '*'
@@ -19448,7 +19471,7 @@ packages:
'@vue/runtime-dom': 3.4.21
'@vue/server-renderer': 3.4.21([email protected])
'@vue/shared': 3.4.21
- typescript: 5.1.6
+ typescript: 5.4.4
dev: false