Backend and UI modifications to allow reordering of backup schedules

Adds drag-and-drop functionality to reorder backup schedules

Introduces a sort order field to the database schema and implements API endpoints to update the schedule order.

This allows users to visually prioritize their backup jobs.
This commit is contained in:
Raj Dave 2025-12-15 13:13:34 +03:00
parent 5216cc195d
commit b51f3549c2
10 changed files with 263 additions and 58 deletions

View file

@ -0,0 +1,82 @@
import { useSortable } from "@dnd-kit/sortable";
import { CSS } from "@dnd-kit/utilities";
import { CalendarClock, Database, GripVertical, HardDrive } from "lucide-react";
import { Link } from "react-router";
import { BackupStatusDot } from "./backup-status-dot";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "~/client/components/ui/card";
import type { ListBackupSchedulesResponse } from "~/client/api-client";
type Schedule = ListBackupSchedulesResponse[number];
interface SortableBackupCardProps {
schedule: Schedule;
isDragging?: boolean;
}
export function SortableBackupCard({ schedule, isDragging }: SortableBackupCardProps) {
const { attributes, listeners, setNodeRef, transform, transition } = useSortable({
id: schedule.id,
});
const style = {
transform: CSS.Transform.toString(transform),
transition,
opacity: isDragging ? 0.5 : 1,
};
return (
<div ref={setNodeRef} style={style} className="relative group">
<div
{...attributes}
{...listeners}
className="absolute left-1/2 -translate-x-1/2 top-1 z-10 cursor-grab active:cursor-grabbing opacity-0 group-hover:opacity-100 transition-opacity p-1 rounded hover:bg-muted/50 bg-background/80 backdrop-blur-sm"
>
<GripVertical className="h-4 w-4 text-muted-foreground rotate-90" />
</div>
<Link to={`/backups/${schedule.id}`} className="block">
<Card className="flex flex-col h-full hover:bg-muted/30 transition-colors">
<CardHeader className="pb-3 overflow-hidden">
<div className="flex items-center justify-between gap-2 w-full">
<div className="flex items-center gap-2 flex-1 min-w-0 w-0">
<CalendarClock className="h-5 w-5 text-muted-foreground shrink-0" />
<CardTitle className="text-lg truncate">{schedule.name}</CardTitle>
</div>
<BackupStatusDot
enabled={schedule.enabled}
hasError={!!schedule.lastBackupError}
isInProgress={schedule.lastBackupStatus === "in_progress"}
/>
</div>
<CardDescription className="ml-0.5 flex items-center gap-2 text-xs">
<HardDrive className="h-3.5 w-3.5" />
<span className="truncate">{schedule.volume.name}</span>
<span className="text-muted-foreground"></span>
<Database className="h-3.5 w-3.5 text-strong-accent" />
<span className="truncate text-strong-accent">{schedule.repository.name}</span>
</CardDescription>
</CardHeader>
<CardContent className="flex-1 space-y-4">
<div className="space-y-2">
<div className="flex items-center justify-between text-sm">
<span className="text-muted-foreground">Schedule</span>
<code className="text-xs bg-muted px-2 py-1 rounded">{schedule.cronExpression}</code>
</div>
<div className="flex items-center justify-between text-sm">
<span className="text-muted-foreground">Last backup</span>
<span className="font-medium">
{schedule.lastBackupAt ? new Date(schedule.lastBackupAt).toLocaleDateString() : "Never"}
</span>
</div>
<div className="flex items-center justify-between text-sm">
<span className="text-muted-foreground">Next backup</span>
<span className="font-medium">
{schedule.nextBackupAt ? new Date(schedule.nextBackupAt).toLocaleDateString() : "N/A"}
</span>
</div>
</div>
</CardContent>
</Card>
</Link>
</div>
);
}

View file

@ -1,6 +1,18 @@
import { useQuery } from "@tanstack/react-query";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import {
DndContext,
closestCenter,
KeyboardSensor,
PointerSensor,
useSensor,
useSensors,
type DragEndEvent,
} from "@dnd-kit/core";
import { arrayMove, SortableContext, sortableKeyboardCoordinates, rectSortingStrategy } from "@dnd-kit/sortable";
import { CalendarClock, Database, HardDrive, Plus } from "lucide-react";
import { Link } from "react-router";
import { useState, useEffect } from "react";
import { SortableBackupCard } from "../components/sortable-backup-card";
import { BackupStatusDot } from "../components/backup-status-dot";
import { EmptyState } from "~/client/components/empty-state";
import { Button } from "~/client/components/ui/button";
@ -9,6 +21,21 @@ import type { Route } from "./+types/backups";
import { listBackupSchedules } from "~/client/api-client";
import { listBackupSchedulesOptions } from "~/client/api-client/@tanstack/react-query.gen";
// Temporary helper until API client is regenerated
async function reorderBackupSchedules(scheduleIds: number[]) {
const response = await fetch("/api/v1/backups/reorder", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ scheduleIds }),
});
if (!response.ok) {
throw new Error("Failed to reorder backup schedules");
}
return response.json();
}
export const handle = {
breadcrumb: () => [{ label: "Backups" }],
};
@ -30,11 +57,58 @@ export const clientLoader = async () => {
};
export default function Backups({ loaderData }: Route.ComponentProps) {
const queryClient = useQueryClient();
const { data: schedules, isLoading } = useQuery({
...listBackupSchedulesOptions(),
initialData: loaderData,
});
const [items, setItems] = useState(schedules?.map((s) => s.id) ?? []);
// Keep items in sync with schedules
useEffect(() => {
if (schedules) {
setItems(schedules.map((s) => s.id));
}
}, [schedules]);
const sensors = useSensors(
useSensor(PointerSensor, {
activationConstraint: {
distance: 8,
},
}),
useSensor(KeyboardSensor, {
coordinateGetter: sortableKeyboardCoordinates,
}),
);
const reorderMutation = useMutation({
mutationFn: async (scheduleIds: number[]) => {
await reorderBackupSchedules(scheduleIds);
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ["listBackupSchedules"] });
},
});
const handleDragEnd = (event: DragEndEvent) => {
const { active, over } = event;
if (over && active.id !== over.id) {
setItems((items) => {
const oldIndex = items.indexOf(active.id as number);
const newIndex = items.indexOf(over.id as number);
const newItems = arrayMove(items, oldIndex, newIndex);
// Save the new order
reorderMutation.mutate(newItems);
return newItems;
});
}
};
if (isLoading) {
return (
<div className="flex items-center justify-center h-full">
@ -61,64 +135,30 @@ export default function Backups({ loaderData }: Route.ComponentProps) {
);
}
// Create a map for quick lookup
const scheduleMap = new Map(schedules.map((s) => [s.id, s]));
return (
<div className="container mx-auto space-y-6">
<div className="grid gap-4 md:grid-cols-2 lg:grid-cols-3 auto-rows-fr">
{schedules.map((schedule) => (
<Link key={schedule.id} to={`/backups/${schedule.id}`}>
<Card key={schedule.id} className="flex flex-col h-full">
<CardHeader className="pb-3 overflow-hidden">
<div className="flex items-center justify-between gap-2 w-full">
<div className="flex items-center gap-2 flex-1 min-w-0 w-0">
<CalendarClock className="h-5 w-5 text-muted-foreground shrink-0" />
<CardTitle className="text-lg truncate">{schedule.name}</CardTitle>
</div>
<BackupStatusDot
enabled={schedule.enabled}
hasError={!!schedule.lastBackupError}
isInProgress={schedule.lastBackupStatus === "in_progress"}
/>
</div>
<CardDescription className="ml-0.5 flex items-center gap-2 text-xs">
<HardDrive className="h-3.5 w-3.5" />
<span className="truncate">{schedule.volume.name}</span>
<span className="text-muted-foreground"></span>
<Database className="h-3.5 w-3.5 text-strong-accent" />
<span className="truncate text-strong-accent">{schedule.repository.name}</span>
</CardDescription>
</CardHeader>
<CardContent className="flex-1 space-y-4">
<div className="space-y-2">
<div className="flex items-center justify-between text-sm">
<span className="text-muted-foreground">Schedule</span>
<code className="text-xs bg-muted px-2 py-1 rounded">{schedule.cronExpression}</code>
</div>
<div className="flex items-center justify-between text-sm">
<span className="text-muted-foreground">Last backup</span>
<span className="font-medium">
{schedule.lastBackupAt ? new Date(schedule.lastBackupAt).toLocaleDateString() : "Never"}
</span>
</div>
<div className="flex items-center justify-between text-sm">
<span className="text-muted-foreground">Next backup</span>
<span className="font-medium">
{schedule.nextBackupAt ? new Date(schedule.nextBackupAt).toLocaleDateString() : "N/A"}
</span>
</div>
</div>
</CardContent>
</Card>
</Link>
))}
<Link to="/backups/create">
<Card className="flex flex-col items-center justify-center h-full hover:bg-muted/50 transition-colors cursor-pointer">
<CardContent className="flex flex-col items-center justify-center gap-2">
<Plus className="h-8 w-8 text-muted-foreground" />
<span className="text-sm font-medium text-muted-foreground">Create a backup job</span>
</CardContent>
</Card>
</Link>
</div>
<DndContext sensors={sensors} collisionDetection={closestCenter} onDragEnd={handleDragEnd}>
<SortableContext items={items} strategy={rectSortingStrategy}>
<div className="grid gap-4 md:grid-cols-2 lg:grid-cols-3 auto-rows-fr">
{items.map((id) => {
const schedule = scheduleMap.get(id);
if (!schedule) return null;
return <SortableBackupCard key={schedule.id} schedule={schedule} />;
})}
<Link to="/backups/create">
<Card className="flex flex-col items-center justify-center h-full hover:bg-muted/50 transition-colors cursor-pointer">
<CardContent className="flex flex-col items-center justify-center gap-2">
<Plus className="h-8 w-8 text-muted-foreground" />
<span className="text-sm font-medium text-muted-foreground">Create a backup job</span>
</CardContent>
</Card>
</Link>
</div>
</SortableContext>
</DndContext>
</div>
);
}

View file

@ -0,0 +1,2 @@
ALTER TABLE `backup_schedules_table` ADD `sort_order` integer DEFAULT 0 NOT NULL;

View file

@ -0,0 +1,17 @@
{
"version": "6",
"dialect": "sqlite",
"id": "0022_add_backup_sort_order",
"prevId": "0021_steady_viper",
"tables": {},
"enums": {},
"_meta": {
"schemas": {},
"tables": {},
"columns": {}
},
"internal": {
"indexes": {}
}
}

View file

@ -155,6 +155,13 @@
"when": 1765307881092,
"tag": "0021_steady_viper",
"breakpoints": true
},
{
"idx": 22,
"version": "6",
"when": 1734278400000,
"tag": "0022_add_backup_sort_order",
"breakpoints": true
}
]
}

View file

@ -92,6 +92,7 @@ export const backupSchedulesTable = sqliteTable("backup_schedules_table", {
lastBackupStatus: text("last_backup_status").$type<"success" | "error" | "in_progress" | "warning">(),
lastBackupError: text("last_backup_error"),
nextBackupAt: int("next_backup_at", { mode: "number" }),
sortOrder: int("sort_order", { mode: "number" }).notNull().default(0),
createdAt: int("created_at", { mode: "number" }).notNull().default(sql`(unixepoch() * 1000)`),
updatedAt: int("updated_at", { mode: "number" }).notNull().default(sql`(unixepoch() * 1000)`),
});

View file

@ -16,6 +16,8 @@ import {
updateScheduleMirrorsDto,
updateScheduleMirrorsBody,
getMirrorCompatibilityDto,
reorderBackupSchedulesDto,
reorderBackupSchedulesBody,
type CreateBackupScheduleDto,
type DeleteBackupScheduleDto,
type GetBackupScheduleDto,
@ -28,6 +30,7 @@ import {
type GetScheduleMirrorsDto,
type UpdateScheduleMirrorsDto,
type GetMirrorCompatibilityDto,
type ReorderBackupSchedulesDto,
} from "./backups.dto";
import { backupsService } from "./backups.service";
import {
@ -139,4 +142,11 @@ export const backupScheduleController = new Hono()
const compatibility = await backupsService.getMirrorCompatibility(scheduleId);
return c.json<GetMirrorCompatibilityDto>(compatibility, 200);
})
.post("/reorder", reorderBackupSchedulesDto, validator("json", reorderBackupSchedulesBody), async (c) => {
const body = c.req.valid("json");
await backupsService.reorderSchedules(body.scheduleIds);
return c.json<ReorderBackupSchedulesDto>({ success: true }, 200);
});

View file

@ -367,3 +367,34 @@ export const getMirrorCompatibilityDto = describeRoute({
},
},
});
/**
* Reorder backup schedules
*/
export const reorderBackupSchedulesBody = type({
scheduleIds: "number[]",
});
export type ReorderBackupSchedulesBody = typeof reorderBackupSchedulesBody.infer;
export const reorderBackupSchedulesResponse = type({
success: "boolean",
});
export type ReorderBackupSchedulesDto = typeof reorderBackupSchedulesResponse.infer;
export const reorderBackupSchedulesDto = describeRoute({
description: "Reorder backup schedules by providing an array of schedule IDs in the desired order",
operationId: "reorderBackupSchedules",
tags: ["Backups"],
responses: {
200: {
description: "Backup schedules reordered successfully",
content: {
"application/json": {
schema: resolver(reorderBackupSchedulesResponse),
},
},
},
},
});

View file

@ -1,4 +1,4 @@
import { and, eq, ne } from "drizzle-orm";
import { and, asc, eq, ne } from "drizzle-orm";
import cron from "node-cron";
import { CronExpressionParser } from "cron-parser";
import { NotFoundError, BadRequestError, ConflictError } from "http-errors-enhanced";
@ -38,6 +38,7 @@ const listSchedules = async () => {
volume: true,
repository: true,
},
orderBy: [asc(backupSchedulesTable.sortOrder), asc(backupSchedulesTable.id)],
});
return schedules;
};
@ -637,6 +638,16 @@ const getMirrorCompatibility = async (scheduleId: number) => {
return compatibility;
};
const reorderSchedules = async (scheduleIds: number[]) => {
// Update each schedule's sortOrder based on its position in the array
for (let i = 0; i < scheduleIds.length; i++) {
await db
.update(backupSchedulesTable)
.set({ sortOrder: i, updatedAt: Date.now() })
.where(eq(backupSchedulesTable.id, scheduleIds[i]));
}
};
export const backupsService = {
listSchedules,
getSchedule,
@ -651,4 +662,5 @@ export const backupsService = {
getMirrors,
updateMirrors,
getMirrorCompatibility,
reorderSchedules,
};

View file

@ -17,6 +17,9 @@
"studio": "drizzle-kit studio"
},
"dependencies": {
"@dnd-kit/core": "^6.3.1",
"@dnd-kit/sortable": "^10.0.0",
"@dnd-kit/utilities": "^3.2.2",
"@hono/standard-validator": "^0.2.0",
"@hookform/resolvers": "^5.2.2",
"@radix-ui/react-alert-dialog": "^1.1.15",