From b51f3549c29f2c37d553ab61cc6fded4c18bf968 Mon Sep 17 00:00:00 2001 From: Raj Dave Date: Mon, 15 Dec 2025 13:13:34 +0300 Subject: [PATCH 1/7] 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. --- .../components/sortable-backup-card.tsx | 82 ++++++++++ app/client/modules/backups/routes/backups.tsx | 154 +++++++++++------- app/drizzle/0022_add_backup_sort_order.sql | 2 + app/drizzle/meta/0022_snapshot.json | 17 ++ app/drizzle/meta/_journal.json | 7 + app/server/db/schema.ts | 1 + .../modules/backups/backups.controller.ts | 10 ++ app/server/modules/backups/backups.dto.ts | 31 ++++ app/server/modules/backups/backups.service.ts | 14 +- package.json | 3 + 10 files changed, 263 insertions(+), 58 deletions(-) create mode 100644 app/client/modules/backups/components/sortable-backup-card.tsx create mode 100644 app/drizzle/0022_add_backup_sort_order.sql create mode 100644 app/drizzle/meta/0022_snapshot.json diff --git a/app/client/modules/backups/components/sortable-backup-card.tsx b/app/client/modules/backups/components/sortable-backup-card.tsx new file mode 100644 index 00000000..8a7b98f5 --- /dev/null +++ b/app/client/modules/backups/components/sortable-backup-card.tsx @@ -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 ( +
+
+ +
+ + + +
+
+ + {schedule.name} +
+ +
+ + + {schedule.volume.name} + + + {schedule.repository.name} + +
+ +
+
+ Schedule + {schedule.cronExpression} +
+
+ Last backup + + {schedule.lastBackupAt ? new Date(schedule.lastBackupAt).toLocaleDateString() : "Never"} + +
+
+ Next backup + + {schedule.nextBackupAt ? new Date(schedule.nextBackupAt).toLocaleDateString() : "N/A"} + +
+
+
+
+ +
+ ); +} diff --git a/app/client/modules/backups/routes/backups.tsx b/app/client/modules/backups/routes/backups.tsx index 651c86f4..929da13c 100644 --- a/app/client/modules/backups/routes/backups.tsx +++ b/app/client/modules/backups/routes/backups.tsx @@ -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 (
@@ -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 (
-
- {schedules.map((schedule) => ( - - - -
-
- - {schedule.name} -
- -
- - - {schedule.volume.name} - - - {schedule.repository.name} - -
- -
-
- Schedule - {schedule.cronExpression} -
-
- Last backup - - {schedule.lastBackupAt ? new Date(schedule.lastBackupAt).toLocaleDateString() : "Never"} - -
-
- Next backup - - {schedule.nextBackupAt ? new Date(schedule.nextBackupAt).toLocaleDateString() : "N/A"} - -
-
-
-
- - ))} - - - - - Create a backup job - - - -
+ + +
+ {items.map((id) => { + const schedule = scheduleMap.get(id); + if (!schedule) return null; + return ; + })} + + + + + Create a backup job + + + +
+
+
); } diff --git a/app/drizzle/0022_add_backup_sort_order.sql b/app/drizzle/0022_add_backup_sort_order.sql new file mode 100644 index 00000000..487a1bff --- /dev/null +++ b/app/drizzle/0022_add_backup_sort_order.sql @@ -0,0 +1,2 @@ +ALTER TABLE `backup_schedules_table` ADD `sort_order` integer DEFAULT 0 NOT NULL; + diff --git a/app/drizzle/meta/0022_snapshot.json b/app/drizzle/meta/0022_snapshot.json new file mode 100644 index 00000000..bf0ce995 --- /dev/null +++ b/app/drizzle/meta/0022_snapshot.json @@ -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": {} + } +} + diff --git a/app/drizzle/meta/_journal.json b/app/drizzle/meta/_journal.json index 004e9b77..f4f849f8 100644 --- a/app/drizzle/meta/_journal.json +++ b/app/drizzle/meta/_journal.json @@ -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 } ] } \ No newline at end of file diff --git a/app/server/db/schema.ts b/app/server/db/schema.ts index 55c741c2..cb94d29b 100644 --- a/app/server/db/schema.ts +++ b/app/server/db/schema.ts @@ -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)`), }); diff --git a/app/server/modules/backups/backups.controller.ts b/app/server/modules/backups/backups.controller.ts index 0bcc93eb..653cd659 100644 --- a/app/server/modules/backups/backups.controller.ts +++ b/app/server/modules/backups/backups.controller.ts @@ -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(compatibility, 200); + }) + .post("/reorder", reorderBackupSchedulesDto, validator("json", reorderBackupSchedulesBody), async (c) => { + const body = c.req.valid("json"); + + await backupsService.reorderSchedules(body.scheduleIds); + + return c.json({ success: true }, 200); }); diff --git a/app/server/modules/backups/backups.dto.ts b/app/server/modules/backups/backups.dto.ts index fc771bf1..6173bd82 100644 --- a/app/server/modules/backups/backups.dto.ts +++ b/app/server/modules/backups/backups.dto.ts @@ -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), + }, + }, + }, + }, +}); diff --git a/app/server/modules/backups/backups.service.ts b/app/server/modules/backups/backups.service.ts index 9994e503..372ac0d8 100644 --- a/app/server/modules/backups/backups.service.ts +++ b/app/server/modules/backups/backups.service.ts @@ -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, }; diff --git a/package.json b/package.json index e6d2fcb9..697d0fe4 100644 --- a/package.json +++ b/package.json @@ -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", From fa8e06a92e35a8450ca41ce3fe547f5e51b2c8e6 Mon Sep 17 00:00:00 2001 From: Raj Dave Date: Mon, 15 Dec 2025 13:26:47 +0300 Subject: [PATCH 2/7] fix timestamp in drizzle journal --- app/drizzle/meta/_journal.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/drizzle/meta/_journal.json b/app/drizzle/meta/_journal.json index f4f849f8..05caf4a0 100644 --- a/app/drizzle/meta/_journal.json +++ b/app/drizzle/meta/_journal.json @@ -159,7 +159,7 @@ { "idx": 22, "version": "6", - "when": 1734278400000, + "when": 1765794227000, "tag": "0022_add_backup_sort_order", "breakpoints": true } From c3f5cd6b4e4c9f45a54f29124210125f55d4b892 Mon Sep 17 00:00:00 2001 From: Raj Dave Date: Mon, 15 Dec 2025 13:30:51 +0300 Subject: [PATCH 3/7] properly generate migration --- ...kup_sort_order.sql => 0022_woozy_shen.sql} | 3 +- app/drizzle/meta/0022_snapshot.json | 824 +++++++++++++++++- app/drizzle/meta/_journal.json | 4 +- 3 files changed, 822 insertions(+), 9 deletions(-) rename app/drizzle/{0022_add_backup_sort_order.sql => 0022_woozy_shen.sql} (75%) diff --git a/app/drizzle/0022_add_backup_sort_order.sql b/app/drizzle/0022_woozy_shen.sql similarity index 75% rename from app/drizzle/0022_add_backup_sort_order.sql rename to app/drizzle/0022_woozy_shen.sql index 487a1bff..df63c5aa 100644 --- a/app/drizzle/0022_add_backup_sort_order.sql +++ b/app/drizzle/0022_woozy_shen.sql @@ -1,2 +1 @@ -ALTER TABLE `backup_schedules_table` ADD `sort_order` integer DEFAULT 0 NOT NULL; - +ALTER TABLE `backup_schedules_table` ADD `sort_order` integer DEFAULT 0 NOT NULL; \ No newline at end of file diff --git a/app/drizzle/meta/0022_snapshot.json b/app/drizzle/meta/0022_snapshot.json index bf0ce995..ee9d34d9 100644 --- a/app/drizzle/meta/0022_snapshot.json +++ b/app/drizzle/meta/0022_snapshot.json @@ -1,9 +1,824 @@ { "version": "6", "dialect": "sqlite", - "id": "0022_add_backup_sort_order", - "prevId": "0021_steady_viper", - "tables": {}, + "id": "11c24867-3186-4578-b8dd-cee4c48a28d1", + "prevId": "e7c02f6c-e255-402e-9f18-d50a3fef8e4d", + "tables": { + "app_metadata": { + "name": "app_metadata", + "columns": { + "key": { + "name": "key", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "value": { + "name": "value", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(unixepoch() * 1000)" + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(unixepoch() * 1000)" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "backup_schedule_mirrors_table": { + "name": "backup_schedule_mirrors_table", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "schedule_id": { + "name": "schedule_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "repository_id": { + "name": "repository_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "enabled": { + "name": "enabled", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": true + }, + "last_copy_at": { + "name": "last_copy_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "last_copy_status": { + "name": "last_copy_status", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "last_copy_error": { + "name": "last_copy_error", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(unixepoch() * 1000)" + } + }, + "indexes": { + "backup_schedule_mirrors_table_schedule_id_repository_id_unique": { + "name": "backup_schedule_mirrors_table_schedule_id_repository_id_unique", + "columns": [ + "schedule_id", + "repository_id" + ], + "isUnique": true + } + }, + "foreignKeys": { + "backup_schedule_mirrors_table_schedule_id_backup_schedules_table_id_fk": { + "name": "backup_schedule_mirrors_table_schedule_id_backup_schedules_table_id_fk", + "tableFrom": "backup_schedule_mirrors_table", + "tableTo": "backup_schedules_table", + "columnsFrom": [ + "schedule_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "backup_schedule_mirrors_table_repository_id_repositories_table_id_fk": { + "name": "backup_schedule_mirrors_table_repository_id_repositories_table_id_fk", + "tableFrom": "backup_schedule_mirrors_table", + "tableTo": "repositories_table", + "columnsFrom": [ + "repository_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "backup_schedule_notifications_table": { + "name": "backup_schedule_notifications_table", + "columns": { + "schedule_id": { + "name": "schedule_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "destination_id": { + "name": "destination_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "notify_on_start": { + "name": "notify_on_start", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": false + }, + "notify_on_success": { + "name": "notify_on_success", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": false + }, + "notify_on_warning": { + "name": "notify_on_warning", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": true + }, + "notify_on_failure": { + "name": "notify_on_failure", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": true + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(unixepoch() * 1000)" + } + }, + "indexes": {}, + "foreignKeys": { + "backup_schedule_notifications_table_schedule_id_backup_schedules_table_id_fk": { + "name": "backup_schedule_notifications_table_schedule_id_backup_schedules_table_id_fk", + "tableFrom": "backup_schedule_notifications_table", + "tableTo": "backup_schedules_table", + "columnsFrom": [ + "schedule_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "backup_schedule_notifications_table_destination_id_notification_destinations_table_id_fk": { + "name": "backup_schedule_notifications_table_destination_id_notification_destinations_table_id_fk", + "tableFrom": "backup_schedule_notifications_table", + "tableTo": "notification_destinations_table", + "columnsFrom": [ + "destination_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "backup_schedule_notifications_table_schedule_id_destination_id_pk": { + "columns": [ + "schedule_id", + "destination_id" + ], + "name": "backup_schedule_notifications_table_schedule_id_destination_id_pk" + } + }, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "backup_schedules_table": { + "name": "backup_schedules_table", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "volume_id": { + "name": "volume_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "repository_id": { + "name": "repository_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "enabled": { + "name": "enabled", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": true + }, + "cron_expression": { + "name": "cron_expression", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "retention_policy": { + "name": "retention_policy", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "exclude_patterns": { + "name": "exclude_patterns", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false, + "default": "'[]'" + }, + "exclude_if_present": { + "name": "exclude_if_present", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false, + "default": "'[]'" + }, + "include_patterns": { + "name": "include_patterns", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false, + "default": "'[]'" + }, + "last_backup_at": { + "name": "last_backup_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "last_backup_status": { + "name": "last_backup_status", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "last_backup_error": { + "name": "last_backup_error", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "next_backup_at": { + "name": "next_backup_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "sort_order": { + "name": "sort_order", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(unixepoch() * 1000)" + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(unixepoch() * 1000)" + } + }, + "indexes": { + "backup_schedules_table_name_unique": { + "name": "backup_schedules_table_name_unique", + "columns": [ + "name" + ], + "isUnique": true + } + }, + "foreignKeys": { + "backup_schedules_table_volume_id_volumes_table_id_fk": { + "name": "backup_schedules_table_volume_id_volumes_table_id_fk", + "tableFrom": "backup_schedules_table", + "tableTo": "volumes_table", + "columnsFrom": [ + "volume_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "backup_schedules_table_repository_id_repositories_table_id_fk": { + "name": "backup_schedules_table_repository_id_repositories_table_id_fk", + "tableFrom": "backup_schedules_table", + "tableTo": "repositories_table", + "columnsFrom": [ + "repository_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "notification_destinations_table": { + "name": "notification_destinations_table", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "enabled": { + "name": "enabled", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": true + }, + "type": { + "name": "type", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "config": { + "name": "config", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(unixepoch() * 1000)" + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(unixepoch() * 1000)" + } + }, + "indexes": { + "notification_destinations_table_name_unique": { + "name": "notification_destinations_table_name_unique", + "columns": [ + "name" + ], + "isUnique": true + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "repositories_table": { + "name": "repositories_table", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "short_id": { + "name": "short_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "type": { + "name": "type", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "config": { + "name": "config", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "compression_mode": { + "name": "compression_mode", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false, + "default": "'auto'" + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false, + "default": "'unknown'" + }, + "last_checked": { + "name": "last_checked", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "last_error": { + "name": "last_error", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(unixepoch() * 1000)" + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(unixepoch() * 1000)" + } + }, + "indexes": { + "repositories_table_short_id_unique": { + "name": "repositories_table_short_id_unique", + "columns": [ + "short_id" + ], + "isUnique": true + }, + "repositories_table_name_unique": { + "name": "repositories_table_name_unique", + "columns": [ + "name" + ], + "isUnique": true + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "sessions_table": { + "name": "sessions_table", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "user_id": { + "name": "user_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "expires_at": { + "name": "expires_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(unixepoch() * 1000)" + } + }, + "indexes": {}, + "foreignKeys": { + "sessions_table_user_id_users_table_id_fk": { + "name": "sessions_table_user_id_users_table_id_fk", + "tableFrom": "sessions_table", + "tableTo": "users_table", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "users_table": { + "name": "users_table", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "username": { + "name": "username", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "password_hash": { + "name": "password_hash", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "has_downloaded_restic_password": { + "name": "has_downloaded_restic_password", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(unixepoch() * 1000)" + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(unixepoch() * 1000)" + } + }, + "indexes": { + "users_table_username_unique": { + "name": "users_table_username_unique", + "columns": [ + "username" + ], + "isUnique": true + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "volumes_table": { + "name": "volumes_table", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "short_id": { + "name": "short_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "type": { + "name": "type", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'unmounted'" + }, + "last_error": { + "name": "last_error", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "last_health_check": { + "name": "last_health_check", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(unixepoch() * 1000)" + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(unixepoch() * 1000)" + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(unixepoch() * 1000)" + }, + "config": { + "name": "config", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "auto_remount": { + "name": "auto_remount", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": true + } + }, + "indexes": { + "volumes_table_short_id_unique": { + "name": "volumes_table_short_id_unique", + "columns": [ + "short_id" + ], + "isUnique": true + }, + "volumes_table_name_unique": { + "name": "volumes_table_name_unique", + "columns": [ + "name" + ], + "isUnique": true + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + } + }, + "views": {}, "enums": {}, "_meta": { "schemas": {}, @@ -13,5 +828,4 @@ "internal": { "indexes": {} } -} - +} \ No newline at end of file diff --git a/app/drizzle/meta/_journal.json b/app/drizzle/meta/_journal.json index 05caf4a0..2b034fbf 100644 --- a/app/drizzle/meta/_journal.json +++ b/app/drizzle/meta/_journal.json @@ -159,8 +159,8 @@ { "idx": 22, "version": "6", - "when": 1765794227000, - "tag": "0022_add_backup_sort_order", + "when": 1765794552191, + "tag": "0022_woozy_shen", "breakpoints": true } ] From 8e49b100426af46d65ef4316646f199596354525 Mon Sep 17 00:00:00 2001 From: Raj Dave Date: Mon, 15 Dec 2025 16:06:21 +0300 Subject: [PATCH 4/7] Validates and improves schedule reordering Ensures schedule reordering requests are valid by checking for duplicate and non-existent IDs. Improves performance by using a transaction for batch updates. --- app/server/modules/backups/backups.service.ts | 35 +++++++++++++++---- 1 file changed, 29 insertions(+), 6 deletions(-) diff --git a/app/server/modules/backups/backups.service.ts b/app/server/modules/backups/backups.service.ts index 372ac0d8..fd7943b6 100644 --- a/app/server/modules/backups/backups.service.ts +++ b/app/server/modules/backups/backups.service.ts @@ -639,13 +639,36 @@ const getMirrorCompatibility = async (scheduleId: number) => { }; 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])); + // Validate input - check for duplicates + const uniqueIds = new Set(scheduleIds); + if (uniqueIds.size !== scheduleIds.length) { + throw new BadRequestError("Duplicate schedule IDs in reorder request"); } + + // Verify all schedules exist + const existingSchedules = await db.query.backupSchedulesTable.findMany({ + columns: { id: true }, + }); + const existingIds = new Set(existingSchedules.map((s) => s.id)); + + for (const id of scheduleIds) { + if (!existingIds.has(id)) { + throw new NotFoundError(`Backup schedule with ID ${id} not found`); + } + } + + // Batch update in a transaction + await db.transaction(async (tx) => { + const now = Date.now(); + await Promise.all( + scheduleIds.map((scheduleId, index) => + tx + .update(backupSchedulesTable) + .set({ sortOrder: index, updatedAt: now }) + .where(eq(backupSchedulesTable.id, scheduleId)), + ), + ); + }); }; export const backupsService = { From 008af5487df7e971108c2c37f745e1132b85a34b Mon Sep 17 00:00:00 2001 From: Raj Dave Date: Mon, 15 Dec 2025 16:19:33 +0300 Subject: [PATCH 5/7] Invalidates backup schedule queries on reorder Ensures the backup schedule list is refreshed after reordering, both on success and on error, by using the dedicated query key instead of a generic string. This guarantees the UI reflects the latest state. --- app/client/modules/backups/routes/backups.tsx | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/app/client/modules/backups/routes/backups.tsx b/app/client/modules/backups/routes/backups.tsx index 929da13c..764ba0ec 100644 --- a/app/client/modules/backups/routes/backups.tsx +++ b/app/client/modules/backups/routes/backups.tsx @@ -19,7 +19,7 @@ import { Button } from "~/client/components/ui/button"; import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "~/client/components/ui/card"; import type { Route } from "./+types/backups"; import { listBackupSchedules } from "~/client/api-client"; -import { listBackupSchedulesOptions } from "~/client/api-client/@tanstack/react-query.gen"; +import { listBackupSchedulesOptions, listBackupSchedulesQueryKey } from "~/client/api-client/@tanstack/react-query.gen"; // Temporary helper until API client is regenerated async function reorderBackupSchedules(scheduleIds: number[]) { @@ -88,7 +88,11 @@ export default function Backups({ loaderData }: Route.ComponentProps) { await reorderBackupSchedules(scheduleIds); }, onSuccess: () => { - queryClient.invalidateQueries({ queryKey: ["listBackupSchedules"] }); + queryClient.invalidateQueries({ queryKey: listBackupSchedulesQueryKey() }); + }, + onError: () => { + // Revert the order or display error to user + queryClient.invalidateQueries({ queryKey: listBackupSchedulesQueryKey() }); }, }); From b983add4ca56ec4f36a35d46a1aba2ebe3fa7042 Mon Sep 17 00:00:00 2001 From: Nicolas Meienberger Date: Tue, 16 Dec 2025 17:38:02 +0100 Subject: [PATCH 6/7] chore(frontend): parametrize server IP --- app/client/api-client/client.gen.ts | 2 +- app/client/api-client/types.gen.ts | 2 +- app/server/core/config.ts | 2 ++ app/server/index.ts | 3 ++- openapi-ts.config.ts | 3 ++- 5 files changed, 8 insertions(+), 4 deletions(-) diff --git a/app/client/api-client/client.gen.ts b/app/client/api-client/client.gen.ts index 4dc9424f..a31c7b49 100644 --- a/app/client/api-client/client.gen.ts +++ b/app/client/api-client/client.gen.ts @@ -13,4 +13,4 @@ import type { ClientOptions as ClientOptions2 } from './types.gen'; */ export type CreateClientConfig = (override?: Config) => Config & T>; -export const client = createClient(createConfig({ baseUrl: 'http://192.168.2.42:4096' })); +export const client = createClient(createConfig({ baseUrl: 'http://localhost:4096' })); diff --git a/app/client/api-client/types.gen.ts b/app/client/api-client/types.gen.ts index 87b61d3e..9da667c1 100644 --- a/app/client/api-client/types.gen.ts +++ b/app/client/api-client/types.gen.ts @@ -1,7 +1,7 @@ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { - baseUrl: 'http://192.168.2.42:4096' | (string & {}); + baseUrl: 'http://localhost:4096' | (string & {}); }; export type RegisterData = { diff --git a/app/server/core/config.ts b/app/server/core/config.ts index bd138c4b..356b341f 100644 --- a/app/server/core/config.ts +++ b/app/server/core/config.ts @@ -3,9 +3,11 @@ import "dotenv/config"; const envSchema = type({ NODE_ENV: type.enumerated("development", "production", "test").default("production"), + SERVER_IP: 'string = "localhost"', }).pipe((s) => ({ __prod__: s.NODE_ENV === "production", environment: s.NODE_ENV, + serverIp: s.SERVER_IP, })); const parseConfig = (env: unknown) => { diff --git a/app/server/index.ts b/app/server/index.ts index 4e4516a5..a9a1d647 100644 --- a/app/server/index.ts +++ b/app/server/index.ts @@ -19,6 +19,7 @@ import { logger } from "./utils/logger"; import { shutdown } from "./modules/lifecycle/shutdown"; import { REQUIRED_MIGRATIONS } from "./core/constants"; import { validateRequiredMigrations } from "./modules/lifecycle/checkpoint"; +import { config } from "./core/config"; export const generalDescriptor = (app: Hono) => openAPIRouteHandler(app, { @@ -28,7 +29,7 @@ export const generalDescriptor = (app: Hono) => version: "1.0.0", description: "API for managing volumes", }, - servers: [{ url: "http://192.168.2.42:4096", description: "Development Server" }], + servers: [{ url: `http://${config.serverIp}:4096`, description: "Development Server" }], }, }); diff --git a/openapi-ts.config.ts b/openapi-ts.config.ts index 08a16687..1cde65df 100644 --- a/openapi-ts.config.ts +++ b/openapi-ts.config.ts @@ -1,7 +1,8 @@ import { defaultPlugins, defineConfig } from "@hey-api/openapi-ts"; +import { config } from "./app/server/core/config.js"; export default defineConfig({ - input: "http://192.168.2.42:4096/api/v1/openapi.json", + input: `http://${config.serverIp}:4096/api/v1/openapi.json`, output: { path: "./app/client/api-client", format: "biome", From e57efcfcdc4af5cabd0656b03950f98be14ceba9 Mon Sep 17 00:00:00 2001 From: Nicolas Meienberger Date: Tue, 16 Dec 2025 20:23:44 +0100 Subject: [PATCH 7/7] refactor: extract sortable card into its own component --- .../api-client/@tanstack/react-query.gen.ts | 21 ++++- app/client/api-client/sdk.gen.ts | 14 +++- app/client/api-client/types.gen.ts | 20 +++++ app/client/components/sortable-card.tsx | 34 ++++++++ .../backups/components/backup-card.tsx | 54 ++++++++++++ .../components/sortable-backup-card.tsx | 82 ------------------- app/client/modules/backups/routes/backups.tsx | 59 ++++--------- app/server/modules/backups/backups.service.ts | 3 - bun.lock | 11 +++ 9 files changed, 168 insertions(+), 130 deletions(-) create mode 100644 app/client/components/sortable-card.tsx create mode 100644 app/client/modules/backups/components/backup-card.tsx delete mode 100644 app/client/modules/backups/components/sortable-backup-card.tsx diff --git a/app/client/api-client/@tanstack/react-query.gen.ts b/app/client/api-client/@tanstack/react-query.gen.ts index d346c652..e5c39e40 100644 --- a/app/client/api-client/@tanstack/react-query.gen.ts +++ b/app/client/api-client/@tanstack/react-query.gen.ts @@ -3,8 +3,8 @@ import { type DefaultError, queryOptions, type UseMutationOptions } from '@tanstack/react-query'; import { client } from '../client.gen'; -import { browseFilesystem, changePassword, createBackupSchedule, createNotificationDestination, createRepository, createVolume, deleteBackupSchedule, deleteNotificationDestination, deleteRepository, deleteSnapshot, deleteVolume, doctorRepository, downloadResticPassword, getBackupSchedule, getBackupScheduleForVolume, getMe, getMirrorCompatibility, getNotificationDestination, getRepository, getScheduleMirrors, getScheduleNotifications, getSnapshotDetails, getStatus, getSystemInfo, getVolume, healthCheckVolume, listBackupSchedules, listFiles, listNotificationDestinations, listRcloneRemotes, listRepositories, listSnapshotFiles, listSnapshots, listVolumes, login, logout, mountVolume, type Options, register, restoreSnapshot, runBackupNow, runForget, stopBackup, testConnection, testNotificationDestination, unmountVolume, updateBackupSchedule, updateNotificationDestination, updateRepository, updateScheduleMirrors, updateScheduleNotifications, updateVolume } from '../sdk.gen'; -import type { BrowseFilesystemData, BrowseFilesystemResponse, ChangePasswordData, ChangePasswordResponse, CreateBackupScheduleData, CreateBackupScheduleResponse, CreateNotificationDestinationData, CreateNotificationDestinationResponse, CreateRepositoryData, CreateRepositoryResponse, CreateVolumeData, CreateVolumeResponse, DeleteBackupScheduleData, DeleteBackupScheduleResponse, DeleteNotificationDestinationData, DeleteNotificationDestinationResponse, DeleteRepositoryData, DeleteRepositoryResponse, DeleteSnapshotData, DeleteSnapshotResponse, DeleteVolumeData, DeleteVolumeResponse, DoctorRepositoryData, DoctorRepositoryResponse, DownloadResticPasswordData, DownloadResticPasswordResponse, GetBackupScheduleData, GetBackupScheduleForVolumeData, GetBackupScheduleForVolumeResponse, GetBackupScheduleResponse, GetMeData, GetMeResponse, GetMirrorCompatibilityData, GetMirrorCompatibilityResponse, GetNotificationDestinationData, GetNotificationDestinationResponse, GetRepositoryData, GetRepositoryResponse, GetScheduleMirrorsData, GetScheduleMirrorsResponse, GetScheduleNotificationsData, GetScheduleNotificationsResponse, GetSnapshotDetailsData, GetSnapshotDetailsResponse, GetStatusData, GetStatusResponse, GetSystemInfoData, GetSystemInfoResponse, GetVolumeData, GetVolumeResponse, HealthCheckVolumeData, HealthCheckVolumeResponse, ListBackupSchedulesData, ListBackupSchedulesResponse, ListFilesData, ListFilesResponse, ListNotificationDestinationsData, ListNotificationDestinationsResponse, ListRcloneRemotesData, ListRcloneRemotesResponse, ListRepositoriesData, ListRepositoriesResponse, ListSnapshotFilesData, ListSnapshotFilesResponse, ListSnapshotsData, ListSnapshotsResponse, ListVolumesData, ListVolumesResponse, LoginData, LoginResponse, LogoutData, LogoutResponse, MountVolumeData, MountVolumeResponse, RegisterData, RegisterResponse, RestoreSnapshotData, RestoreSnapshotResponse, RunBackupNowData, RunBackupNowResponse, RunForgetData, RunForgetResponse, StopBackupData, StopBackupResponse, TestConnectionData, TestConnectionResponse, TestNotificationDestinationData, TestNotificationDestinationResponse, UnmountVolumeData, UnmountVolumeResponse, UpdateBackupScheduleData, UpdateBackupScheduleResponse, UpdateNotificationDestinationData, UpdateNotificationDestinationResponse, UpdateRepositoryData, UpdateRepositoryResponse, UpdateScheduleMirrorsData, UpdateScheduleMirrorsResponse, UpdateScheduleNotificationsData, UpdateScheduleNotificationsResponse, UpdateVolumeData, UpdateVolumeResponse } from '../types.gen'; +import { browseFilesystem, changePassword, createBackupSchedule, createNotificationDestination, createRepository, createVolume, deleteBackupSchedule, deleteNotificationDestination, deleteRepository, deleteSnapshot, deleteVolume, doctorRepository, downloadResticPassword, getBackupSchedule, getBackupScheduleForVolume, getMe, getMirrorCompatibility, getNotificationDestination, getRepository, getScheduleMirrors, getScheduleNotifications, getSnapshotDetails, getStatus, getSystemInfo, getVolume, healthCheckVolume, listBackupSchedules, listFiles, listNotificationDestinations, listRcloneRemotes, listRepositories, listSnapshotFiles, listSnapshots, listVolumes, login, logout, mountVolume, type Options, register, reorderBackupSchedules, restoreSnapshot, runBackupNow, runForget, stopBackup, testConnection, testNotificationDestination, unmountVolume, updateBackupSchedule, updateNotificationDestination, updateRepository, updateScheduleMirrors, updateScheduleNotifications, updateVolume } from '../sdk.gen'; +import type { BrowseFilesystemData, BrowseFilesystemResponse, ChangePasswordData, ChangePasswordResponse, CreateBackupScheduleData, CreateBackupScheduleResponse, CreateNotificationDestinationData, CreateNotificationDestinationResponse, CreateRepositoryData, CreateRepositoryResponse, CreateVolumeData, CreateVolumeResponse, DeleteBackupScheduleData, DeleteBackupScheduleResponse, DeleteNotificationDestinationData, DeleteNotificationDestinationResponse, DeleteRepositoryData, DeleteRepositoryResponse, DeleteSnapshotData, DeleteSnapshotResponse, DeleteVolumeData, DeleteVolumeResponse, DoctorRepositoryData, DoctorRepositoryResponse, DownloadResticPasswordData, DownloadResticPasswordResponse, GetBackupScheduleData, GetBackupScheduleForVolumeData, GetBackupScheduleForVolumeResponse, GetBackupScheduleResponse, GetMeData, GetMeResponse, GetMirrorCompatibilityData, GetMirrorCompatibilityResponse, GetNotificationDestinationData, GetNotificationDestinationResponse, GetRepositoryData, GetRepositoryResponse, GetScheduleMirrorsData, GetScheduleMirrorsResponse, GetScheduleNotificationsData, GetScheduleNotificationsResponse, GetSnapshotDetailsData, GetSnapshotDetailsResponse, GetStatusData, GetStatusResponse, GetSystemInfoData, GetSystemInfoResponse, GetVolumeData, GetVolumeResponse, HealthCheckVolumeData, HealthCheckVolumeResponse, ListBackupSchedulesData, ListBackupSchedulesResponse, ListFilesData, ListFilesResponse, ListNotificationDestinationsData, ListNotificationDestinationsResponse, ListRcloneRemotesData, ListRcloneRemotesResponse, ListRepositoriesData, ListRepositoriesResponse, ListSnapshotFilesData, ListSnapshotFilesResponse, ListSnapshotsData, ListSnapshotsResponse, ListVolumesData, ListVolumesResponse, LoginData, LoginResponse, LogoutData, LogoutResponse, MountVolumeData, MountVolumeResponse, RegisterData, RegisterResponse, ReorderBackupSchedulesData, ReorderBackupSchedulesResponse, RestoreSnapshotData, RestoreSnapshotResponse, RunBackupNowData, RunBackupNowResponse, RunForgetData, RunForgetResponse, StopBackupData, StopBackupResponse, TestConnectionData, TestConnectionResponse, TestNotificationDestinationData, TestNotificationDestinationResponse, UnmountVolumeData, UnmountVolumeResponse, UpdateBackupScheduleData, UpdateBackupScheduleResponse, UpdateNotificationDestinationData, UpdateNotificationDestinationResponse, UpdateRepositoryData, UpdateRepositoryResponse, UpdateScheduleMirrorsData, UpdateScheduleMirrorsResponse, UpdateScheduleNotificationsData, UpdateScheduleNotificationsResponse, UpdateVolumeData, UpdateVolumeResponse } from '../types.gen'; /** * Register a new user @@ -788,6 +788,23 @@ export const getMirrorCompatibilityOptions = (options: Options>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await reorderBackupSchedules({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + export const listNotificationDestinationsQueryKey = (options?: Options) => createQueryKey('listNotificationDestinations', options); /** diff --git a/app/client/api-client/sdk.gen.ts b/app/client/api-client/sdk.gen.ts index 034c5f9d..4f3e083e 100644 --- a/app/client/api-client/sdk.gen.ts +++ b/app/client/api-client/sdk.gen.ts @@ -2,7 +2,7 @@ import type { Client, Options as Options2, TDataShape } from './client'; import { client } from './client.gen'; -import type { BrowseFilesystemData, BrowseFilesystemResponses, ChangePasswordData, ChangePasswordResponses, CreateBackupScheduleData, CreateBackupScheduleResponses, CreateNotificationDestinationData, CreateNotificationDestinationResponses, CreateRepositoryData, CreateRepositoryResponses, CreateVolumeData, CreateVolumeResponses, DeleteBackupScheduleData, DeleteBackupScheduleResponses, DeleteNotificationDestinationData, DeleteNotificationDestinationErrors, DeleteNotificationDestinationResponses, DeleteRepositoryData, DeleteRepositoryResponses, DeleteSnapshotData, DeleteSnapshotResponses, DeleteVolumeData, DeleteVolumeResponses, DoctorRepositoryData, DoctorRepositoryResponses, DownloadResticPasswordData, DownloadResticPasswordResponses, GetBackupScheduleData, GetBackupScheduleForVolumeData, GetBackupScheduleForVolumeResponses, GetBackupScheduleResponses, GetMeData, GetMeResponses, GetMirrorCompatibilityData, GetMirrorCompatibilityResponses, GetNotificationDestinationData, GetNotificationDestinationErrors, GetNotificationDestinationResponses, GetRepositoryData, GetRepositoryResponses, GetScheduleMirrorsData, GetScheduleMirrorsResponses, GetScheduleNotificationsData, GetScheduleNotificationsResponses, GetSnapshotDetailsData, GetSnapshotDetailsResponses, GetStatusData, GetStatusResponses, GetSystemInfoData, GetSystemInfoResponses, GetVolumeData, GetVolumeErrors, GetVolumeResponses, HealthCheckVolumeData, HealthCheckVolumeErrors, HealthCheckVolumeResponses, ListBackupSchedulesData, ListBackupSchedulesResponses, ListFilesData, ListFilesResponses, ListNotificationDestinationsData, ListNotificationDestinationsResponses, ListRcloneRemotesData, ListRcloneRemotesResponses, ListRepositoriesData, ListRepositoriesResponses, ListSnapshotFilesData, ListSnapshotFilesResponses, ListSnapshotsData, ListSnapshotsResponses, ListVolumesData, ListVolumesResponses, LoginData, LoginResponses, LogoutData, LogoutResponses, MountVolumeData, MountVolumeResponses, RegisterData, RegisterResponses, RestoreSnapshotData, RestoreSnapshotResponses, RunBackupNowData, RunBackupNowResponses, RunForgetData, RunForgetResponses, StopBackupData, StopBackupErrors, StopBackupResponses, TestConnectionData, TestConnectionResponses, TestNotificationDestinationData, TestNotificationDestinationErrors, TestNotificationDestinationResponses, UnmountVolumeData, UnmountVolumeResponses, UpdateBackupScheduleData, UpdateBackupScheduleResponses, UpdateNotificationDestinationData, UpdateNotificationDestinationErrors, UpdateNotificationDestinationResponses, UpdateRepositoryData, UpdateRepositoryErrors, UpdateRepositoryResponses, UpdateScheduleMirrorsData, UpdateScheduleMirrorsResponses, UpdateScheduleNotificationsData, UpdateScheduleNotificationsResponses, UpdateVolumeData, UpdateVolumeErrors, UpdateVolumeResponses } from './types.gen'; +import type { BrowseFilesystemData, BrowseFilesystemResponses, ChangePasswordData, ChangePasswordResponses, CreateBackupScheduleData, CreateBackupScheduleResponses, CreateNotificationDestinationData, CreateNotificationDestinationResponses, CreateRepositoryData, CreateRepositoryResponses, CreateVolumeData, CreateVolumeResponses, DeleteBackupScheduleData, DeleteBackupScheduleResponses, DeleteNotificationDestinationData, DeleteNotificationDestinationErrors, DeleteNotificationDestinationResponses, DeleteRepositoryData, DeleteRepositoryResponses, DeleteSnapshotData, DeleteSnapshotResponses, DeleteVolumeData, DeleteVolumeResponses, DoctorRepositoryData, DoctorRepositoryResponses, DownloadResticPasswordData, DownloadResticPasswordResponses, GetBackupScheduleData, GetBackupScheduleForVolumeData, GetBackupScheduleForVolumeResponses, GetBackupScheduleResponses, GetMeData, GetMeResponses, GetMirrorCompatibilityData, GetMirrorCompatibilityResponses, GetNotificationDestinationData, GetNotificationDestinationErrors, GetNotificationDestinationResponses, GetRepositoryData, GetRepositoryResponses, GetScheduleMirrorsData, GetScheduleMirrorsResponses, GetScheduleNotificationsData, GetScheduleNotificationsResponses, GetSnapshotDetailsData, GetSnapshotDetailsResponses, GetStatusData, GetStatusResponses, GetSystemInfoData, GetSystemInfoResponses, GetVolumeData, GetVolumeErrors, GetVolumeResponses, HealthCheckVolumeData, HealthCheckVolumeErrors, HealthCheckVolumeResponses, ListBackupSchedulesData, ListBackupSchedulesResponses, ListFilesData, ListFilesResponses, ListNotificationDestinationsData, ListNotificationDestinationsResponses, ListRcloneRemotesData, ListRcloneRemotesResponses, ListRepositoriesData, ListRepositoriesResponses, ListSnapshotFilesData, ListSnapshotFilesResponses, ListSnapshotsData, ListSnapshotsResponses, ListVolumesData, ListVolumesResponses, LoginData, LoginResponses, LogoutData, LogoutResponses, MountVolumeData, MountVolumeResponses, RegisterData, RegisterResponses, ReorderBackupSchedulesData, ReorderBackupSchedulesResponses, RestoreSnapshotData, RestoreSnapshotResponses, RunBackupNowData, RunBackupNowResponses, RunForgetData, RunForgetResponses, StopBackupData, StopBackupErrors, StopBackupResponses, TestConnectionData, TestConnectionResponses, TestNotificationDestinationData, TestNotificationDestinationErrors, TestNotificationDestinationResponses, UnmountVolumeData, UnmountVolumeResponses, UpdateBackupScheduleData, UpdateBackupScheduleResponses, UpdateNotificationDestinationData, UpdateNotificationDestinationErrors, UpdateNotificationDestinationResponses, UpdateRepositoryData, UpdateRepositoryErrors, UpdateRepositoryResponses, UpdateScheduleMirrorsData, UpdateScheduleMirrorsResponses, UpdateScheduleNotificationsData, UpdateScheduleNotificationsResponses, UpdateVolumeData, UpdateVolumeErrors, UpdateVolumeResponses } from './types.gen'; export type Options = Options2 & { /** @@ -324,6 +324,18 @@ export const updateScheduleMirrors = (opti */ export const getMirrorCompatibility = (options: Options) => (options.client ?? client).get({ url: '/api/v1/backups/{scheduleId}/mirrors/compatibility', ...options }); +/** + * Reorder backup schedules by providing an array of schedule IDs in the desired order + */ +export const reorderBackupSchedules = (options?: Options) => (options?.client ?? client).post({ + url: '/api/v1/backups/reorder', + ...options, + headers: { + 'Content-Type': 'application/json', + ...options?.headers + } +}); + /** * List all notification destinations */ diff --git a/app/client/api-client/types.gen.ts b/app/client/api-client/types.gen.ts index 9da667c1..eb9dc447 100644 --- a/app/client/api-client/types.gen.ts +++ b/app/client/api-client/types.gen.ts @@ -2376,6 +2376,26 @@ export type GetMirrorCompatibilityResponses = { export type GetMirrorCompatibilityResponse = GetMirrorCompatibilityResponses[keyof GetMirrorCompatibilityResponses]; +export type ReorderBackupSchedulesData = { + body?: { + scheduleIds: Array; + }; + path?: never; + query?: never; + url: '/api/v1/backups/reorder'; +}; + +export type ReorderBackupSchedulesResponses = { + /** + * Backup schedules reordered successfully + */ + 200: { + success: boolean; + }; +}; + +export type ReorderBackupSchedulesResponse = ReorderBackupSchedulesResponses[keyof ReorderBackupSchedulesResponses]; + export type ListNotificationDestinationsData = { body?: never; path?: never; diff --git a/app/client/components/sortable-card.tsx b/app/client/components/sortable-card.tsx new file mode 100644 index 00000000..bca84b7f --- /dev/null +++ b/app/client/components/sortable-card.tsx @@ -0,0 +1,34 @@ +import { useSortable } from "@dnd-kit/sortable"; +import { CSS } from "@dnd-kit/utilities"; +import { GripVertical } from "lucide-react"; +import type { PropsWithChildren } from "react"; + +interface SortableBackupCardProps { + isDragging?: boolean; + uniqueId: number; +} + +export function SortableCard({ isDragging, uniqueId, children }: PropsWithChildren) { + const { attributes, listeners, setNodeRef, transform, transition } = useSortable({ + id: uniqueId, + }); + + const style = { + transform: CSS.Transform.toString(transform), + transition, + opacity: isDragging ? 0.5 : 1, + }; + + return ( +
+
+ +
+ {children} +
+ ); +} diff --git a/app/client/modules/backups/components/backup-card.tsx b/app/client/modules/backups/components/backup-card.tsx new file mode 100644 index 00000000..85249704 --- /dev/null +++ b/app/client/modules/backups/components/backup-card.tsx @@ -0,0 +1,54 @@ +import { CalendarClock, Database, HardDrive } from "lucide-react"; +import { Link } from "react-router"; +import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "~/client/components/ui/card"; +import type { BackupSchedule } from "~/client/lib/types"; +import { BackupStatusDot } from "./backup-status-dot"; + +export const BackupCard = ({ schedule }: { schedule: BackupSchedule }) => { + return ( + + + +
+
+ + {schedule.name} +
+ +
+ + + {schedule.volume.name} + + + {schedule.repository.name} + +
+ +
+
+ Schedule + {schedule.cronExpression} +
+
+ Last backup + + {schedule.lastBackupAt ? new Date(schedule.lastBackupAt).toLocaleDateString() : "Never"} + +
+
+ Next backup + + {schedule.nextBackupAt ? new Date(schedule.nextBackupAt).toLocaleDateString() : "N/A"} + +
+
+
+
+ + ); +}; diff --git a/app/client/modules/backups/components/sortable-backup-card.tsx b/app/client/modules/backups/components/sortable-backup-card.tsx deleted file mode 100644 index 8a7b98f5..00000000 --- a/app/client/modules/backups/components/sortable-backup-card.tsx +++ /dev/null @@ -1,82 +0,0 @@ -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 ( -
-
- -
- - - -
-
- - {schedule.name} -
- -
- - - {schedule.volume.name} - - - {schedule.repository.name} - -
- -
-
- Schedule - {schedule.cronExpression} -
-
- Last backup - - {schedule.lastBackupAt ? new Date(schedule.lastBackupAt).toLocaleDateString() : "Never"} - -
-
- Next backup - - {schedule.nextBackupAt ? new Date(schedule.nextBackupAt).toLocaleDateString() : "N/A"} - -
-
-
-
- -
- ); -} diff --git a/app/client/modules/backups/routes/backups.tsx b/app/client/modules/backups/routes/backups.tsx index 764ba0ec..76f0c714 100644 --- a/app/client/modules/backups/routes/backups.tsx +++ b/app/client/modules/backups/routes/backups.tsx @@ -1,4 +1,4 @@ -import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; +import { useMutation, useQuery } from "@tanstack/react-query"; import { DndContext, closestCenter, @@ -9,32 +9,20 @@ import { type DragEndEvent, } from "@dnd-kit/core"; import { arrayMove, SortableContext, sortableKeyboardCoordinates, rectSortingStrategy } from "@dnd-kit/sortable"; -import { CalendarClock, Database, HardDrive, Plus } from "lucide-react"; +import { CalendarClock, 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"; -import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "~/client/components/ui/card"; +import { Card, CardContent } from "~/client/components/ui/card"; import type { Route } from "./+types/backups"; import { listBackupSchedules } from "~/client/api-client"; -import { listBackupSchedulesOptions, listBackupSchedulesQueryKey } 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(); -} +import { + listBackupSchedulesOptions, + reorderBackupSchedulesMutation, +} from "~/client/api-client/@tanstack/react-query.gen"; +import { SortableCard } from "~/client/components/sortable-card"; +import { BackupCard } from "../components/backup-card"; export const handle = { breadcrumb: () => [{ label: "Backups" }], @@ -57,15 +45,12 @@ 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)); @@ -74,9 +59,7 @@ export default function Backups({ loaderData }: Route.ComponentProps) { const sensors = useSensors( useSensor(PointerSensor, { - activationConstraint: { - distance: 8, - }, + activationConstraint: { distance: 8 }, }), useSensor(KeyboardSensor, { coordinateGetter: sortableKeyboardCoordinates, @@ -84,16 +67,7 @@ export default function Backups({ loaderData }: Route.ComponentProps) { ); const reorderMutation = useMutation({ - mutationFn: async (scheduleIds: number[]) => { - await reorderBackupSchedules(scheduleIds); - }, - onSuccess: () => { - queryClient.invalidateQueries({ queryKey: listBackupSchedulesQueryKey() }); - }, - onError: () => { - // Revert the order or display error to user - queryClient.invalidateQueries({ queryKey: listBackupSchedulesQueryKey() }); - }, + ...reorderBackupSchedulesMutation(), }); const handleDragEnd = (event: DragEndEvent) => { @@ -104,9 +78,7 @@ export default function Backups({ loaderData }: Route.ComponentProps) { 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); + reorderMutation.mutate({ body: { scheduleIds: newItems } }); return newItems; }); @@ -139,7 +111,6 @@ export default function Backups({ loaderData }: Route.ComponentProps) { ); } - // Create a map for quick lookup const scheduleMap = new Map(schedules.map((s) => [s.id, s])); return ( @@ -150,7 +121,11 @@ export default function Backups({ loaderData }: Route.ComponentProps) { {items.map((id) => { const schedule = scheduleMap.get(id); if (!schedule) return null; - return ; + return ( + + + + ); })} diff --git a/app/server/modules/backups/backups.service.ts b/app/server/modules/backups/backups.service.ts index fd7943b6..584fada7 100644 --- a/app/server/modules/backups/backups.service.ts +++ b/app/server/modules/backups/backups.service.ts @@ -639,13 +639,11 @@ const getMirrorCompatibility = async (scheduleId: number) => { }; const reorderSchedules = async (scheduleIds: number[]) => { - // Validate input - check for duplicates const uniqueIds = new Set(scheduleIds); if (uniqueIds.size !== scheduleIds.length) { throw new BadRequestError("Duplicate schedule IDs in reorder request"); } - // Verify all schedules exist const existingSchedules = await db.query.backupSchedulesTable.findMany({ columns: { id: true }, }); @@ -657,7 +655,6 @@ const reorderSchedules = async (scheduleIds: number[]) => { } } - // Batch update in a transaction await db.transaction(async (tx) => { const now = Date.now(); await Promise.all( diff --git a/bun.lock b/bun.lock index dc0ac731..1668570b 100644 --- a/bun.lock +++ b/bun.lock @@ -4,6 +4,9 @@ "workspaces": { "": { "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", @@ -156,6 +159,14 @@ "@dabh/diagnostics": ["@dabh/diagnostics@2.0.8", "", { "dependencies": { "@so-ric/colorspace": "^1.1.6", "enabled": "2.0.x", "kuler": "^2.0.0" } }, "sha512-R4MSXTVnuMzGD7bzHdW2ZhhdPC/igELENcq5IjEverBvq5hn1SXCWcsi6eSsdWP0/Ur+SItRRjAktmdoX/8R/Q=="], + "@dnd-kit/accessibility": ["@dnd-kit/accessibility@3.1.1", "", { "dependencies": { "tslib": "^2.0.0" }, "peerDependencies": { "react": ">=16.8.0" } }, "sha512-2P+YgaXF+gRsIihwwY1gCsQSYnu9Zyj2py8kY5fFvUM1qm2WA2u639R6YNVfU4GWr+ZM5mqEsfHZZLoRONbemw=="], + + "@dnd-kit/core": ["@dnd-kit/core@6.3.1", "", { "dependencies": { "@dnd-kit/accessibility": "^3.1.1", "@dnd-kit/utilities": "^3.2.2", "tslib": "^2.0.0" }, "peerDependencies": { "react": ">=16.8.0", "react-dom": ">=16.8.0" } }, "sha512-xkGBRQQab4RLwgXxoqETICr6S5JlogafbhNsidmrkVv2YRs5MLwpjoF2qpiGjQt8S9AoxtIV603s0GIUpY5eYQ=="], + + "@dnd-kit/sortable": ["@dnd-kit/sortable@10.0.0", "", { "dependencies": { "@dnd-kit/utilities": "^3.2.2", "tslib": "^2.0.0" }, "peerDependencies": { "@dnd-kit/core": "^6.3.0", "react": ">=16.8.0" } }, "sha512-+xqhmIIzvAYMGfBYYnbKuNicfSsk4RksY2XdmJhT+HAC01nix6fHCztU68jooFiMUB01Ky3F0FyOvhG/BZrWkg=="], + + "@dnd-kit/utilities": ["@dnd-kit/utilities@3.2.2", "", { "dependencies": { "tslib": "^2.0.0" }, "peerDependencies": { "react": ">=16.8.0" } }, "sha512-+MKAJEOfaBe5SmV6t34p80MMKhjvUz0vRrvVJbPT0WElzaOJ/1xs+D+KDv+tD/NE5ujfrChEcshd4fLn0wpiqg=="], + "@drizzle-team/brocli": ["@drizzle-team/brocli@0.10.2", "", {}, "sha512-z33Il7l5dKjUgGULTqBsQBQwckHh5AbIuxhdsIxDDiZAzBOrZO6q9ogcWC65kU382AfynTfgNumVcNIjuIua6w=="], "@esbuild-kit/core-utils": ["@esbuild-kit/core-utils@3.3.2", "", { "dependencies": { "esbuild": "~0.18.20", "source-map-support": "^0.5.21" } }, "sha512-sPRAnw9CdSsRmEtnsl2WXWdyquogVpB3yZ3dgwJfe8zrOzTsV7cJvmwrKVa+0ma5BoiGJ+BoqkMvawbayKUsqQ=="],