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

View File

@@ -2,11 +2,17 @@ import { notFound } from "next/navigation"
import { cookies } from "next/headers"
import prisma from "@/lib/prisma"
import { PlanLoginForm } from "@/components/plan-login-form"
import { Toaster } from "@/components/ui/sonner"
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({
where: { id: planId },
include: { bookings: true },
@@ -22,7 +28,7 @@ export default async function DashboardPage({ params }: { params: Promise<{ plan
if (!isAuthenticated) {
return (
<main className="flex min-h-screen flex-col items-center p-4">
<PlanLoginForm planId={plan.id} />
<PlanLoginForm planId={plan.id} dict={dict.login} />
</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="flex flex-col md:flex-row justify-between items-start md:items-center gap-4">
<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">
{plan.startDate.toLocaleDateString()} - {plan.endDate.toLocaleDateString()}
{plan.startDate.toLocaleDateString(lang)} - {plan.endDate.toLocaleDateString(lang)}
</p>
</div>
<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 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>
</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 { CreatePlanForm } from "@/components/create-plan-form";
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 (
<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">
@@ -19,22 +27,21 @@ export default function Home() {
</div>
</div>
<div className="space-y-2">
<h1 className="text-3xl font-bold tracking-tighter">Cat Sitting Planner</h1>
<p className="text-muted-foreground">Coordinate care for your furry friends while you're away.</p>
<h1 className="text-3xl font-bold tracking-tighter">{dict.home.title}</h1>
<p className="text-muted-foreground">{dict.home.description}</p>
</div>
</div>
<Card>
<CardHeader>
<CardTitle>Create a New Plan</CardTitle>
<CardDescription>Select your travel dates and set a group password.</CardDescription>
<CardTitle>{dict.home.createPlan}</CardTitle>
<CardDescription>{dict.home.createPlanDesc}</CardDescription>
</CardHeader>
<CardContent>
<CreatePlanForm />
<CreatePlanForm dict={dict.createPlanForm} lang={lang} />
</CardContent>
</Card>
</div>
</main>
);
}

View File

@@ -4,8 +4,11 @@ import prisma from "@/lib/prisma"
import { revalidatePath } from "next/cache"
import { headers } from "next/headers"
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
const existing = await prisma.booking.findFirst({
where: {
@@ -34,19 +37,22 @@ export async function createBooking(planId: string, date: Date, name: string, ty
if (plan?.webhookUrl && plan.notifyAll) {
const host = (await headers()).get("host")
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"
? `🏠 OWNER HOME: Marked for ${dateStr}.\nPlan: ${planUrl}`
: `✅ NEW BOOKING: ${name} is sitting on ${dateStr}.\nPlan: ${planUrl}`
? dict.notifications.ownerHome.replace("{date}", dateStr).replace("{url}", planUrl)
: dict.notifications.newBooking.replace("{name}", name).replace("{date}", dateStr).replace("{url}", planUrl)
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({
where: { id: bookingId },
include: { plan: true }
@@ -61,11 +67,16 @@ export async function deleteBooking(bookingId: number, planId: string) {
if (booking.plan.webhookUrl) {
const host = (await headers()).get("host")
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()
await sendNotification(booking.plan.webhookUrl, `🚨 CANCELLATION: ${booking.sitterName} removed their booking for ${dateStr}.\nPlan: ${planUrl}`)
const dateStr = booking.date.toLocaleDateString(lang)
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 { headers } from "next/headers"
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({
where: { id: planId },
data: {
@@ -18,9 +25,13 @@ export async function updatePlan(planId: string, data: { instructions?: string;
if (data.instructions && plan.webhookUrl && plan.notifyAll) {
const host = (await headers()).get("host")
const protocol = host?.includes("localhost") ? "http" : "https"
const planUrl = `${protocol}://${host}/dashboard/${planId}`
await sendNotification(plan.webhookUrl, `📝 UPDATED: Cat instructions have been modified.\nPlan: ${planUrl}`)
const planUrl = `${protocol}://${host}/${lang}/dashboard/${planId}`
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 { format } from "date-fns"
import { de, enUS } from "date-fns/locale"
import { CalendarIcon } from "lucide-react"
import { useForm } from "react-hook-form"
import { z } from "zod"
@@ -23,19 +24,25 @@ import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover
import { toast } from "sonner"
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({
from: z.date(),
to: z.date(),
}),
password: z.string().min(4, {
message: "Password must be at least 4 characters.",
message: dict.passwordError,
}),
instructions: z.string().optional(),
})
})
export function CreatePlanForm() {
const router = useRouter()
const form = useForm<z.infer<typeof formSchema>>({
resolver: zodResolver(formSchema),
defaultValues: {
@@ -44,6 +51,8 @@ export function CreatePlanForm() {
},
})
const dateLocale = lang === "de" ? de : enUS
async function onSubmit(values: z.infer<typeof formSchema>) {
try {
const response = await fetch("/api/plan", {
@@ -62,10 +71,10 @@ export function CreatePlanForm() {
}
const data = await response.json()
toast.success("Plan created successfully!")
router.push(`/dashboard/${data.planId}`)
toast.success(dict.success)
router.push(`/${lang}/dashboard/${data.planId}`)
} catch (error) {
toast.error("Something went wrong. Please try again.")
toast.error(dict.error)
console.error(error)
}
}
@@ -78,7 +87,7 @@ export function CreatePlanForm() {
name="dateRange"
render={({ field }) => (
<FormItem className="flex flex-col">
<FormLabel>Travel Dates</FormLabel>
<FormLabel>{dict.travelDates}</FormLabel>
<Popover>
<PopoverTrigger asChild>
<FormControl>
@@ -92,14 +101,14 @@ export function CreatePlanForm() {
{field.value?.from ? (
field.value.to ? (
<>
{format(field.value.from, "LLL dd, y")} -{" "}
{format(field.value.to, "LLL dd, y")}
{format(field.value.from, "PPP", { locale: dateLocale })} -{" "}
{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" />
</Button>
@@ -114,11 +123,12 @@ export function CreatePlanForm() {
date < new Date(new Date().setHours(0, 0, 0, 0))
}
initialFocus
locale={dateLocale}
/>
</PopoverContent>
</Popover>
<FormDescription>
Select the days you will be away.
{dict.dateRangeDesc}
</FormDescription>
<FormMessage />
</FormItem>
@@ -129,18 +139,18 @@ export function CreatePlanForm() {
name="password"
render={({ field }) => (
<FormItem>
<FormLabel>Group Password</FormLabel>
<FormLabel>{dict.groupPassword}</FormLabel>
<FormControl>
<Input placeholder="secret-meow" {...field} />
<Input placeholder={dict.passwordPlaceholder} {...field} />
</FormControl>
<FormDescription>
Share this password with your cat sitters.
{dict.passwordDesc}
</FormDescription>
<FormMessage />
</FormItem>
)}
/>
<Button type="submit">Create Plan</Button>
<Button type="submit">{dict.submit}</Button>
</form>
</Form>
)

View File

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

View File

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