Implement i18n with German and English support (default DE)

This commit is contained in:
2026-01-12 21:38:05 +01:00
parent a60d456b3b
commit 62e1f5f1b4
14 changed files with 471 additions and 228 deletions

View File

@@ -2,6 +2,7 @@
import { useState, useEffect } from "react" import { useState, useEffect } from "react"
import { format, eachDayOfInterval, isSameDay } from "date-fns" import { format, eachDayOfInterval, isSameDay } from "date-fns"
import { de, enUS } from "date-fns/locale"
import { CalendarIcon, User, Home, X, Info } from "lucide-react" import { CalendarIcon, User, Home, X, Info } from "lucide-react"
import { toast } from "sonner" import { toast } from "sonner"
@@ -38,13 +39,22 @@ type Plan = {
bookings: Booking[] bookings: Booking[]
} }
export function PlanDashboard({ plan }: { plan: Plan }) { interface PlanDashboardProps {
plan: Plan;
dict: any;
settingsDict: any;
lang: string;
}
export function PlanDashboard({ plan, dict, settingsDict, lang }: PlanDashboardProps) {
const [selectedDate, setSelectedDate] = useState<Date | null>(null) const [selectedDate, setSelectedDate] = useState<Date | null>(null)
const [sitterName, setSitterName] = useState("") const [sitterName, setSitterName] = useState("")
const [bookingType, setBookingType] = useState<"SITTER" | "OWNER_HOME">("SITTER") const [bookingType, setBookingType] = useState<"SITTER" | "OWNER_HOME">("SITTER")
const [isDialogOpen, setIsDialogOpen] = useState(false) const [isDialogOpen, setIsDialogOpen] = useState(false)
const [isSubmitting, setIsSubmitting] = useState(false) const [isSubmitting, setIsSubmitting] = useState(false)
const dateLocale = lang === "de" ? de : enUS
// Load saved name from localStorage // Load saved name from localStorage
useEffect(() => { useEffect(() => {
const savedName = localStorage.getItem("sitter_name") const savedName = localStorage.getItem("sitter_name")
@@ -60,38 +70,36 @@ export function PlanDashboard({ plan }: { plan: Plan }) {
const handleBook = async () => { const handleBook = async () => {
if (!selectedDate) return if (!selectedDate) return
if (bookingType === "SITTER" && !sitterName.trim()) { if (bookingType === "SITTER" && !sitterName.trim()) {
toast.error("Please enter your name") toast.error(dict.namePlaceholder) // Could use a more specific key if needed
return return
} }
setIsSubmitting(true) setIsSubmitting(true)
try { try {
await createBooking(plan.id, selectedDate, bookingType === "SITTER" ? sitterName : "Owner", bookingType) await createBooking(plan.id, selectedDate, bookingType === "SITTER" ? sitterName : "Owner", bookingType, lang)
// Save name to localStorage if it's a sitter booking // Save name to localStorage if it's a sitter booking
if (bookingType === "SITTER") { if (bookingType === "SITTER") {
localStorage.setItem("sitter_name", sitterName) localStorage.setItem("sitter_name", sitterName)
} }
toast.success("Spot booked!") toast.success(dict.bookedSuccess)
setIsDialogOpen(false) setIsDialogOpen(false)
// We keep the sitterName in state for the next booking
} catch (error) { } catch (error) {
toast.error("Failed to book spot. Maybe it was just taken?") toast.error(dict.bookError)
} finally { } finally {
setIsSubmitting(false) setIsSubmitting(false)
} }
} }
const handleCancel = async (bookingId: number) => { const handleCancel = async (bookingId: number) => {
// Optimistic UI could stay here, but relying on revalidatePath is safer for simple apps if (!confirm(dict.cancelConfirm)) return
if (!confirm("Are you sure you want to remove this entry?")) return
try { try {
await deleteBooking(bookingId, plan.id) await deleteBooking(bookingId, plan.id, lang)
toast.success("Entry removed") toast.success(dict.cancelSuccess)
} catch { } catch {
toast.error("Failed to remove entry") toast.error(dict.cancelError)
} }
} }
@@ -99,18 +107,18 @@ export function PlanDashboard({ plan }: { plan: Plan }) {
<div className="space-y-4"> <div className="space-y-4">
<div className="flex justify-between items-center bg-muted/50 p-4 rounded-lg"> <div className="flex justify-between items-center bg-muted/50 p-4 rounded-lg">
<div className="flex items-center gap-2"> <div className="flex items-center gap-2">
<h2 className="text-lg font-semibold">Overview</h2> <h2 className="text-lg font-semibold">{dict.overview}</h2>
{plan.instructions && ( {plan.instructions && (
<Dialog> <Dialog>
<DialogTrigger asChild> <DialogTrigger asChild>
<Button variant="ghost" size="sm" className="gap-2"> <Button variant="ghost" size="sm" className="gap-2">
<Info className="w-4 h-4" /> <Info className="w-4 h-4" />
Instructions {dict.instructions}
</Button> </Button>
</DialogTrigger> </DialogTrigger>
<DialogContent> <DialogContent>
<DialogHeader> <DialogHeader>
<DialogTitle>Cat Care Instructions</DialogTitle> <DialogTitle>{dict.instructionsTitle}</DialogTitle>
</DialogHeader> </DialogHeader>
<div className="whitespace-pre-wrap">{plan.instructions}</div> <div className="whitespace-pre-wrap">{plan.instructions}</div>
</DialogContent> </DialogContent>
@@ -121,7 +129,7 @@ export function PlanDashboard({ plan }: { plan: Plan }) {
<Button variant="outline" size="sm" asChild> <Button variant="outline" size="sm" asChild>
<a href={`/api/plan/${plan.id}/ics`} target="_blank" rel="noopener noreferrer"> <a href={`/api/plan/${plan.id}/ics`} target="_blank" rel="noopener noreferrer">
<CalendarIcon className="w-4 h-4 mr-2" /> <CalendarIcon className="w-4 h-4 mr-2" />
Export {dict.export}
</a> </a>
</Button> </Button>
<PlanSettings <PlanSettings
@@ -129,6 +137,8 @@ export function PlanDashboard({ plan }: { plan: Plan }) {
initialWebhookUrl={plan.webhookUrl} initialWebhookUrl={plan.webhookUrl}
initialInstructions={plan.instructions} initialInstructions={plan.instructions}
initialNotifyAll={plan.notifyAll} initialNotifyAll={plan.notifyAll}
dict={settingsDict}
lang={lang}
/> />
</div> </div>
</div> </div>
@@ -151,7 +161,7 @@ export function PlanDashboard({ plan }: { plan: Plan }) {
<div className="flex justify-between items-start mb-2"> <div className="flex justify-between items-start mb-2">
<div className="font-semibold flex items-center gap-2"> <div className="font-semibold flex items-center gap-2">
<CalendarIcon className="w-4 h-4 opacity-70" /> <CalendarIcon className="w-4 h-4 opacity-70" />
{format(day, "EEEE, MMMM do")} {format(day, "PPPP", { locale: dateLocale })}
</div> </div>
{booking && ( {booking && (
<Button <Button
@@ -171,7 +181,7 @@ export function PlanDashboard({ plan }: { plan: Plan }) {
{isOwnerHome ? ( {isOwnerHome ? (
<> <>
<Home className="w-5 h-5 text-blue-500" /> <Home className="w-5 h-5 text-blue-500" />
<span className="font-medium text-blue-700 dark:text-blue-300">Owner Home</span> <span className="font-medium text-blue-700 dark:text-blue-300">{dict.ownerHome}</span>
</> </>
) : ( ) : (
<> <>
@@ -187,13 +197,13 @@ export function PlanDashboard({ plan }: { plan: Plan }) {
else setSelectedDate(null) else setSelectedDate(null)
}}> }}>
<DialogTrigger asChild> <DialogTrigger asChild>
<Button variant="outline" className="w-full dashed border-2">I'll do it!</Button> <Button variant="outline" className="w-full dashed border-2">{dict.illDoIt}</Button>
</DialogTrigger> </DialogTrigger>
<DialogContent> <DialogContent>
<DialogHeader> <DialogHeader>
<DialogTitle>Book {format(day, "MMMM do")}</DialogTitle> <DialogTitle>{dict.bookTitle.replace("{date}", format(day, "PPP", { locale: dateLocale }))}</DialogTitle>
<DialogDescription> <DialogDescription>
Who is taking care of the cats? {dict.bookDesc}
</DialogDescription> </DialogDescription>
</DialogHeader> </DialogHeader>
@@ -201,22 +211,22 @@ export function PlanDashboard({ plan }: { plan: Plan }) {
<RadioGroup value={bookingType} onValueChange={(v: any) => setBookingType(v)} className="flex gap-4"> <RadioGroup value={bookingType} onValueChange={(v: any) => setBookingType(v)} className="flex gap-4">
<div className="flex items-center space-x-2"> <div className="flex items-center space-x-2">
<RadioGroupItem value="SITTER" id="r1" /> <RadioGroupItem value="SITTER" id="r1" />
<Label htmlFor="r1">I am Sitting</Label> <Label htmlFor="r1">{dict.imSitting}</Label>
</div> </div>
<div className="flex items-center space-x-2"> <div className="flex items-center space-x-2">
<RadioGroupItem value="OWNER_HOME" id="r2" /> <RadioGroupItem value="OWNER_HOME" id="r2" />
<Label htmlFor="r2">Owner is Home</Label> <Label htmlFor="r2">{dict.ownerIsHome}</Label>
</div> </div>
</RadioGroup> </RadioGroup>
{bookingType === "SITTER" && ( {bookingType === "SITTER" && (
<div className="grid gap-2"> <div className="grid gap-2">
<Label htmlFor="name">Name</Label> <Label htmlFor="name">{dict.nameLabel}</Label>
<Input <Input
id="name" id="name"
value={sitterName} value={sitterName}
onChange={(e) => setSitterName(e.target.value)} onChange={(e) => setSitterName(e.target.value)}
placeholder="Your Name" placeholder={dict.namePlaceholder}
autoFocus autoFocus
/> />
</div> </div>
@@ -225,7 +235,7 @@ export function PlanDashboard({ plan }: { plan: Plan }) {
<DialogFooter> <DialogFooter>
<Button onClick={handleBook} disabled={isSubmitting}> <Button onClick={handleBook} disabled={isSubmitting}>
{isSubmitting ? "Saving..." : "Confirm Booking"} {isSubmitting ? dict.saving : dict.confirmBooking}
</Button> </Button>
</DialogFooter> </DialogFooter>
</DialogContent> </DialogContent>

View File

@@ -2,11 +2,17 @@ import { notFound } from "next/navigation"
import { cookies } from "next/headers" import { cookies } from "next/headers"
import prisma from "@/lib/prisma" import prisma from "@/lib/prisma"
import { PlanLoginForm } from "@/components/plan-login-form" import { PlanLoginForm } from "@/components/plan-login-form"
import { Toaster } from "@/components/ui/sonner"
import { PlanDashboard } from "./_components/plan-dashboard" import { PlanDashboard } from "./_components/plan-dashboard"
import { getDictionary } from "@/get-dictionary"
export default async function DashboardPage({
params
}: {
params: Promise<{ planId: string, lang: string }>
}) {
const { planId, lang } = await params
const dict = await getDictionary(lang as any)
export default async function DashboardPage({ params }: { params: Promise<{ planId: string }> }) {
const { planId } = await params
const plan = await prisma.plan.findUnique({ const plan = await prisma.plan.findUnique({
where: { id: planId }, where: { id: planId },
include: { bookings: true }, include: { bookings: true },
@@ -22,7 +28,7 @@ export default async function DashboardPage({ params }: { params: Promise<{ plan
if (!isAuthenticated) { if (!isAuthenticated) {
return ( return (
<main className="flex min-h-screen flex-col items-center p-4"> <main className="flex min-h-screen flex-col items-center p-4">
<PlanLoginForm planId={plan.id} /> <PlanLoginForm planId={plan.id} dict={dict.login} />
</main> </main>
) )
} }
@@ -32,18 +38,18 @@ export default async function DashboardPage({ params }: { params: Promise<{ plan
<div className="w-full max-w-4xl space-y-6"> <div className="w-full max-w-4xl space-y-6">
<div className="flex flex-col md:flex-row justify-between items-start md:items-center gap-4"> <div className="flex flex-col md:flex-row justify-between items-start md:items-center gap-4">
<div> <div>
<h1 className="text-2xl font-bold">Cat Sitting Plan</h1> <h1 className="text-2xl font-bold">{dict.home.title}</h1>
<p className="text-muted-foreground text-sm"> <p className="text-muted-foreground text-sm">
{plan.startDate.toLocaleDateString()} - {plan.endDate.toLocaleDateString()} {plan.startDate.toLocaleDateString(lang)} - {plan.endDate.toLocaleDateString(lang)}
</p> </p>
</div> </div>
<div className="text-sm bg-muted px-3 py-1 rounded-md"> <div className="text-sm bg-muted px-3 py-1 rounded-md">
Group ID: <span className="font-mono font-bold">{plan.id}</span> Plan ID: <span className="font-mono font-bold">{plan.id}</span>
</div> </div>
</div> </div>
<div className="p-4 border rounded-lg bg-card text-card-foreground shadow-sm"> <div className="p-4 border rounded-lg bg-card text-card-foreground shadow-sm">
<PlanDashboard plan={plan} /> <PlanDashboard plan={plan} dict={dict.dashboard} settingsDict={dict.settings} lang={lang} />
</div> </div>
</div> </div>
</main> </main>

51
app/[lang]/layout.tsx Normal file
View File

@@ -0,0 +1,51 @@
import type { Metadata } from "next";
import { Geist, Geist_Mono } from "next/font/google";
import "../globals.css";
import { Toaster } from "@/components/ui/sonner";
const geistSans = Geist({
variable: "--font-geist-sans",
subsets: ["latin"],
});
const geistMono = Geist_Mono({
variable: "--font-geist-mono",
subsets: ["latin"],
});
import { getDictionary } from "@/get-dictionary";
export async function generateMetadata({ params }: { params: Promise<{ lang: string }> }): Promise<Metadata> {
const { lang } = await params;
const dict = await getDictionary(lang as any);
return {
title: dict.home.title,
description: dict.home.description,
};
}
export async function generateStaticParams() {
return [{ lang: "en" }, { lang: "de" }];
}
export default async function RootLayout({
children,
params,
}: {
children: React.ReactNode;
params: Promise<{ lang: string }>;
}) {
const { lang } = await params;
return (
<html lang={lang}>
<body
className={`${geistSans.variable} ${geistMono.variable} antialiased`}
>
{children}
<Toaster />
</body>
</html>
);
}

View File

@@ -1,8 +1,16 @@
import Image from "next/image"; import Image from "next/image";
import { CreatePlanForm } from "@/components/create-plan-form"; import { CreatePlanForm } from "@/components/create-plan-form";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"; import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { getDictionary } from "@/get-dictionary";
export default async function Home({
params,
}: {
params: Promise<{ lang: string }>;
}) {
const { lang } = await params;
const dict = await getDictionary(lang as any);
export default function Home() {
return ( return (
<main className="flex min-h-screen flex-col items-center justify-center p-4 bg-muted/20"> <main className="flex min-h-screen flex-col items-center justify-center p-4 bg-muted/20">
<div className="w-full max-w-md space-y-4"> <div className="w-full max-w-md space-y-4">
@@ -19,22 +27,21 @@ export default function Home() {
</div> </div>
</div> </div>
<div className="space-y-2"> <div className="space-y-2">
<h1 className="text-3xl font-bold tracking-tighter">Cat Sitting Planner</h1> <h1 className="text-3xl font-bold tracking-tighter">{dict.home.title}</h1>
<p className="text-muted-foreground">Coordinate care for your furry friends while you're away.</p> <p className="text-muted-foreground">{dict.home.description}</p>
</div> </div>
</div> </div>
<Card> <Card>
<CardHeader> <CardHeader>
<CardTitle>Create a New Plan</CardTitle> <CardTitle>{dict.home.createPlan}</CardTitle>
<CardDescription>Select your travel dates and set a group password.</CardDescription> <CardDescription>{dict.home.createPlanDesc}</CardDescription>
</CardHeader> </CardHeader>
<CardContent> <CardContent>
<CreatePlanForm /> <CreatePlanForm dict={dict.createPlanForm} lang={lang} />
</CardContent> </CardContent>
</Card> </Card>
</div> </div>
</main> </main>
); );
} }

View File

@@ -4,8 +4,11 @@ import prisma from "@/lib/prisma"
import { revalidatePath } from "next/cache" import { revalidatePath } from "next/cache"
import { headers } from "next/headers" import { headers } from "next/headers"
import { sendNotification } from "@/lib/notifications" import { sendNotification } from "@/lib/notifications"
import { getDictionary } from "@/get-dictionary"
export async function createBooking(planId: string, date: Date, name: string, type: "SITTER" | "OWNER_HOME" = "SITTER", lang: string = "en") {
const dict = await getDictionary(lang as any)
export async function createBooking(planId: string, date: Date, name: string, type: "SITTER" | "OWNER_HOME" = "SITTER") {
// Simple check to ensure no double booking on server side // Simple check to ensure no double booking on server side
const existing = await prisma.booking.findFirst({ const existing = await prisma.booking.findFirst({
where: { where: {
@@ -34,19 +37,22 @@ export async function createBooking(planId: string, date: Date, name: string, ty
if (plan?.webhookUrl && plan.notifyAll) { if (plan?.webhookUrl && plan.notifyAll) {
const host = (await headers()).get("host") const host = (await headers()).get("host")
const protocol = host?.includes("localhost") ? "http" : "https" const protocol = host?.includes("localhost") ? "http" : "https"
const planUrl = `${protocol}://${host}/dashboard/${planId}` const planUrl = `${protocol}://${host}/${lang}/dashboard/${planId}`
const dateStr = date.toLocaleDateString() const dateStr = date.toLocaleDateString(lang)
const message = type === "OWNER_HOME" const message = type === "OWNER_HOME"
? `🏠 OWNER HOME: Marked for ${dateStr}.\nPlan: ${planUrl}` ? dict.notifications.ownerHome.replace("{date}", dateStr).replace("{url}", planUrl)
: `✅ NEW BOOKING: ${name} is sitting on ${dateStr}.\nPlan: ${planUrl}` : dict.notifications.newBooking.replace("{name}", name).replace("{date}", dateStr).replace("{url}", planUrl)
await sendNotification(plan.webhookUrl, message) await sendNotification(plan.webhookUrl, message)
} }
revalidatePath(`/dashboard/${planId}`) revalidatePath(`/${lang}/dashboard/${planId}`)
} }
export async function deleteBooking(bookingId: number, planId: string) { export async function deleteBooking(bookingId: number, planId: string, lang: string = "en") {
const dict = await getDictionary(lang as any)
const booking = await prisma.booking.findUnique({ const booking = await prisma.booking.findUnique({
where: { id: bookingId }, where: { id: bookingId },
include: { plan: true } include: { plan: true }
@@ -61,11 +67,16 @@ export async function deleteBooking(bookingId: number, planId: string) {
if (booking.plan.webhookUrl) { if (booking.plan.webhookUrl) {
const host = (await headers()).get("host") const host = (await headers()).get("host")
const protocol = host?.includes("localhost") ? "http" : "https" const protocol = host?.includes("localhost") ? "http" : "https"
const planUrl = `${protocol}://${host}/dashboard/${planId}` const planUrl = `${protocol}://${host}/${lang}/dashboard/${planId}`
const dateStr = booking.date.toLocaleDateString() const dateStr = booking.date.toLocaleDateString(lang)
await sendNotification(booking.plan.webhookUrl, `🚨 CANCELLATION: ${booking.sitterName} removed their booking for ${dateStr}.\nPlan: ${planUrl}`) const message = dict.notifications.cancellation
.replace("{name}", booking.sitterName || "Someone")
.replace("{date}", dateStr)
.replace("{url}", planUrl)
await sendNotification(booking.plan.webhookUrl, message)
} }
revalidatePath(`/dashboard/${planId}`) revalidatePath(`/${lang}/dashboard/${planId}`)
} }

View File

@@ -4,8 +4,15 @@ import prisma from "@/lib/prisma"
import { revalidatePath } from "next/cache" import { revalidatePath } from "next/cache"
import { headers } from "next/headers" import { headers } from "next/headers"
import { sendNotification } from "@/lib/notifications" import { sendNotification } from "@/lib/notifications"
import { getDictionary } from "@/get-dictionary"
export async function updatePlan(
planId: string,
data: { instructions?: string; webhookUrl?: string; notifyAll?: boolean },
lang: string = "en"
) {
const dict = await getDictionary(lang as any)
export async function updatePlan(planId: string, data: { instructions?: string; webhookUrl?: string; notifyAll?: boolean }) {
const plan = await prisma.plan.update({ const plan = await prisma.plan.update({
where: { id: planId }, where: { id: planId },
data: { data: {
@@ -18,9 +25,13 @@ export async function updatePlan(planId: string, data: { instructions?: string;
if (data.instructions && plan.webhookUrl && plan.notifyAll) { if (data.instructions && plan.webhookUrl && plan.notifyAll) {
const host = (await headers()).get("host") const host = (await headers()).get("host")
const protocol = host?.includes("localhost") ? "http" : "https" const protocol = host?.includes("localhost") ? "http" : "https"
const planUrl = `${protocol}://${host}/dashboard/${planId}` const planUrl = `${protocol}://${host}/${lang}/dashboard/${planId}`
await sendNotification(plan.webhookUrl, `📝 UPDATED: Cat instructions have been modified.\nPlan: ${planUrl}`)
await sendNotification(
plan.webhookUrl,
dict.notifications.instructionsUpdated.replace("{url}", planUrl)
)
} }
revalidatePath(`/dashboard/${planId}`) revalidatePath(`/${lang}/dashboard/${planId}`)
} }

View File

@@ -1,36 +0,0 @@
import type { Metadata } from "next";
import { Geist, Geist_Mono } from "next/font/google";
import "./globals.css";
import { Toaster } from "@/components/ui/sonner";
const geistSans = Geist({
variable: "--font-geist-sans",
subsets: ["latin"],
});
const geistMono = Geist_Mono({
variable: "--font-geist-mono",
subsets: ["latin"],
});
export const metadata: Metadata = {
title: "Cat Sitting Planner",
description: "Simple and collaborative cat sitting coordination for your neighborhood.",
};
export default function RootLayout({
children,
}: Readonly<{
children: React.ReactNode;
}>) {
return (
<html lang="en">
<body
className={`${geistSans.variable} ${geistMono.variable} antialiased`}
>
{children}
<Toaster />
</body>
</html>
);
}

View File

@@ -2,6 +2,7 @@
import { zodResolver } from "@hookform/resolvers/zod" import { zodResolver } from "@hookform/resolvers/zod"
import { format } from "date-fns" import { format } from "date-fns"
import { de, enUS } from "date-fns/locale"
import { CalendarIcon } from "lucide-react" import { CalendarIcon } from "lucide-react"
import { useForm } from "react-hook-form" import { useForm } from "react-hook-form"
import { z } from "zod" import { z } from "zod"
@@ -23,19 +24,25 @@ import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover
import { toast } from "sonner" import { toast } from "sonner"
import { useRouter } from "next/navigation" import { useRouter } from "next/navigation"
const formSchema = z.object({ interface CreatePlanFormProps {
dict: any;
lang: string;
}
export function CreatePlanForm({ dict, lang }: CreatePlanFormProps) {
const router = useRouter()
const formSchema = z.object({
dateRange: z.object({ dateRange: z.object({
from: z.date(), from: z.date(),
to: z.date(), to: z.date(),
}), }),
password: z.string().min(4, { password: z.string().min(4, {
message: "Password must be at least 4 characters.", message: dict.passwordError,
}), }),
instructions: z.string().optional(), instructions: z.string().optional(),
}) })
export function CreatePlanForm() {
const router = useRouter()
const form = useForm<z.infer<typeof formSchema>>({ const form = useForm<z.infer<typeof formSchema>>({
resolver: zodResolver(formSchema), resolver: zodResolver(formSchema),
defaultValues: { defaultValues: {
@@ -44,6 +51,8 @@ export function CreatePlanForm() {
}, },
}) })
const dateLocale = lang === "de" ? de : enUS
async function onSubmit(values: z.infer<typeof formSchema>) { async function onSubmit(values: z.infer<typeof formSchema>) {
try { try {
const response = await fetch("/api/plan", { const response = await fetch("/api/plan", {
@@ -62,10 +71,10 @@ export function CreatePlanForm() {
} }
const data = await response.json() const data = await response.json()
toast.success("Plan created successfully!") toast.success(dict.success)
router.push(`/dashboard/${data.planId}`) router.push(`/${lang}/dashboard/${data.planId}`)
} catch (error) { } catch (error) {
toast.error("Something went wrong. Please try again.") toast.error(dict.error)
console.error(error) console.error(error)
} }
} }
@@ -78,7 +87,7 @@ export function CreatePlanForm() {
name="dateRange" name="dateRange"
render={({ field }) => ( render={({ field }) => (
<FormItem className="flex flex-col"> <FormItem className="flex flex-col">
<FormLabel>Travel Dates</FormLabel> <FormLabel>{dict.travelDates}</FormLabel>
<Popover> <Popover>
<PopoverTrigger asChild> <PopoverTrigger asChild>
<FormControl> <FormControl>
@@ -92,14 +101,14 @@ export function CreatePlanForm() {
{field.value?.from ? ( {field.value?.from ? (
field.value.to ? ( field.value.to ? (
<> <>
{format(field.value.from, "LLL dd, y")} -{" "} {format(field.value.from, "PPP", { locale: dateLocale })} -{" "}
{format(field.value.to, "LLL dd, y")} {format(field.value.to, "PPP", { locale: dateLocale })}
</> </>
) : ( ) : (
format(field.value.from, "LLL dd, y") format(field.value.from, "PPP", { locale: dateLocale })
) )
) : ( ) : (
<span>Pick a date range</span> <span>{dict.pickDateRange}</span>
)} )}
<CalendarIcon className="ml-auto h-4 w-4 opacity-50" /> <CalendarIcon className="ml-auto h-4 w-4 opacity-50" />
</Button> </Button>
@@ -114,11 +123,12 @@ export function CreatePlanForm() {
date < new Date(new Date().setHours(0, 0, 0, 0)) date < new Date(new Date().setHours(0, 0, 0, 0))
} }
initialFocus initialFocus
locale={dateLocale}
/> />
</PopoverContent> </PopoverContent>
</Popover> </Popover>
<FormDescription> <FormDescription>
Select the days you will be away. {dict.dateRangeDesc}
</FormDescription> </FormDescription>
<FormMessage /> <FormMessage />
</FormItem> </FormItem>
@@ -129,18 +139,18 @@ export function CreatePlanForm() {
name="password" name="password"
render={({ field }) => ( render={({ field }) => (
<FormItem> <FormItem>
<FormLabel>Group Password</FormLabel> <FormLabel>{dict.groupPassword}</FormLabel>
<FormControl> <FormControl>
<Input placeholder="secret-meow" {...field} /> <Input placeholder={dict.passwordPlaceholder} {...field} />
</FormControl> </FormControl>
<FormDescription> <FormDescription>
Share this password with your cat sitters. {dict.passwordDesc}
</FormDescription> </FormDescription>
<FormMessage /> <FormMessage />
</FormItem> </FormItem>
)} )}
/> />
<Button type="submit">Create Plan</Button> <Button type="submit">{dict.submit}</Button>
</form> </form>
</Form> </Form>
) )

View File

@@ -1,77 +1,63 @@
"use client" "use client"
import { zodResolver } from "@hookform/resolvers/zod" import { useState } from "react"
import { useForm } from "react-hook-form"
import { z } from "zod"
import { useRouter } from "next/navigation" import { useRouter } from "next/navigation"
import { toast } from "sonner"
import { Lock } from "lucide-react"
import { Button } from "@/components/ui/button"
import {
Form,
FormControl,
FormField,
FormItem,
FormLabel,
FormMessage,
} from "@/components/ui/form"
import { Input } from "@/components/ui/input"
import { verifyPlanPassword } from "@/app/actions/auth" import { verifyPlanPassword } from "@/app/actions/auth"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { toast } from "sonner"
const formSchema = z.object({ interface PlanLoginFormProps {
password: z.string().min(1, "Password is required"), planId: string;
}) dict: any;
}
export function PlanLoginForm({ planId }: { planId: string }) { export function PlanLoginForm({ planId, dict }: PlanLoginFormProps) {
const [password, setPassword] = useState("")
const [isPending, setIsPending] = useState(false)
const router = useRouter() const router = useRouter()
const form = useForm<z.infer<typeof formSchema>>({
resolver: zodResolver(formSchema),
defaultValues: {
password: "",
},
})
async function onSubmit(values: z.infer<typeof formSchema>) { async function handleSubmit(e: React.FormEvent) {
e.preventDefault()
setIsPending(true)
try { try {
const success = await verifyPlanPassword(planId, values.password) const success = await verifyPlanPassword(planId, password)
if (success) { if (success) {
toast.success("Access granted!") router.refresh()
router.refresh() // Refresh to trigger server re-render with cookie
} else { } else {
toast.error("Invalid password") toast.error(dict.error)
} }
} catch { } catch (error) {
toast.error("Something went wrong") toast.error("An error occurred")
} finally {
setIsPending(false)
} }
} }
return ( return (
<div className="flex flex-col items-center justify-center min-h-[50vh] space-y-4"> <Card className="w-full max-w-sm">
<div className="p-4 bg-muted rounded-full"> <CardHeader>
<Lock className="w-8 h-8 opacity-50" /> <CardTitle>{dict.title}</CardTitle>
</div> <CardDescription>
<h2 className="text-xl font-semibold">Enter Plan Password</h2> {dict.description}
<Form {...form}> </CardDescription>
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4 w-full max-w-xs"> </CardHeader>
<FormField <CardContent>
control={form.control} <form onSubmit={handleSubmit} className="space-y-4">
name="password" <Input
render={({ field }) => ( type="password"
<FormItem> placeholder="••••••••"
<FormLabel className="sr-only">Password</FormLabel> value={password}
<FormControl> onChange={(e) => setPassword(e.target.value)}
<Input type="password" placeholder="Password" {...field} /> required
</FormControl>
<FormMessage />
</FormItem>
)}
/> />
<Button type="submit" className="w-full"> <Button type="submit" className="w-full" disabled={isPending}>
Unlock Plan {isPending ? "..." : dict.submit}
</Button> </Button>
</form> </form>
</Form> </CardContent>
</div> </Card>
) )
} }

View File

@@ -1,12 +1,11 @@
"use client" "use client"
import { useState } from "react" import { useState } from "react"
import { useRouter } from "next/navigation"
import { toast } from "sonner"
import { Settings } from "lucide-react"
import { useForm } from "react-hook-form" import { useForm } from "react-hook-form"
import { z } from "zod"
import { zodResolver } from "@hookform/resolvers/zod" import { zodResolver } from "@hookform/resolvers/zod"
import * as z from "zod"
import { Settings } from "lucide-react"
import { toast } from "sonner"
import { Button } from "@/components/ui/button" import { Button } from "@/components/ui/button"
import { import {
@@ -32,46 +31,53 @@ import { Textarea } from "@/components/ui/textarea"
import { Checkbox } from "@/components/ui/checkbox" import { Checkbox } from "@/components/ui/checkbox"
import { updatePlan } from "@/app/actions/plan" import { updatePlan } from "@/app/actions/plan"
const formSchema = z.object({ interface PlanSettingsProps {
webhookUrl: z.string().optional().or(z.literal("")),
instructions: z.string().optional().or(z.literal("")),
notifyAll: z.boolean(),
})
type FormValues = z.infer<typeof formSchema>
type PlanSettingsProps = {
planId: string planId: string
initialWebhookUrl?: string | null initialInstructions: string | null
initialInstructions?: string | null initialWebhookUrl: string | null
initialNotifyAll?: boolean initialNotifyAll: boolean
dict: any
lang: string
} }
export function PlanSettings({ planId, initialWebhookUrl, initialInstructions, initialNotifyAll = true }: PlanSettingsProps) { export function PlanSettings({
planId,
initialInstructions,
initialWebhookUrl,
initialNotifyAll,
dict,
lang
}: PlanSettingsProps) {
const [open, setOpen] = useState(false) const [open, setOpen] = useState(false)
const router = useRouter() const [isPending, setIsPending] = useState(false)
const formSchema = z.object({
instructions: z.string().optional(),
webhookUrl: z.string().url().optional().or(z.literal("")),
notifyAll: z.boolean(),
})
type FormValues = z.infer<typeof formSchema>
const form = useForm<FormValues>({ const form = useForm<FormValues>({
resolver: zodResolver(formSchema), resolver: zodResolver(formSchema),
defaultValues: { defaultValues: {
webhookUrl: initialWebhookUrl || "",
instructions: initialInstructions || "", instructions: initialInstructions || "",
webhookUrl: initialWebhookUrl || "",
notifyAll: initialNotifyAll, notifyAll: initialNotifyAll,
}, },
}) })
async function onSubmit(values: FormValues) { async function onSubmit(data: FormValues) {
setIsPending(true)
try { try {
await updatePlan(planId, { await updatePlan(planId, data, lang)
webhookUrl: values.webhookUrl || "", toast.success(dict.success)
instructions: values.instructions || "",
notifyAll: values.notifyAll,
})
toast.success("Settings updated")
setOpen(false) setOpen(false)
router.refresh() } catch (error) {
} catch { toast.error(dict.error)
toast.error("Failed to update settings") } finally {
setIsPending(false)
} }
} }
@@ -80,49 +86,32 @@ export function PlanSettings({ planId, initialWebhookUrl, initialInstructions, i
<DialogTrigger asChild> <DialogTrigger asChild>
<Button variant="outline" size="sm"> <Button variant="outline" size="sm">
<Settings className="w-4 h-4 mr-2" /> <Settings className="w-4 h-4 mr-2" />
Settings {dict.title.split(" ")[1] || "Settings"}
</Button> </Button>
</DialogTrigger> </DialogTrigger>
<DialogContent className="sm:max-w-[425px]"> <DialogContent className="sm:max-w-[425px]">
<DialogHeader> <DialogHeader>
<DialogTitle>Plan Settings</DialogTitle> <DialogTitle>{dict.title}</DialogTitle>
<DialogDescription> <DialogDescription>
Configure notification webhooks and cat care instructions. {dict.description}
</DialogDescription> </DialogDescription>
</DialogHeader> </DialogHeader>
<Form {...form}> <Form {...form}>
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4"> <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
<FormField <FormField
control={form.control} control={form.control}
name="instructions" name="webhookUrl"
render={({ field }) => ( render={({ field }) => (
<FormItem> <FormItem>
<FormLabel>Cat Instructions</FormLabel> <FormLabel>{dict.webhookLabel}</FormLabel>
<FormControl> <FormControl>
<Textarea <Input
placeholder="Feeding times, vet contact, special needs..." placeholder={dict.webhookPlaceholder}
className="min-h-[100px]"
{...field} {...field}
/> />
</FormControl> </FormControl>
<FormDescription> <FormDescription>
Visible to all sitters. {dict.webhookDesc}
</FormDescription>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="webhookUrl"
render={({ field }) => (
<FormItem>
<FormLabel>Notification Webhook</FormLabel>
<FormControl>
<Input placeholder="https://discord.com/api/webhooks/..." {...field} />
</FormControl>
<FormDescription>
Telegram or Discord webhook URL.
</FormDescription> </FormDescription>
<FormMessage /> <FormMessage />
</FormItem> </FormItem>
@@ -141,17 +130,36 @@ export function PlanSettings({ planId, initialWebhookUrl, initialInstructions, i
</FormControl> </FormControl>
<div className="space-y-1 leading-none"> <div className="space-y-1 leading-none">
<FormLabel> <FormLabel>
Notify for all events {dict.notifyAllLabel}
</FormLabel> </FormLabel>
<FormDescription> <FormDescription>
If disabled, only cancellations will be notified. {dict.notifyAllDesc}
</FormDescription> </FormDescription>
</div> </div>
</FormItem> </FormItem>
)} )}
/> />
<FormField
control={form.control}
name="instructions"
render={({ field }) => (
<FormItem>
<FormLabel>{dict.instructionsLabel}</FormLabel>
<FormControl>
<Textarea
placeholder={dict.instructionsPlaceholder}
className="h-32"
{...field}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<DialogFooter> <DialogFooter>
<Button type="submit">Save changes</Button> <Button type="submit" disabled={isPending}>
{isPending ? dict.saving : dict.save}
</Button>
</DialogFooter> </DialogFooter>
</form> </form>
</Form> </Form>

70
dictionaries/de.json Normal file
View File

@@ -0,0 +1,70 @@
{
"home": {
"title": "Katzen-Sitting-Planer",
"description": "Koordiniere die Pflege deiner Vierbeiner, während du weg bist.",
"createPlan": "Neuen Plan erstellen",
"createPlanDesc": "Wähle deine Reisedaten und setze ein Gruppen-Passwort."
},
"createPlanForm": {
"travelDates": "Reisedaten",
"pickDateRange": "Zeitraum wählen",
"dateRangeDesc": "Wähle die Tage aus, an denen du weg bist.",
"groupPassword": "Gruppen-Passwort",
"passwordPlaceholder": "geheim-miau",
"passwordDesc": "Teile dieses Passwort mit deinen Katzen-Sittern.",
"submit": "Plan erstellen",
"success": "Plan erfolgreich erstellt!",
"error": "Etwas ist schiefgelaufen. Bitte versuche es erneut.",
"passwordError": "Das Passwort muss mindestens 4 Zeichen lang sein."
},
"dashboard": {
"overview": "Übersicht",
"instructions": "Anleitungen",
"instructionsTitle": "Katzenpflege-Anleitungen",
"export": "Exportieren",
"settings": "Einstellungen",
"ownerHome": "Besitzer zu Hause",
"illDoIt": "Ich mache das!",
"bookTitle": "Buchung für den {date}",
"bookDesc": "Wer kümmert sich um die Katzen?",
"imSitting": "Ich sitte",
"ownerIsHome": "Besitzer ist zu Hause",
"nameLabel": "Name",
"namePlaceholder": "Dein Name",
"confirmBooking": "Buchung bestätigen",
"saving": "Speichere...",
"bookedSuccess": "Termin gebucht!",
"bookError": "Buchung fehlgeschlagen. Vielleicht war jemand schneller?",
"cancelConfirm": "Bist du sicher, dass du diesen Eintrag entfernen möchtest?",
"cancelSuccess": "Eintrag entfernt",
"cancelError": "Entfernen fehlgeschlagen",
"noInstructions": "Noch keine spezifischen Instruktionen hinterlegt."
},
"login": {
"title": "Passwort eingeben",
"description": "Bitte gib das Passwort ein, das du vom Katzenbesitzer erhalten hast.",
"submit": "Plan öffnen",
"error": "Ungültiges Passwort"
},
"settings": {
"title": "Plan-Einstellungen",
"description": "Aktualisiere die Instruktionen oder den Benachrichtigungs-Webhook.",
"webhookLabel": "Benachrichtigungs-Webhook (Discord/Telegram)",
"webhookPlaceholder": "https://discord.com/api/webhooks/...",
"webhookDesc": "Lass dich informieren, wenn jemand bucht oder absagt.",
"instructionsLabel": "Katzen-Instruktionen",
"instructionsPlaceholder": "Futter: 2x täglich, Klo: täglich...",
"notifyAllLabel": "Alle Ereignisse melden",
"notifyAllDesc": "Falls deaktiviert, werden nur Absagen gemeldet.",
"save": "Änderungen speichern",
"saving": "Speichere...",
"success": "Einstellungen aktualisiert!",
"error": "Aktualisierung fehlgeschlagen"
},
"notifications": {
"ownerHome": "🏠 BESITZER ZU HAUSE: Markiert für den {date}.\nPlan: {url}",
"newBooking": "✅ NEUE BUCHUNG: {name} sittet am {date}.\nPlan: {url}",
"cancellation": "🚨 ABSAGE: {name} hat die Buchung für den {date} gelöscht.\nPlan: {url}",
"instructionsUpdated": "📝 UPDATE: Die Katzen-Instruktionen wurden geändert.\nPlan: {url}"
}
}

70
dictionaries/en.json Normal file
View File

@@ -0,0 +1,70 @@
{
"home": {
"title": "Cat Sitting Planner",
"description": "Coordinate care for your furry friends while you're away.",
"createPlan": "Create a New Plan",
"createPlanDesc": "Select your travel dates and set a group password."
},
"createPlanForm": {
"travelDates": "Travel Dates",
"pickDateRange": "Pick a date range",
"dateRangeDesc": "Select the days you will be away.",
"groupPassword": "Group Password",
"passwordPlaceholder": "secret-meow",
"passwordDesc": "Share this password with your cat sitters.",
"submit": "Create Plan",
"success": "Plan created successfully!",
"error": "Something went wrong. Please try again.",
"passwordError": "Password must be at least 4 characters."
},
"dashboard": {
"overview": "Overview",
"instructions": "Instructions",
"instructionsTitle": "Cat Care Instructions",
"export": "Export",
"settings": "Settings",
"ownerHome": "Owner Home",
"illDoIt": "I'll do it!",
"bookTitle": "Book {date}",
"bookDesc": "Who is taking care of the cats?",
"imSitting": "I am Sitting",
"ownerIsHome": "Owner is Home",
"nameLabel": "Name",
"namePlaceholder": "Your Name",
"confirmBooking": "Confirm Booking",
"saving": "Saving...",
"bookedSuccess": "Spot booked!",
"bookError": "Failed to book spot. Maybe it was just taken?",
"cancelConfirm": "Are you sure you want to remove this entry?",
"cancelSuccess": "Entry removed",
"cancelError": "Failed to remove entry",
"noInstructions": "No specific instructions provided yet."
},
"login": {
"title": "Enter Password",
"description": "Please enter the password provided by the cat owner to access this plan.",
"submit": "Access Plan",
"error": "Invalid password"
},
"settings": {
"title": "Plan Settings",
"description": "Update the cat care instructions or notification webhook.",
"webhookLabel": "Notification Webhook (Discord/Telegram)",
"webhookPlaceholder": "https://discord.com/api/webhooks/...",
"webhookDesc": "Get notified on Discord/Telegram when someone books or cancels.",
"instructionsLabel": "Cat Instructions",
"instructionsPlaceholder": "Food: 2x daily, Litter: daily...",
"notifyAllLabel": "Notify for all events",
"notifyAllDesc": "If disabled, only cancellations will be notified.",
"save": "Save changes",
"saving": "Saving...",
"success": "Settings updated!",
"error": "Failed to update settings"
},
"notifications": {
"ownerHome": "🏠 OWNER HOME: Marked for {date}.\nPlan: {url}",
"newBooking": "✅ NEW BOOKING: {name} is sitting on {date}.\nPlan: {url}",
"cancellation": "🚨 CANCELLATION: {name} removed their booking for {date}.\nPlan: {url}",
"instructionsUpdated": "📝 UPDATED: Cat instructions have been modified.\nPlan: {url}"
}
}

9
get-dictionary.ts Normal file
View File

@@ -0,0 +1,9 @@
import "server-only";
const dictionaries = {
en: () => import("./dictionaries/en.json").then((module) => module.default),
de: () => import("./dictionaries/de.json").then((module) => module.default),
};
export const getDictionary = async (locale: keyof typeof dictionaries) =>
dictionaries[locale]();

30
middleware.ts Normal file
View File

@@ -0,0 +1,30 @@
import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
const locales = ["en", "de"];
const defaultLocale = "de";
export function middleware(request: NextRequest) {
const { pathname } = request.nextUrl;
// Check if there is any supported locale in the pathname
const pathnameHasLocale = locales.some(
(locale) => pathname.startsWith(`/${locale}/`) || pathname === `/${locale}`
);
if (pathnameHasLocale) return;
// Redirect if there is no locale
const locale = defaultLocale; // For simplicity, we default to 'de' as requested
request.nextUrl.pathname = `/${locale}${pathname}`;
// Keep searching if the URL changes
return NextResponse.redirect(request.nextUrl);
}
export const config = {
matcher: [
// Skip all internal paths (_next)
"/((?!_next|api|public|manifest|icon|file|globe|next|vercel|window).*)",
],
};