feat: add booking management, Open Day, unified signup modal

- MC registrations: notification toggles (confirm/remind) with urgency
- Group bookings: save to DB from BookingModal, admin CRUD at /admin/bookings
- Open Day: full event system with schedule grid (halls × time), per-class
  booking, discount pricing (30 BYN / 20 BYN from 3+), auto-cancel threshold
- Unified SignupModal replaces 3 separate forms — consistent fields
  (name, phone, instagram, telegram), Instagram DM fallback on network error
- Centralized /admin/bookings page with 3 tabs (classes, MC, Open Day),
  collapsible sections, notification toggles, filter chips
- Unread booking badge on sidebar + dashboard widget with per-type breakdown
- Pricing: contact hint (Instagram/Telegram/phone) on price & rental tabs,
  admin toggle to show/hide
- DB migrations 5-7: group_bookings table, open_day tables, unified fields

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-03-19 12:58:04 +03:00
parent 7497ede2fd
commit b94ee69033
31 changed files with 3198 additions and 407 deletions

View File

@@ -0,0 +1,597 @@
"use client";
import { useState, useEffect, useMemo } from "react";
import { Loader2, Trash2, Phone, Instagram, Send, ChevronDown, ChevronRight } from "lucide-react";
import { adminFetch } from "@/lib/csrf";
import { NotifyToggle } from "../_components/NotifyToggle";
// --- Types ---
interface GroupBooking {
id: number;
name: string;
phone: string;
groupInfo?: string;
notifiedConfirm: boolean;
notifiedReminder: boolean;
createdAt: string;
}
interface McRegistration {
id: number;
masterClassTitle: string;
name: string;
instagram: string;
telegram?: string;
notifiedConfirm: boolean;
notifiedReminder: boolean;
createdAt: string;
}
interface OpenDayBooking {
id: number;
classId: number;
eventId: number;
name: string;
phone: string;
instagram?: string;
telegram?: string;
notifiedConfirm: boolean;
notifiedReminder: boolean;
createdAt: string;
classStyle?: string;
classTrainer?: string;
classTime?: string;
classHall?: string;
}
interface MasterClassSlot {
date: string;
startTime: string;
endTime: string;
}
interface MasterClassItem {
title: string;
slots: MasterClassSlot[];
}
type Tab = "classes" | "master-classes" | "open-day";
type NotifyFilter = "all" | "new" | "no-reminder";
// --- Filter Chips ---
function FilterChips({
filter,
setFilter,
newCount,
noReminderCount,
}: {
filter: NotifyFilter;
setFilter: (f: NotifyFilter) => void;
newCount: number;
noReminderCount: number;
}) {
const FILTERS: { key: NotifyFilter; label: string; count?: number }[] = [
{ key: "all", label: "Все" },
{ key: "new", label: "Новые", count: newCount },
{ key: "no-reminder", label: "Без напоминания", count: noReminderCount },
];
return (
<div className="flex items-center gap-2">
{FILTERS.map((f) => (
<button
key={f.key}
onClick={() => setFilter(f.key)}
className={`rounded-full px-3 py-1.5 text-xs font-medium transition-all ${
filter === f.key
? "bg-gold/20 text-gold border border-gold/40"
: "bg-neutral-800 text-neutral-400 border border-white/10 hover:text-white"
}`}
>
{f.label}
{f.count !== undefined && f.count > 0 && (
<span className="ml-1.5 rounded-full bg-red-500/20 text-red-400 px-1.5 py-0.5 text-[10px]">
{f.count}
</span>
)}
</button>
))}
</div>
);
}
// --- Group Bookings Tab ---
function GroupBookingsTab() {
const [bookings, setBookings] = useState<GroupBooking[]>([]);
const [loading, setLoading] = useState(true);
const [filter, setFilter] = useState<NotifyFilter>("all");
useEffect(() => {
adminFetch("/api/admin/group-bookings")
.then((r) => r.json())
.then((data: GroupBooking[]) => setBookings(data))
.catch(() => {})
.finally(() => setLoading(false));
}, []);
const newCount = bookings.filter((b) => !b.notifiedConfirm).length;
const noReminderCount = bookings.filter((b) => !b.notifiedReminder).length;
const filtered = useMemo(() => {
if (filter === "new") return bookings.filter((b) => !b.notifiedConfirm);
if (filter === "no-reminder") return bookings.filter((b) => !b.notifiedReminder);
return bookings;
}, [bookings, filter]);
async function handleToggle(id: number, field: "notified_confirm" | "notified_reminder") {
const b = bookings.find((x) => x.id === id);
if (!b) return;
const key = field === "notified_confirm" ? "notifiedConfirm" : "notifiedReminder";
const newValue = !b[key];
setBookings((prev) => prev.map((x) => x.id === id ? { ...x, [key]: newValue } : x));
await adminFetch("/api/admin/group-bookings", {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ action: "toggle-notify", id, field, value: newValue }),
});
}
async function handleDelete(id: number) {
await adminFetch(`/api/admin/group-bookings?id=${id}`, { method: "DELETE" });
setBookings((prev) => prev.filter((b) => b.id !== id));
}
if (loading) return <LoadingSpinner />;
return (
<>
<FilterChips filter={filter} setFilter={setFilter} newCount={newCount} noReminderCount={noReminderCount} />
<div className="mt-3 space-y-2">
{filtered.length === 0 && <EmptyState total={bookings.length} />}
{filtered.map((b) => (
<div
key={b.id}
className={`rounded-xl border p-4 space-y-2 transition-colors ${
!b.notifiedConfirm ? "border-gold/20 bg-gold/[0.03]" : "border-white/10 bg-neutral-900"
}`}
>
<div className="flex items-center gap-3 flex-wrap">
<span className="font-medium text-white">{b.name}</span>
<a href={`tel:${b.phone.replace(/\D/g, "")}`} className="inline-flex items-center gap-1 text-emerald-400 hover:text-emerald-300 text-sm">
<Phone size={12} />{b.phone}
</a>
{b.groupInfo && (
<>
<span className="text-neutral-600">·</span>
<span className="text-xs text-neutral-400 bg-neutral-800 rounded-full px-2 py-0.5">{b.groupInfo}</span>
</>
)}
<span className="text-neutral-600 text-xs ml-auto">{fmtDate(b.createdAt)}</span>
<DeleteBtn onClick={() => handleDelete(b.id)} />
</div>
<NotifyToggle
confirmed={b.notifiedConfirm}
reminded={b.notifiedReminder}
onToggleConfirm={() => handleToggle(b.id, "notified_confirm")}
onToggleReminder={() => handleToggle(b.id, "notified_reminder")}
/>
</div>
))}
</div>
</>
);
}
// --- MC Registrations Tab ---
function McRegistrationsTab() {
const [regs, setRegs] = useState<McRegistration[]>([]);
const [mcItems, setMcItems] = useState<MasterClassItem[]>([]);
const [loading, setLoading] = useState(true);
const [filter, setFilter] = useState<NotifyFilter>("all");
useEffect(() => {
Promise.all([
adminFetch("/api/admin/mc-registrations").then((r) => r.json()),
adminFetch("/api/admin/sections/masterClasses").then((r) => r.json()),
])
.then(([regData, mcData]: [McRegistration[], { items: MasterClassItem[] }]) => {
setRegs(regData);
setMcItems(mcData.items || []);
})
.catch(() => {})
.finally(() => setLoading(false));
}, []);
// Compute reminder urgency per MC title
const urgencyMap = useMemo(() => {
const map: Record<string, boolean> = {};
const now = Date.now();
const twoDays = 2 * 24 * 60 * 60 * 1000;
for (const mc of mcItems) {
map[mc.title] = (mc.slots || []).some((s) => {
if (!s.date) return false;
const slotTime = new Date(s.date + "T" + (s.startTime || "23:59")).getTime();
const diff = slotTime - now;
return diff >= 0 && diff <= twoDays;
});
}
return map;
}, [mcItems]);
const newCount = regs.filter((r) => !r.notifiedConfirm).length;
const noReminderCount = regs.filter((r) => !r.notifiedReminder).length;
const filtered = useMemo(() => {
if (filter === "new") return regs.filter((r) => !r.notifiedConfirm);
if (filter === "no-reminder") return regs.filter((r) => !r.notifiedReminder);
return regs;
}, [regs, filter]);
// Group by MC title
const grouped = useMemo(() => {
const map: Record<string, McRegistration[]> = {};
for (const r of filtered) {
if (!map[r.masterClassTitle]) map[r.masterClassTitle] = [];
map[r.masterClassTitle].push(r);
}
return map;
}, [filtered]);
const [expanded, setExpanded] = useState<Record<string, boolean>>({});
function toggleExpand(key: string) {
setExpanded((prev) => ({ ...prev, [key]: !prev[key] }));
}
async function handleToggle(id: number, field: "notified_confirm" | "notified_reminder") {
const r = regs.find((x) => x.id === id);
if (!r) return;
const key = field === "notified_confirm" ? "notifiedConfirm" : "notifiedReminder";
const newValue = !r[key];
setRegs((prev) => prev.map((x) => x.id === id ? { ...x, [key]: newValue } : x));
await adminFetch("/api/admin/mc-registrations", {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ action: "toggle-notify", id, field, value: newValue }),
});
}
async function handleDelete(id: number) {
await adminFetch(`/api/admin/mc-registrations?id=${id}`, { method: "DELETE" });
setRegs((prev) => prev.filter((r) => r.id !== id));
}
if (loading) return <LoadingSpinner />;
return (
<>
<FilterChips filter={filter} setFilter={setFilter} newCount={newCount} noReminderCount={noReminderCount} />
<div className="mt-3 space-y-2">
{Object.keys(grouped).length === 0 && <EmptyState total={regs.length} />}
{Object.entries(grouped).map(([title, items]) => {
const isOpen = expanded[title] ?? false;
const groupNewCount = items.filter((r) => !r.notifiedConfirm).length;
return (
<div key={title} className="rounded-xl border border-white/10 overflow-hidden">
<button
onClick={() => toggleExpand(title)}
className="w-full flex items-center gap-3 px-4 py-3 bg-neutral-900 hover:bg-neutral-800/80 transition-colors text-left"
>
{isOpen ? <ChevronDown size={14} className="text-neutral-500 shrink-0" /> : <ChevronRight size={14} className="text-neutral-500 shrink-0" />}
<span className="font-medium text-white text-sm truncate">{title}</span>
<span className="text-[10px] text-neutral-500 bg-neutral-800 rounded-full px-2 py-0.5 shrink-0">{items.length}</span>
{urgencyMap[title] && (
<span className="text-[10px] text-red-400 bg-red-500/10 rounded-full px-2 py-0.5 shrink-0">скоро</span>
)}
{groupNewCount > 0 && (
<span className="text-[10px] text-gold bg-gold/10 rounded-full px-2 py-0.5 shrink-0">{groupNewCount} новых</span>
)}
</button>
{isOpen && (
<div className="px-4 pb-3 pt-1 space-y-1.5">
{items.map((r) => (
<div
key={r.id}
className={`rounded-lg border p-3 space-y-1.5 transition-colors ${
!r.notifiedConfirm ? "border-gold/20 bg-gold/[0.03]" : "border-white/5 bg-neutral-800/30"
}`}
>
<div className="flex items-center gap-2 flex-wrap text-sm">
<span className="font-medium text-white">{r.name}</span>
<span className="text-neutral-500">·</span>
<a
href={`https://ig.me/m/${r.instagram.replace(/^@/, "")}`}
target="_blank"
rel="noopener noreferrer"
className="inline-flex items-center gap-1 text-pink-400 hover:text-pink-300"
>
<Instagram size={12} />
<span className="text-neutral-300">{r.instagram}</span>
</a>
{r.telegram && (
<>
<span className="text-neutral-600">·</span>
<a
href={`https://t.me/${r.telegram.replace(/^@/, "")}`}
target="_blank"
rel="noopener noreferrer"
className="inline-flex items-center gap-1 text-blue-400 hover:text-blue-300"
>
<Send size={12} />
<span className="text-neutral-300">{r.telegram}</span>
</a>
</>
)}
<span className="text-neutral-600 text-xs ml-auto">{fmtDate(r.createdAt)}</span>
<DeleteBtn onClick={() => handleDelete(r.id)} />
</div>
<NotifyToggle
confirmed={r.notifiedConfirm}
reminded={r.notifiedReminder}
reminderUrgent={urgencyMap[r.masterClassTitle] && !r.notifiedReminder}
onToggleConfirm={() => handleToggle(r.id, "notified_confirm")}
onToggleReminder={() => handleToggle(r.id, "notified_reminder")}
/>
</div>
))}
</div>
)}
</div>
);
})}
</div>
</>
);
}
// --- Open Day Bookings Tab ---
function OpenDayBookingsTab() {
const [bookings, setBookings] = useState<OpenDayBooking[]>([]);
const [eventDate, setEventDate] = useState("");
const [loading, setLoading] = useState(true);
const [filter, setFilter] = useState<NotifyFilter>("all");
useEffect(() => {
// Get events to find active one
adminFetch("/api/admin/open-day")
.then((r) => r.json())
.then((events: { id: number; date: string }[]) => {
if (events.length === 0) {
setLoading(false);
return;
}
const ev = events[0];
setEventDate(ev.date);
return adminFetch(`/api/admin/open-day/bookings?eventId=${ev.id}`)
.then((r) => r.json())
.then((data: OpenDayBooking[]) => setBookings(data));
})
.catch(() => {})
.finally(() => setLoading(false));
}, []);
const reminderUrgent = useMemo(() => {
if (!eventDate) return false;
const now = Date.now();
const twoDays = 2 * 24 * 60 * 60 * 1000;
const eventTime = new Date(eventDate + "T10:00").getTime();
const diff = eventTime - now;
return diff >= 0 && diff <= twoDays;
}, [eventDate]);
const newCount = bookings.filter((b) => !b.notifiedConfirm).length;
const noReminderCount = bookings.filter((b) => !b.notifiedReminder).length;
const filtered = useMemo(() => {
if (filter === "new") return bookings.filter((b) => !b.notifiedConfirm);
if (filter === "no-reminder") return bookings.filter((b) => !b.notifiedReminder);
return bookings;
}, [bookings, filter]);
// Group by class — sorted by hall then time
const grouped = useMemo(() => {
const map: Record<string, { hall: string; time: string; style: string; trainer: string; items: OpenDayBooking[] }> = {};
for (const b of filtered) {
const key = `${b.classHall}|${b.classTime}|${b.classStyle}`;
if (!map[key]) map[key] = { hall: b.classHall || "—", time: b.classTime || "—", style: b.classStyle || "—", trainer: b.classTrainer || "—", items: [] };
map[key].items.push(b);
}
// Sort by hall, then time
return Object.entries(map).sort(([, a], [, b]) => {
const hallCmp = a.hall.localeCompare(b.hall);
return hallCmp !== 0 ? hallCmp : a.time.localeCompare(b.time);
});
}, [filtered]);
const [expanded, setExpanded] = useState<Record<string, boolean>>({});
function toggleExpand(key: string) {
setExpanded((prev) => ({ ...prev, [key]: !prev[key] }));
}
async function handleToggle(id: number, field: "notified_confirm" | "notified_reminder") {
const b = bookings.find((x) => x.id === id);
if (!b) return;
const key = field === "notified_confirm" ? "notifiedConfirm" : "notifiedReminder";
const newValue = !b[key];
setBookings((prev) => prev.map((x) => x.id === id ? { ...x, [key]: newValue } : x));
await adminFetch("/api/admin/open-day/bookings", {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ action: "toggle-notify", id, field, value: newValue }),
});
}
async function handleDelete(id: number) {
await adminFetch(`/api/admin/open-day/bookings?id=${id}`, { method: "DELETE" });
setBookings((prev) => prev.filter((b) => b.id !== id));
}
if (loading) return <LoadingSpinner />;
return (
<>
<FilterChips filter={filter} setFilter={setFilter} newCount={newCount} noReminderCount={noReminderCount} />
<div className="mt-3 space-y-2">
{grouped.length === 0 && <EmptyState total={bookings.length} />}
{grouped.map(([key, group]) => {
const isOpen = expanded[key] ?? false;
const groupNewCount = group.items.filter((b) => !b.notifiedConfirm).length;
return (
<div key={key} className="rounded-xl border border-white/10 overflow-hidden">
<button
onClick={() => toggleExpand(key)}
className="w-full flex items-center gap-3 px-4 py-3 bg-neutral-900 hover:bg-neutral-800/80 transition-colors text-left"
>
{isOpen ? <ChevronDown size={14} className="text-neutral-500 shrink-0" /> : <ChevronRight size={14} className="text-neutral-500 shrink-0" />}
<span className="text-gold text-xs font-medium shrink-0">{group.time}</span>
<span className="font-medium text-white text-sm truncate">{group.style}</span>
<span className="text-xs text-neutral-500 truncate hidden sm:inline">· {group.trainer}</span>
<span className="text-[10px] text-neutral-500 bg-neutral-800 rounded-full px-2 py-0.5 shrink-0 ml-auto">{group.hall}</span>
<span className="text-[10px] text-neutral-500 bg-neutral-800 rounded-full px-2 py-0.5 shrink-0">{group.items.length} чел.</span>
{groupNewCount > 0 && (
<span className="text-[10px] text-gold bg-gold/10 rounded-full px-2 py-0.5 shrink-0">{groupNewCount} новых</span>
)}
</button>
{isOpen && (
<div className="px-4 pb-3 pt-1 space-y-1.5">
{group.items.map((b) => (
<div
key={b.id}
className={`rounded-lg border p-3 space-y-1.5 transition-colors ${
!b.notifiedConfirm ? "border-gold/20 bg-gold/[0.03]" : "border-white/5 bg-neutral-800/30"
}`}
>
<div className="flex items-center gap-2 flex-wrap text-sm">
<span className="font-medium text-white">{b.name}</span>
<a href={`tel:${b.phone}`} className="inline-flex items-center gap-1 text-emerald-400 hover:text-emerald-300 text-xs">
<Phone size={10} />{b.phone}
</a>
{b.instagram && (
<a
href={`https://ig.me/m/${b.instagram.replace(/^@/, "")}`}
target="_blank"
rel="noopener noreferrer"
className="inline-flex items-center gap-1 text-pink-400 hover:text-pink-300 text-xs"
>
<Instagram size={10} />{b.instagram}
</a>
)}
{b.telegram && (
<a
href={`https://t.me/${b.telegram.replace(/^@/, "")}`}
target="_blank"
rel="noopener noreferrer"
className="inline-flex items-center gap-1 text-blue-400 hover:text-blue-300 text-xs"
>
<Send size={10} />{b.telegram}
</a>
)}
<span className="text-neutral-600 text-xs ml-auto">{fmtDate(b.createdAt)}</span>
<DeleteBtn onClick={() => handleDelete(b.id)} />
</div>
<NotifyToggle
confirmed={b.notifiedConfirm}
reminded={b.notifiedReminder}
reminderUrgent={reminderUrgent && !b.notifiedReminder}
onToggleConfirm={() => handleToggle(b.id, "notified_confirm")}
onToggleReminder={() => handleToggle(b.id, "notified_reminder")}
/>
</div>
))}
</div>
)}
</div>
);
})}
</div>
</>
);
}
// --- Shared helpers ---
function LoadingSpinner() {
return (
<div className="flex items-center gap-2 py-8 text-neutral-500 justify-center">
<Loader2 size={16} className="animate-spin" />
Загрузка...
</div>
);
}
function EmptyState({ total }: { total: number }) {
return (
<p className="text-sm text-neutral-500 py-8 text-center">
{total === 0 ? "Пока нет записей" : "Нет записей по фильтру"}
</p>
);
}
function DeleteBtn({ onClick }: { onClick: () => void }) {
return (
<button
type="button"
onClick={onClick}
className="rounded p-1 text-neutral-500 hover:text-red-400 transition-colors"
title="Удалить"
>
<Trash2 size={14} />
</button>
);
}
function fmtDate(iso: string): string {
return new Date(iso).toLocaleDateString("ru-RU");
}
// --- Main Page ---
const TABS: { key: Tab; label: string }[] = [
{ key: "classes", label: "Занятия" },
{ key: "master-classes", label: "Мастер-классы" },
{ key: "open-day", label: "День открытых дверей" },
];
export default function BookingsPage() {
const [tab, setTab] = useState<Tab>("classes");
return (
<div>
<h1 className="text-2xl font-bold">Записи</h1>
<p className="mt-1 text-neutral-400 text-sm">
Все заявки и записи в одном месте
</p>
{/* Tabs */}
<div className="mt-5 flex border-b border-white/10">
{TABS.map((t) => (
<button
key={t.key}
onClick={() => setTab(t.key)}
className={`px-4 py-2.5 text-sm font-medium transition-colors relative ${
tab === t.key
? "text-gold"
: "text-neutral-400 hover:text-white"
}`}
>
{t.label}
{tab === t.key && (
<span className="absolute bottom-0 left-0 right-0 h-0.5 bg-gold rounded-full" />
)}
</button>
))}
</div>
{/* Tab content */}
<div className="mt-4">
{tab === "classes" && <GroupBookingsTab />}
{tab === "master-classes" && <McRegistrationsTab />}
{tab === "open-day" && <OpenDayBookingsTab />}
</div>
</div>
);
}