Skip to content

Your favorite shift management application!

feat: Add multi-calendar export support (#121)

panteLc0256ff578a6
diff --git a/.env.example b/.env.example
index e13991a..2a181bf 100644
--- a/.env.example
+++ b/.env.example
@@ -133,6 +133,8 @@ GITHUB_REPO_NAME=BetterShift
# Export Features
# RATE_LIMIT_EXPORT_PDF_REQUESTS=10 # Per user
# RATE_LIMIT_EXPORT_PDF_WINDOW=600 # 10 minutes
+# RATE_LIMIT_EXPORT_ICS_REQUESTS=20 # Per user
+# RATE_LIMIT_EXPORT_ICS_WINDOW=600 # 10 minutes
# Calendar Access Tokens (Share Links)
# RATE_LIMIT_TOKEN_VALIDATION_REQUESTS=10 # Per IP
diff --git a/app/api/calendars/[id]/export/ics/route.ts b/app/api/export/ics/route.ts
similarity index 58%
rename from app/api/calendars/[id]/export/ics/route.ts
rename to app/api/export/ics/route.ts
index 296f68d..3be14c4 100644
--- a/app/api/calendars/[id]/export/ics/route.ts
+++ b/app/api/export/ics/route.ts
@@ -1,50 +1,76 @@
-import { NextResponse } from "next/server";
+import { NextRequest, NextResponse } from "next/server";
import { db } from "@/lib/db";
import { calendars, shifts } from "@/lib/db/schema";
-import { eq } from "drizzle-orm";
+import { inArray } from "drizzle-orm";
import ICAL from "ical.js";
import { getSessionUser } from "@/lib/auth/sessions";
import { canViewCalendar } from "@/lib/auth/permissions";
import { getServerTimezone, formatDateToLocal } from "@/lib/date-utils";
+import { rateLimit } from "@/lib/rate-limiter";
-export async function GET(
- request: Request,
- { params }: { params: Promise<{ id: string }> }
-) {
+export async function POST(request: NextRequest) {
try {
- const { id } = await params;
const user = await getSessionUser(request.headers);
- // Get calendar
- const calendar = await db.query.calendars.findFirst({
- where: eq(calendars.id, id),
+ // Rate limiting: 20 ICS exports per 10 minutes
+ const rateLimitResponse = rateLimit(request, user?.id, "export-ics");
+ if (rateLimitResponse) return rateLimitResponse;
+
+ const { calendarIds } = await request.json();
+
+ if (!Array.isArray(calendarIds) || calendarIds.length === 0) {
+ return NextResponse.json(
+ { error: "No calendar IDs provided" },
+ { status: 400 }
+ );
+ }
+
+ // Get all requested calendars
+ const requestedCalendars = await db.query.calendars.findMany({
+ where: inArray(calendars.id, calendarIds),
});
- if (!calendar) {
+ if (requestedCalendars.length === 0) {
return NextResponse.json(
- { error: "Calendar not found" },
+ { error: "No calendars found" },
{ status: 404 }
);
}
- // Check read permission (works for both authenticated users and guests)
- const hasAccess = await canViewCalendar(user?.id, id);
- if (!hasAccess) {
+ // Filter calendars by permission - only include calendars user can view
+ const accessibleCalendars = [];
+ for (const calendar of requestedCalendars) {
+ const hasAccess = await canViewCalendar(user?.id, calendar.id);
+ if (hasAccess) {
+ accessibleCalendars.push(calendar);
+ }
+ }
+
+ if (accessibleCalendars.length === 0) {
return NextResponse.json(
- { error: "Insufficient permissions" },
+ { error: "Insufficient permissions for selected calendars" },
{ status: 403 }
);
}
- // Get all shifts for this calendar
- const calendarShifts = await db.query.shifts.findMany({
- where: eq(shifts.calendarId, id),
+ // Get all shifts for accessible calendars
+ const allShifts = await db.query.shifts.findMany({
+ where: inArray(
+ shifts.calendarId,
+ accessibleCalendars.map((c) => c.id)
+ ),
orderBy: (shifts, { asc }) => [asc(shifts.date)],
});
+ // Create calendar name lookup
+ const calendarMap = new Map(accessibleCalendars.map((c) => [c.id, c.name]));
+
// Get server timezone for proper time conversion
const serverTimezone = getServerTimezone();
+ // Determine if multi-calendar export
+ const isMultiCalendar = accessibleCalendars.length > 1;
+
// Create iCalendar
const cal = new ICAL.Component(["vcalendar", [], []]);
cal.updatePropertyWithValue(
@@ -54,19 +80,27 @@ export async function GET(
cal.updatePropertyWithValue("version", "2.0");
cal.updatePropertyWithValue("calscale", "GREGORIAN");
cal.updatePropertyWithValue("method", "PUBLISH");
- cal.updatePropertyWithValue("x-wr-calname", calendar.name);
+ cal.updatePropertyWithValue(
+ "x-wr-calname",
+ isMultiCalendar
+ ? "BetterShift Multi-Calendar"
+ : accessibleCalendars[0].name
+ );
cal.updatePropertyWithValue("x-wr-timezone", serverTimezone);
// Add shifts as events
- for (const shift of calendarShifts) {
+ for (const shift of allShifts) {
const vevent = new ICAL.Component("vevent");
const event = new ICAL.Event(vevent);
// Set event ID
event.uid = shift.id;
- // Set title
- event.summary = shift.title;
+ // Set title with calendar prefix only for multi-calendar exports
+ const calendarName = calendarMap.get(shift.calendarId);
+ event.summary = isMultiCalendar
+ ? `[${calendarName}] ${shift.title}`
+ : shift.title;
// Set description (notes)
if (shift.notes) {
@@ -74,12 +108,10 @@ export async function GET(
}
// Set times
- // shift.date is already a Date object from Drizzle (mode: "timestamp")
const shiftDate = shift.date as Date;
if (shift.isAllDay) {
// All-day event (DTEND is exclusive per RFC 5545)
- // Use formatDateToLocal to get YYYY-MM-DD format
const dateStr = formatDateToLocal(shiftDate);
const startTime = ICAL.Time.fromDateString(dateStr);
@@ -112,7 +144,6 @@ export async function GET(
}
// Convert to UTC for iCalendar standard compliance
- // JavaScript Date objects are timezone-aware and will be correctly converted
const startIcalTime = ICAL.Time.fromJSDate(startDateTime, true);
const endIcalTime = ICAL.Time.fromJSDate(endDateTime, true);
@@ -131,10 +162,19 @@ export async function GET(
// Generate ICS content
const icsContent = cal.toString();
- // Return as downloadable file
- const filename = `${calendar.name
- .replace(/[^a-z0-9]/gi, "_")
- .toLowerCase()}_${new Date().toISOString().split("T")[0]}.ics`;
+ // Create filename from calendar names (truncated)
+ const calendarNamesParts = accessibleCalendars
+ .map((c) =>
+ c.name
+ .replace(/[^a-z0-9]/gi, "_")
+ .toLowerCase()
+ .substring(0, 20)
+ )
+ .slice(0, 3); // Max 3 calendar names
+
+ const filename = `${calendarNamesParts.join("_")}_${
+ new Date().toISOString().split("T")[0]
+ }.ics`;
return new NextResponse(icsContent, {
headers: {
@@ -143,9 +183,9 @@ export async function GET(
},
});
} catch (error) {
- console.error("Error exporting calendar as ICS:", error);
+ console.error("Error exporting calendars as ICS:", error);
return NextResponse.json(
- { error: "Failed to export calendar" },
+ { error: "Failed to export calendars" },
{ status: 500 }
);
}
diff --git a/app/api/calendars/[id]/export/pdf/route.ts b/app/api/export/pdf/route.ts
similarity index 56%
rename from app/api/calendars/[id]/export/pdf/route.ts
rename to app/api/export/pdf/route.ts
index 9f33147..a499a7a 100644
--- a/app/api/calendars/[id]/export/pdf/route.ts
+++ b/app/api/export/pdf/route.ts
@@ -1,18 +1,14 @@
import { NextRequest, NextResponse } from "next/server";
import { db } from "@/lib/db";
import { calendars, shifts } from "@/lib/db/schema";
-import { eq } from "drizzle-orm";
+import { inArray } from "drizzle-orm";
import { jsPDF } from "jspdf";
import { getSessionUser } from "@/lib/auth/sessions";
import { canViewCalendar } from "@/lib/auth/permissions";
import { rateLimit } from "@/lib/rate-limiter";
-export async function GET(
- request: NextRequest,
- { params }: { params: Promise<{ id: string }> }
-) {
+export async function POST(request: NextRequest) {
try {
- const { id } = await params;
const user = await getSessionUser(request.headers);
// Rate limiting: 10 PDF exports per 10 minutes
@@ -24,37 +20,56 @@ export async function GET(
const year = searchParams.get("year"); // Format: YYYY
const locale = searchParams.get("locale") || "en"; // Default to English
- // Get calendar
- const calendar = await db.query.calendars.findFirst({
- where: eq(calendars.id, id),
+ const { calendarIds } = await request.json();
+
+ if (!Array.isArray(calendarIds) || calendarIds.length === 0) {
+ return NextResponse.json(
+ { error: "No calendar IDs provided" },
+ { status: 400 }
+ );
+ }
+
+ // Get all requested calendars
+ const requestedCalendars = await db.query.calendars.findMany({
+ where: inArray(calendars.id, calendarIds),
});
- if (!calendar) {
+ if (requestedCalendars.length === 0) {
return NextResponse.json(
- { error: "Calendar not found" },
+ { error: "No calendars found" },
{ status: 404 }
);
}
- // Check read permission (works for both authenticated users and guests)
- const hasAccess = await canViewCalendar(user?.id, id);
- if (!hasAccess) {
+ // Filter calendars by permission - only include calendars user can view
+ const accessibleCalendars = [];
+ for (const calendar of requestedCalendars) {
+ const hasAccess = await canViewCalendar(user?.id, calendar.id);
+ if (hasAccess) {
+ accessibleCalendars.push(calendar);
+ }
+ }
+
+ if (accessibleCalendars.length === 0) {
return NextResponse.json(
- { error: "Insufficient permissions" },
+ { error: "Insufficient permissions for selected calendars" },
{ status: 403 }
);
}
- // Get all shifts for this calendar
- let calendarShifts = await db.query.shifts.findMany({
- where: eq(shifts.calendarId, id),
+ // Get all shifts for accessible calendars
+ let allShifts = await db.query.shifts.findMany({
+ where: inArray(
+ shifts.calendarId,
+ accessibleCalendars.map((c) => c.id)
+ ),
orderBy: (shifts, { asc }) => [asc(shifts.date)],
});
// Filter by month or year if provided
if (month) {
const [filterYear, filterMonth] = month.split("-").map(Number);
- calendarShifts = calendarShifts.filter((shift) => {
+ allShifts = allShifts.filter((shift) => {
const shiftDate = shift.date as Date;
return (
shiftDate.getFullYear() === filterYear &&
@@ -63,12 +78,27 @@ export async function GET(
});
} else if (year) {
const filterYear = parseInt(year);
- calendarShifts = calendarShifts.filter((shift) => {
+ allShifts = allShifts.filter((shift) => {
const shiftDate = shift.date as Date;
return shiftDate.getFullYear() === filterYear;
});
}
+ // Create calendar lookup map
+ const calendarMap = new Map(
+ accessibleCalendars.map((c) => [c.id, { name: c.name, color: c.color }])
+ );
+
+ // Determine if multi-calendar export
+ const isMultiCalendar = accessibleCalendars.length > 1;
+
+ // Sort all shifts by date (already sorted from DB, but ensure it)
+ allShifts.sort((a, b) => {
+ const dateA = (a.date as Date).getTime();
+ const dateB = (b.date as Date).getTime();
+ return dateA - dateB;
+ });
+
// Create PDF
const doc = new jsPDF();
const pageWidth = doc.internal.pageSize.getWidth();
@@ -86,19 +116,51 @@ export async function GET(
return false;
};
+ // Helper function to parse hex color
+ const hexToRgb = (hex: string) => {
+ const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
+ return result
+ ? {
+ r: parseInt(result[1], 16),
+ g: parseInt(result[2], 16),
+ b: parseInt(result[3], 16),
+ }
+ : { r: 0, g: 0, b: 0 };
+ };
+
// Title
doc.setFontSize(20);
doc.setFont("helvetica", "bold");
- doc.text(calendar.name, pageWidth / 2, yPosition, { align: "center" });
+ doc.text(
+ isMultiCalendar
+ ? "BetterShift Multi-Calendar Export"
+ : accessibleCalendars[0].name,
+ pageWidth / 2,
+ yPosition,
+ { align: "center" }
+ );
yPosition += 10;
+ // Calendar names (only for multi-calendar)
+ if (isMultiCalendar) {
+ doc.setFontSize(10);
+ doc.setFont("helvetica", "normal");
+ const calendarNames = accessibleCalendars.map((c) => c.name).join(", ");
+ const wrappedNames = doc.splitTextToSize(
+ calendarNames,
+ pageWidth - margin * 2
+ );
+ for (const line of wrappedNames) {
+ doc.text(line, pageWidth / 2, yPosition, { align: "center" });
+ yPosition += 5;
+ }
+ }
+
// Date range
- doc.setFontSize(10);
- doc.setFont("helvetica", "normal");
if (month || year) {
const dateRangeText = month ? `${month}` : `${year}`;
doc.text(dateRangeText, pageWidth / 2, yPosition, { align: "center" });
- yPosition += 10;
+ yPosition += 5;
}
// Horizontal line
@@ -106,13 +168,13 @@ export async function GET(
doc.line(margin, yPosition, pageWidth - margin, yPosition);
yPosition += 8;
- if (calendarShifts.length === 0) {
- // Empty state - no text needed, the date range shows the filter
+ if (allShifts.length === 0) {
+ // Empty state
yPosition += 20;
} else {
// Group shifts by month
- const shiftsByMonth = new Map<string, typeof calendarShifts>();
- for (const shift of calendarShifts) {
+ const shiftsByMonth = new Map<string, typeof allShifts>();
+ for (const shift of allShifts) {
const shiftDate = shift.date as Date;
const monthKey = `${shiftDate.getFullYear()}-${String(
shiftDate.getMonth() + 1
@@ -157,8 +219,10 @@ export async function GET(
month: "2-digit",
});
- // Color indicator (small rectangle)
- doc.setFillColor(shift.color);
+ // Calendar color indicator (small rectangle)
+ const calendarInfo = calendarMap.get(shift.calendarId);
+ const rgb = hexToRgb(shift.color);
+ doc.setFillColor(rgb.r, rgb.g, rgb.b);
doc.rect(margin, yPosition - 2, 3, 3, "F");
// Date
@@ -172,9 +236,25 @@ export async function GET(
: `${shift.startTime} - ${shift.endTime}`;
doc.text(timeStr, margin + 35, yPosition);
- // Title
+ // Calendar name (only for multi-calendar exports)
+ if (isMultiCalendar) {
+ doc.setFont("helvetica", "italic");
+ doc.setFontSize(9);
+ doc.text(
+ `[${calendarInfo?.name || "Unknown"}]`,
+ margin + 70,
+ yPosition
+ );
+ }
+
+ // Shift title
doc.setFont("helvetica", "bold");
- doc.text(shift.title, margin + 70, yPosition);
+ doc.setFontSize(10);
+ doc.text(
+ shift.title,
+ isMultiCalendar ? margin + 105 : margin + 70,
+ yPosition
+ );
yPosition += 5;
@@ -198,17 +278,24 @@ export async function GET(
}
}
- yPosition += 5;
+ yPosition += 5; // Extra space between months
}
}
- // Generate PDF buffer
+ // Generate PDF
const pdfBuffer = Buffer.from(doc.output("arraybuffer"));
- // Return as downloadable file
- const filename = `${calendar.name
- .replace(/[^a-z0-9]/gi, "_")
- .toLowerCase()}_${month || year || "all"}_${
+ // Create filename from calendar names (truncated)
+ const calendarNamesParts = accessibleCalendars
+ .map((c) =>
+ c.name
+ .replace(/[^a-z0-9]/gi, "_")
+ .toLowerCase()
+ .substring(0, 20)
+ )
+ .slice(0, 3); // Max 3 calendar names
+
+ const filename = `${calendarNamesParts.join("_")}_${
new Date().toISOString().split("T")[0]
}.pdf`;
@@ -219,9 +306,9 @@ export async function GET(
},
});
} catch (error) {
- console.error("Error exporting calendar as PDF:", error);
+ console.error("Error exporting calendars as PDF:", error);
return NextResponse.json(
- { error: "Failed to export calendar" },
+ { error: "Failed to export calendars" },
{ status: 500 }
);
}
diff --git a/components/calendar-settings-sheet.tsx b/components/calendar-settings-sheet.tsx
index 0ba8e35..81d7867 100644
--- a/components/calendar-settings-sheet.tsx
+++ b/components/calendar-settings-sheet.tsx
@@ -24,6 +24,7 @@ import { AlertTriangle, Trash2, Download, Cloud, Users } from "lucide-react";
import { ExportDialog } from "@/components/export-dialog";
import { ConfirmationDialog } from "@/components/ui/confirmation-dialog";
import { useDirtyState } from "@/hooks/useDirtyState";
+import { CalendarWithCount } from "@/lib/types";
interface CalendarSettingsSheetProps {
open: boolean;
@@ -35,6 +36,7 @@ interface CalendarSettingsSheetProps {
onSuccess: () => void;
onDelete: () => void;
onExternalSync?: () => void;
+ availableCalendars?: CalendarWithCount[];
}
interface FormState {
@@ -52,6 +54,7 @@ export function CalendarSettingsSheet({
onSuccess,
onDelete,
onExternalSync,
+ availableCalendars = [],
}: CalendarSettingsSheetProps) {
const t = useTranslations();
const { updateCalendar } = useCalendars();
@@ -316,6 +319,7 @@ export function CalendarSettingsSheet({
open={showExportDialog}
onOpenChange={setShowExportDialog}
calendarId={calendarId}
+ availableCalendars={availableCalendars}
calendarName={calendarName}
/>
diff --git a/components/dialog-manager.tsx b/components/dialog-manager.tsx
index 449ea7a..979595d 100644
--- a/components/dialog-manager.tsx
+++ b/components/dialog-manager.tsx
@@ -150,6 +150,7 @@ export function DialogManager(props: DialogManagerProps) {
onSuccess={props.onCalendarSettingsSuccess}
onDelete={props.onDeleteCalendar}
onExternalSync={props.onExternalSyncFromSettings}
+ availableCalendars={props.calendars}
/>
<ExternalSyncManageSheet
diff --git a/components/export-dialog.tsx b/components/export-dialog.tsx
index e44d699..4e682a5 100644
--- a/components/export-dialog.tsx
+++ b/components/export-dialog.tsx
@@ -18,18 +18,22 @@ import {
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
+import { Checkbox } from "@/components/ui/checkbox";
import {
isRateLimitError,
handleRateLimitError,
} from "@/lib/rate-limit-client";
import { Download, FileText, Calendar } from "lucide-react";
import { toast } from "sonner";
+import { CalendarWithCount } from "@/lib/types";
+import { motion } from "motion/react";
interface ExportDialogProps {
open: boolean;
onOpenChange: (open: boolean) => void;
calendarId: string;
calendarName: string;
+ availableCalendars?: CalendarWithCount[];
}
export function ExportDialog({
@@ -37,6 +41,7 @@ export function ExportDialog({
onOpenChange,
calendarId,
calendarName,
+ availableCalendars = [],
}: ExportDialogProps) {
const t = useTranslations();
const locale = useLocale();
@@ -47,6 +52,8 @@ export function ExportDialog({
const [selectedMonth, setSelectedMonth] = useState("");
const [selectedYear, setSelectedYear] = useState("");
const [loading, setLoading] = useState(false);
+ const [multiCalendar, setMultiCalendar] = useState(false);
+ const [selectedCalendarIds, setSelectedCalendarIds] = useState<string[]>([]);
// Generate month options (current month ± 12 months)
const monthOptions = useMemo(() => {
@@ -87,9 +94,9 @@ export function ExportDialog({
today.getMonth() + 1
).padStart(2, "0")}`;
const currentYear = today.getFullYear();
-
setSelectedMonth(defaultMonth);
setSelectedYear(currentYear.toString());
+ setSelectedCalendarIds([calendarId]); // Pre-select current calendar
} else {
// Reset state when dialog closes
setExportFormat("ics");
@@ -97,21 +104,29 @@ export function ExportDialog({
setSelectedMonth("");
setSelectedYear("");
setLoading(false);
+ setMultiCalendar(false);
+ setSelectedCalendarIds([]);
}
- }, [open]);
+ }, [open, calendarId]);
+ // Handle export action
const handleExport = async () => {
+ // Validate calendar selection for multi-calendar export
+ if (multiCalendar && selectedCalendarIds.length === 0) {
+ toast.error(t("export.selectAtLeastOne"));
+ return;
+ }
+
setLoading(true);
try {
- // Build URL
- let url = `/api/calendars/${calendarId}/export/${exportFormat}`;
+ // Unified API endpoint
+ const url = `/api/export/${exportFormat}`;
const params = new URLSearchParams();
+ // Add PDF-specific params
if (exportFormat === "pdf") {
- // Add locale for proper date formatting and translations
params.append("locale", locale);
-
if (exportRange === "month" && selectedMonth) {
params.append("month", selectedMonth);
} else if (exportRange === "year" && selectedYear) {
@@ -119,12 +134,21 @@ export function ExportDialog({
}
}
- if (params.toString()) {
- url += `?${params.toString()}`;
- }
+ const urlWithParams = params.toString() ? `${url}?${params}` : url;
+
+ // Determine calendar IDs to export
+ const idsToExport = multiCalendar ? selectedCalendarIds : [calendarId];
+
+ const fetchOptions: RequestInit = {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ },
+ body: JSON.stringify({ calendarIds: idsToExport }),
+ };
// Fetch the file
- const response = await fetch(url);
+ const response = await fetch(urlWithParams, fetchOptions);
if (isRateLimitError(response)) {
await handleRateLimitError(response, t);
@@ -177,17 +201,95 @@ export function ExportDialog({
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">
+ <DialogContent className="max-h-[90vh] overflow-y-auto sm:max-w-[500px]">
+ <DialogHeader>
+ <DialogTitle className="flex items-center gap-2">
+ <Download className="size-5" />
{t("export.title")}
</DialogTitle>
- <DialogDescription className="text-sm text-muted-foreground">
- {t("export.description")}
- </DialogDescription>
+ <DialogDescription>{t("export.description")}</DialogDescription>
</DialogHeader>
- <div className="space-y-4 overflow-y-auto flex-1 px-6 pb-6 pt-6">
+ <div className="space-y-4">
+ {/* Multi-Calendar Export Toggle */}
+ {availableCalendars.length > 1 && (
+ <div className="space-y-2 rounded-lg border border-border/50 bg-muted/20 p-4">
+ <div className="flex items-start gap-3">
+ <Checkbox
+ id="multi-calendar"
+ checked={multiCalendar}
+ onCheckedChange={(checked) => {
+ setMultiCalendar(checked === true);
+ if (checked) {
+ setSelectedCalendarIds([calendarId]);
+ }
+ }}
+ className="mt-0.5"
+ />
+ <div className="flex-1 space-y-1">
+ <Label
+ htmlFor="multi-calendar"
+ className="cursor-pointer font-medium"
+ >
+ {t("export.multiCalendar")}
+ </Label>
+ <p className="text-xs text-muted-foreground">
+ {t("export.multiCalendarHint")}
+ </p>
+ </div>
+ </div>
+ </div>
+ )}
+
+ {/* Calendar Selection (shown when multi-calendar is enabled) */}
+ {multiCalendar && availableCalendars.length > 0 && (
+ <div className="space-y-2">
+ <Label>{t("export.selectCalendars")}</Label>
+ <p className="text-xs text-muted-foreground mb-3">
+ {t("export.selectCalendarsDescription")}
+ </p>
+ <div className="max-h-[200px] overflow-y-auto space-y-2 border border-border/50 rounded-md p-3 bg-background/50">
+ {availableCalendars.map((calendar) => {
+ const isSelected = selectedCalendarIds.includes(calendar.id);
+ return (
+ <motion.div
+ key={calendar.id}
+ className="flex items-center gap-3 p-2 rounded-md hover:bg-accent/50 cursor-pointer transition-colors"
+ onClick={() => {
+ setSelectedCalendarIds((prev) =>
+ prev.includes(calendar.id)
+ ? prev.filter((id) => id !== calendar.id)
+ : [...prev, calendar.id]
+ );
+ }}
+ whileHover={{ scale: 1.01 }}
+ whileTap={{ scale: 0.99 }}
+ >
+ <Checkbox
+ checked={isSelected}
+ className="pointer-events-none"
+ />
+ <div
+ className="w-4 h-4 rounded-full shrink-0"
+ style={{ backgroundColor: calendar.color }}
+ />
+ <div className="flex-1 min-w-0">
+ <p className="font-medium truncate text-sm">
+ {calendar.name}
+ </p>
+ </div>
+ </motion.div>
+ );
+ })}
+ </div>
+ <p className="text-xs text-muted-foreground mt-2">
+ {t("export.selectedCount", {
+ count: selectedCalendarIds.length,
+ })}
+ </p>
+ </div>
+ )}
+
{/* Export Format */}
<div className="space-y-2">
<Label>{t("export.formatLabel")}</Label>
diff --git a/lib/rate-limiter.ts b/lib/rate-limiter.ts
index 0a6de73..0b4622a 100644
--- a/lib/rate-limiter.ts
+++ b/lib/rate-limiter.ts
@@ -98,6 +98,11 @@ const config = {
windowMs:
parseInt(process.env.RATE_LIMIT_EXPORT_PDF_WINDOW || "600", 10) * 1000, // 10 minutes
},
+ exportIcs: {
+ requests: parseInt(process.env.RATE_LIMIT_EXPORT_ICS_REQUESTS || "20", 10),
+ windowMs:
+ parseInt(process.env.RATE_LIMIT_EXPORT_ICS_WINDOW || "600", 10) * 1000, // 10 minutes
+ },
tokenValidation: {
requests: parseInt(
process.env.RATE_LIMIT_TOKEN_VALIDATION_REQUESTS || "10",
@@ -319,6 +324,7 @@ export function rateLimit(
| "calendar-create"
| "external-sync"
| "export-pdf"
+ | "export-ics"
| "token-validation"
| "token-creation"
| "admin-user-mutations"
@@ -367,6 +373,9 @@ export function rateLimit(
case "export-pdf":
options = config.exportPdf;
break;
+ case "export-ics":
+ options = config.exportIcs;
+ break;
case "token-validation":
options = config.tokenValidation;
break;
@@ -442,6 +451,7 @@ export function getRateLimitStatus(
| "calendar-create"
| "external-sync"
| "export-pdf"
+ | "export-ics"
| "token-validation"
| "token-creation" = "auth"
): RateLimitResult {
@@ -474,6 +484,9 @@ export function getRateLimitStatus(
case "export-pdf":
options = config.exportPdf;
break;
+ case "export-ics":
+ options = config.exportIcs;
+ break;
case "token-validation":
options = config.tokenValidation;
break;
diff --git a/messages/de.json b/messages/de.json
index 0104a39..f2c8a33 100644
--- a/messages/de.json
+++ b/messages/de.json
@@ -429,7 +429,13 @@
"rangeYear": "Einzelnes Jahr",
"monthLabel": "Monat auswählen",
"yearLabel": "Jahr auswählen",
- "download": "Herunterladen"
+ "download": "Herunterladen",
+ "multiCalendar": "Mehrere Kalender exportieren",
+ "multiCalendarHint": "Schichten aus mehreren Kalendern in einer Export-Datei kombinieren",
+ "selectCalendars": "Kalender auswählen",
+ "selectCalendarsDescription": "Wähle aus, welche Kalender in den Export einbezogen werden sollen",
+ "selectedCount": "{count, plural, =0 {Keine Kalender ausgewählt} =1 {1 Kalender ausgewählt} other {# Kalender ausgewählt}}",
+ "selectAtLeastOne": "Bitte wähle mindestens einen Kalender aus"
},
"update": {
"available": "Update verfügbar",
diff --git a/messages/en.json b/messages/en.json
index ae78fb9..87922af 100644
--- a/messages/en.json
+++ b/messages/en.json
@@ -429,7 +429,13 @@
"rangeYear": "Single Year",
"monthLabel": "Select Month",
"yearLabel": "Select Year",
- "download": "Download"
+ "download": "Download",
+ "multiCalendar": "Export multiple calendars",
+ "multiCalendarHint": "Combine shifts from multiple calendars into one export file",
+ "selectCalendars": "Select Calendars",
+ "selectCalendarsDescription": "Choose which calendars to include in the export",
+ "selectedCount": "{count, plural, =0 {No calendars selected} =1 {1 calendar selected} other {# calendars selected}}",
+ "selectAtLeastOne": "Please select at least one calendar"
},
"update": {
"available": "Update Available",
diff --git a/messages/it.json b/messages/it.json
index 8f06c1f..9f43abe 100644
--- a/messages/it.json
+++ b/messages/it.json
@@ -429,7 +429,13 @@
"rangeYear": "Singolo anno",
"monthLabel": "Seleziona mese",
"yearLabel": "Seleziona anno",
- "download": "Scarica"
+ "download": "Scarica",
+ "multiCalendar": "Esporta più calendari",
+ "multiCalendarHint": "Combina i turni da più calendari in un unico file di esportazione",
+ "selectCalendars": "Seleziona Calendari",
+ "selectCalendarsDescription": "Scegli quali calendari includere nell'esportazione",
+ "selectedCount": "{count, plural, =0 {Nessun calendario selezionato} =1 {1 calendario selezionato} other {# calendari selezionati}}",
+ "selectAtLeastOne": "Seleziona almeno un calendario"
},
"update": {
"available": "Aggiornamento disponibile",