Skip to content

Your favorite shift management application!

feat: add shift statistics feature with API endpoint and UI component

panteLx88383df9236e
diff --git a/README.md b/README.md
index f34180a..7120f2b 100644
--- a/README.md
+++ b/README.md
@@ -1,6 +1,6 @@
# BetterShift
-A modern shift management application built with Next.js and SQLite. BetterShift helps you organize and manage work shifts across multiple calendars with customizable presets, color coding, and password protection.
+A modern shift management application built with Next.js and SQLite. BetterShift helps you organize and manage work shifts across multiple calendars with customizable presets, color coding, shift statistics and password protection.
## Features
@@ -11,6 +11,7 @@ A modern shift management application built with Next.js and SQLite. BetterShift
- πŸ—“οΈ **Calendar View**: Interactive monthly calendar with week-based layout
- πŸ”’ **Password Protection**: Secure calendars with optional passwords
- 🌐 **Internationalization (i18n)**: Supports multiple languages with automatic detection and manual switching
+- πŸ“Š **Shift Statistics**: View statistics for shifts over different time periods
- πŸ’Ύ **SQLite Database**: Lightweight, file-based database with Drizzle ORM
- 🐳 **Docker Support**: Easy deployment with Docker and Docker Compose
diff --git a/app/api/shifts/stats/route.ts b/app/api/shifts/stats/route.ts
new file mode 100644
index 0000000..22b5ea9
--- /dev/null
+++ b/app/api/shifts/stats/route.ts
@@ -0,0 +1,87 @@
+import { NextResponse } from "next/server";
+import { db } from "@/lib/db";
+import { shifts } from "@/lib/db/schema";
+import { eq, and, gte, lte, sql } from "drizzle-orm";
+import {
+ startOfWeek,
+ endOfWeek,
+ startOfMonth,
+ endOfMonth,
+ startOfYear,
+ endOfYear,
+} from "date-fns";
+
+// GET shift statistics for a calendar
+export async function GET(request: Request) {
+ try {
+ const { searchParams } = new URL(request.url);
+ const calendarId = searchParams.get("calendarId");
+ const period = searchParams.get("period") || "month"; // week, month, year
+ const date = searchParams.get("date"); // reference date for the period
+
+ if (!calendarId) {
+ return NextResponse.json(
+ { error: "Calendar ID is required" },
+ { status: 400 }
+ );
+ }
+
+ const referenceDate = date ? new Date(date) : new Date();
+
+ let startDate: Date;
+ let endDate: Date;
+
+ // Determine date range based on period
+ switch (period) {
+ case "week":
+ startDate = startOfWeek(referenceDate, { weekStartsOn: 1 }); // Monday
+ endDate = endOfWeek(referenceDate, { weekStartsOn: 1 });
+ break;
+ case "year":
+ startDate = startOfYear(referenceDate);
+ endDate = endOfYear(referenceDate);
+ break;
+ case "month":
+ default:
+ startDate = startOfMonth(referenceDate);
+ endDate = endOfMonth(referenceDate);
+ break;
+ }
+
+ // Fetch shifts for the period
+ const result = await db
+ .select({
+ title: shifts.title,
+ count: sql<number>`count(*)`.as("count"),
+ })
+ .from(shifts)
+ .where(
+ and(
+ eq(shifts.calendarId, calendarId),
+ gte(shifts.date, startDate),
+ lte(shifts.date, endDate)
+ )
+ )
+ .groupBy(shifts.title)
+ .orderBy(sql`count(*) DESC`);
+
+ // Transform result to object format
+ const stats = result.reduce((acc, item) => {
+ acc[item.title] = Number(item.count);
+ return acc;
+ }, {} as Record<string, number>);
+
+ return NextResponse.json({
+ period,
+ startDate: startDate.toISOString(),
+ endDate: endDate.toISOString(),
+ stats,
+ });
+ } catch (error) {
+ console.error("Failed to fetch shift statistics:", error);
+ return NextResponse.json(
+ { error: "Failed to fetch shift statistics" },
+ { status: 500 }
+ );
+ }
+}
diff --git a/app/page.tsx b/app/page.tsx
index 38bf53b..72d96cb 100644
--- a/app/page.tsx
+++ b/app/page.tsx
@@ -12,6 +12,7 @@ import { PresetSelector } from "@/components/preset-selector";
import { PasswordDialog } from "@/components/password-dialog";
import { ManagePasswordDialog } from "@/components/manage-password-dialog";
import { LanguageSwitcher } from "@/components/language-switcher";
+import { ShiftStats } from "@/components/shift-stats";
import { Button } from "@/components/ui/button";
import {
Dialog,
@@ -72,6 +73,7 @@ function HomeContent() {
presetAction?: () => Promise<void>;
} | null>(null);
const [loading, setLoading] = useState(true);
+ const [statsRefreshTrigger, setStatsRefreshTrigger] = useState(0);
// Fetch calendars on mount
useEffect(() => {
@@ -183,6 +185,7 @@ function HomeContent() {
});
const newShift = await response.json();
setShifts([...shifts, newShift]);
+ setStatsRefreshTrigger((prev) => prev + 1);
} catch (error) {
console.error("Failed to create shift:", error);
}
@@ -210,6 +213,7 @@ function HomeContent() {
const updatedShift = await response.json();
setShifts(shifts.map((s) => (s.id === id ? updatedShift : s)));
+ setStatsRefreshTrigger((prev) => prev + 1);
} catch (error) {
console.error("Failed to update shift:", error);
}
@@ -236,6 +240,7 @@ function HomeContent() {
}
setShifts(shifts.filter((s) => s.id !== id));
+ setStatsRefreshTrigger((prev) => prev + 1);
} catch (error) {
console.error("Failed to delete shift:", error);
}
@@ -254,6 +259,7 @@ function HomeContent() {
);
if (response.ok) {
setShifts(shifts.filter((s) => s.id !== pendingAction.shiftId));
+ setStatsRefreshTrigger((prev) => prev + 1); // Refresh stats
}
} else if (
pendingAction.type === "edit" &&
@@ -272,6 +278,7 @@ function HomeContent() {
s.id === pendingAction.shiftId ? updatedShift : s
)
);
+ setStatsRefreshTrigger((prev) => prev + 1);
}
} else if (pendingAction.presetAction) {
// Execute the pending preset action
@@ -655,6 +662,13 @@ function HomeContent() {
{/* Shifts List */}
<div className="space-y-3 sm:space-y-4 px-2 sm:px-0">
+ {/* Shift Statistics */}
+ <ShiftStats
+ calendarId={selectedCalendar}
+ currentDate={currentDate}
+ refreshTrigger={statsRefreshTrigger}
+ />
+
<div className="flex items-center justify-between flex-wrap gap-2">
<h3 className="text-lg sm:text-xl font-bold">{t("shift.title")}</h3>
{shifts.length > 0 && (
diff --git a/components/shift-stats.tsx b/components/shift-stats.tsx
new file mode 100644
index 0000000..07b7452
--- /dev/null
+++ b/components/shift-stats.tsx
@@ -0,0 +1,218 @@
+"use client";
+
+import { useState, useEffect } from "react";
+import { useTranslations } from "next-intl";
+import { Button } from "@/components/ui/button";
+import { BarChart3, ChevronDown, ChevronUp } from "lucide-react";
+
+interface ShiftStats {
+ period: string;
+ startDate: string;
+ endDate: string;
+ stats: Record<string, number>;
+}
+
+interface ShiftStatsProps {
+ calendarId: string | undefined;
+ currentDate: Date;
+ refreshTrigger?: number;
+}
+
+export function ShiftStats({
+ calendarId,
+ currentDate,
+ refreshTrigger,
+}: ShiftStatsProps) {
+ const t = useTranslations();
+ const [period, setPeriod] = useState<"week" | "month" | "year">("month");
+ const [stats, setStats] = useState<ShiftStats | null>(null);
+ const [loading, setLoading] = useState(false);
+ const [isExpanded, setIsExpanded] = useState(false);
+
+ useEffect(() => {
+ if (calendarId) {
+ fetchStats();
+ }
+ }, [calendarId, period, currentDate, refreshTrigger]);
+
+ const fetchStats = async () => {
+ if (!calendarId) return;
+
+ const isInitialLoad = stats === null;
+ if (isInitialLoad) {
+ setLoading(true);
+ }
+
+ try {
+ const response = await fetch(
+ `/api/shifts/stats?calendarId=${calendarId}&period=${period}&date=${currentDate.toISOString()}`
+ );
+ const data = await response.json();
+ setStats(data);
+ } catch (error) {
+ console.error("Failed to fetch shift statistics:", error);
+ } finally {
+ if (isInitialLoad) {
+ setLoading(false);
+ }
+ }
+ };
+
+ if (!calendarId) return null;
+
+ const totalShifts = stats
+ ? Object.values(stats.stats).reduce((sum, count) => sum + count, 0)
+ : 0;
+
+ return (
+ <div className="border rounded-lg bg-card/50 backdrop-blur-sm overflow-hidden">
+ {/* Header */}
+ <button
+ onClick={() => setIsExpanded(!isExpanded)}
+ className="w-full px-3 sm:px-4 py-2.5 sm:py-3 flex items-center justify-between hover:bg-accent/50 transition-colors"
+ >
+ <div className="flex items-center gap-2">
+ <BarChart3 className="h-4 w-4 sm:h-5 sm:w-5 text-primary" />
+ <h3 className="text-sm sm:text-base font-semibold">
+ {t("stats.title")}
+ </h3>
+ {!isExpanded && stats && totalShifts > 0 && (
+ <span className="text-xs sm:text-sm text-muted-foreground">
+ ({totalShifts} {t("stats.shiftsTotal")})
+ </span>
+ )}
+ </div>
+ <div className="flex items-center gap-2">
+ {!isExpanded && stats && totalShifts > 0 && (
+ <div className="hidden sm:flex gap-1.5">
+ <span
+ className={`h-6 text-xs px-2 inline-flex items-center justify-center rounded-md font-medium transition-colors ${
+ period === "week"
+ ? "bg-primary text-primary-foreground"
+ : "border border-input bg-background hover:bg-accent hover:text-accent-foreground"
+ }`}
+ onClick={(e) => {
+ e.stopPropagation();
+ setPeriod("week");
+ }}
+ >
+ {t("stats.week")}
+ </span>
+ <span
+ className={`h-6 text-xs px-2 inline-flex items-center justify-center rounded-md font-medium transition-colors cursor-pointer ${
+ period === "month"
+ ? "bg-primary text-primary-foreground"
+ : "border border-input bg-background hover:bg-accent hover:text-accent-foreground"
+ }`}
+ onClick={(e) => {
+ e.stopPropagation();
+ setPeriod("month");
+ }}
+ >
+ {t("stats.month")}
+ </span>
+ <span
+ className={`h-6 text-xs px-2 inline-flex items-center justify-center rounded-md font-medium transition-colors cursor-pointer ${
+ period === "year"
+ ? "bg-primary text-primary-foreground"
+ : "border border-input bg-background hover:bg-accent hover:text-accent-foreground"
+ }`}
+ onClick={(e) => {
+ e.stopPropagation();
+ setPeriod("year");
+ }}
+ >
+ {t("stats.year")}
+ </span>
+ </div>
+ )}
+ {isExpanded ? (
+ <ChevronUp className="h-4 w-4 text-muted-foreground" />
+ ) : (
+ <ChevronDown className="h-4 w-4 text-muted-foreground" />
+ )}
+ </div>
+ </button>
+
+ {/* Content */}
+ {isExpanded && (
+ <div className="px-3 sm:px-4 pb-3 sm:pb-4 space-y-3 border-t">
+ {/* Period Selector - Mobile and Desktop when expanded */}
+ <div className="flex gap-2 pt-3">
+ <Button
+ variant={period === "week" ? "default" : "outline"}
+ size="sm"
+ onClick={() => setPeriod("week")}
+ className="flex-1 sm:flex-none"
+ >
+ {t("stats.week")}
+ </Button>
+ <Button
+ variant={period === "month" ? "default" : "outline"}
+ size="sm"
+ onClick={() => setPeriod("month")}
+ className="flex-1 sm:flex-none"
+ >
+ {t("stats.month")}
+ </Button>
+ <Button
+ variant={period === "year" ? "default" : "outline"}
+ size="sm"
+ onClick={() => setPeriod("year")}
+ className="flex-1 sm:flex-none"
+ >
+ {t("stats.year")}
+ </Button>
+ </div>
+
+ {/* Stats Display */}
+ {loading ? (
+ <p className="text-sm text-muted-foreground py-4 text-center">
+ {t("common.loading")}
+ </p>
+ ) : stats && Object.keys(stats.stats).length > 0 ? (
+ <div className="space-y-3">
+ <div className="flex justify-between items-center pb-2 border-b">
+ <span className="font-semibold text-sm sm:text-base">
+ {t("stats.total")}
+ </span>
+ <span className="font-bold text-lg sm:text-xl">
+ {totalShifts}
+ </span>
+ </div>
+ {Object.entries(stats.stats)
+ .sort(([, a], [, b]) => b - a)
+ .map(([title, count]) => (
+ <div
+ key={title}
+ className="flex justify-between items-center gap-3"
+ >
+ <span className="text-sm truncate flex-shrink min-w-0">
+ {title}
+ </span>
+ <div className="flex items-center gap-2 sm:gap-3 flex-shrink-0">
+ <div className="w-24 sm:w-32 h-2 bg-secondary rounded-full overflow-hidden">
+ <div
+ className="h-full bg-primary transition-all"
+ style={{
+ width: `${(count / totalShifts) * 100}%`,
+ }}
+ />
+ </div>
+ <span className="font-semibold text-sm w-6 sm:w-8 text-right">
+ {count}
+ </span>
+ </div>
+ </div>
+ ))}
+ </div>
+ ) : (
+ <p className="text-sm text-muted-foreground py-4 text-center">
+ {t("stats.noData")}
+ </p>
+ )}
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/messages/de.json b/messages/de.json
index 2830210..0f05e8b 100644
--- a/messages/de.json
+++ b/messages/de.json
@@ -133,5 +133,14 @@
"pink": "Pink",
"cyan": "Cyan",
"orange": "Orange"
+ },
+ "stats": {
+ "title": "Schichtenstatistik",
+ "week": "Woche",
+ "month": "Monat",
+ "year": "Jahr",
+ "total": "Gesamt",
+ "noData": "Keine Schichten in diesem Zeitraum",
+ "shiftsTotal": "Schichten"
}
}
diff --git a/messages/en.json b/messages/en.json
index d92ae0f..cfca711 100644
--- a/messages/en.json
+++ b/messages/en.json
@@ -133,5 +133,14 @@
"pink": "Pink",
"cyan": "Cyan",
"orange": "Orange"
+ },
+ "stats": {
+ "title": "Shift Statistics",
+ "week": "Week",
+ "month": "Month",
+ "year": "Year",
+ "total": "Total",
+ "noData": "No shifts in this period",
+ "shiftsTotal": "shifts"
}
}