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 edit support for program brand asset resources (#3365)

Marcus Farrell1e2be4725d1c
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/resources/program-brand-assets/add-color-modal.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/resources/program-brand-assets/add-color-modal.tsx
index 2d148c66fc..5fb0a277f6 100644
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/resources/program-brand-assets/add-color-modal.tsx
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/resources/program-brand-assets/add-color-modal.tsx
@@ -1,8 +1,10 @@
"use client";
import { addProgramResourceAction } from "@/lib/actions/partners/program-resources/add-program-resource";
+import { updateProgramResourceAction } from "@/lib/actions/partners/program-resources/update-program-resource";
import useProgramResources from "@/lib/swr/use-program-resources";
import useWorkspace from "@/lib/swr/use-workspace";
+import { ProgramResourceColor } from "@/lib/zod/schemas/program-resources";
import { Button, Modal } from "@dub/ui";
import { cn } from "@dub/utils";
import { useAction } from "next-safe-action/hooks";
@@ -19,9 +21,10 @@ import { useForm } from "react-hook-form";
import { toast } from "sonner";
import * as z from "zod/v4";
-type AddColorModalProps = {
- showAddColorModal: boolean;
- setShowAddColorModal: Dispatch<SetStateAction<boolean>>;
+type ColorModalProps = {
+ showColorModal: boolean;
+ setShowColorModal: Dispatch<SetStateAction<boolean>>;
+ existingResource?: ProgramResourceColor;
};
const colorFormSchema = z.object({
@@ -31,23 +34,30 @@ const colorFormSchema = z.object({
type ColorFormData = z.infer<typeof colorFormSchema>;
-function AddColorModal(props: AddColorModalProps) {
+function ColorModal(props: ColorModalProps) {
return (
<Modal
- showModal={props.showAddColorModal}
- setShowModal={props.setShowAddColorModal}
+ showModal={props.showColorModal}
+ setShowModal={props.setShowColorModal}
>
- <AddColorModalInner {...props} />
+ <ColorModalInner {...props} />
</Modal>
);
}
const DEFAULT_COLORS = ["#dc2626", "#84cc16", "#14b8a6", "#0ea5e9", "#d946ef"];
-function AddColorModalInner({ setShowAddColorModal }: AddColorModalProps) {
+function ColorModalInner({
+ setShowColorModal,
+ existingResource,
+}: ColorModalProps) {
const { id: workspaceId } = useWorkspace();
const { mutate } = useProgramResources();
- const [hexInputValue, setHexInputValue] = useState("#000000");
+ const isEditing = Boolean(existingResource);
+
+ const [hexInputValue, setHexInputValue] = useState(
+ existingResource?.color || "#000000",
+ );
const {
register,
@@ -58,8 +68,10 @@ function AddColorModalInner({ setShowAddColorModal }: AddColorModalProps) {
formState: { errors, isSubmitting, isSubmitSuccessful },
} = useForm<ColorFormData>({
defaultValues: {
- name: "",
- color: DEFAULT_COLORS[Math.floor(Math.random() * DEFAULT_COLORS.length)],
+ name: existingResource?.name || "",
+ color:
+ existingResource?.color ||
+ DEFAULT_COLORS[Math.floor(Math.random() * DEFAULT_COLORS.length)],
},
});
@@ -78,10 +90,10 @@ function AddColorModalInner({ setShowAddColorModal }: AddColorModalProps) {
}
};
- const { executeAsync } = useAction(addProgramResourceAction, {
+ const { executeAsync: executeAdd } = useAction(addProgramResourceAction, {
onSuccess: () => {
mutate();
- setShowAddColorModal(false);
+ setShowColorModal(false);
toast.success("Color added successfully!");
},
onError({ error }) {
@@ -96,20 +108,50 @@ function AddColorModalInner({ setShowAddColorModal }: AddColorModalProps) {
},
});
+ const { executeAsync: executeUpdate } = useAction(updateProgramResourceAction, {
+ onSuccess: () => {
+ mutate();
+ setShowColorModal(false);
+ toast.success("Color updated successfully!");
+ },
+ onError({ error }) {
+ if (error.serverError) {
+ setError("root.serverError", {
+ message: error.serverError,
+ });
+ toast.error(error.serverError);
+ } else {
+ toast.error("Failed to update color");
+ }
+ },
+ });
+
return (
<>
<div className="space-y-2 border-b border-neutral-200 p-4 sm:p-6">
- <h3 className="text-lg font-medium leading-none">Add color</h3>
+ <h3 className="text-lg font-medium leading-none">
+ {isEditing ? "Edit color" : "Add color"}
+ </h3>
</div>
<form
onSubmit={handleSubmit(async (data: ColorFormData) => {
- await executeAsync({
- workspaceId: workspaceId!,
- name: data.name,
- resourceType: "color",
- color: data.color,
- });
+ if (isEditing && existingResource) {
+ await executeUpdate({
+ workspaceId: workspaceId!,
+ resourceId: existingResource.id,
+ resourceType: "color",
+ name: data.name,
+ color: data.color,
+ });
+ } else {
+ await executeAdd({
+ workspaceId: workspaceId!,
+ name: data.name,
+ resourceType: "color",
+ color: data.color,
+ });
+ }
})}
>
<div className="bg-neutral-50 p-4 sm:p-6">
@@ -179,7 +221,7 @@ function AddColorModalInner({ setShowAddColorModal }: AddColorModalProps) {
<div className="flex items-center justify-end gap-2 border-t border-neutral-200 bg-neutral-50 px-4 py-5 sm:px-6">
<Button
- onClick={() => setShowAddColorModal(false)}
+ onClick={() => setShowColorModal(false)}
variant="secondary"
text="Cancel"
className="h-8 w-fit px-3"
@@ -189,7 +231,7 @@ function AddColorModalInner({ setShowAddColorModal }: AddColorModalProps) {
type="submit"
autoFocus
loading={isSubmitting || isSubmitSuccessful}
- text="Add Color"
+ text={isEditing ? "Save Changes" : "Add Color"}
className="h-8 w-fit px-3"
/>
</div>
@@ -198,23 +240,29 @@ function AddColorModalInner({ setShowAddColorModal }: AddColorModalProps) {
);
}
-export function useAddColorModal() {
- const [showAddColorModal, setShowAddColorModal] = useState(false);
+export function useColorModal({
+ existingResource,
+}: { existingResource?: ProgramResourceColor } = {}) {
+ const [showColorModal, setShowColorModal] = useState(false);
- const AddColorModalCallback = useCallback(() => {
+ const ColorModalCallback = useCallback(() => {
return (
- <AddColorModal
- showAddColorModal={showAddColorModal}
- setShowAddColorModal={setShowAddColorModal}
+ <ColorModal
+ showColorModal={showColorModal}
+ setShowColorModal={setShowColorModal}
+ existingResource={existingResource}
/>
);
- }, [showAddColorModal, setShowAddColorModal]);
+ }, [showColorModal, setShowColorModal, existingResource]);
return useMemo(
() => ({
- setShowAddColorModal,
- AddColorModal: AddColorModalCallback,
+ setShowColorModal,
+ ColorModal: ColorModalCallback,
}),
- [setShowAddColorModal, AddColorModalCallback],
+ [setShowColorModal, ColorModalCallback],
);
}
+
+// Keep backwards compatibility alias
+export const useAddColorModal = useColorModal;
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/resources/program-brand-assets/add-file-modal.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/resources/program-brand-assets/add-file-modal.tsx
index a414985cc2..77ace6da69 100644
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/resources/program-brand-assets/add-file-modal.tsx
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/resources/program-brand-assets/add-file-modal.tsx
@@ -1,8 +1,10 @@
"use client";
import { addProgramResourceAction } from "@/lib/actions/partners/program-resources/add-program-resource";
+import { updateProgramResourceAction } from "@/lib/actions/partners/program-resources/update-program-resource";
import useProgramResources from "@/lib/swr/use-program-resources";
import useWorkspace from "@/lib/swr/use-workspace";
+import { ProgramResourceFile } from "@/lib/zod/schemas/program-resources";
import { Button, FileContent, FileUpload, Modal } from "@dub/ui";
import { cn, truncate } from "@dub/utils";
import { useAction } from "next-safe-action/hooks";
@@ -17,34 +19,39 @@ import { Controller, useForm } from "react-hook-form";
import { toast } from "sonner";
import * as z from "zod/v4";
-type AddFileModalProps = {
- showAddFileModal: boolean;
- setShowAddFileModal: Dispatch<SetStateAction<boolean>>;
+type FileModalProps = {
+ showFileModal: boolean;
+ setShowFileModal: Dispatch<SetStateAction<boolean>>;
+ existingResource?: ProgramResourceFile;
};
// Define the form schema
const fileFormSchema = z.object({
name: z.string().min(1, "Name is required"),
- file: z.string().min(1, "File is required"),
+ file: z.string().optional(),
extension: z.string().nullish(),
});
type FileFormData = z.infer<typeof fileFormSchema>;
-function AddFileModal(props: AddFileModalProps) {
+function FileModal(props: FileModalProps) {
return (
<Modal
- showModal={props.showAddFileModal}
- setShowModal={props.setShowAddFileModal}
+ showModal={props.showFileModal}
+ setShowModal={props.setShowFileModal}
>
- <AddFileModalInner {...props} />
+ <FileModalInner {...props} />
</Modal>
);
}
-function AddFileModalInner({ setShowAddFileModal }: AddFileModalProps) {
+function FileModalInner({
+ setShowFileModal,
+ existingResource,
+}: FileModalProps) {
const { id: workspaceId } = useWorkspace();
const { mutate } = useProgramResources();
+ const isEditing = Boolean(existingResource);
const {
register,
@@ -56,17 +63,18 @@ function AddFileModalInner({ setShowAddFileModal }: AddFileModalProps) {
formState: { errors, isSubmitting, isSubmitSuccessful },
} = useForm<FileFormData>({
defaultValues: {
- name: "",
+ name: existingResource?.name || "",
file: "",
},
});
- const [fileName, setFileName] = useState("");
+ const [fileName, setFileName] = useState(existingResource?.name || "");
+ const [hasNewFile, setHasNewFile] = useState(false);
- const { executeAsync } = useAction(addProgramResourceAction, {
+ const { executeAsync: executeAdd } = useAction(addProgramResourceAction, {
onSuccess: () => {
mutate();
- setShowAddFileModal(false);
+ setShowFileModal(false);
toast.success("File added successfully!");
},
onError({ error }) {
@@ -81,21 +89,57 @@ function AddFileModalInner({ setShowAddFileModal }: AddFileModalProps) {
},
});
+ const { executeAsync: executeUpdate } = useAction(updateProgramResourceAction, {
+ onSuccess: () => {
+ mutate();
+ setShowFileModal(false);
+ toast.success("File updated successfully!");
+ },
+ onError({ error }) {
+ if (error.serverError) {
+ setError("root.serverError", {
+ message: error.serverError,
+ });
+ toast.error(error.serverError);
+ } else {
+ toast.error("Failed to update file");
+ }
+ },
+ });
+
return (
<>
<div className="space-y-2 border-b border-neutral-200 p-4 sm:p-6">
- <h3 className="text-lg font-medium leading-none">Add file</h3>
+ <h3 className="text-lg font-medium leading-none">
+ {isEditing ? "Edit file" : "Add file"}
+ </h3>
</div>
<form
onSubmit={handleSubmit(async (data: FileFormData) => {
- await executeAsync({
- workspaceId: workspaceId!,
- name: data.name,
- resourceType: "file",
- file: data.file,
- extension: data.extension,
- });
+ if (isEditing && existingResource) {
+ await executeUpdate({
+ workspaceId: workspaceId!,
+ resourceId: existingResource.id,
+ resourceType: "file",
+ name: data.name,
+ ...(hasNewFile && data.file
+ ? { file: data.file, extension: data.extension }
+ : {}),
+ });
+ } else {
+ if (!data.file) {
+ setError("file", { message: "File is required" });
+ return;
+ }
+ await executeAdd({
+ workspaceId: workspaceId!,
+ name: data.name,
+ resourceType: "file",
+ file: data.file,
+ extension: data.extension,
+ });
+ }
})}
>
<div className="bg-neutral-50 p-4 sm:p-6">
@@ -110,7 +154,7 @@ function AddFileModalInner({ setShowAddFileModal }: AddFileModalProps) {
<Controller
control={control}
name="file"
- rules={{ required: "File is required" }}
+ rules={{ required: !isEditing ? "File is required" : false }}
render={({ field }) => (
<FileUpload
accept="programResourceFiles"
@@ -125,6 +169,7 @@ function AddFileModalInner({ setShowAddFileModal }: AddFileModalProps) {
setFileName(file.name);
field.onChange(src);
setValue("extension", file.name.split(".").pop());
+ setHasNewFile(true);
// Set the file name to the file name without extension if no name is provided
const currentName = getValues("name");
@@ -136,11 +181,13 @@ function AddFileModalInner({ setShowAddFileModal }: AddFileModalProps) {
setValue("name", nameWithoutExtension || file.name);
}
}}
- icon={field.value ? FileContent : undefined}
+ icon={field.value || isEditing ? FileContent : undefined}
content={
field.value
? truncate(fileName, 25)
- : "Any document or zip file, max size of 10MB"
+ : isEditing
+ ? `Current: ${truncate(existingResource?.name || "", 25)} (drop to replace)`
+ : "Any document or zip file, max size of 10MB"
}
maxFileSizeMB={10}
/>
@@ -181,7 +228,7 @@ function AddFileModalInner({ setShowAddFileModal }: AddFileModalProps) {
<div className="flex items-center justify-end gap-2 border-t border-neutral-200 bg-neutral-50 px-4 py-5 sm:px-6">
<Button
- onClick={() => setShowAddFileModal(false)}
+ onClick={() => setShowFileModal(false)}
variant="secondary"
text="Cancel"
className="h-8 w-fit px-3"
@@ -191,7 +238,7 @@ function AddFileModalInner({ setShowAddFileModal }: AddFileModalProps) {
type="submit"
autoFocus
loading={isSubmitting || isSubmitSuccessful}
- text="Add File"
+ text={isEditing ? "Save Changes" : "Add File"}
className="h-8 w-fit px-3"
/>
</div>
@@ -200,23 +247,29 @@ function AddFileModalInner({ setShowAddFileModal }: AddFileModalProps) {
);
}
-export function useAddFileModal() {
- const [showAddFileModal, setShowAddFileModal] = useState(false);
+export function useFileModal({
+ existingResource,
+}: { existingResource?: ProgramResourceFile } = {}) {
+ const [showFileModal, setShowFileModal] = useState(false);
- const AddFileModalCallback = useCallback(() => {
+ const FileModalCallback = useCallback(() => {
return (
- <AddFileModal
- showAddFileModal={showAddFileModal}
- setShowAddFileModal={setShowAddFileModal}
+ <FileModal
+ showFileModal={showFileModal}
+ setShowFileModal={setShowFileModal}
+ existingResource={existingResource}
/>
);
- }, [showAddFileModal, setShowAddFileModal]);
+ }, [showFileModal, setShowFileModal, existingResource]);
return useMemo(
() => ({
- setShowAddFileModal,
- AddFileModal: AddFileModalCallback,
+ setShowFileModal,
+ FileModal: FileModalCallback,
}),
- [setShowAddFileModal, AddFileModalCallback],
+ [setShowFileModal, FileModalCallback],
);
}
+
+// Keep backwards compatibility alias
+export const useAddFileModal = useFileModal;
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/resources/program-brand-assets/add-link-modal.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/resources/program-brand-assets/add-link-modal.tsx
index 66c726dc42..8f581d8115 100644
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/resources/program-brand-assets/add-link-modal.tsx
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/resources/program-brand-assets/add-link-modal.tsx
@@ -1,8 +1,10 @@
"use client";
import { addProgramResourceAction } from "@/lib/actions/partners/program-resources/add-program-resource";
+import { updateProgramResourceAction } from "@/lib/actions/partners/program-resources/update-program-resource";
import useProgramResources from "@/lib/swr/use-program-resources";
import useWorkspace from "@/lib/swr/use-workspace";
+import { ProgramResourceLink } from "@/lib/zod/schemas/program-resources";
import { Button, Modal } from "@dub/ui";
import { cn } from "@dub/utils";
import { useAction } from "next-safe-action/hooks";
@@ -17,9 +19,10 @@ import { useForm } from "react-hook-form";
import { toast } from "sonner";
import * as z from "zod/v4";
-type AddLinkModalProps = {
- showAddLinkModal: boolean;
- setShowAddLinkModal: Dispatch<SetStateAction<boolean>>;
+type LinkModalProps = {
+ showLinkModal: boolean;
+ setShowLinkModal: Dispatch<SetStateAction<boolean>>;
+ existingResource?: ProgramResourceLink;
};
const linkFormSchema = z.object({
@@ -29,20 +32,24 @@ const linkFormSchema = z.object({
type LinkFormData = z.infer<typeof linkFormSchema>;
-function AddLinkModal(props: AddLinkModalProps) {
+function LinkModal(props: LinkModalProps) {
return (
<Modal
- showModal={props.showAddLinkModal}
- setShowModal={props.setShowAddLinkModal}
+ showModal={props.showLinkModal}
+ setShowModal={props.setShowLinkModal}
>
- <AddLinkModalInner {...props} />
+ <LinkModalInner {...props} />
</Modal>
);
}
-function AddLinkModalInner({ setShowAddLinkModal }: AddLinkModalProps) {
+function LinkModalInner({
+ setShowLinkModal,
+ existingResource,
+}: LinkModalProps) {
const { id: workspaceId } = useWorkspace();
const { mutate } = useProgramResources();
+ const isEditing = Boolean(existingResource);
const {
register,
@@ -51,15 +58,15 @@ function AddLinkModalInner({ setShowAddLinkModal }: AddLinkModalProps) {
formState: { errors, isSubmitting, isSubmitSuccessful },
} = useForm<LinkFormData>({
defaultValues: {
- name: "",
- url: "",
+ name: existingResource?.name || "",
+ url: existingResource?.url || "",
},
});
- const { executeAsync } = useAction(addProgramResourceAction, {
+ const { executeAsync: executeAdd } = useAction(addProgramResourceAction, {
onSuccess: () => {
mutate();
- setShowAddLinkModal(false);
+ setShowLinkModal(false);
toast.success("Link added successfully!");
},
onError({ error }) {
@@ -74,20 +81,50 @@ function AddLinkModalInner({ setShowAddLinkModal }: AddLinkModalProps) {
},
});
+ const { executeAsync: executeUpdate } = useAction(updateProgramResourceAction, {
+ onSuccess: () => {
+ mutate();
+ setShowLinkModal(false);
+ toast.success("Link updated successfully!");
+ },
+ onError({ error }) {
+ if (error.serverError) {
+ setError("root.serverError", {
+ message: error.serverError,
+ });
+ toast.error(error.serverError);
+ } else {
+ toast.error("Failed to update link");
+ }
+ },
+ });
+
return (
<>
<div className="space-y-2 border-b border-neutral-200 p-4 sm:p-6">
- <h3 className="text-lg font-medium leading-none">Add link</h3>
+ <h3 className="text-lg font-medium leading-none">
+ {isEditing ? "Edit link" : "Add link"}
+ </h3>
</div>
<form
onSubmit={handleSubmit(async (data: LinkFormData) => {
- await executeAsync({
- workspaceId: workspaceId!,
- name: data.name,
- resourceType: "link",
- url: data.url,
- });
+ if (isEditing && existingResource) {
+ await executeUpdate({
+ workspaceId: workspaceId!,
+ resourceId: existingResource.id,
+ resourceType: "link",
+ name: data.name,
+ url: data.url,
+ });
+ } else {
+ await executeAdd({
+ workspaceId: workspaceId!,
+ name: data.name,
+ resourceType: "link",
+ url: data.url,
+ });
+ }
})}
>
<div className="bg-neutral-50 p-4 sm:p-6">
@@ -154,7 +191,7 @@ function AddLinkModalInner({ setShowAddLinkModal }: AddLinkModalProps) {
<div className="flex items-center justify-end gap-2 border-t border-neutral-200 bg-neutral-50 px-4 py-5 sm:px-6">
<Button
- onClick={() => setShowAddLinkModal(false)}
+ onClick={() => setShowLinkModal(false)}
variant="secondary"
text="Cancel"
className="h-8 w-fit px-3"
@@ -164,7 +201,7 @@ function AddLinkModalInner({ setShowAddLinkModal }: AddLinkModalProps) {
type="submit"
autoFocus
loading={isSubmitting || isSubmitSuccessful}
- text="Add link"
+ text={isEditing ? "Save Changes" : "Add link"}
className="h-8 w-fit px-3"
/>
</div>
@@ -173,23 +210,29 @@ function AddLinkModalInner({ setShowAddLinkModal }: AddLinkModalProps) {
);
}
-export function useAddLinkModal() {
- const [showAddLinkModal, setShowAddLinkModal] = useState(false);
+export function useLinkModal({
+ existingResource,
+}: { existingResource?: ProgramResourceLink } = {}) {
+ const [showLinkModal, setShowLinkModal] = useState(false);
- const AddLinkModalCallback = useCallback(() => {
+ const LinkModalCallback = useCallback(() => {
return (
- <AddLinkModal
- showAddLinkModal={showAddLinkModal}
- setShowAddLinkModal={setShowAddLinkModal}
+ <LinkModal
+ showLinkModal={showLinkModal}
+ setShowLinkModal={setShowLinkModal}
+ existingResource={existingResource}
/>
);
- }, [showAddLinkModal, setShowAddLinkModal]);
+ }, [showLinkModal, setShowLinkModal, existingResource]);
return useMemo(
() => ({
- setShowAddLinkModal,
- AddLinkModal: AddLinkModalCallback,
+ setShowLinkModal,
+ LinkModal: LinkModalCallback,
}),
- [setShowAddLinkModal, AddLinkModalCallback],
+ [setShowLinkModal, LinkModalCallback],
);
}
+
+// Keep backwards compatibility alias
+export const useAddLinkModal = useLinkModal;
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/resources/program-brand-assets/add-logo-modal.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/resources/program-brand-assets/add-logo-modal.tsx
index bd24b1aa50..7c6811f706 100644
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/resources/program-brand-assets/add-logo-modal.tsx
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/resources/program-brand-assets/add-logo-modal.tsx
@@ -1,8 +1,10 @@
"use client";
import { addProgramResourceAction } from "@/lib/actions/partners/program-resources/add-program-resource";
+import { updateProgramResourceAction } from "@/lib/actions/partners/program-resources/update-program-resource";
import useProgramResources from "@/lib/swr/use-program-resources";
import useWorkspace from "@/lib/swr/use-workspace";
+import { ProgramResourceFile } from "@/lib/zod/schemas/program-resources";
import { Button, FileUpload, Modal } from "@dub/ui";
import { cn } from "@dub/utils";
import { useAction } from "next-safe-action/hooks";
@@ -17,34 +19,39 @@ import { Controller, useForm } from "react-hook-form";
import { toast } from "sonner";
import * as z from "zod/v4";
-type AddLogoModalProps = {
- showAddLogoModal: boolean;
- setShowAddLogoModal: Dispatch<SetStateAction<boolean>>;
+type LogoModalProps = {
+ showLogoModal: boolean;
+ setShowLogoModal: Dispatch<SetStateAction<boolean>>;
+ existingResource?: ProgramResourceFile;
};
// Define the form schema
const logoFormSchema = z.object({
name: z.string(),
- file: z.string().min(1, "Logo file is required"),
+ file: z.string().optional(),
extension: z.string().nullish(),
});
type LogoFormData = z.infer<typeof logoFormSchema>;
-function AddLogoModal(props: AddLogoModalProps) {
+function LogoModal(props: LogoModalProps) {
return (
<Modal
- showModal={props.showAddLogoModal}
- setShowModal={props.setShowAddLogoModal}
+ showModal={props.showLogoModal}
+ setShowModal={props.setShowLogoModal}
>
- <AddLogoModalInner {...props} />
+ <LogoModalInner {...props} />
</Modal>
);
}
-function AddLogoModalInner({ setShowAddLogoModal }: AddLogoModalProps) {
+function LogoModalInner({
+ setShowLogoModal,
+ existingResource,
+}: LogoModalProps) {
const { id: workspaceId } = useWorkspace();
const { mutate } = useProgramResources();
+ const isEditing = Boolean(existingResource);
const {
register,
@@ -56,15 +63,18 @@ function AddLogoModalInner({ setShowAddLogoModal }: AddLogoModalProps) {
formState: { errors, isSubmitting, isSubmitSuccessful },
} = useForm<LogoFormData>({
defaultValues: {
- name: "",
+ name: existingResource?.name || "",
file: "",
},
});
- const { executeAsync } = useAction(addProgramResourceAction, {
+ // Track if user has selected a new file
+ const [hasNewFile, setHasNewFile] = useState(false);
+
+ const { executeAsync: executeAdd } = useAction(addProgramResourceAction, {
onSuccess: () => {
mutate();
- setShowAddLogoModal(false);
+ setShowLogoModal(false);
toast.success("Logo added successfully!");
},
onError({ error }) {
@@ -79,21 +89,57 @@ function AddLogoModalInner({ setShowAddLogoModal }: AddLogoModalProps) {
},
});
+ const { executeAsync: executeUpdate } = useAction(updateProgramResourceAction, {
+ onSuccess: () => {
+ mutate();
+ setShowLogoModal(false);
+ toast.success("Logo updated successfully!");
+ },
+ onError({ error }) {
+ if (error.serverError) {
+ setError("root.serverError", {
+ message: error.serverError,
+ });
+ toast.error(error.serverError);
+ } else {
+ toast.error("Failed to update logo");
+ }
+ },
+ });
+
return (
<>
<div className="space-y-2 border-b border-neutral-200 p-4 sm:p-6">
- <h3 className="text-lg font-medium leading-none">Add logo</h3>
+ <h3 className="text-lg font-medium leading-none">
+ {isEditing ? "Edit logo" : "Add logo"}
+ </h3>
</div>
<form
onSubmit={handleSubmit(async (data: LogoFormData) => {
- await executeAsync({
- workspaceId: workspaceId!,
- name: data.name,
- resourceType: "logo",
- file: data.file,
- extension: data.extension,
- });
+ if (isEditing && existingResource) {
+ await executeUpdate({
+ workspaceId: workspaceId!,
+ resourceId: existingResource.id,
+ resourceType: "logo",
+ name: data.name,
+ ...(hasNewFile && data.file
+ ? { file: data.file, extension: data.extension }
+ : {}),
+ });
+ } else {
+ if (!data.file) {
+ setError("file", { message: "Logo file is required" });
+ return;
+ }
+ await executeAdd({
+ workspaceId: workspaceId!,
+ name: data.name,
+ resourceType: "logo",
+ file: data.file,
+ extension: data.extension,
+ });
+ }
})}
>
<div className="bg-neutral-50 p-4 sm:p-6">
@@ -108,7 +154,7 @@ function AddLogoModalInner({ setShowAddLogoModal }: AddLogoModalProps) {
<Controller
control={control}
name="file"
- rules={{ required: "Logo file is required" }}
+ rules={{ required: !isEditing ? "Logo file is required" : false }}
render={({ field }) => (
<FileUpload
accept="programResourceImages"
@@ -119,11 +165,12 @@ function AddLogoModalInner({ setShowAddLogoModal }: AddLogoModalProps) {
iconClassName="size-5"
previewClassName="object-contain"
variant="plain"
- imageSrc={field.value}
+ imageSrc={field.value || existingResource?.url}
readFile
onChange={({ file, src }) => {
field.onChange(src);
setValue("extension", file.name.split(".").pop());
+ setHasNewFile(true);
// Set the logo name to the file name without extension if no name is provided
const currentName = getValues("name");
@@ -135,7 +182,11 @@ function AddLogoModalInner({ setShowAddLogoModal }: AddLogoModalProps) {
setValue("name", nameWithoutExtension || file.name);
}
}}
- content="SVG, JPG, PNG, or WEBP, max size of 5MB"
+ content={
+ isEditing
+ ? "Drop a new file to replace, or leave unchanged"
+ : "SVG, JPG, PNG, or WEBP, max size of 5MB"
+ }
maxFileSizeMB={5}
/>
)}
@@ -175,7 +226,7 @@ function AddLogoModalInner({ setShowAddLogoModal }: AddLogoModalProps) {
<div className="flex items-center justify-end gap-2 border-t border-neutral-200 bg-neutral-50 px-4 py-5 sm:px-6">
<Button
- onClick={() => setShowAddLogoModal(false)}
+ onClick={() => setShowLogoModal(false)}
variant="secondary"
text="Cancel"
className="h-8 w-fit px-3"
@@ -185,7 +236,7 @@ function AddLogoModalInner({ setShowAddLogoModal }: AddLogoModalProps) {
type="submit"
autoFocus
loading={isSubmitting || isSubmitSuccessful}
- text="Add Logo"
+ text={isEditing ? "Save Changes" : "Add Logo"}
className="h-8 w-fit px-3"
/>
</div>
@@ -194,23 +245,29 @@ function AddLogoModalInner({ setShowAddLogoModal }: AddLogoModalProps) {
);
}
-export function useAddLogoModal() {
- const [showAddLogoModal, setShowAddLogoModal] = useState(false);
+export function useLogoModal({
+ existingResource,
+}: { existingResource?: ProgramResourceFile } = {}) {
+ const [showLogoModal, setShowLogoModal] = useState(false);
- const AddLogoModalCallback = useCallback(() => {
+ const LogoModalCallback = useCallback(() => {
return (
- <AddLogoModal
- showAddLogoModal={showAddLogoModal}
- setShowAddLogoModal={setShowAddLogoModal}
+ <LogoModal
+ showLogoModal={showLogoModal}
+ setShowLogoModal={setShowLogoModal}
+ existingResource={existingResource}
/>
);
- }, [showAddLogoModal, setShowAddLogoModal]);
+ }, [showLogoModal, setShowLogoModal, existingResource]);
return useMemo(
() => ({
- setShowAddLogoModal,
- AddLogoModal: AddLogoModalCallback,
+ setShowLogoModal,
+ LogoModal: LogoModalCallback,
}),
- [setShowAddLogoModal, AddLogoModalCallback],
+ [setShowLogoModal, LogoModalCallback],
);
}
+
+// Keep backwards compatibility alias
+export const useAddLogoModal = useLogoModal;
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/resources/program-brand-assets/index.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/resources/program-brand-assets/index.tsx
index 13a7bb93f3..dd57b7bb8d 100644
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/resources/program-brand-assets/index.tsx
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/resources/program-brand-assets/index.tsx
@@ -3,7 +3,12 @@
import { deleteProgramResourceAction } from "@/lib/actions/partners/program-resources/delete-program-resource";
import useProgramResources from "@/lib/swr/use-program-resources";
import useWorkspace from "@/lib/swr/use-workspace";
-import { ProgramResourceType } from "@/lib/zod/schemas/program-resources";
+import {
+ ProgramResourceColor,
+ ProgramResourceFile,
+ ProgramResourceLink,
+ ProgramResourceType,
+} from "@/lib/zod/schemas/program-resources";
import { ResourceCard } from "@/ui/partners/resources/resource-card";
import { AnimatedSizeContainer, Button, FileContent } from "@dub/ui";
import {
@@ -15,20 +20,45 @@ import {
GOOGLE_FAVICON_URL,
} from "@dub/utils";
import { useAction } from "next-safe-action/hooks";
+import { useState } from "react";
import { toast } from "sonner";
import { SettingsRow } from "../../program-settings-row";
-import { useAddColorModal } from "./add-color-modal";
-import { useAddFileModal } from "./add-file-modal";
-import { useAddLinkModal } from "./add-link-modal";
-import { useAddLogoModal } from "./add-logo-modal";
+import { useColorModal } from "./add-color-modal";
+import { useFileModal } from "./add-file-modal";
+import { useLinkModal } from "./add-link-modal";
+import { useLogoModal } from "./add-logo-modal";
export function ProgramBrandAssets() {
const { id: workspaceId } = useWorkspace();
const { resources, mutate, isLoading } = useProgramResources();
- const { setShowAddLogoModal, AddLogoModal } = useAddLogoModal();
- const { setShowAddColorModal, AddColorModal } = useAddColorModal();
- const { setShowAddFileModal, AddFileModal } = useAddFileModal();
- const { setShowAddLinkModal, AddLinkModal } = useAddLinkModal();
+
+ // Track which resource is being edited (if any)
+ const [editingLogo, setEditingLogo] = useState<
+ ProgramResourceFile | undefined
+ >();
+ const [editingColor, setEditingColor] = useState<
+ ProgramResourceColor | undefined
+ >();
+ const [editingFile, setEditingFile] = useState<
+ ProgramResourceFile | undefined
+ >();
+ const [editingLink, setEditingLink] = useState<
+ ProgramResourceLink | undefined
+ >();
+
+ // Modal hooks with editing support
+ const { setShowLogoModal, LogoModal } = useLogoModal({
+ existingResource: editingLogo,
+ });
+ const { setShowColorModal, ColorModal } = useColorModal({
+ existingResource: editingColor,
+ });
+ const { setShowFileModal, FileModal } = useFileModal({
+ existingResource: editingFile,
+ });
+ const { setShowLinkModal, LinkModal } = useLinkModal({
+ existingResource: editingLink,
+ });
const { executeAsync } = useAction(deleteProgramResourceAction, {
onSuccess: ({ input }) => {
@@ -55,12 +85,52 @@ export function ProgramBrandAssets() {
return !!result?.data?.success;
};
+ const handleAddLogo = () => {
+ setEditingLogo(undefined);
+ setShowLogoModal(true);
+ };
+
+ const handleEditLogo = (logo: ProgramResourceFile) => {
+ setEditingLogo(logo);
+ setShowLogoModal(true);
+ };
+
+ const handleAddColor = () => {
+ setEditingColor(undefined);
+ setShowColorModal(true);
+ };
+
+ const handleEditColor = (color: ProgramResourceColor) => {
+ setEditingColor(color);
+ setShowColorModal(true);
+ };
+
+ const handleAddFile = () => {
+ setEditingFile(undefined);
+ setShowFileModal(true);
+ };
+
+ const handleEditFile = (file: ProgramResourceFile) => {
+ setEditingFile(file);
+ setShowFileModal(true);
+ };
+
+ const handleAddLink = () => {
+ setEditingLink(undefined);
+ setShowLinkModal(true);
+ };
+
+ const handleEditLink = (link: ProgramResourceLink) => {
+ setEditingLink(link);
+ setShowLinkModal(true);
+ };
+
return (
<>
- <AddLogoModal />
- <AddColorModal />
- <AddFileModal />
- <AddLinkModal />
+ <LogoModal />
+ <ColorModal />
+ <FileModal />
+ <LinkModal />
<div className="rounded-lg border border-neutral-200 bg-white">
<div className="p-6">
<h2 className="inline-flex items-center gap-2 text-lg font-semibold text-neutral-900">
@@ -82,7 +152,7 @@ export function ProgramBrandAssets() {
<Button
text="Add Logo"
className="h-8 w-fit px-3"
- onClick={() => setShowAddLogoModal(true)}
+ onClick={handleAddLogo}
loading={isLoading}
/>
</div>
@@ -109,6 +179,7 @@ export function ProgramBrandAssets() {
title={logo.name || "Logo"}
description={`${getFileExtension(logo.url) || "Unknown"}・${formatFileSize(logo.size, 0)}`}
downloadUrl={logo.url}
+ onEdit={() => handleEditLogo(logo)}
onDelete={() => handleDelete("logo", logo.id)}
/>
))}
@@ -127,7 +198,7 @@ export function ProgramBrandAssets() {
<Button
text="Add Link"
className="h-8 w-fit px-3"
- onClick={() => setShowAddLinkModal(true)}
+ onClick={handleAddLink}
loading={isLoading}
/>
</div>
@@ -154,6 +225,7 @@ export function ProgramBrandAssets() {
description={getPrettyUrl(link.url)}
visitUrl={link.url}
copyText={link.url}
+ onEdit={() => handleEditLink(link)}
onDelete={() => handleDelete("link", link.id)}
/>
))}
@@ -172,7 +244,7 @@ export function ProgramBrandAssets() {
<Button
text="Add Color"
className="h-8 w-fit px-3"
- onClick={() => setShowAddColorModal(true)}
+ onClick={handleAddColor}
loading={isLoading}
/>
</div>
@@ -195,6 +267,7 @@ export function ProgramBrandAssets() {
title={color.name || "Color"}
description={color.color.toUpperCase()}
copyText={color.color.toUpperCase()}
+ onEdit={() => handleEditColor(color)}
onDelete={() => handleDelete("color", color.id)}
/>
))}
@@ -213,7 +286,7 @@ export function ProgramBrandAssets() {
<Button
text="Add File"
className="h-8 w-fit px-3"
- onClick={() => setShowAddFileModal(true)}
+ onClick={handleAddFile}
loading={isLoading}
/>
</div>
@@ -235,6 +308,7 @@ export function ProgramBrandAssets() {
title={file.name || "File"}
description={`${getFileExtension(file.url) || "Unknown"}・${formatFileSize(file.size, 0)}`}
downloadUrl={file.url}
+ onEdit={() => handleEditFile(file)}
onDelete={() => handleDelete("file", file.id)}
/>
))}
diff --git a/apps/web/lib/actions/partners/program-resources/update-program-resource.ts b/apps/web/lib/actions/partners/program-resources/update-program-resource.ts
new file mode 100644
index 0000000000..4be70c9a49
--- /dev/null
+++ b/apps/web/lib/actions/partners/program-resources/update-program-resource.ts
@@ -0,0 +1,209 @@
+"use server";
+
+import { getDefaultProgramIdOrThrow } from "@/lib/api/programs/get-default-program-id-or-throw";
+import { storage } from "@/lib/storage";
+import { uploadedImageAllowSVGSchema } from "@/lib/zod/schemas/misc";
+import {
+ programResourceColorSchema,
+ programResourceFileSchema,
+ programResourceLinkSchema,
+ programResourcesSchema,
+} from "@/lib/zod/schemas/program-resources";
+import { prisma } from "@dub/prisma";
+import { nanoid, R2_URL } from "@dub/utils";
+import slugify from "@sindresorhus/slugify";
+import * as z from "zod/v4";
+import { authActionClient } from "../../safe-action";
+import { throwIfNoPermission } from "../../throw-if-no-permission";
+
+// Base schema for all resource types
+const baseUpdateSchema = z.object({
+ workspaceId: z.string(),
+ resourceId: z.string(),
+});
+
+// Schema for logo resources
+const updateLogoSchema = baseUpdateSchema.extend({
+ resourceType: z.literal("logo"),
+ name: z.string().min(1).optional(),
+ file: uploadedImageAllowSVGSchema.optional(),
+ extension: z.string().nullish(),
+});
+
+// Schema for file resources
+const updateFileSchema = baseUpdateSchema.extend({
+ resourceType: z.literal("file"),
+ name: z.string().min(1).optional(),
+ file: z.string().optional(),
+ extension: z.string().nullish(),
+});
+
+// Schema for color resources
+const updateColorSchema = baseUpdateSchema.extend({
+ resourceType: z.literal("color"),
+ name: z.string().min(1).optional(),
+ color: z.string().optional(),
+});
+
+// Schema for link resources
+const updateLinkSchema = baseUpdateSchema.extend({
+ resourceType: z.literal("link"),
+ name: z.string().min(1).optional(),
+ url: z.url().optional(),
+});
+
+// Combined schema that can handle any resource type
+const updateResourceSchema = z.discriminatedUnion("resourceType", [
+ updateLogoSchema,
+ updateFileSchema,
+ updateColorSchema,
+ updateLinkSchema,
+]);
+
+export const updateProgramResourceAction = authActionClient
+ .inputSchema(updateResourceSchema)
+ .action(async ({ ctx, parsedInput }) => {
+ const { workspace } = ctx;
+ const { resourceId, resourceType } = parsedInput;
+
+ throwIfNoPermission({
+ role: workspace.role,
+ requiredRoles: ["owner", "member"],
+ });
+
+ const programId = getDefaultProgramIdOrThrow(workspace);
+
+ // Verify the program exists and belongs to the workspace
+ const program = await prisma.program.findUnique({
+ where: {
+ id: programId,
+ workspaceId: workspace.id,
+ },
+ select: {
+ id: true,
+ resources: true,
+ },
+ });
+
+ if (!program) throw new Error("Program not found");
+ if (!program.resources) throw new Error("Program resources not found");
+
+ const currentResources = program.resources as any;
+ const updatedResources = { ...currentResources };
+
+ // Find the resource to update
+ const resourceKey = `${resourceType}s`;
+ const resourceArray = [...(updatedResources[resourceKey] || [])];
+ const resourceIndex = resourceArray.findIndex(
+ ({ id }) => id === resourceId,
+ );
+
+ if (resourceIndex === -1) throw new Error("Resource not found");
+
+ const existingResource = resourceArray[resourceIndex];
+
+ if (resourceType === "logo" || resourceType === "file") {
+ const { name, file, extension } = parsedInput;
+
+ let newUrl = existingResource.url;
+ let newSize = existingResource.size;
+
+ // If a new file is provided, upload it and delete the old one
+ if (file) {
+ // Validate file size before upload
+ const base64Data = file.replace(/^data:.+;base64,/, "");
+ const fileSize = Math.ceil((base64Data.length * 3) / 4);
+
+ if (fileSize / 1024 / 1024 > 10) {
+ throw new Error("File size is too large");
+ }
+
+ // Upload the new file
+ const fileName = name || existingResource.name;
+ const fileKey = `programs/${program.id}/${resourceType}s/${slugify(fileName || resourceType)}-${nanoid(4)}${extension ? `.${extension}` : ""}`;
+ const uploadResult = await storage.upload({
+ key: fileKey,
+ body: file,
+ opts:
+ resourceType === "logo"
+ ? {
+ headers: {
+ "Content-Disposition": "attachment",
+ ...(extension === "svg" && {
+ "Content-Type": "image/svg+xml",
+ }),
+ },
+ }
+ : undefined,
+ });
+
+ if (!uploadResult || !uploadResult.url) {
+ throw new Error(`Failed to upload ${resourceType}`);
+ }
+
+ newUrl = uploadResult.url;
+ newSize = fileSize;
+
+ // Delete old file from storage (best-effort, after successful upload)
+ if (existingResource.url) {
+ try {
+ await storage.delete({
+ key: existingResource.url.replace(`${R2_URL}/`, ""),
+ });
+ } catch (error) {
+ console.error(
+ "Failed to delete old program resource file from storage:",
+ error,
+ );
+ }
+ }
+ }
+
+ const updatedResource = programResourceFileSchema.parse({
+ id: resourceId,
+ name: name || existingResource.name,
+ size: newSize,
+ url: newUrl,
+ });
+
+ resourceArray[resourceIndex] = updatedResource;
+ } else if (resourceType === "color") {
+ const { name, color } = parsedInput;
+
+ const updatedResource = programResourceColorSchema.parse({
+ id: resourceId,
+ name: name || existingResource.name,
+ color: color || existingResource.color,
+ });
+
+ resourceArray[resourceIndex] = updatedResource;
+ } else if (resourceType === "link") {
+ const { name, url } = parsedInput;
+
+ const updatedResource = programResourceLinkSchema.parse({
+ id: resourceId,
+ name: name || existingResource.name,
+ url: url || existingResource.url,
+ });
+
+ resourceArray[resourceIndex] = updatedResource;
+ } else {
+ throw new Error("Invalid resource type");
+ }
+
+ updatedResources[resourceKey] = resourceArray;
+
+ // Update the program with the updated resources
+ await prisma.program.update({
+ where: {
+ id: program.id,
+ },
+ data: {
+ resources: programResourcesSchema.parse(updatedResources) as any,
+ },
+ });
+
+ return {
+ success: true,
+ };
+ });
diff --git a/apps/web/lib/zod/schemas/program-resources.ts b/apps/web/lib/zod/schemas/program-resources.ts
index 8067e76504..17806882b6 100644
--- a/apps/web/lib/zod/schemas/program-resources.ts
+++ b/apps/web/lib/zod/schemas/program-resources.ts
@@ -34,3 +34,8 @@ export const programResourcesSchema = z.object({
files: z.array(programResourceFileSchema),
links: z.array(programResourceLinkSchema).default([]),
});
+
+export type ProgramResourceFile = z.infer<typeof programResourceFileSchema>;
+export type ProgramResourceColor = z.infer<typeof programResourceColorSchema>;
+export type ProgramResourceLink = z.infer<typeof programResourceLinkSchema>;
+export type ProgramResources = z.infer<typeof programResourcesSchema>;
diff --git a/apps/web/ui/partners/resources/resource-card.tsx b/apps/web/ui/partners/resources/resource-card.tsx
index 56d35cf403..58264fb63e 100644
--- a/apps/web/ui/partners/resources/resource-card.tsx
+++ b/apps/web/ui/partners/resources/resource-card.tsx
@@ -13,6 +13,7 @@ import {
Trash,
useCopyToClipboard,
} from "@dub/ui";
+import { Pen2 } from "@dub/ui/icons";
import { cn } from "@dub/utils";
import { ReactNode, useState } from "react";
import { toast } from "sonner";
@@ -34,6 +35,7 @@ export function ResourceCard({
title,
description,
icon,
+ onEdit,
onDelete,
downloadUrl,
copyText,
@@ -43,6 +45,7 @@ export function ResourceCard({
title: string;
description: string;
icon: ReactNode;
+ onEdit?: () => void;
onDelete?: () => Promise<boolean>;
downloadUrl?: string;
copyText?: string;
@@ -69,7 +72,7 @@ export function ResourceCard({
</div>
</div>
<div className="relative">
- {onDelete || (downloadUrl && copyText && visitUrl) ? (
+ {onEdit || onDelete || (downloadUrl && copyText && visitUrl) ? (
<Popover
content={
<div className="grid w-full grid-cols-1 gap-px p-2 sm:w-48">
@@ -125,6 +128,19 @@ export function ResourceCard({
</a>
)}
+ {onEdit && (
+ <Button
+ text={`Edit ${resourceType}`}
+ variant="outline"
+ onClick={() => {
+ setOpenPopover(false);
+ onEdit();
+ }}
+ icon={<Pen2 className="size-4" />}
+ className="h-9 justify-start px-2 font-medium"
+ />
+ )}
+
{onDelete && (
<Button
text={`Delete ${resourceType}`}