Your favorite shift management application!
feat: Enforce hooks and replace native confirms (#88)
panteL37b0e74a0add
diff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.mdindex 6d41e40..4e0cffd 100644--- a/.github/copilot-instructions.md+++ b/.github/copilot-instructions.md@@ -7,6 +7,7 @@- **UI**: Tailwind CSS 4 + shadcn/ui + BaseSheet component- **i18n**: next-intl (de/en/it) - always use informal "du" in German- **Critical**: Never use `db:push`, always generate migrations+- **State**: ALWAYS use existing hooks from `hooks/` - NEVER implement custom fetch logic## Core Architecture@@ -18,48 +19,30 @@- **i18n**: next-intl (German/English/Italian, cookie-based + browser detection)- **State**: Client-side with React hooks, custom hooks in `hooks/`-### Database Schema (`lib/db/schema.ts`)+### Database SchemaCore tables with cascade relationships:- `calendars` → `shifts`, `shiftPresets`, `calendarNotes` (cascade delete)- `shiftPresets` → `shifts` (set null on delete)-- IDs: `crypto.randomUUID()`-- Timestamps: Stored as integers, auto-converted to Date objects-- Passwords: SHA-256 hashed (via `lib/password-utils.ts`)--## Development Guidelines+- IDs: `crypto.randomUUID()`, Timestamps: integers (auto-converted to Date)+- Passwords: SHA-256 hashed via `lib/password-utils.ts`### Database Migrations-After schema changes in `lib/db/schema.ts`:-```bashnpm run db:generate # Generate migration filesnpm run db:migrate # Apply migrations```-**Critical**:--- Migrations are version-controlled-- Never use `db:push` - prefer explicit migrations-- Schema changes require updating `lib/db/schema.ts` AND generating migrations+**Critical**: Never use `db:push` - prefer explicit migrations. Schema changes require updating `lib/db/schema.ts` AND generating migrations.### API Routes-Follow these patterns (see `app/api/shifts/route.ts`):+Next.js 16 pattern - dynamic params are async:```typescript-export async function GET(request: Request) {- const { searchParams } = new URL(request.url);- const calendarId = searchParams.get("calendarId");-- if (!calendarId) {- return NextResponse.json({ error: "Missing calendarId" }, { status: 400 });- }-}--// Dynamic routes - params are async in Next.js 16+// Dynamic routes - ALWAYS await paramsexport async function PUT(request: Request,{ params }: { params: Promise<{ id: string }> }@@ -70,261 +53,146 @@ export async function PUT(### Password Protection-Calendars support two-tier password protection via `passwordHash` and `isLocked` fields:+Two-tier system via `passwordHash` and `isLocked`:-**Two-Tier Protection System**:+- **Write-Only** (`isLocked=false`): Password for mutations only+- **Full Lock** (`isLocked=true`): Password for all operations-- **Write-Only Protection** (`passwordHash` set, `isLocked=false`): Password required for mutations (POST/PUT/PATCH/DELETE), but read access (GET) is allowed without password-- **Full Protection** (`passwordHash` set, `isLocked=true`): Password required for all operations including read access--**API Route Implementation**:+**Key Implementation**:```typescript-// GET endpoints - check both passwordHash AND isLocked+// GET - check isLocked flagif (calendar.passwordHash && calendar.isLocked) {- const { searchParams } = new URL(request.url);- const password = searchParams.get("password");-- if (!password || !verifyPassword(password, calendar.passwordHash)) {- return NextResponse.json({ error: "Invalid password" }, { status: 401 });- }+ // Require password}-// POST/PUT/PATCH/DELETE endpoints - check only passwordHash+// POST/PUT/DELETE - always check passwordHashif (calendar.passwordHash) {- const { password } = await request.json();-- if (!password || !verifyPassword(password, calendar.passwordHash)) {- return NextResponse.json({ error: "Invalid password" }, { status: 401 });- }+ // Require password}```-**Client-Side Password Flow**:+**Client-Side Flow**:-1. **Password Caching**: Use utilities from `lib/password-cache.ts`:+- Use `lib/password-cache.ts`: `getCachedPassword()`, `verifyAndCachePassword()`, `setCachedPassword()`, `removeCachedPassword()`+- All data hooks auto-include cached passwords in requests+- Locked calendars show integrated unlock form - no page reload needed+- Hooks return empty arrays on 401 (graceful degradation)- - `getCachedPassword(calendarId)` - Retrieve password from localStorage- - `verifyAndCachePassword(calendarId, password)` - Verify with server and cache if valid- - `setCachedPassword(calendarId, password)` - Manually cache password- - `removeCachedPassword(calendarId)` - Clear cached password+### State Management & Custom Hooks-2. **Hooks Auto-Include Password**: All data-fetching hooks (`useShifts`, `usePresets`, `useNotes`) automatically:+**CRITICAL: ALWAYS use existing custom hooks instead of implementing custom logic.**- - Call `getCachedPassword(calendarId)` before each fetch- - Append password as query parameter if present- - Return empty arrays on 401 responses (graceful degradation)+#### Available Custom Hooks-3. **Locked Calendar UX**:+**Data Management** (CRUD operations):- - When `isLocked=true` and no valid cached password: Show integrated password form in main UI- - After successful password entry: Call `handlePasswordSuccess(password)` which triggers:- - `refetchShifts()`, `refetchPresets()`, `refetchNotes()`- - `fetchExternalSyncs()`, `fetchSyncErrorStatus()`- - `setStatsRefreshTrigger((prev) => prev + 1)`- - All data loads immediately after unlock - no page reload needed+- `useCalendars()` - Calendar CRUD with auto-password caching+- `useShifts()` - Shift CRUD with optimistic updates+- `usePresets()` - Preset fetching with silent refresh+- `usePresetManagement()` - Preset CRUD operations+- `useNotes()` - Note CRUD with password protection+- `useShiftStats()` - Aggregated shift statistics+- `useCompareCalendars()` - Multi-calendar data for compare mode-4. **Mutation Password Protection**:- - Check cached password before mutation: `const result = await verifyAndCachePassword(calendarId, password)`- - If `result.protected && !result.valid`: Set `pendingAction` and show `PasswordDialog`- - On successful password entry: Execute pending action automatically+**Action Hooks** (Complex operations):-**Important Implementation Notes**:+- `useShiftActions()` - Shift operations with password handling & optimistic UI+- `useNoteActions()` - Note dialog state & submission flow-- Never require password input twice - the integrated "Currently Locked" form is sufficient-- All hooks handle 401 gracefully by returning empty arrays (prevents UI crashes)-- Calendar list (GET `/api/calendars`) never requires password (allows calendar switching)-- Password verification is asynchronous - always await `verifyAndCachePassword`-- Cached passwords persist across sessions via localStorage+**Password Management**:-### State Management+- `usePasswordManagement()` - Central password state & verification+- `usePasswordProtection()` - Per-component password utilities-Main page (`app/page.tsx`) patterns:+**UI/Form Hooks**:-- `useState` for shifts, presets, notes, calendars-- `useEffect` for data fetching on calendar/date changes-- `useRouter().replace()` for URL state sync-- `statsRefreshTrigger` counter for mutation tracking+- `useDirtyState()` - Unsaved changes tracking (ALWAYS use for forms/sheets)+- `useShiftForm()` - Shift form state & preset application+- `useDialogStates()` - Centralized dialog visibility state+- `useViewSettings()` - View preferences with localStorage-### Internationalization+**External Sync & SSE**:-next-intl setup with auto-detection:+- `useExternalSync()` - iCal/webcal subscription management+- `useSSEConnection()` - Real-time updates via Server-Sent Events-- Cookie `NEXT_LOCALE` overrides browser preference (`lib/i18n.ts`)-- Translations: `messages/{de,en,it}.json` (German, English, Italian)-- Usage: `const t = useTranslations()` → `t("shift.create")`-- Date formatting: `locale === "de" ? de : (locale === "it" ? it : enUS)`-- **Important**: When adding new translation keys, ALWAYS add them to all three files (de.json, en.json, it.json)+#### Hook Usage Rules-**Translation Structure (Optimized)**:+**DO:**-The translation files use a centralized structure to eliminate duplicates and ensure consistency.+- ✅ ALWAYS use existing hooks for CRUD (never custom `fetch()` logic)+- ✅ Use `getCachedPassword()` / `verifyAndCachePassword()` for password handling+- ✅ Use `useDirtyState` for all forms/sheets with input+- ✅ Pass `onPasswordRequired` callbacks to hooks that support it-**German Translation Style**:+**DON'T:**-- Always use informal "du" form (never formal "Sie" form)-- Examples: "Möchtest du..." (not "Möchten Sie..."), "Bitte entsperre..." (not "Bitte entsperren Sie...")-- This applies to all user-facing messages, descriptions, hints, and instructions+- ❌ NEVER implement custom `fetch()` calls for shifts/presets/notes/calendars+- ❌ NEVER manually manage password state - use password hooks+- ❌ NEVER implement custom dirty state tracking-**Common Keys (Parametrized)**:+**See `app/page.tsx` for complete hook integration pattern.**-```typescript-// Success/Error Messages - use {item} parameter-toast.success(t("common.created", { item: t("common.shifts") }));-toast.error(t("common.createError", { item: t("calendar.title") }));-toast.success(t("common.updated", { item: t("preset.preset") }));-toast.error(t("common.deleteError", { item: t("note.note") }));--// Available: common.created, common.updated, common.deleted-// common.createError, common.updateError, common.deleteError-// common.deleteConfirm, common.deleteConfirmWithWarning-```--**Validation Keys (Centralized)**:+### Internationalization-```typescript-// Password validation-setError(t("validation.passwordMatch"));-setError(t("validation.passwordIncorrect"));-setError(t("validation.passwordRequired"));--// File/URL validation-toast.error(t("validation.fileRequired"));-toast.error(t("validation.fileTooLarge", { maxSize: "5MB" }));-toast.error(t("validation.urlRequired"));-toast.error(t("validation.urlInvalid"));-toast.error(t("validation.urlAlreadyExists"));-```+next-intl setup: `messages/{de,en,it}.json` - cookie-based with browser detection fallback-**Form Field Keys (Reusable)**:+**Usage**:```typescript-// Form labels and placeholders-<Label>{t("form.nameLabel")}</Label>-<Input placeholder={t("form.namePlaceholder", { example: t("calendar.name") })} />-<Label>{t("form.colorLabel")}</Label>-<Label>{t("form.passwordLabel")}</Label>-<Input placeholder={t("form.passwordPlaceholder")} />-<Label>{t("form.notesLabel")}</Label>-<Textarea placeholder={t("form.notesPlaceholder")} />-<Label>{t("form.urlLabel")}</Label>-<Input placeholder={t("form.urlPlaceholder")} />+const t = useTranslations();+t("shift.create"); // Feature-specific keys+t("common.created", { item: t("shift.shift_one") }); // Parametrized```-**Key Rules**:+**Key Structure** (centralized to avoid duplicates):-- **Never duplicate** CRUD success/error messages - always use `common.*` with `{item}` parameter-- **Never duplicate** validation messages - use `validation.*` namespace-- **Never duplicate** form field labels - use `form.*` namespace-- Feature-specific keys (e.g., `shift.startTime`, `calendar.select`) remain in their namespace-- When adding new features, check if message fits `common.*`, `validation.*`, or `form.*` before creating new keys+- `common.*` - CRUD operations with `{item}` parameter (`created`, `updated`, `deleted`, `createError`, `updateError`, `deleteError`)+- `validation.*` - All validation messages (`passwordMatch`, `passwordIncorrect`, `urlInvalid`, etc.)+- `form.*` - Reusable form labels (`nameLabel`, `colorLabel`, `passwordLabel`, `notesLabel`, `urlLabel`)+- Feature namespaces - Specific keys (`shift.startTime`, `calendar.select`, etc.)-**Translation Key Usage Status**:+**Rules**:-All translation keys in `messages/{de,en}.json` are actively used.--When adding new features, ensure all translation keys are actually used in components. Remove unused keys to keep translation files clean.+- ALWAYS add new keys to all three language files (de.json, en.json, it.json)+- German: ALWAYS use informal "du" form (never "Sie")+- Check `common.*`, `validation.*`, `form.*` before creating new keys### Component Design Patterns-#### BaseSheet Component (Preferred)--**Use `BaseSheet` from `components/ui/base-sheet.tsx` for simple sheets** (create, edit, settings). Only build custom sheets for complex multi-step forms or specialized layouts.+#### Sheets-**BaseSheet Usage**:+**Use `BaseSheet` for simple forms** (create, edit, settings):```typescript-import { BaseSheet } from "@/components/ui/base-sheet";-<BaseSheetopen={open}onOpenChange={onOpenChange}title={t("sheet.title")}- description={t("sheet.description")}showSaveButtononSave={handleSave}isSaving={isSaving}saveDisabled={!isValid || !isDirty}hasUnsavedChanges={isDirty}- maxWidth="md" // sm(480px) | md(600px) | lg(700px) | xl(800px)+ maxWidth="md" // sm|md|lg|xl>- {/* Your form content */}-</BaseSheet>;+ {/* Form content */}+</BaseSheet>```-**BaseSheet Features**:--- Automatic dirty state tracking with confirmation dialog-- Built-in Save/Cancel buttons with loading states-- Consistent styling (gradients, borders, spacing)-- Responsive max-width options-- Custom footer support via `footer` prop--**When to Use Custom Sheets**:+**Custom sheets only for**: Multi-step wizards, complex layouts, custom footer actions-- Multi-step wizards-- Complex layouts with tabs or sidebars-- Sheets requiring custom footer actions (e.g., Delete + Save)+**Styling**: Gradient headers (`from-primary/10 via-primary/5`), border opacity (`border-border/50`), consistent padding (`px-6 py-6`), sticky footer-#### Custom Sheet Pattern (Complex Cases Only)--For complex sheets, follow this structure:--```tsx-<SheetContent- side="right"- className="w-full sm:max-w-[600px] p-0 flex flex-col gap-0 border-l border-border/50 overflow-hidden"->- <SheetHeader className="border-b border-border/50 bg-gradient-to-r from-primary/10 via-primary/5 to-transparent px-6 pt-6 pb-5 space-y-1.5">- <SheetTitle className="text-xl font-semibold bg-gradient-to-r from-foreground to-foreground/70 bg-clip-text">- {t("sheet.title")}- </SheetTitle>- <SheetDescription className="text-sm text-muted-foreground">- {t("sheet.description")}- </SheetDescription>- </SheetHeader>-- <div className="flex-1 overflow-y-auto px-6 py-6 space-y-4">- {/* Sheet content */}- </div>-- <SheetFooter className="border-t border-border/50 bg-muted/20 px-6 py-4 mt-auto">- <div className="flex gap-2.5 w-full">- <Button variant="outline" onClick={handleClose} disabled={isSaving}>- {t("common.cancel")}- </Button>- <Button onClick={handleSave} disabled={!isValid || isSaving}>- {isSaving ? t("common.saving") : t("common.save")}- </Button>- </div>- </SheetFooter>-</SheetContent>-```--**Dirty State Tracking**: ALWAYS use `useDirtyState` hook for unsaved changes:--```typescript-const {- isDirty,- handleClose,- showConfirmDialog,- setShowConfirmDialog,- handleConfirmClose,-} = useDirtyState({- onClose: onOpenChange,- hasChanges: () => name !== initialName,- onConfirm: () => resetForm(), // Optional cleanup-});-```+**ALWAYS use `useDirtyState` hook** for unsaved changes tracking - see `preset-manage-sheet.tsx` for reference.#### Other Patterns-- **Dialogs**: Only for read-only info or simple confirmations (no forms)-- **Confirmation Dialogs**: NEVER use native `confirm()` - always use `ConfirmationDialog` component with state management--- **Forms**: Prevent default, validate, show errors, use explicit save actions-- **Colors**: Use `PRESET_COLORS` array, hex format (`#3b82f6`), 20% opacity for backgrounds-- **Dates**: `formatDateToLocal()` for YYYY-MM-DD format+- **Dialogs**: Read-only info or confirmations only (no forms)+- **Confirmation**: Use `ConfirmationDialog` component (NEVER native `confirm()`)+- **Colors**: `PRESET_COLORS` array, hex format, 20% opacity for backgrounds+- **Dates**: `formatDateToLocal()` for YYYY-MM-DD### UI/UX Design Principles@@ -393,36 +261,35 @@ docker compose exec bettershift npm run db:migrate2. Export types: `export type TableName = typeof tableName.$inferSelect;`3. Run `npm run db:generate && npm run db:migrate`4. Create API routes: `app/api/tablename/route.ts` and `app/api/tablename/[id]/route.ts`-5. Add translations to `messages/de.json`, `messages/en.json`, and `messages/it.json`+5. Add translations to all language files (`messages/{de,en,it}.json`)+6. Create custom hook in `hooks/` for CRUD operations (follow existing patterns)++## Development Workflow-### New Component with Sheet+**Local Setup**:-1. Create in `components/` - prefer `BaseSheet` for simple forms-2. Props: `open`, `onOpenChange`, `onSubmit`, optional `onDelete`-3. Use `useTranslations()` for all text-4. For BaseSheet: Pass `showSaveButton`, `onSave`, `isSaving`, `saveDisabled`, `hasUnsavedChanges`-5. For custom sheets: Include explicit Save button in SheetFooter with loading state-6. Reset local state when `open` changes to false-7. Import and integrate in parent component+```bash+npm install+npm run db:migrate # One-time setup+npm run dev # http://localhost:3000+```-### New Component with Dialog+**Docker**:-1. Create in `components/` using shadcn/ui Dialog-2. Props: `open`, `onOpenChange`, `onSubmit`, optional `onDelete`-3. Use `useTranslations()` for all text-4. Reset local state when `open` changes to false-5. Import and integrate in `app/page.tsx`+```bash+cp docker-compose.override.yml.example docker-compose.override.yml+docker-compose up -d --build+docker compose exec bettershift npm run db:migrate+```-## Testing & Debugging+**Debugging**:-- Database GUI: `npm run db:studio` (opens Drizzle Studio)-- Build validation: `npm run build` (checks TypeScript errors)-- Production test: Use Docker locally before deploying-- Check console errors for API failures - all errors logged with `console.error()`+- Database GUI: `npm run db:studio`+- Build check: `npm run build`+- All API errors logged via `console.error()`-## Code Style Guidelines+## Code Style-- **Language**: All code, comments, variable names, and messages in English-- **Comments**: Only add comments for complex logic or non-obvious behavior-- **Migrations**: Never use `db:push` - prefer safe migrations (db:generate + manual review)-- **Code clarity**: Write self-documenting code with clear variable/function names+- **Language**: English for all code, comments, variable names+- **Comments**: Only for complex/non-obvious logic+- **Code clarity**: Self-documenting names over commentsdiff --git a/components/external-sync-manage-sheet.tsx b/components/external-sync-manage-sheet.tsxindex 7577ae3..02524f7 100644--- a/components/external-sync-manage-sheet.tsx+++ b/components/external-sync-manage-sheet.tsx@@ -1240,7 +1240,11 @@ export function ExternalSyncManageSheet({open={showDeleteConfirm}onOpenChange={setShowDeleteConfirm}onConfirm={confirmDelete}+ title={t("externalSync.delete")}description={t("externalSync.deleteConfirm")}+ cancelText={t("common.cancel")}+ confirmText={t("common.delete")}+ confirmVariant="destructive"/></>);diff --git a/components/preset-manage-sheet.tsx b/components/preset-manage-sheet.tsxindex 1407bac..ec17fbf 100644--- a/components/preset-manage-sheet.tsx+++ b/components/preset-manage-sheet.tsx@@ -36,10 +36,9 @@ import { ColorPicker } from "@/components/ui/color-picker";import { ShiftPreset } from "@/lib/db/schema";import { PRESET_COLORS } from "@/lib/constants";import { Plus, Trash2, Edit2, Loader2, GripVertical } from "lucide-react";-import { toast } from "sonner";-import { getCachedPassword } from "@/lib/password-cache";import { ConfirmationDialog } from "@/components/ui/confirmation-dialog";import { useDirtyState } from "@/hooks/useDirtyState";+import { usePresetManagement } from "@/hooks/usePresetManagement";interface PresetFormData {title: string;@@ -193,6 +192,8 @@ export function PresetManageSheet({});const [isLoading, setIsLoading] = useState(false);const [isDeleting, setIsDeleting] = useState<string | null>(null);+ const [showDeleteConfirm, setShowDeleteConfirm] = useState(false);+ const [deleteTargetId, setDeleteTargetId] = useState<string | null>(null);const [orderedPrimaryPresets, setOrderedPrimaryPresets] = useState<ShiftPreset[]>([]);@@ -201,6 +202,12 @@ export function PresetManageSheet({>([]);const initialFormDataRef = useRef<PresetFormData | null>(null);+ const { createPreset, updatePreset, deletePreset, reorderPresets } =+ usePresetManagement({+ calendarId,+ onSuccess: onPresetsChange,+ });+// Initialize ordered presetsuseEffect(() => {if (open) {@@ -261,37 +268,13 @@ export function PresetManageSheet({};const savePresetOrder = async (allPresets: ShiftPreset[]) => {- try {- const password = getCachedPassword(calendarId);- const presetOrders = allPresets.map((preset, index) => ({- id: preset.id,- order: index,- }));-- const response = await fetch("/api/presets/reorder", {- method: "PATCH",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({- calendarId,- presetOrders,- password,- }),- });+ const presetOrders = allPresets.map((preset, index) => ({+ id: preset.id,+ order: index,+ }));- if (response.ok) {- onPresetsChange();- } else {- const data = await response.json();- toast.error(- data.error || t("common.updateError", { item: t("preset.preset") })- );- // Revert order on error- setOrderedPrimaryPresets(presets.filter((p) => !p.isSecondary));- setOrderedSecondaryPresets(presets.filter((p) => p.isSecondary));- }- } catch (error) {- console.error("Failed to reorder presets:", error);- toast.error(t("common.updateError", { item: t("preset.preset") }));+ const success = await reorderPresets(presetOrders);+ if (!success) {// Revert order on errorsetOrderedPrimaryPresets(presets.filter((p) => !p.isSecondary));setOrderedSecondaryPresets(presets.filter((p) => p.isSecondary));@@ -323,117 +306,55 @@ export function PresetManageSheet({setIsLoading(true);try {- const password = getCachedPassword(calendarId);+ let success = false;if (editingPreset) {- // Update existing preset- const response = await fetch(`/api/presets/${editingPreset.id}`, {- method: "PATCH",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({- ...formData,- password,- }),- });-- if (response.ok) {- setEditingPreset(null);- setFormData({- title: "",- startTime: "09:00",- endTime: "17:00",- color: PRESET_COLORS[0].value,- notes: "",- isSecondary: false,- isAllDay: false,- hideFromStats: false,- });- onPresetsChange();- toast.success(t("common.updated", { item: t("preset.preset") }));- } else {- const data = await response.json();- toast.error(- data.error || t("common.updateError", { item: t("preset.preset") })- );- }+ success = await updatePreset(editingPreset.id, formData);} else {- // Create new preset- const response = await fetch("/api/presets", {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({- calendarId,- ...formData,- password,- }),- });+ success = await createPreset(formData);+ }- if (response.ok) {- setFormData({- title: "",- startTime: "09:00",- endTime: "17:00",- color: PRESET_COLORS[0].value,- notes: "",- isSecondary: false,- isAllDay: false,- hideFromStats: false,- });- setShowAddForm(false);- onPresetsChange();- toast.success(t("common.created", { item: t("preset.preset") }));- } else {- const data = await response.json();- toast.error(- data.error || t("common.createError", { item: t("preset.preset") })- );- }+ if (success) {+ setEditingPreset(null);+ setShowAddForm(false);+ setFormData({+ title: "",+ startTime: "09:00",+ endTime: "17:00",+ color: PRESET_COLORS[0].value,+ notes: "",+ isSecondary: false,+ isAllDay: false,+ hideFromStats: false,+ });}- } catch (error) {- console.error("Failed to save preset:", error);- toast.error(- editingPreset- ? t("common.updateError", { item: t("preset.preset") })- : t("common.createError", { item: t("preset.preset") })- );} finally {setIsLoading(false);}};- const handleDelete = async (presetId: string) => {- if (!confirm(t("preset.deleteConfirm"))) {- return;- }+ const handleDeleteClick = (presetId: string) => {+ setDeleteTargetId(presetId);+ setShowDeleteConfirm(true);+ };- setIsDeleting(presetId);- try {- const password = getCachedPassword(calendarId);+ const handleDeleteConfirm = async () => {+ if (!deleteTargetId) return;- const response = await fetch(`/api/presets/${presetId}`, {- method: "DELETE",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ password }),- });+ setIsDeleting(deleteTargetId);+ setShowDeleteConfirm(false);- if (response.ok) {- onPresetsChange();- toast.success(t("common.deleted", { item: t("preset.preset") }));+ try {+ const success = await deletePreset(deleteTargetId);+ if (success) {// If we're editing the deleted preset, close the edit form- if (editingPreset?.id === presetId) {+ if (editingPreset?.id === deleteTargetId) {setEditingPreset(null);}- } else {- const data = await response.json();- toast.error(- data.error || t("common.deleteError", { item: t("preset.preset") })- );}- } catch (error) {- console.error("Delete error:", error);- toast.error(t("common.deleteError", { item: t("preset.preset") }));} finally {setIsDeleting(null);+ setDeleteTargetId(null);}};@@ -585,7 +506,7 @@ export function PresetManageSheet({preset={preset}isDeleting={isDeleting === preset.id}onEdit={startEdit}- onDelete={handleDelete}+ onDelete={handleDeleteClick}t={t}showDragHandle={orderedPrimaryPresets.length > 1}/>@@ -620,7 +541,7 @@ export function PresetManageSheet({preset={preset}isDeleting={isDeleting === preset.id}onEdit={startEdit}- onDelete={handleDelete}+ onDelete={handleDeleteClick}t={t}showDragHandle={orderedSecondaryPresets.length > 1}/>@@ -638,7 +559,7 @@ export function PresetManageSheet({preset={editingPreset}isDeleting={isDeleting === editingPreset.id}onEdit={startEdit}- onDelete={handleDelete}+ onDelete={handleDeleteClick}t={t}showDragHandle={false}/>@@ -879,6 +800,19 @@ export function PresetManageSheet({open={showConfirmDialog}onOpenChange={setShowConfirmDialog}onConfirm={handleConfirmClose}+ title={t("common.unsavedChanges")}+ description={t("common.unsavedChangesDescription")}+ />++ <ConfirmationDialog+ open={showDeleteConfirm}+ onOpenChange={setShowDeleteConfirm}+ onConfirm={handleDeleteConfirm}+ title={t("preset.preset") + " " + t("common.delete")}+ description={t("preset.deleteConfirm")}+ cancelText={t("common.cancel")}+ confirmText={t("common.delete")}+ confirmVariant="destructive"/></>);diff --git a/components/sync-notification-dialog.tsx b/components/sync-notification-dialog.tsxindex e8fd99d..3f15362 100644--- a/components/sync-notification-dialog.tsx+++ b/components/sync-notification-dialog.tsx@@ -9,6 +9,7 @@ import {DialogHeader,DialogTitle,} from "@/components/ui/dialog";+import { ConfirmationDialog } from "@/components/ui/confirmation-dialog";import { Button } from "@/components/ui/button";import {Select,@@ -53,6 +54,7 @@ export function SyncNotificationDialog({const [filter, setFilter] = useState<"all" | "success" | "error">("all");const [isDeleting, setIsDeleting] = useState(false);const [isMarkingRead, setIsMarkingRead] = useState(false);+ const [showDeleteConfirm, setShowDeleteConfirm] = useState(false);const fetchLogs = useCallback(async (showLoadingState = true) => {@@ -134,9 +136,10 @@ export function SyncNotificationDialog({const handleDeleteLogs = async () => {if (!calendarId) return;- if (!confirm(t("syncNotifications.deleteConfirm"))) return;setIsDeleting(true);+ setShowDeleteConfirm(false);+try {const password = getCachedPassword(calendarId);@@ -208,159 +211,172 @@ export function SyncNotificationDialog({});return (- <Dialog open={open} onOpenChange={onOpenChange}>- <DialogContent className="sm:max-w-[600px] max-w-[95vw] max-h-[85vh] flex flex-col p-0 gap-0 border border-border/50 bg-gradient-to-b from-background via-background to-muted/30 backdrop-blur-xl shadow-2xl">- <DialogHeader className="border-b border-border/50 bg-gradient-to-r from-primary/10 via-primary/5 to-transparent p-6 pb-5 space-y-1.5">- <DialogTitle className="text-xl font-semibold bg-gradient-to-r from-foreground to-foreground/70 bg-clip-text">- {t("syncNotifications.title")}- </DialogTitle>- </DialogHeader>+ <>+ <Dialog open={open} onOpenChange={onOpenChange}>+ <DialogContent className="sm:max-w-[600px] max-w-[95vw] max-h-[85vh] flex flex-col p-0 gap-0 border border-border/50 bg-gradient-to-b from-background via-background to-muted/30 backdrop-blur-xl shadow-2xl">+ <DialogHeader className="border-b border-border/50 bg-gradient-to-r from-primary/10 via-primary/5 to-transparent p-6 pb-5 space-y-1.5">+ <DialogTitle className="text-xl font-semibold bg-gradient-to-r from-foreground to-foreground/70 bg-clip-text">+ {t("syncNotifications.title")}+ </DialogTitle>+ </DialogHeader>- {/* Filter and Actions */}- <div className="flex flex-wrap gap-2 items-center pb-4 border-b border-border/50 px-6 pt-6">- <Select- value={filter}- onValueChange={(v: typeof filter) => setFilter(v)}- >- <SelectTrigger className="w-[140px]">- <SelectValue />- </SelectTrigger>- <SelectContent>- <SelectItem value="all">- {t("syncNotifications.filterAll")}- </SelectItem>- <SelectItem value="success">- {t("syncNotifications.filterSuccess")}- </SelectItem>- <SelectItem value="error">- {t("syncNotifications.filterError")}- </SelectItem>- </SelectContent>- </Select>- <div className="flex gap-2 ml-auto">- {logs.some((log) => log.status === "error" && !log.isRead) && (+ {/* Filter and Actions */}+ <div className="flex flex-wrap gap-2 items-center pb-4 border-b border-border/50 px-6 pt-6">+ <Select+ value={filter}+ onValueChange={(v: typeof filter) => setFilter(v)}+ >+ <SelectTrigger className="w-[140px]">+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ <SelectItem value="all">+ {t("syncNotifications.filterAll")}+ </SelectItem>+ <SelectItem value="success">+ {t("syncNotifications.filterSuccess")}+ </SelectItem>+ <SelectItem value="error">+ {t("syncNotifications.filterError")}+ </SelectItem>+ </SelectContent>+ </Select>+ <div className="flex gap-2 ml-auto">+ {logs.some((log) => log.status === "error" && !log.isRead) && (+ <Button+ variant="outline"+ size="sm"+ onClick={handleMarkErrorsAsRead}+ disabled={isMarkingRead}+ >+ <CheckCheck className="h-4 w-4 mr-2" />+ {t("syncNotifications.markAsRead")}+ </Button>+ )}<Buttonvariant="outline"size="sm"- onClick={handleMarkErrorsAsRead}- disabled={isMarkingRead}+ onClick={() => setShowDeleteConfirm(true)}+ disabled={isDeleting || logs.length === 0}>- <CheckCheck className="h-4 w-4 mr-2" />- {t("syncNotifications.markAsRead")}+ <Trash2 className="h-4 w-4 mr-2" />+ {t("syncNotifications.deleteAll")}</Button>- )}- <Button- variant="outline"- size="sm"- onClick={handleDeleteLogs}- disabled={isDeleting || logs.length === 0}- >- <Trash2 className="h-4 w-4 mr-2" />- {t("syncNotifications.deleteAll")}- </Button>+ </div></div>- </div>- <div className="space-y-4 overflow-y-auto flex-1 px-6 pb-6">- {loading ? (- <div className="space-y-4">- <Skeleton className="h-32 w-full rounded-lg" />- <Skeleton className="h-32 w-full rounded-lg" />- <Skeleton className="h-32 w-full rounded-lg" />- </div>- ) : filteredLogs.length === 0 ? (- <div className="text-center py-8 text-muted-foreground">- {logs.length === 0- ? t("syncNotifications.noLogs")- : t("syncNotifications.noLogsFiltered")}- </div>- ) : (- filteredLogs.map((log) => (- <div- key={log.id}- className="border rounded-lg p-4 space-y-3 hover:bg-accent/50 transition-colors"- >- {/* Header with status and sync type */}- <div className="flex items-start justify-between">- <div className="flex items-center gap-2">- {getStatusIcon(log.status)}- <div>- <div className="font-medium flex items-center gap-2">- {log.externalSyncName}- {log.isRead && log.status === "error" && (- <span className="text-xs px-1.5 py-0.5 rounded bg-muted text-muted-foreground">- {t("syncNotifications.read")}- </span>- )}- </div>- <div className="text-sm text-muted-foreground flex items-center gap-1.5">- <Clock className="h-3.5 w-3.5" />- {formatDateTime(log.syncedAt)}+ <div className="space-y-4 overflow-y-auto flex-1 px-6 pb-6">+ {loading ? (+ <div className="space-y-4">+ <Skeleton className="h-32 w-full rounded-lg" />+ <Skeleton className="h-32 w-full rounded-lg" />+ <Skeleton className="h-32 w-full rounded-lg" />+ </div>+ ) : filteredLogs.length === 0 ? (+ <div className="text-center py-8 text-muted-foreground">+ {logs.length === 0+ ? t("syncNotifications.noLogs")+ : t("syncNotifications.noLogsFiltered")}+ </div>+ ) : (+ filteredLogs.map((log) => (+ <div+ key={log.id}+ className="border rounded-lg p-4 space-y-3 hover:bg-accent/50 transition-colors"+ >+ {/* Header with status and sync type */}+ <div className="flex items-start justify-between">+ <div className="flex items-center gap-2">+ {getStatusIcon(log.status)}+ <div>+ <div className="font-medium flex items-center gap-2">+ {log.externalSyncName}+ {log.isRead && log.status === "error" && (+ <span className="text-xs px-1.5 py-0.5 rounded bg-muted text-muted-foreground">+ {t("syncNotifications.read")}+ </span>+ )}+ </div>+ <div className="text-sm text-muted-foreground flex items-center gap-1.5">+ <Clock className="h-3.5 w-3.5" />+ {formatDateTime(log.syncedAt)}+ </div></div></div>+ <div className="flex items-center gap-1.5 text-sm text-muted-foreground">+ {getSyncTypeIcon(log.syncType)}+ <span>+ {log.syncType === "auto"+ ? t("syncNotifications.syncTypeAuto")+ : t("syncNotifications.syncTypeManual")}+ </span>+ </div></div>- <div className="flex items-center gap-1.5 text-sm text-muted-foreground">- {getSyncTypeIcon(log.syncType)}- <span>- {log.syncType === "auto"- ? t("syncNotifications.syncTypeAuto")- : t("syncNotifications.syncTypeManual")}- </span>- </div>- </div>- {/* Status and changes */}- {log.status === "success" ? (- <div>- {hasChanges(log) ? (- <div className="flex flex-wrap gap-3 text-sm">- {log.shiftsCreated > 0 && (- <div className="flex items-center gap-1.5 text-green-700">- <span className="font-medium">- {t("common.createdCount", {- count: log.shiftsCreated,- })}- </span>- </div>- )}- {log.shiftsUpdated > 0 && (- <div className="flex items-center gap-1.5 text-blue-700">- <span className="font-medium">- {t("common.updatedCount", {- count: log.shiftsUpdated,- })}- </span>- </div>- )}- {log.shiftsDeleted > 0 && (- <div className="flex items-center gap-1.5 text-orange-700">- <span className="font-medium">- {t("common.deletedCount", {- count: log.shiftsDeleted,- })}- </span>- </div>- )}- </div>- ) : (- <div className="text-sm text-muted-foreground">- {t("syncNotifications.noChanges")}+ {/* Status and changes */}+ {log.status === "success" ? (+ <div>+ {hasChanges(log) ? (+ <div className="flex flex-wrap gap-3 text-sm">+ {log.shiftsCreated > 0 && (+ <div className="flex items-center gap-1.5 text-green-700">+ <span className="font-medium">+ {t("common.createdCount", {+ count: log.shiftsCreated,+ })}+ </span>+ </div>+ )}+ {log.shiftsUpdated > 0 && (+ <div className="flex items-center gap-1.5 text-blue-700">+ <span className="font-medium">+ {t("common.updatedCount", {+ count: log.shiftsUpdated,+ })}+ </span>+ </div>+ )}+ {log.shiftsDeleted > 0 && (+ <div className="flex items-center gap-1.5 text-orange-700">+ <span className="font-medium">+ {t("common.deletedCount", {+ count: log.shiftsDeleted,+ })}+ </span>+ </div>+ )}+ </div>+ ) : (+ <div className="text-sm text-muted-foreground">+ {t("syncNotifications.noChanges")}+ </div>+ )}+ </div>+ ) : (+ <div className="text-sm text-red-100 bg-red-950/90 p-3 rounded border border-red-800">+ <div className="font-medium mb-1">+ {t("syncNotifications.errorMessage")}:</div>- )}- </div>- ) : (- <div className="text-sm text-red-100 bg-red-950/90 p-3 rounded border border-red-800">- <div className="font-medium mb-1">- {t("syncNotifications.errorMessage")}:+ <div className="text-red-200">{log.errorMessage}</div></div>- <div className="text-red-200">{log.errorMessage}</div>- </div>- )}- </div>- ))- )}- </div>- </DialogContent>- </Dialog>+ )}+ </div>+ ))+ )}+ </div>+ </DialogContent>+ </Dialog>++ <ConfirmationDialog+ open={showDeleteConfirm}+ onOpenChange={setShowDeleteConfirm}+ onConfirm={handleDeleteLogs}+ title={t("syncNotifications.title") + " " + t("common.delete")}+ description={t("syncNotifications.deleteConfirm")}+ cancelText={t("common.cancel")}+ confirmText={t("common.delete")}+ confirmVariant="destructive"+ />+ </>);}diff --git a/components/ui/confirmation-dialog.tsx b/components/ui/confirmation-dialog.tsxindex 1f196ce..6eca753 100644--- a/components/ui/confirmation-dialog.tsx+++ b/components/ui/confirmation-dialog.tsx@@ -18,6 +18,9 @@ interface ConfirmationDialogProps {onConfirm: () => void;title?: string;description?: string;+ cancelText?: string;+ confirmText?: string;+ confirmVariant?: "default" | "destructive";}export function ConfirmationDialog({@@ -26,6 +29,9 @@ export function ConfirmationDialog({onConfirm,title,description,+ cancelText,+ confirmText,+ confirmVariant = "default",}: ConfirmationDialogProps) {const t = useTranslations();@@ -41,9 +47,18 @@ export function ConfirmationDialog({</AlertDialogDescription></AlertDialogHeader><AlertDialogFooter>- <AlertDialogCancel>{t("common.cancel")}</AlertDialogCancel>- <AlertDialogAction onClick={onConfirm}>- {t("common.closeWithoutSaving")}+ <AlertDialogCancel>+ {cancelText || t("common.cancel")}+ </AlertDialogCancel>+ <AlertDialogAction+ onClick={onConfirm}+ className={+ confirmVariant === "destructive"+ ? "bg-destructive text-destructive-foreground hover:bg-destructive/90"+ : ""+ }+ >+ {confirmText || t("common.closeWithoutSaving")}</AlertDialogAction></AlertDialogFooter></AlertDialogContent>diff --git a/hooks/usePresetManagement.ts b/hooks/usePresetManagement.tsnew file mode 100644index 0000000..8c83f58--- /dev/null+++ b/hooks/usePresetManagement.ts@@ -0,0 +1,168 @@+import { useCallback } from "react";+import { toast } from "sonner";+import { useTranslations } from "next-intl";+import { getCachedPassword } from "@/lib/password-cache";++interface PresetFormData {+ title: string;+ startTime: string;+ endTime: string;+ color: string;+ notes: string;+ isSecondary: boolean;+ isAllDay: boolean;+ hideFromStats: boolean;+}++interface UsePresetManagementOptions {+ calendarId: string;+ onSuccess: () => void;+}++export function usePresetManagement({+ calendarId,+ onSuccess,+}: UsePresetManagementOptions) {+ const t = useTranslations();++ const createPreset = useCallback(+ async (formData: PresetFormData) => {+ try {+ const password = getCachedPassword(calendarId);++ const response = await fetch("/api/presets", {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({+ calendarId,+ ...formData,+ password,+ }),+ });++ if (response.ok) {+ onSuccess();+ toast.success(t("common.created", { item: t("preset.preset") }));+ return true;+ } else {+ const data = await response.json();+ toast.error(+ data.error || t("common.createError", { item: t("preset.preset") })+ );+ return false;+ }+ } catch (error) {+ console.error("Failed to create preset:", error);+ toast.error(t("common.createError", { item: t("preset.preset") }));+ return false;+ }+ },+ [calendarId, onSuccess, t]+ );++ const updatePreset = useCallback(+ async (presetId: string, formData: PresetFormData) => {+ try {+ const password = getCachedPassword(calendarId);++ const response = await fetch(`/api/presets/${presetId}`, {+ method: "PATCH",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({+ ...formData,+ password,+ }),+ });++ if (response.ok) {+ onSuccess();+ toast.success(t("common.updated", { item: t("preset.preset") }));+ return true;+ } else {+ const data = await response.json();+ toast.error(+ data.error || t("common.updateError", { item: t("preset.preset") })+ );+ return false;+ }+ } catch (error) {+ console.error("Failed to update preset:", error);+ toast.error(t("common.updateError", { item: t("preset.preset") }));+ return false;+ }+ },+ [calendarId, onSuccess, t]+ );++ const deletePreset = useCallback(+ async (presetId: string) => {+ try {+ const password = getCachedPassword(calendarId);++ const response = await fetch(`/api/presets/${presetId}`, {+ method: "DELETE",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ password }),+ });++ if (response.ok) {+ onSuccess();+ toast.success(t("common.deleted", { item: t("preset.preset") }));+ return true;+ } else {+ const data = await response.json();+ toast.error(+ data.error || t("common.deleteError", { item: t("preset.preset") })+ );+ return false;+ }+ } catch (error) {+ console.error("Failed to delete preset:", error);+ toast.error(t("common.deleteError", { item: t("preset.preset") }));+ return false;+ }+ },+ [calendarId, onSuccess, t]+ );++ const reorderPresets = useCallback(+ async (presetOrders: Array<{ id: string; order: number }>) => {+ try {+ const password = getCachedPassword(calendarId);++ const response = await fetch("/api/presets/reorder", {+ method: "PATCH",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({+ calendarId,+ presetOrders,+ password,+ }),+ });++ if (response.ok) {+ onSuccess();+ return true;+ } else {+ const data = await response.json();+ toast.error(+ data.error || t("common.updateError", { item: t("preset.preset") })+ );+ return false;+ }+ } catch (error) {+ console.error("Failed to reorder presets:", error);+ toast.error(t("common.updateError", { item: t("preset.preset") }));+ return false;+ }+ },+ [calendarId, onSuccess, t]+ );++ return {+ createPreset,+ updatePreset,+ deletePreset,+ reorderPresets,+ };+}diff --git a/messages/de.json b/messages/de.jsonindex b3a90c8..6d1615e 100644--- a/messages/de.json+++ b/messages/de.json@@ -260,6 +260,7 @@"hideFromStatsHint": "Schichten dieses Kalenders aus der Statistik ausschließen","lastSynced": "Zuletzt synchronisiert","syncError": "Kalender konnte nicht synchronisiert werden",+ "delete": "Externen Kalender löschen","deleteConfirm": "Diesen externen Kalender löschen? Alle importierten Schichten werden entfernt.","hintsTitle": "Kalender-URL finden","hintsDescription": "Wähle deinen Kalendertyp, um Anweisungen zu erhalten:",diff --git a/messages/en.json b/messages/en.jsonindex f3fcbf7..9f8950a 100644--- a/messages/en.json+++ b/messages/en.json@@ -260,6 +260,7 @@"hideFromStatsHint": "Exclude shifts from this calendar from statistics","lastSynced": "Last synced","syncError": "Failed to sync calendar",+ "delete": "Delete External Calendar","deleteConfirm": "Delete this external calendar? All imported shifts will be removed.","hintsTitle": "Finding Your Calendar URL","hintsDescription": "Select your calendar type to see instructions:",diff --git a/messages/it.json b/messages/it.jsonindex e53eb78..3ed344b 100644--- a/messages/it.json+++ b/messages/it.json@@ -260,6 +260,7 @@"hideFromStatsHint": "Escludi i turni da questo calendario dalle statistiche","lastSynced": "Ultima sincronizzazione","syncError": "Impossibile sincronizzare il calendario",+ "delete": "Elimina Calendario Esterno","deleteConfirm": "Eliminare questo calendario esterno? Tutti i turni importati verranno rimossi.","hintsTitle": "Trovare l'URL del Calendario","hintsDescription": "Seleziona il tipo di calendario per visualizzare le istruzioni:",