import { zodResolver } from "@hookform/resolvers/zod"; import { CheckIcon, ChevronsUpDown, DatabaseZap, PenBoxIcon, PlusIcon, RefreshCw, } from "lucide-react"; import { useEffect, useState } from "react"; import { useForm } from "react-hook-form"; import { toast } from "sonner"; import { z } from "zod"; import { AlertBlock } from "@/components/shared/alert-block"; import { Button } from "@/components/ui/button"; import { Command, CommandEmpty, CommandGroup, CommandInput, CommandItem, } from "@/components/ui/command"; import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, DialogTrigger, } from "@/components/ui/dialog"; import { Form, FormControl, FormDescription, FormField, FormItem, FormLabel, FormMessage, } from "@/components/ui/form"; import { Input } from "@/components/ui/input"; import { Popover, PopoverContent, PopoverTrigger, } from "@/components/ui/popover"; import { ScrollArea } from "@/components/ui/scroll-area"; import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue, } from "@/components/ui/select"; import { Switch } from "@/components/ui/switch"; import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger, } from "@/components/ui/tooltip"; import { cn } from "@/lib/utils"; import { api } from "@/utils/api"; import { ScheduleFormField } from "../../application/schedules/handle-schedules"; type CacheType = "cache" | "fetch"; type DatabaseType = "postgres" | "mariadb" | "mysql" | "mongo" | "web-server"; const Schema = z .object({ destinationId: z.string().min(1, "Destination required"), schedule: z.string().min(1, "Schedule (Cron) required"), prefix: z.string().min(1, "Prefix required"), enabled: z.boolean(), database: z.string().min(1, "Database required"), keepLatestCount: z.coerce.number().optional(), serviceName: z.string().nullable(), databaseType: z .enum(["postgres", "mariadb", "mysql", "mongo", "web-server"]) .optional(), backupType: z.enum(["database", "compose"]), metadata: z .object({ postgres: z .object({ databaseUser: z.string(), }) .optional(), mariadb: z .object({ databaseUser: z.string(), databasePassword: z.string(), }) .optional(), mongo: z .object({ databaseUser: z.string(), databasePassword: z.string(), }) .optional(), mysql: z .object({ databaseRootPassword: z.string(), }) .optional(), }) .optional(), }) .superRefine((data, ctx) => { if (data.backupType === "compose" && !data.databaseType) { ctx.addIssue({ code: z.ZodIssueCode.custom, message: "Database type is required for compose backups", path: ["databaseType"], }); } if (data.backupType === "compose" && !data.serviceName) { ctx.addIssue({ code: z.ZodIssueCode.custom, message: "Service name is required for compose backups", path: ["serviceName"], }); } if (data.backupType === "compose" && data.databaseType) { if (data.databaseType === "postgres") { if (!data.metadata?.postgres?.databaseUser) { ctx.addIssue({ code: z.ZodIssueCode.custom, message: "Database user is required for PostgreSQL", path: ["metadata", "postgres", "databaseUser"], }); } } else if (data.databaseType === "mariadb") { if (!data.metadata?.mariadb?.databaseUser) { ctx.addIssue({ code: z.ZodIssueCode.custom, message: "Database user is required for MariaDB", path: ["metadata", "mariadb", "databaseUser"], }); } if (!data.metadata?.mariadb?.databasePassword) { ctx.addIssue({ code: z.ZodIssueCode.custom, message: "Database password is required for MariaDB", path: ["metadata", "mariadb", "databasePassword"], }); } } else if (data.databaseType === "mongo") { if (!data.metadata?.mongo?.databaseUser) { ctx.addIssue({ code: z.ZodIssueCode.custom, message: "Database user is required for MongoDB", path: ["metadata", "mongo", "databaseUser"], }); } if (!data.metadata?.mongo?.databasePassword) { ctx.addIssue({ code: z.ZodIssueCode.custom, message: "Database password is required for MongoDB", path: ["metadata", "mongo", "databasePassword"], }); } } else if (data.databaseType === "mysql") { if (!data.metadata?.mysql?.databaseRootPassword) { ctx.addIssue({ code: z.ZodIssueCode.custom, message: "Root password is required for MySQL", path: ["metadata", "mysql", "databaseRootPassword"], }); } } } }); interface Props { id?: string; backupId?: string; databaseType?: DatabaseType; refetch: () => void; backupType: "database" | "compose"; } export const HandleBackup = ({ id, backupId, databaseType = "postgres", refetch, backupType = "database", }: Props) => { const [isOpen, setIsOpen] = useState(false); const { data, isLoading } = api.destination.all.useQuery(); const { data: backup } = api.backup.one.useQuery( { backupId: backupId ?? "", }, { enabled: !!backupId, }, ); const [cacheType, setCacheType] = useState("cache"); const { mutateAsync: createBackup, isLoading: isCreatingPostgresBackup } = backupId ? api.backup.update.useMutation() : api.backup.create.useMutation(); const form = useForm>({ defaultValues: { database: databaseType === "web-server" ? "dokploy" : "", destinationId: "", enabled: true, prefix: "/", schedule: "", keepLatestCount: undefined, serviceName: null, databaseType: backupType === "compose" ? undefined : databaseType, backupType: backupType, metadata: {}, }, resolver: zodResolver(Schema), }); const { data: services, isFetching: isLoadingServices, error: errorServices, refetch: refetchServices, } = api.compose.loadServices.useQuery( { composeId: backup?.composeId ?? id ?? "", type: cacheType, }, { retry: false, refetchOnWindowFocus: false, enabled: backupType === "compose" && !!backup?.composeId && !!id, }, ); useEffect(() => { form.reset({ database: backup?.database ? backup?.database : databaseType === "web-server" ? "dokploy" : "", destinationId: backup?.destinationId ?? "", enabled: backup?.enabled ?? true, prefix: backup?.prefix ?? "/", schedule: backup?.schedule ?? "", keepLatestCount: backup?.keepLatestCount ?? undefined, serviceName: backup?.serviceName ?? null, databaseType: backup?.databaseType ?? databaseType, backupType: backup?.backupType ?? backupType, metadata: backup?.metadata ?? {}, }); }, [form, form.reset, backupId, backup]); const onSubmit = async (data: z.infer) => { const getDatabaseId = backupType === "compose" ? { composeId: id, } : databaseType === "postgres" ? { postgresId: id, } : databaseType === "mariadb" ? { mariadbId: id, } : databaseType === "mysql" ? { mysqlId: id, } : databaseType === "mongo" ? { mongoId: id, } : databaseType === "web-server" ? { userId: id, } : undefined; await createBackup({ destinationId: data.destinationId, prefix: data.prefix, schedule: data.schedule, enabled: data.enabled, database: data.database, keepLatestCount: data.keepLatestCount ?? null, databaseType: data.databaseType || databaseType, serviceName: data.serviceName, ...getDatabaseId, backupId: backupId ?? "", backupType, metadata: data.metadata, }) .then(async () => { toast.success(`Backup ${backupId ? "Updated" : "Created"}`); refetch(); setIsOpen(false); }) .catch(() => { toast.error(`Error ${backupId ? "updating" : "creating"} a backup`); }); }; return ( {backupId ? ( ) : ( )} {backupId ? "Update Backup" : "Create Backup"} {backupId ? "Update a backup" : "Add a new backup"}
{errorServices && ( {errorServices?.message} )} {backupType === "compose" && ( ( Database Type )} /> )} ( Destination {isLoading && ( Loading Destinations.... )} No destinations found. {data?.map((destination) => ( { form.setValue( "destinationId", destination.destinationId, ); }} > {destination.name} ))} )} /> {backupType === "compose" && (
( Service Name

Fetch: Will clone the repository and load the services

Cache: If you previously deployed this compose, it will read the services from the last deployment/fetch from the repository

)} />
)} { return ( Database ); }} /> { return ( Prefix Destination Use if you want to back up in a specific path of your destination/bucket ); }} /> { return ( Keep the latest Optional. If provided, only keeps the latest N backups in the cloud. ); }} /> (
Enabled Enable or disable the backup
)} /> {backupType === "compose" && ( <> {form.watch("databaseType") === "postgres" && ( ( Database User )} /> )} {form.watch("databaseType") === "mariadb" && ( <> ( Database User )} /> ( Database Password )} /> )} {form.watch("databaseType") === "mongo" && ( <> ( Database User )} /> ( Database Password )} /> )} {form.watch("databaseType") === "mysql" && ( ( Root Password )} /> )} )}
); };