Skip to content

Your favorite shift management application!

feat: Add shift duration tracking to stats and enhance UI (#61)

panteL91a883ed0147
diff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.md
index 3a2d114..8e3141f 100644
--- a/.github/copilot-instructions.md
+++ b/.github/copilot-instructions.md
@@ -163,7 +163,7 @@ The translation files use a centralized structure to eliminate duplicates and en
```typescript
// Success/Error Messages - use {item} parameter
-toast.success(t("common.created", { item: t("shift.title") }));
+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.create") }));
toast.error(t("common.deleteError", { item: t("note.note") }));
diff --git a/app/api/shifts/stats/route.ts b/app/api/shifts/stats/route.ts
index d094b85..e74f994 100644
--- a/app/api/shifts/stats/route.ts
+++ b/app/api/shifts/stats/route.ts
@@ -6,8 +6,9 @@ import {
shiftPresets,
calendars,
} from "@/lib/db/schema";
-import { eq, and, gte, lte, sql, or, isNull } from "drizzle-orm";
+import { eq, and, gte, lte, or, isNull } from "drizzle-orm";
import { verifyPassword } from "@/lib/password-utils";
+import { calculateShiftDuration } from "@/lib/date-utils";
import {
startOfWeek,
endOfWeek,
@@ -83,7 +84,9 @@ export async function GET(request: Request) {
const result = await db
.select({
title: shifts.title,
- count: sql<number>`count(*)`.as("count"),
+ startTime: shifts.startTime,
+ endTime: shifts.endTime,
+ isAllDay: shifts.isAllDay,
})
.from(shifts)
.leftJoin(externalSyncs, eq(shifts.externalSyncId, externalSyncs.id))
@@ -104,21 +107,47 @@ export async function GET(request: Request) {
// Exclude shifts from presets that are hidden from stats
or(isNull(shifts.presetId), eq(shiftPresets.hideFromStats, false))
)
- )
- .groupBy(shifts.title)
- .orderBy(sql`count(*) DESC`);
+ );
+
+ // Group by title and calculate stats
+ const statsMap = new Map<string, { count: number; totalMinutes: number }>();
+
+ result.forEach((shift) => {
+ const existing = statsMap.get(shift.title) || {
+ count: 0,
+ totalMinutes: 0,
+ };
+ existing.count++;
+ existing.totalMinutes += shift.isAllDay
+ ? 0
+ : calculateShiftDuration(shift.startTime, shift.endTime);
+ statsMap.set(shift.title, existing);
+ });
// Transform result to object format
- const stats = result.reduce((acc, item) => {
- acc[item.title] = Number(item.count);
- return acc;
- }, {} as Record<string, number>);
+ const stats = Array.from(statsMap.entries()).reduce(
+ (acc, [title, data]) => {
+ acc[title] = {
+ count: data.count,
+ totalMinutes: data.totalMinutes,
+ };
+ return acc;
+ },
+ {} as Record<string, { count: number; totalMinutes: number }>
+ );
+
+ // Calculate total duration
+ const totalMinutes = Object.values(stats).reduce(
+ (sum, data) => sum + data.totalMinutes,
+ 0
+ );
return NextResponse.json({
period,
startDate: startDate.toISOString(),
endDate: endDate.toISOString(),
stats,
+ totalMinutes,
});
} catch (error) {
console.error("Failed to fetch shift statistics:", error);
diff --git a/components/day-shifts-dialog.tsx b/components/day-shifts-dialog.tsx
index 292bf79..aeb5d77 100644
--- a/components/day-shifts-dialog.tsx
+++ b/components/day-shifts-dialog.tsx
@@ -49,7 +49,7 @@ export function DayShiftsDialog({
</DialogTitle>
<DialogDescription className="text-sm text-muted-foreground">
{shifts.length}{" "}
- {shifts.length === 1 ? t("shift.shift_one") : t("shift.shifts")}
+ {shifts.length === 1 ? t("shift.shift_one") : t("common.shifts")}
</DialogDescription>
</DialogHeader>
diff --git a/components/shift-stats.tsx b/components/shift-stats.tsx
index e1276a0..9aec4f4 100644
--- a/components/shift-stats.tsx
+++ b/components/shift-stats.tsx
@@ -5,12 +5,14 @@ import { useTranslations } from "next-intl";
import { Button } from "@/components/ui/button";
import { BarChart3, ChevronDown, ChevronUp } from "lucide-react";
import { getCachedPassword } from "@/lib/password-cache";
+import { formatDuration } from "@/lib/date-utils";
interface ShiftStats {
period: string;
startDate: string;
endDate: string;
- stats: Record<string, number>;
+ stats: Record<string, { count: number; totalMinutes: number }>;
+ totalMinutes: number;
}
interface ShiftStatsProps {
@@ -79,9 +81,11 @@ export function ShiftStats({
const totalShifts =
stats && stats.stats
- ? Object.values(stats.stats).reduce((sum, count) => sum + count, 0)
+ ? Object.values(stats.stats).reduce((sum, data) => sum + data.count, 0)
: 0;
+ const totalMinutes = stats?.totalMinutes || 0;
+
return (
<div className="border border-border/50 rounded-xl bg-gradient-to-b from-card/80 via-card/60 to-card/40 backdrop-blur-sm overflow-hidden shadow-lg">
{/* Header */}
@@ -99,11 +103,20 @@ export function ShiftStats({
</div>
<div className="flex items-center gap-2">
{!isExpanded && stats && totalShifts > 0 && (
- <div className="px-3 py-1.5 bg-primary/10 rounded-full">
- <span className="font-semibold text-primary text-xs sm:text-sm">
- {totalShifts}
- </span>
- </div>
+ <>
+ <div className="px-2.5 py-1 bg-gradient-to-r from-primary/20 to-primary/10 border border-primary/30 rounded-lg">
+ <span className="font-bold text-primary text-xs sm:text-sm">
+ {totalShifts}
+ </span>
+ </div>
+ {totalMinutes > 0 && (
+ <div className="px-2.5 py-1 bg-gradient-to-r from-primary/20 to-primary/10 border border-primary/30 rounded-lg">
+ <span className="font-bold text-primary text-xs sm:text-sm">
+ {formatDuration(totalMinutes)}
+ </span>
+ </div>
+ )}
+ </>
)}
{!isExpanded && stats && totalShifts > 0 && (
<div className="hidden sm:flex gap-1.5">
@@ -194,37 +207,82 @@ export function ShiftStats({
</p>
) : stats && Object.keys(stats.stats).length > 0 ? (
<div className="space-y-3.5">
- <div className="flex justify-between items-center pb-2.5 border-b border-border/50">
- <span className="font-semibold text-sm sm:text-base flex items-center gap-2">
- <div className="w-1 h-5 bg-gradient-to-b from-primary to-primary/50 rounded-full"></div>
- {t("stats.total")}
- </span>
- <span className="font-bold text-xl sm:text-2xl bg-gradient-to-r from-primary to-primary/70 bg-clip-text">
- {totalShifts}
- </span>
+ {/* Total Statistics Card */}
+ <div className="p-3 rounded-lg bg-gradient-to-br from-primary/10 via-primary/5 to-transparent border border-primary/20">
+ <div className="flex items-center justify-between gap-3">
+ <span className="font-semibold text-xs sm:text-sm flex items-center gap-2">
+ <div className="w-1 h-4 bg-gradient-to-b from-primary to-primary/50 rounded-full shadow-sm shadow-primary/20"></div>
+ {t("stats.total")}
+ </span>
+ <div className="flex items-center gap-3">
+ {/* Shift Count */}
+ <div className="flex flex-col items-end">
+ <span className="text-[10px] text-muted-foreground font-medium mb-0.5">
+ {t("common.shifts")}
+ </span>
+ <div className="px-2.5 py-1 rounded-md bg-gradient-to-r from-primary/20 to-primary/10 border border-primary/30">
+ <span className="font-bold text-base sm:text-lg bg-gradient-to-r from-primary to-primary/70 bg-clip-text text-transparent">
+ {totalShifts}
+ </span>
+ </div>
+ </div>
+ {totalMinutes > 0 && (
+ <>
+ <div className="h-8 w-px bg-gradient-to-b from-transparent via-border to-transparent"></div>
+ {/* Duration */}
+ <div className="flex flex-col items-end">
+ <span className="text-[10px] text-muted-foreground font-medium mb-0.5">
+ {t("stats.hours")}
+ </span>
+ <div className="px-2.5 py-1 rounded-md bg-gradient-to-r from-primary/20 to-primary/10 border border-primary/30">
+ <span className="font-bold text-base sm:text-lg bg-gradient-to-r from-primary to-primary/70 bg-clip-text text-transparent">
+ {formatDuration(totalMinutes)}
+ </span>
+ </div>
+ </div>
+ </>
+ )}
+ </div>
+ </div>
</div>
+
+ {/* Individual Shift Types */}
{Object.entries(stats.stats)
- .sort(([, a], [, b]) => b - a)
- .map(([title, count]) => (
+ .sort(([, a], [, b]) => b.count - a.count)
+ .map(([title, data]) => (
<div
key={title}
- className="flex justify-between items-center gap-3 p-2.5 rounded-lg bg-muted/30 border border-border/30 hover:bg-muted/50 transition-colors"
+ className="group relative p-3 rounded-lg bg-gradient-to-br from-card via-card/80 to-card/60 border border-border/40 hover:border-primary/30 hover:shadow-md hover:shadow-primary/5 transition-all duration-200"
>
- <span className="text-sm font-medium truncate flex-shrink min-w-0">
- {title}
- </span>
- <div className="flex items-center gap-2 sm:gap-3 flex-shrink-0">
- <div className="w-20 sm:w-28 h-2.5 bg-muted rounded-full overflow-hidden border border-border/30">
- <div
- className="h-full bg-gradient-to-r from-primary to-primary/80 transition-all shadow-sm"
- style={{
- width: `${(count / totalShifts) * 100}%`,
- }}
- />
- </div>
- <span className="font-bold text-sm w-6 sm:w-8 text-right">
- {count}
+ <div className="flex justify-between items-center gap-3">
+ <span className="text-sm font-semibold truncate flex-shrink min-w-0 group-hover:text-primary transition-colors">
+ {title}
</span>
+ <div className="flex items-center gap-3 flex-shrink-0">
+ {/* Progress Bar */}
+ <div className="w-24 sm:w-32 h-2 bg-muted/50 rounded-full overflow-hidden border border-border/20 shadow-inner">
+ <div
+ className="h-full bg-gradient-to-r from-primary via-primary/90 to-primary/80 transition-all duration-300 shadow-sm"
+ style={{
+ width: `${(data.count / totalShifts) * 100}%`,
+ }}
+ />
+ </div>
+ {/* Count Badge */}
+ <div className="min-w-[2.5rem] px-2 py-1 rounded-md bg-primary/10 border border-primary/20">
+ <span className="font-bold text-sm text-primary text-center block">
+ {data.count}
+ </span>
+ </div>
+ {/* Duration Badge */}
+ {data.totalMinutes > 0 && (
+ <div className="min-w-[3rem] sm:min-w-[3.5rem] px-2 py-1 rounded-md bg-primary/10 border border-primary/20">
+ <span className="font-semibold text-xs sm:text-sm text-primary text-center block">
+ {formatDuration(data.totalMinutes)}
+ </span>
+ </div>
+ )}
+ </div>
</div>
</div>
))}
diff --git a/components/shifts-list.tsx b/components/shifts-list.tsx
index 5ae9933..87b5f7f 100644
--- a/components/shifts-list.tsx
+++ b/components/shifts-list.tsx
@@ -58,7 +58,7 @@ export function ShiftsList({
<CalendarIcon className="h-4 w-4 sm:h-5 sm:w-5 text-primary-foreground" />
</div>
<h3 className="text-sm sm:text-base font-semibold bg-gradient-to-r from-foreground to-foreground/70 bg-clip-text">
- {t("shift.title")}
+ {t("common.shifts")}
</h3>
</div>
<div className="flex items-center gap-3">
@@ -147,7 +147,7 @@ export function ShiftsList({
{dayShifts.length}{" "}
{dayShifts.length === 1
? t("shift.shift_one")
- : t("shift.shifts")}
+ : t("common.shifts")}
</div>
</div>
</div>
diff --git a/lib/date-utils.ts b/lib/date-utils.ts
index 4d7ebdc..3f69c6a 100644
--- a/lib/date-utils.ts
+++ b/lib/date-utils.ts
@@ -8,3 +8,66 @@ export function formatDateToLocal(date: Date): string {
const day = String(date.getDate()).padStart(2, "0");
return `${year}-${month}-${day}`;
}
+
+/**
+ * Calculates the duration in minutes between two time strings
+ * @param startTime - Time string in HH:MM format
+ * @param endTime - Time string in HH:MM format
+ * @returns Duration in minutes
+ */
+export function calculateShiftDuration(
+ startTime: string,
+ endTime: string
+): number {
+ // Validate time format (HH:MM)
+ const timeRegex = /^([0-1]?[0-9]|2[0-3]):([0-5][0-9])$/;
+ if (!timeRegex.test(startTime) || !timeRegex.test(endTime)) {
+ console.error(
+ `Invalid time format: startTime="${startTime}", endTime="${endTime}"`
+ );
+ return 0; // Return 0 for invalid formats
+ }
+
+ const [startHour, startMinute] = startTime.split(":").map(Number);
+ const [endHour, endMinute] = endTime.split(":").map(Number);
+
+ // Additional validation for NaN values
+ if (
+ isNaN(startHour) ||
+ isNaN(startMinute) ||
+ isNaN(endHour) ||
+ isNaN(endMinute)
+ ) {
+ console.error(
+ `Invalid time values: startTime="${startTime}", endTime="${endTime}"`
+ );
+ return 0;
+ }
+
+ const startMinutes = startHour * 60 + startMinute;
+ let endMinutes = endHour * 60 + endMinute;
+
+ // Handle overnight shifts (end time is before start time)
+ if (endMinutes < startMinutes) {
+ endMinutes += 24 * 60; // Add 24 hours
+ }
+
+ return endMinutes - startMinutes;
+}
+
+/**
+ * Formats duration in minutes to HH:MM format
+ * @param minutes - Duration in minutes (must be non-negative)
+ * @returns Formatted duration string (e.g., "8:30")
+ */
+export function formatDuration(minutes: number): string {
+ // Handle negative values or invalid inputs
+ if (minutes < 0 || isNaN(minutes)) {
+ console.error(`Invalid duration: ${minutes} minutes`);
+ return "0:00";
+ }
+
+ const hours = Math.floor(minutes / 60);
+ const mins = minutes % 60;
+ return `${hours}:${String(mins).padStart(2, "0")}`;
+}
diff --git a/messages/de.json b/messages/de.json
index 307ce1e..b854411 100644
--- a/messages/de.json
+++ b/messages/de.json
@@ -23,7 +23,8 @@
"updateError": "{item} konnte nicht aktualisiert werden",
"deleteError": "{item} konnte nicht gelöscht werden",
"deleteConfirm": "{item} \"{name}\" wirklich löschen?",
- "deleteConfirmWithWarning": "{item} \"{name}\" wirklich löschen? {warning}"
+ "deleteConfirmWithWarning": "{item} \"{name}\" wirklich löschen? {warning}",
+ "shifts": "Schichten"
},
"validation": {
"passwordMatch": "Passwörter stimmen nicht überein",
@@ -97,7 +98,6 @@
"hintDesktop": "Rechtsklick auf einen Tag öffnet Notizen. Das Notiz-Icon zeigt vorhandene Notizen an."
},
"shift": {
- "title": "Schichten",
"create": "Neue Schicht",
"createDescription": "Füge eine neue Schicht zu deinem Kalender hinzu",
"edit": "Schicht bearbeiten",
@@ -111,7 +111,6 @@
"allDayShift": "Ganztägige Schicht",
"noShiftsInMonth": "Keine Schichten in diesem Monat",
"noShiftsInMonthDescription": "Füge Schichten hinzu, indem du auf Tage im Kalender oben klickst.",
- "shifts": "Schichten",
"shift_one": "Schicht",
"selectPreset": "Vorlage auswählen",
"none": "Keine",
@@ -179,7 +178,8 @@
"month": "Monat",
"year": "Jahr",
"total": "Gesamt",
- "noData": "Keine Schichten in diesem Zeitraum"
+ "noData": "Keine Schichten in diesem Zeitraum",
+ "hours": "Stunden"
},
"sync": {
"refreshing": "Aktualisiere Daten...",
@@ -193,9 +193,6 @@
"description": "Erstelle deinen ersten Kalender, um deine Schichten zu verwalten.",
"createCalendar": "Kalender erstellen"
},
- "version": {
- "label": "Version"
- },
"footer": {
"version": "Version",
"github": "GitHub",
diff --git a/messages/en.json b/messages/en.json
index c043e04..0a17c93 100644
--- a/messages/en.json
+++ b/messages/en.json
@@ -23,7 +23,8 @@
"updateError": "Failed to update {item}",
"deleteError": "Failed to delete {item}",
"deleteConfirm": "Really delete {item} \"{name}\"?",
- "deleteConfirmWithWarning": "Really delete {item} \"{name}\"? {warning}"
+ "deleteConfirmWithWarning": "Really delete {item} \"{name}\"? {warning}",
+ "shifts": "Shifts"
},
"validation": {
"passwordMatch": "Passwords do not match",
@@ -97,7 +98,6 @@
"hintDesktop": "Right-click on a day to open notes. The note icon shows existing notes."
},
"shift": {
- "title": "Shifts",
"create": "New Shift",
"createDescription": "Add a new shift to your calendar",
"edit": "Edit Shift",
@@ -111,7 +111,6 @@
"allDayShift": "All-day shift",
"noShiftsInMonth": "No shifts this month",
"noShiftsInMonthDescription": "Add shifts by clicking on days in the calendar above.",
- "shifts": "shifts",
"shift_one": "shift",
"selectPreset": "Select Preset",
"none": "None",
@@ -179,7 +178,8 @@
"month": "Month",
"year": "Year",
"total": "Total",
- "noData": "No shifts in this period"
+ "noData": "No shifts in this period",
+ "hours": "Hours"
},
"sync": {
"refreshing": "Refreshing data...",
@@ -193,9 +193,6 @@
"description": "Create your first calendar to manage your shifts.",
"createCalendar": "Create Calendar"
},
- "version": {
- "label": "Version"
- },
"footer": {
"version": "Version",
"github": "GitHub",
diff --git a/messages/it.json b/messages/it.json
index 44a62e2..3f7243d 100644
--- a/messages/it.json
+++ b/messages/it.json
@@ -23,7 +23,8 @@
"updateError": "Impossibile aggiornare {item}",
"deleteError": "Impossibile eliminare {item}",
"deleteConfirm": "Eliminare davvero {item} \"{name}\"?",
- "deleteConfirmWithWarning": "Eliminare davvero {item} \"{name}\"? {warning}"
+ "deleteConfirmWithWarning": "Eliminare davvero {item} \"{name}\"? {warning}",
+ "shifts": "Turni"
},
"validation": {
"passwordMatch": "Le password non corrispondono",
@@ -97,7 +98,6 @@
"hintDesktop": "Fai clic con il pulsante destro del mouse su un giorno per aprire le note. L'icona della nota indica le note esistenti."
},
"shift": {
- "title": "Turni",
"create": "Nuovo Turno",
"createDescription": "Aggiungi un nuovo turno al tuo calendario",
"edit": "Modifica Turno",
@@ -111,7 +111,6 @@
"allDayShift": "Turno di un'intera giornata",
"noShiftsInMonth": "Nessun turno questo mese",
"noShiftsInMonthDescription": "Aggiungi turni cliccando sui giorni nel calendario in alto.",
- "shifts": "turni",
"shift_one": "turno",
"selectPreset": "Seleziona Preset",
"none": "Nessuno",
@@ -178,7 +177,8 @@
"month": "Mese",
"year": "Anno",
"total": "Totale",
- "noData": "Nessun turno in questo periodo"
+ "noData": "Nessun turno in questo periodo",
+ "hours": "Ore"
},
"sync": {
"refreshing": "Aggiornamento dati...",
@@ -192,9 +192,6 @@
"description": "Crea il tuo primo calendario per gestire i tuoi turni.",
"createCalendar": "Crea Calendario"
},
- "version": {
- "label": "Versione"
- },
"footer": {
"version": "Versione",
"github": "GitHub",