Your favorite shift management application!
feat: implement calendar deletion feature with confirmation dialog and password protection
panteLx03c633629f01
diff --git a/README.md b/README.mdindex f530ab4..61fdc64 100644--- a/README.md+++ b/README.md@@ -4,7 +4,7 @@ A modern shift management application built with Next.js and SQLite. BetterShift## Features-- 📅 **Multiple Calendars**: Create and manage multiple shift calendars+- 📅 **Multiple Calendars**: Create, manage and delete multiple shift calendars- ⏰ **Shift Management**: Add, edit, and delete shifts with start/end times- 🎨 **Color Coding**: Assign colors to calendars for better visualization- 📋 **Shift Presets**: Create reusable shift templates for faster schedulingdiff --git a/app/page.tsx b/app/page.tsxindex 2704a1c..a78e44f 100644--- a/app/page.tsx+++ b/app/page.tsx@@ -1,6 +1,6 @@"use client";-import { useState, useEffect, Suspense } from "react";+import { useState, useEffect, Suspense, useRef } from "react";import { useRouter, useSearchParams } from "next/navigation";import { useTranslations, useLocale } from "next-intl";import { ShiftWithCalendar, CalendarWithCount } from "@/lib/types";@@ -11,6 +11,7 @@ import { ShiftCard } from "@/components/shift-card";import { PresetSelector } from "@/components/preset-selector";import { PasswordDialog } from "@/components/password-dialog";import { ManagePasswordDialog } from "@/components/manage-password-dialog";+import { DeleteCalendarDialog } from "@/components/delete-calendar-dialog";import { LanguageSwitcher } from "@/components/language-switcher";import { ShiftStats } from "@/components/shift-stats";import { NoteDialog } from "@/components/note-dialog";@@ -70,6 +71,11 @@ function HomeContent() {const [showMobileCalendarDialog, setShowMobileCalendarDialog] =useState(false);const [showNoteDialog, setShowNoteDialog] = useState(false);+ const [showDeleteCalendarDialog, setShowDeleteCalendarDialog] =+ useState(false);+ const [calendarToDelete, setCalendarToDelete] = useState<+ string | undefined+ >();const [selectedNote, setSelectedNote] = useState<CalendarNote | undefined>();const [notes, setNotes] = useState<CalendarNote[]>([]);const [pendingAction, setPendingAction] = useState<{@@ -80,10 +86,18 @@ function HomeContent() {} | null>(null);const [loading, setLoading] = useState(true);const [statsRefreshTrigger, setStatsRefreshTrigger] = useState(0);+ const [isTogglingShift, setIsTogglingShift] = useState(false);+ const pollingIntervalRef = useRef<NodeJS.Timeout | null>(null);- // Fetch calendars on mount+ // Fetch calendars on mount and setup cleanupuseEffect(() => {fetchCalendars();++ return () => {+ if (pollingIntervalRef.current) {+ clearInterval(pollingIntervalRef.current);+ }+ };}, []);// Update URL when selected calendar changes@@ -93,16 +107,34 @@ function HomeContent() {}}, [selectedCalendar, router]);- // Fetch shifts and presets when calendar changes+ // Fetch shifts and presets when calendar changes and setup pollinguseEffect(() => {if (selectedCalendar) {fetchShifts();fetchPresets();fetchNotes();++ // Setup polling for live sync (every 5 seconds)+ if (pollingIntervalRef.current) {+ clearInterval(pollingIntervalRef.current);+ }+ const interval = setInterval(() => {+ fetchShifts();+ fetchPresets();+ fetchNotes();+ }, 5000);+ pollingIntervalRef.current = interval;++ return () => {+ clearInterval(interval);+ };} else {setShifts([]);setPresets([]);setNotes([]);+ if (pollingIntervalRef.current) {+ clearInterval(pollingIntervalRef.current);+ }}}, [selectedCalendar]);@@ -191,9 +223,72 @@ function HomeContent() {}};+ const initiateDeleteCalendar = (id: string) => {+ setCalendarToDelete(id);+ setShowDeleteCalendarDialog(true);+ };++ const deleteCalendar = async (password?: string) => {+ if (!calendarToDelete) return;++ try {+ const url = password+ ? `/api/calendars/${calendarToDelete}?password=${encodeURIComponent(+ password+ )}`+ : `/api/calendars/${calendarToDelete}`;++ const response = await fetch(url, { method: "DELETE" });++ if (response.status === 401) {+ alert(t("password.errorIncorrect"));+ return;+ }++ if (response.ok) {+ const remainingCalendars = calendars.filter(+ (c) => c.id !== calendarToDelete+ );+ setCalendars(remainingCalendars);+ localStorage.removeItem(`calendar_password_${calendarToDelete}`);++ // If deleting the selected calendar, select the first remaining one or undefined+ if (selectedCalendar === calendarToDelete) {+ setSelectedCalendar(+ remainingCalendars.length > 0 ? remainingCalendars[0].id : undefined+ );+ }++ setShowDeleteCalendarDialog(false);+ setCalendarToDelete(undefined);+ }+ } catch (error) {+ console.error("Failed to delete calendar:", error);+ }+ };+const createShift = async (formData: ShiftFormData) => {if (!selectedCalendar) return;+ // Optimistic update: add shift immediately with temporary ID+ const tempId = `temp-${Date.now()}`;+ const optimisticShift: ShiftWithCalendar = {+ id: tempId,+ date: new Date(formData.date),+ startTime: formData.startTime,+ endTime: formData.endTime,+ title: formData.title,+ color: formData.color || "#000000",+ notes: formData.notes || null,+ isAllDay: formData.isAllDay || false,+ calendarId: selectedCalendar,+ createdAt: new Date(),+ updatedAt: new Date(),+ };++ setShifts([...shifts, optimisticShift]);+ setStatsRefreshTrigger((prev) => prev + 1);+try {const response = await fetch("/api/shifts", {method: "POST",@@ -204,10 +299,15 @@ function HomeContent() {}),});const newShift = await response.json();- setShifts([...shifts, newShift]);- setStatsRefreshTrigger((prev) => prev + 1);+ // Replace optimistic shift with real one+ setShifts((shifts) =>+ shifts.map((s) => (s.id === tempId ? newShift : s))+ );} catch (error) {console.error("Failed to create shift:", error);+ // Rollback optimistic update on error+ setShifts((shifts) => shifts.filter((s) => s.id !== tempId));+ setStatsRefreshTrigger((prev) => prev + 1);}};@@ -414,6 +514,9 @@ function HomeContent() {};const handleAddShift = async (date: Date) => {+ // Prevent multiple simultaneous toggles (debouncing)+ if (isTogglingShift) return;+// Only proceed if a preset is selectedif (!selectedPresetId) return;@@ -422,62 +525,94 @@ function HomeContent() {// Check password before adding/deleting shiftconst checkAndToggle = async () => {- const password = selectedCalendar- ? localStorage.getItem(`calendar_password_${selectedCalendar}`)- : null;+ setIsTogglingShift(true);++ try {+ const password = selectedCalendar+ ? localStorage.getItem(`calendar_password_${selectedCalendar}`)+ : null;++ // Verify password if calendar is protected+ if (selectedCalendar) {+ const response = await fetch(+ `/api/calendars/${selectedCalendar}/verify-password`,+ {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ password }),+ }+ );- // Verify password if calendar is protected- if (selectedCalendar) {- const response = await fetch(- `/api/calendars/${selectedCalendar}/verify-password`,- {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ password }),+ const data = await response.json();++ if (data.protected && !data.valid) {+ // Password required or invalid+ localStorage.removeItem(`calendar_password_${selectedCalendar}`);+ setPendingAction({+ type: "edit",+ presetAction: () => handleAddShift(date),+ });+ setShowPasswordDialog(true);+ setIsTogglingShift(false);+ return;}- );-- const data = await response.json();-- if (data.protected && !data.valid) {- // Password required or invalid- localStorage.removeItem(`calendar_password_${selectedCalendar}`);- setPendingAction({- type: "edit",- presetAction: () => handleAddShift(date),- });- setShowPasswordDialog(true);- return;}- }- // Password valid or not required, proceed with toggle- // Check if a shift with the same preset already exists on this date- const existingShift = shifts.find(- (shift) =>- shift.date &&- isSameDay(new Date(shift.date), date) &&- shift.title === preset.title &&- shift.startTime === preset.startTime &&- shift.endTime === preset.endTime- );+ // Password valid or not required, proceed with toggle+ // Check if a shift with the same preset already exists on this date+ const existingShift = shifts.find(+ (shift) =>+ shift.date &&+ isSameDay(new Date(shift.date), date) &&+ shift.title === preset.title &&+ shift.startTime === preset.startTime &&+ shift.endTime === preset.endTime+ );- if (existingShift) {- // Toggle: remove the existing shift- await deleteShift(existingShift.id);- } else {- // Toggle: add the shift- const shiftData: ShiftFormData = {- date: formatDateToLocal(date),- startTime: preset.startTime,- endTime: preset.endTime,- title: preset.title,- color: preset.color,- notes: preset.notes || "",- presetId: preset.id,- isAllDay: preset.isAllDay || false,- };- createShift(shiftData);+ if (existingShift) {+ // Toggle: remove the existing shift+ // Optimistic delete+ setShifts(shifts.filter((s) => s.id !== existingShift.id));+ setStatsRefreshTrigger((prev) => prev + 1);++ try {+ const password = selectedCalendar+ ? localStorage.getItem(`calendar_password_${selectedCalendar}`)+ : null;+ const url = password+ ? `/api/shifts/${existingShift.id}?password=${encodeURIComponent(+ password+ )}`+ : `/api/shifts/${existingShift.id}`;+ const response = await fetch(url, { method: "DELETE" });++ if (!response.ok) {+ // Rollback on error+ setShifts(shifts);+ setStatsRefreshTrigger((prev) => prev + 1);+ }+ } catch (error) {+ console.error("Failed to delete shift:", error);+ // Rollback on error+ setShifts(shifts);+ setStatsRefreshTrigger((prev) => prev + 1);+ }+ } else {+ // Toggle: add the shift+ const shiftData: ShiftFormData = {+ date: formatDateToLocal(date),+ startTime: preset.startTime,+ endTime: preset.endTime,+ title: preset.title,+ color: preset.color,+ notes: preset.notes || "",+ presetId: preset.id,+ isAllDay: preset.isAllDay || false,+ };+ await createShift(shiftData);+ }+ } finally {+ setIsTogglingShift(false);}};@@ -510,17 +645,24 @@ function HomeContent() {if (calendars.length === 0) {return (- <div className="min-h-screen flex items-center justify-center p-4">- <div className="text-center space-y-4 max-w-md">- <CalendarIcon className="h-16 w-16 mx-auto text-muted-foreground" />- <h1 className="text-2xl font-bold">Welcome to BetterShift</h1>- <p className="text-muted-foreground">- Get started by creating your first calendar to track your shifts.- </p>- <Button onClick={() => setShowCalendarDialog(true)} size="lg">- <Plus className="mr-2 h-4 w-4" />- Create Calendar- </Button>+ <div className="min-h-screen flex flex-col">+ <div className="flex-1 flex items-center justify-center p-4">+ <div className="text-center space-y-4 max-w-md">+ <CalendarIcon className="h-16 w-16 mx-auto text-muted-foreground" />+ <h1 className="text-2xl font-bold">{t("onboarding.welcome")}</h1>+ <p className="text-muted-foreground">+ {t("onboarding.description")}+ </p>+ <Button onClick={() => setShowCalendarDialog(true)} size="lg">+ <Plus className="mr-2 h-4 w-4" />+ {t("onboarding.createCalendar")}+ </Button>+ </div>+ </div>+ <div className="border-t bg-background">+ <div className="container max-w-4xl mx-auto p-3 sm:p-4 flex justify-center">+ <LanguageSwitcher />+ </div></div><CalendarDialogopen={showCalendarDialog}@@ -567,6 +709,7 @@ function HomeContent() {onSelect={setSelectedCalendar}onCreateNew={() => setShowCalendarDialog(true)}onManagePassword={() => setShowManagePasswordDialog(true)}+ onDelete={initiateDeleteCalendar}/></div></div>@@ -656,6 +799,7 @@ function HomeContent() {setShowMobileCalendarDialog(false);setShowManagePasswordDialog(true);}}+ onDelete={initiateDeleteCalendar}/></div></DialogContent>@@ -817,6 +961,31 @@ function HomeContent() {})}</div>+ {/* Note Hint */}+ <div className="px-2 sm:px-0 mb-3">+ <div className="bg-muted/30 border border-muted/50 rounded-md p-2 sm:p-2.5">+ <div className="flex items-start gap-2">+ <StickyNote className="h-3.5 w-3.5 text-amber-500 shrink-0 mt-0.5" />+ <div>+ {/* Mobile hint */}+ <p className="text-[11px] sm:hidden text-muted-foreground leading-snug">+ {t("note.hintMobile", {+ default:+ "Long press on a day to open notes. The note icon shows existing notes.",+ })}+ </p>+ {/* Desktop hint */}+ <p className="hidden sm:block text-xs text-muted-foreground leading-snug">+ {t("note.hintDesktop", {+ default:+ "Right-click on a day to open notes. The note icon shows existing notes.",+ })}+ </p>+ </div>+ </div>+ </div>+ </div>+{/* Shifts List */}<div className="space-y-3 sm:space-y-4 px-2 sm:px-0">{/* Shift Statistics */}@@ -870,9 +1039,6 @@ function HomeContent() {? t("shift.createPresetFirst"): t("shift.noShiftsDescription")}</p>- <p className="text-xs text-muted-foreground/70 mt-2">- 💡 {t("note.rightClick")}- </p></div></div>) : (@@ -988,6 +1154,19 @@ function HomeContent() {selectedDate={selectedDate}note={selectedNote}/>+ {calendarToDelete && (+ <DeleteCalendarDialog+ open={showDeleteCalendarDialog}+ onOpenChange={setShowDeleteCalendarDialog}+ calendarName={+ calendars.find((c) => c.id === calendarToDelete)?.name || ""+ }+ hasPassword={+ !!calendars.find((c) => c.id === calendarToDelete)?.passwordHash+ }+ onConfirm={deleteCalendar}+ />+ )}{/* Footer */}<div className="border-t bg-background mt-auto">diff --git a/components/calendar-selector.tsx b/components/calendar-selector.tsxindex ce28ac0..7ffaddf 100644--- a/components/calendar-selector.tsx+++ b/components/calendar-selector.tsx@@ -10,7 +10,7 @@ import {SelectValue,} from "@/components/ui/select";import { Button } from "@/components/ui/button";-import { Plus, Settings } from "lucide-react";+import { Plus, Settings, Trash2 } from "lucide-react";interface CalendarSelectorProps {calendars: CalendarWithCount[];@@ -18,6 +18,7 @@ interface CalendarSelectorProps {onSelect: (id: string) => void;onCreateNew: () => void;onManagePassword?: () => void;+ onDelete?: (id: string) => void;}export function CalendarSelector({@@ -26,6 +27,7 @@ export function CalendarSelector({onSelect,onCreateNew,onManagePassword,+ onDelete,}: CalendarSelectorProps) {const t = useTranslations();@@ -60,6 +62,17 @@ export function CalendarSelector({<Settings className="h-4 w-4" /></Button>)}+ {onDelete && selectedId && (+ <Button+ onClick={() => onDelete(selectedId)}+ size="icon"+ variant="outline"+ className="h-9 w-9 sm:h-10 sm:w-10 text-destructive hover:text-destructive"+ title={t("calendar.deleteCalendar")}+ >+ <Trash2 className="h-4 w-4" />+ </Button>+ )}<ButtononClick={onCreateNew}size="icon"diff --git a/components/delete-calendar-dialog.tsx b/components/delete-calendar-dialog.tsxnew file mode 100644index 0000000..0d03b89--- /dev/null+++ b/components/delete-calendar-dialog.tsx@@ -0,0 +1,100 @@+"use client";++import { useState, useEffect } from "react";+import { useTranslations } from "next-intl";+import {+ Dialog,+ DialogContent,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogTitle,+} from "@/components/ui/dialog";+import { Button } from "@/components/ui/button";+import { Input } from "@/components/ui/input";+import { Label } from "@/components/ui/label";+import { AlertTriangle } from "lucide-react";++interface DeleteCalendarDialogProps {+ open: boolean;+ onOpenChange: (open: boolean) => void;+ calendarName: string;+ hasPassword: boolean;+ onConfirm: (password?: string) => void;+}++export function DeleteCalendarDialog({+ open,+ onOpenChange,+ calendarName,+ hasPassword,+ onConfirm,+}: DeleteCalendarDialogProps) {+ const t = useTranslations();+ const [password, setPassword] = useState("");++ useEffect(() => {+ if (!open) {+ setPassword("");+ }+ }, [open]);++ const handleSubmit = (e: React.FormEvent) => {+ e.preventDefault();+ onConfirm(hasPassword ? password : undefined);+ };++ return (+ <Dialog open={open} onOpenChange={onOpenChange}>+ <DialogContent className="sm:max-w-md">+ <DialogHeader>+ <DialogTitle className="flex items-center gap-2 text-destructive">+ <AlertTriangle className="h-5 w-5" />+ {t("calendar.deleteCalendar")}+ </DialogTitle>+ <DialogDescription asChild>+ <div className="space-y-2 pt-2">+ <div className="font-semibold">+ {t("calendar.deleteConfirm", { name: calendarName })}+ </div>+ <div className="text-sm text-muted-foreground">+ {t("calendar.deleteWarning", {+ default:+ "This action cannot be undone. All shifts, presets, and notes will be permanently deleted.",+ })}+ </div>+ </div>+ </DialogDescription>+ </DialogHeader>+ <form onSubmit={handleSubmit} className="space-y-4">+ {hasPassword && (+ <div className="space-y-2">+ <Label htmlFor="password">{t("password.password")}</Label>+ <Input+ id="password"+ type="password"+ value={password}+ onChange={(e) => setPassword(e.target.value)}+ placeholder={t("password.passwordPlaceholder")}+ required+ autoFocus+ />+ </div>+ )}+ <DialogFooter className="gap-2">+ <Button+ type="button"+ variant="outline"+ onClick={() => onOpenChange(false)}+ >+ {t("common.cancel")}+ </Button>+ <Button type="submit" variant="destructive">+ {t("common.delete")}+ </Button>+ </DialogFooter>+ </form>+ </DialogContent>+ </Dialog>+ );+}diff --git a/messages/de.json b/messages/de.jsonindex a85c21e..11f146f 100644--- a/messages/de.json+++ b/messages/de.json@@ -26,7 +26,11 @@"noCalendars": "Noch keine Kalender","createFirst": "Erstelle deinen ersten Kalender","managePassword": "Passwort verwalten",- "select": "Dein BetterShift Kalender"+ "select": "Dein BetterShift Kalender",+ "deleteCalendar": "Kalender löschen",+ "deleteConfirm": "Kalender \"{name}\" wirklich löschen? Alle Schichten, Presets und Notizen werden ebenfalls gelöscht.",+ "deleteWarning": "Diese Aktion kann nicht rückgängig gemacht werden. Alle Schichten, Presets und Notizen werden permanent gelöscht.",+ "deleteSuccess": "Kalender erfolgreich gelöscht"},"password": {"use": "Passwort verwenden",@@ -48,8 +52,8 @@"currentlyProtected": "Dieser Kalender ist derzeit passwortgeschützt.","notProtected": "Dieser Kalender ist derzeit nicht passwortgeschützt.","errorMatch": "Passwörter stimmen nicht überein",- "errorRequired": "Passwort erforderlich","errorIncorrect": "Falsches Passwort",+ "errorRequired": "Passwort erforderlich","unlock": "Entsperren"},"note": {@@ -59,7 +63,9 @@"delete": "Notiz löschen","note": "Notiz","notePlaceholder": "z.B. Frühdienst weil nachmittags Friseur...",- "rightClick": "Rechtsklick / Langes Drücken auf einen Tag oder Klick auf das Notiz-Icon"+ "hint": "Notizen zu Tagen hinzufügen",+ "hintMobile": "Langes Drücken auf einen Tag öffnet Notizen. Das Notiz-Icon zeigt vorhandene Notizen an.",+ "hintDesktop": "Rechtsklick auf einen Tag öffnet Notizen. Das Notiz-Icon zeigt vorhandene Notizen an."},"shift": {"title": "Schichten",@@ -158,5 +164,10 @@"total": "Gesamt","noData": "Keine Schichten in diesem Zeitraum","shiftsTotal": "Schichten"+ },+ "onboarding": {+ "welcome": "Willkommen bei BetterShift",+ "description": "Erstelle deinen ersten Kalender, um deine Schichten zu verwalten.",+ "createCalendar": "Kalender erstellen"}}diff --git a/messages/en.json b/messages/en.jsonindex f5ee72a..8e6e1c4 100644--- a/messages/en.json+++ b/messages/en.json@@ -26,7 +26,11 @@"noCalendars": "No calendars yet","createFirst": "Create your first calendar","managePassword": "Manage Password",- "select": "Your BetterShift Calendar"+ "select": "Your BetterShift Calendar",+ "deleteCalendar": "Delete Calendar",+ "deleteConfirm": "Really delete calendar \"{name}\"? All shifts, presets and notes will also be deleted.",+ "deleteWarning": "This action cannot be undone. All shifts, presets, and notes will be permanently deleted.",+ "deleteSuccess": "Calendar deleted successfully"},"password": {"use": "Use password",@@ -48,8 +52,8 @@"currentlyProtected": "This calendar is currently password protected.","notProtected": "This calendar is currently not password protected.","errorMatch": "Passwords do not match",- "errorRequired": "Password is required","errorIncorrect": "Incorrect password",+ "errorRequired": "Password required","unlock": "Unlock"},"note": {@@ -58,8 +62,10 @@"edit": "Edit Note","delete": "Delete Note","note": "Note",- "notePlaceholder": "e.g., Morning shift because afternoon hairdresser...",- "rightClick": "Right-click / Long press on a day or click the note icon"+ "notePlaceholder": "e.g., Early shift because appointment in the afternoon...",+ "hint": "Add notes to days",+ "hintMobile": "Long press on a day to open notes. The note icon shows existing notes.",+ "hintDesktop": "Right-click on a day to open notes. The note icon shows existing notes."},"shift": {"title": "Shifts",@@ -157,6 +163,11 @@"year": "Year","total": "Total","noData": "No shifts in this period",- "shiftsTotal": "shifts"+ "shiftsTotal": "Shifts"+ },+ "onboarding": {+ "welcome": "Welcome to BetterShift",+ "description": "Get started by creating your first calendar to track your shifts.",+ "createCalendar": "Create Calendar"}}