Compare commits

...

2 Commits

Author SHA1 Message Date
diana.dolgolyova 87f488e2c1 feat: dashboard summary on bookings page, archive expired MC and Open Day
- Dashboard cards show new/pending counts per tab, click to navigate
- MC tab: expired master classes (past date or deleted) move to collapsible archive
- Open Day tab: past events move to archive section
- Date badges on MC group headers (gold active, strikethrough archived)
- Fix MC content API key (masterClasses not master-classes)
- Fuzzy title matching for MC registration → content date lookup

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-23 19:13:49 +03:00
diana.dolgolyova b906216317 feat: add status workflow to MC and Open Day bookings, refactor into separate files
- DB migration v12: add status column to mc_registrations and open_day_bookings
- MC and Open Day tabs now have full status workflow (new → contacted → confirmed/declined)
- Filter tabs with counts, status badges, action buttons matching group bookings
- Extract shared components (_shared.tsx): FilterTabs, StatusBadge, StatusActions, BookingCard, ContactLinks
- Split monolith into _McRegistrationsTab.tsx, _OpenDayBookingsTab.tsx, _shared.tsx

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-23 19:05:44 +03:00
7 changed files with 742 additions and 291 deletions
@@ -0,0 +1,198 @@
"use client";
import { useState, useEffect, useMemo } from "react";
import { ChevronDown, ChevronRight, Archive } from "lucide-react";
import { adminFetch } from "@/lib/csrf";
import {
type BookingStatus, type BookingFilter,
LoadingSpinner, EmptyState, DeleteBtn, ContactLinks,
FilterTabs, StatusBadge, StatusActions, BookingCard,
fmtDate, countStatuses, sortByStatus,
} from "./_shared";
interface McRegistration {
id: number;
masterClassTitle: string;
name: string;
phone?: string;
instagram?: string;
telegram?: string;
status: BookingStatus;
createdAt: string;
}
interface McSlot { date: string; startTime: string }
interface McItem { title: string; slots: McSlot[] }
export function McRegistrationsTab() {
const [regs, setRegs] = useState<McRegistration[]>([]);
const [mcDates, setMcDates] = useState<Record<string, string>>({}); // title → latest slot date
const [loading, setLoading] = useState(true);
const [filter, setFilter] = useState<BookingFilter>("all");
const [showArchived, setShowArchived] = useState(false);
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?: McItem[] }]) => {
setRegs(regData);
// Build lookup: MC title → latest slot date
// Use both exact match and fuzzy match (registration title contains MC title or vice versa)
const dates: Record<string, string> = {};
const mcItems = mcData.items || [];
for (const mc of mcItems) {
const latestSlot = mc.slots?.reduce((latest, s) => s.date > latest ? s.date : latest, "");
if (latestSlot) dates[mc.title] = latestSlot;
}
// Also match registration titles that don't exactly match MC titles
const regTitles = new Set(regData.map((r) => r.masterClassTitle));
for (const regTitle of regTitles) {
if (dates[regTitle]) continue; // already matched
// Try fuzzy: find MC whose title is contained in regTitle or vice versa
for (const mc of mcItems) {
const latestSlot = mc.slots?.reduce((latest, s) => s.date > latest ? s.date : latest, "");
if (!latestSlot) continue;
if (regTitle.toLowerCase().includes(mc.title.toLowerCase()) || mc.title.toLowerCase().includes(regTitle.toLowerCase())) {
dates[regTitle] = latestSlot;
break;
}
}
}
setMcDates(dates);
}).catch(() => {}).finally(() => setLoading(false));
}, []);
const today = new Date().toISOString().split("T")[0];
function isExpired(title: string) {
const date = mcDates[title];
if (!date) return true; // no matching MC in content = deleted/archived
return date < today;
}
const counts = useMemo(() => countStatuses(regs), [regs]);
const { active, archived } = useMemo(() => {
const active: Record<string, McRegistration[]> = {};
const archived: Record<string, McRegistration[]> = {};
for (const r of regs) {
if (filter !== "all" && r.status !== filter) continue;
const target = isExpired(r.masterClassTitle) ? archived : active;
if (!target[r.masterClassTitle]) target[r.masterClassTitle] = [];
target[r.masterClassTitle].push(r);
}
for (const items of [...Object.values(active), ...Object.values(archived)]) {
const sorted = sortByStatus(items);
items.length = 0;
items.push(...sorted);
}
return { active, archived };
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [regs, filter, mcDates]);
const [expanded, setExpanded] = useState<Record<string, boolean>>({});
async function handleStatus(id: number, status: BookingStatus) {
setRegs((prev) => prev.map((r) => r.id === id ? { ...r, status } : r));
await adminFetch("/api/admin/mc-registrations", {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ action: "set-status", id, status }),
});
}
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 />;
function renderGroup(title: string, items: McRegistration[], isArchived: boolean) {
const isOpen = expanded[title] ?? !isArchived;
const groupCounts = countStatuses(items);
return (
<div key={title} className={`rounded-xl border overflow-hidden ${isArchived ? "border-white/5 opacity-60" : "border-white/10"}`}>
<button
onClick={() => setExpanded((p) => ({ ...p, [title]: !isOpen }))}
className={`w-full flex items-center gap-3 px-4 py-3 transition-colors text-left ${isArchived ? "bg-neutral-900/50 hover:bg-neutral-800/50" : "bg-neutral-900 hover:bg-neutral-800/80"}`}
>
{isOpen ? <ChevronDown size={14} className="text-neutral-500 shrink-0" /> : <ChevronRight size={14} className="text-neutral-500 shrink-0" />}
<span className={`font-medium text-sm truncate ${isArchived ? "text-neutral-400" : "text-white"}`}>{title}</span>
{mcDates[title] && (
<span className={`text-[10px] rounded-full px-2 py-0.5 shrink-0 ${
isArchived ? "text-neutral-600 bg-neutral-800 line-through" : "text-gold bg-gold/10"
}`}>
{new Date(mcDates[title] + "T12:00").toLocaleDateString("ru-RU", { day: "numeric", month: "short" })}
</span>
)}
{isArchived && (
<span className="text-[10px] text-neutral-600 bg-neutral-800 rounded-full px-2 py-0.5 shrink-0">архив</span>
)}
<span className="text-[10px] text-neutral-500 bg-neutral-800 rounded-full px-2 py-0.5 shrink-0">{items.length} чел.</span>
{!isArchived && (
<div className="flex gap-2 ml-auto text-[10px]">
{groupCounts.new > 0 && <span className="text-gold">{groupCounts.new} новых</span>}
{groupCounts.contacted > 0 && <span className="text-blue-400">{groupCounts.contacted} связ.</span>}
{groupCounts.confirmed > 0 && <span className="text-emerald-400">{groupCounts.confirmed} подтв.</span>}
</div>
)}
</button>
{isOpen && (
<div className="px-4 pb-3 pt-1 space-y-2">
{items.map((r) => (
<BookingCard key={r.id} status={r.status}>
<div className="flex items-start justify-between gap-3">
<div className="flex items-center gap-2 flex-wrap text-sm min-w-0">
<span className="font-medium text-white">{r.name}</span>
<ContactLinks phone={r.phone} instagram={r.instagram} telegram={r.telegram} />
</div>
<div className="flex items-center gap-2 shrink-0">
<span className="text-neutral-600 text-xs">{fmtDate(r.createdAt)}</span>
<DeleteBtn onClick={() => handleDelete(r.id)} />
</div>
</div>
<div className="flex items-center gap-2 mt-2 flex-wrap">
<StatusBadge status={r.status} />
{!isArchived && <StatusActions status={r.status} onStatus={(s) => handleStatus(r.id, s)} />}
</div>
</BookingCard>
))}
</div>
)}
</div>
);
}
const archivedCount = Object.values(archived).reduce((sum, items) => sum + items.length, 0);
return (
<div>
<FilterTabs filter={filter} counts={counts} total={regs.length} onFilter={setFilter} />
<div className="mt-3 space-y-2">
{Object.keys(active).length === 0 && Object.keys(archived).length === 0 && <EmptyState total={regs.length} />}
{Object.entries(active).map(([title, items]) => renderGroup(title, items, false))}
</div>
{archivedCount > 0 && (
<div className="mt-4">
<button
onClick={() => setShowArchived((v) => !v)}
className="flex items-center gap-2 text-xs text-neutral-500 hover:text-neutral-300 transition-colors"
>
<Archive size={13} />
{showArchived ? "Скрыть архив" : `Архив (${archivedCount} записей)`}
{showArchived ? <ChevronDown size={12} /> : <ChevronRight size={12} />}
</button>
{showArchived && (
<div className="mt-2 space-y-2">
{Object.entries(archived).map(([title, items]) => renderGroup(title, items, true))}
</div>
)}
</div>
)}
</div>
);
}
@@ -0,0 +1,202 @@
"use client";
import { useState, useEffect, useMemo } from "react";
import { ChevronDown, ChevronRight, Archive } from "lucide-react";
import { adminFetch } from "@/lib/csrf";
import {
type BookingStatus, type BookingFilter,
LoadingSpinner, EmptyState, DeleteBtn, ContactLinks,
FilterTabs, StatusBadge, StatusActions, BookingCard,
fmtDate, countStatuses, sortByStatus,
} from "./_shared";
interface OpenDayBooking {
id: number;
classId: number;
eventId: number;
name: string;
phone: string;
instagram?: string;
telegram?: string;
status: BookingStatus;
createdAt: string;
classStyle?: string;
classTrainer?: string;
classTime?: string;
classHall?: string;
}
interface EventInfo { id: number; date: string; title?: string }
export function OpenDayBookingsTab() {
const [bookings, setBookings] = useState<OpenDayBooking[]>([]);
const [events, setEvents] = useState<EventInfo[]>([]);
const [loading, setLoading] = useState(true);
const [filter, setFilter] = useState<BookingFilter>("all");
const [showArchived, setShowArchived] = useState(false);
useEffect(() => {
adminFetch("/api/admin/open-day")
.then((r) => r.json())
.then(async (evts: EventInfo[]) => {
setEvents(evts);
if (evts.length === 0) return;
// Fetch bookings for all events
const allBookings: OpenDayBooking[] = [];
for (const ev of evts) {
const data = await adminFetch(`/api/admin/open-day/bookings?eventId=${ev.id}`).then((r) => r.json());
allBookings.push(...data);
}
setBookings(allBookings);
})
.catch(() => {})
.finally(() => setLoading(false));
}, []);
const today = new Date().toISOString().split("T")[0];
const eventDateMap = useMemo(() => {
const map: Record<number, string> = {};
for (const ev of events) map[ev.id] = ev.date;
return map;
}, [events]);
function isExpired(eventId: number) {
const date = eventDateMap[eventId];
return date ? date < today : false;
}
const counts = useMemo(() => countStatuses(bookings), [bookings]);
type GroupInfo = { hall: string; time: string; style: string; trainer: string; items: OpenDayBooking[]; eventId: number };
const { activeGroups, archivedGroups } = useMemo(() => {
const filtered = filter === "all" ? bookings : bookings.filter((b) => b.status === filter);
const activeMap: Record<string, GroupInfo> = {};
const archivedMap: Record<string, GroupInfo> = {};
for (const b of filtered) {
const key = `${b.eventId}|${b.classHall}|${b.classTime}|${b.classStyle}`;
const target = isExpired(b.eventId) ? archivedMap : activeMap;
if (!target[key]) target[key] = { hall: b.classHall || "—", time: b.classTime || "—", style: b.classStyle || "—", trainer: b.classTrainer || "—", items: [], eventId: b.eventId };
target[key].items.push(b);
}
for (const g of [...Object.values(activeMap), ...Object.values(archivedMap)]) {
const sorted = sortByStatus(g.items);
g.items.length = 0;
g.items.push(...sorted);
}
const sortGroups = (entries: [string, GroupInfo][]) =>
entries.sort(([, a], [, b]) => {
const hallCmp = a.hall.localeCompare(b.hall);
return hallCmp !== 0 ? hallCmp : a.time.localeCompare(b.time);
});
return {
activeGroups: sortGroups(Object.entries(activeMap)),
archivedGroups: sortGroups(Object.entries(archivedMap)),
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [bookings, filter, eventDateMap]);
const [expanded, setExpanded] = useState<Record<string, boolean>>({});
async function handleStatus(id: number, status: BookingStatus) {
setBookings((prev) => prev.map((b) => b.id === id ? { ...b, status } : b));
await adminFetch("/api/admin/open-day/bookings", {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ action: "set-status", id, status }),
});
}
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 />;
function renderGroup(key: string, group: GroupInfo, isArchived: boolean) {
const isOpen = expanded[key] ?? !isArchived;
const groupCounts = countStatuses(group.items);
const eventDate = eventDateMap[group.eventId];
return (
<div key={key} className={`rounded-xl border overflow-hidden ${isArchived ? "border-white/5 opacity-60" : "border-white/10"}`}>
<button
onClick={() => setExpanded((p) => ({ ...p, [key]: !isOpen }))}
className={`w-full flex items-center gap-3 px-4 py-3 transition-colors text-left ${isArchived ? "bg-neutral-900/50 hover:bg-neutral-800/50" : "bg-neutral-900 hover:bg-neutral-800/80"}`}
>
{isOpen ? <ChevronDown size={14} className="text-neutral-500 shrink-0" /> : <ChevronRight size={14} className="text-neutral-500 shrink-0" />}
<span className={`text-xs font-medium shrink-0 ${isArchived ? "text-neutral-500" : "text-gold"}`}>{group.time}</span>
<span className={`font-medium text-sm truncate ${isArchived ? "text-neutral-400" : "text-white"}`}>{group.style}</span>
<span className="text-xs text-neutral-500 truncate hidden sm:inline">· {group.trainer}</span>
{isArchived && (
<span className="text-[10px] text-neutral-600 bg-neutral-800 rounded-full px-2 py-0.5 shrink-0">
{eventDate ? new Date(eventDate + "T12:00").toLocaleDateString("ru-RU", { day: "numeric", month: "short" }) : "архив"}
</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>
{!isArchived && (
<div className="flex gap-2 text-[10px] shrink-0">
{groupCounts.new > 0 && <span className="text-gold">{groupCounts.new} нов.</span>}
{groupCounts.confirmed > 0 && <span className="text-emerald-400">{groupCounts.confirmed} подтв.</span>}
</div>
)}
</button>
{isOpen && (
<div className="px-4 pb-3 pt-1 space-y-2">
{group.items.map((b) => (
<BookingCard key={b.id} status={b.status}>
<div className="flex items-start justify-between gap-3">
<div className="flex items-center gap-2 flex-wrap text-sm min-w-0">
<span className="font-medium text-white">{b.name}</span>
<ContactLinks phone={b.phone} instagram={b.instagram} telegram={b.telegram} />
</div>
<div className="flex items-center gap-2 shrink-0">
<span className="text-neutral-600 text-xs">{fmtDate(b.createdAt)}</span>
<DeleteBtn onClick={() => handleDelete(b.id)} />
</div>
</div>
<div className="flex items-center gap-2 mt-2 flex-wrap">
<StatusBadge status={b.status} />
{!isArchived && <StatusActions status={b.status} onStatus={(s) => handleStatus(b.id, s)} />}
</div>
</BookingCard>
))}
</div>
)}
</div>
);
}
const archivedCount = archivedGroups.reduce((sum, [, g]) => sum + g.items.length, 0);
return (
<div>
<FilterTabs filter={filter} counts={counts} total={bookings.length} onFilter={setFilter} />
<div className="mt-3 space-y-2">
{activeGroups.length === 0 && archivedGroups.length === 0 && <EmptyState total={bookings.length} />}
{activeGroups.map(([key, group]) => renderGroup(key, group, false))}
</div>
{archivedCount > 0 && (
<div className="mt-4">
<button
onClick={() => setShowArchived((v) => !v)}
className="flex items-center gap-2 text-xs text-neutral-500 hover:text-neutral-300 transition-colors"
>
<Archive size={13} />
{showArchived ? "Скрыть архив" : `Архив (${archivedCount} записей)`}
{showArchived ? <ChevronDown size={12} /> : <ChevronRight size={12} />}
</button>
{showArchived && (
<div className="mt-2 space-y-2">
{archivedGroups.map(([key, group]) => renderGroup(key, group, true))}
</div>
)}
</div>
)}
</div>
);
}
+172
View File
@@ -0,0 +1,172 @@
"use client";
import { Loader2, Trash2, Phone, Instagram, Send } from "lucide-react";
// --- Types ---
export type BookingStatus = "new" | "contacted" | "confirmed" | "declined";
export type BookingFilter = "all" | BookingStatus;
export const SHORT_DAYS: Record<string, string> = {
"Понедельник": "ПН", "Вторник": "ВТ", "Среда": "СР", "Четверг": "ЧТ",
"Пятница": "ПТ", "Суббота": "СБ", "Воскресенье": "ВС",
};
export const BOOKING_STATUSES: { key: BookingStatus; label: string; color: string; bg: string; border: string }[] = [
{ key: "new", label: "Новая", color: "text-gold", bg: "bg-gold/10", border: "border-gold/30" },
{ key: "contacted", label: "Связались", color: "text-blue-400", bg: "bg-blue-500/10", border: "border-blue-500/30" },
{ key: "confirmed", label: "Подтверждено", color: "text-emerald-400", bg: "bg-emerald-500/10", border: "border-emerald-500/30" },
{ key: "declined", label: "Отказ", color: "text-red-400", bg: "bg-red-500/10", border: "border-red-500/30" },
];
// --- Shared Components ---
export function LoadingSpinner() {
return (
<div className="flex items-center gap-2 py-8 text-neutral-500 justify-center">
<Loader2 size={16} className="animate-spin" />
Загрузка...
</div>
);
}
export function EmptyState({ total }: { total: number }) {
return (
<p className="text-sm text-neutral-500 py-8 text-center">
{total === 0 ? "Пока нет записей" : "Нет записей по фильтру"}
</p>
);
}
export 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>
);
}
export function ContactLinks({ phone, instagram, telegram }: { phone?: string; instagram?: string; telegram?: string }) {
return (
<>
{phone && (
<a href={`tel:${phone.replace(/\D/g, "")}`} className="inline-flex items-center gap-1 text-emerald-400 hover:text-emerald-300 text-xs">
<Phone size={10} />{phone}
</a>
)}
{instagram && (
<a href={`https://ig.me/m/${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} />{instagram}
</a>
)}
{telegram && (
<a href={`https://t.me/${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} />{telegram}
</a>
)}
</>
);
}
export function FilterTabs({ filter, counts, total, onFilter }: {
filter: BookingFilter;
counts: Record<string, number>;
total: number;
onFilter: (f: BookingFilter) => void;
}) {
return (
<div className="flex items-center gap-2 flex-wrap">
<button
onClick={() => onFilter("all")}
className={`rounded-full px-3 py-1.5 text-xs font-medium transition-all ${
filter === "all" ? "bg-gold/20 text-gold border border-gold/40" : "bg-neutral-800 text-neutral-400 border border-white/10 hover:text-white"
}`}
>
Все <span className="text-neutral-500 ml-1">{total}</span>
</button>
{BOOKING_STATUSES.map((s) => (
<button
key={s.key}
onClick={() => onFilter(s.key)}
className={`rounded-full px-3 py-1.5 text-xs font-medium transition-all ${
filter === s.key ? `${s.bg} ${s.color} border ${s.border}` : "bg-neutral-800 text-neutral-400 border border-white/10 hover:text-white"
}`}
>
{s.label}
{counts[s.key] > 0 && <span className="ml-1.5">{counts[s.key]}</span>}
</button>
))}
</div>
);
}
export function StatusBadge({ status }: { status: BookingStatus }) {
const conf = BOOKING_STATUSES.find((s) => s.key === status) || BOOKING_STATUSES[0];
return (
<span className={`text-[10px] font-medium ${conf.bg} ${conf.color} border ${conf.border} rounded-full px-2.5 py-0.5`}>
{conf.label}
</span>
);
}
export function StatusActions({ status, onStatus }: { status: BookingStatus; onStatus: (s: BookingStatus) => void }) {
return (
<div className="flex gap-1 ml-auto">
{status === "new" && (
<button onClick={() => onStatus("contacted")} className="inline-flex items-center gap-1 rounded-full px-2.5 py-1 text-[10px] font-medium bg-blue-500/10 text-blue-400 border border-blue-500/30 hover:bg-blue-500/20 transition-all">
Связались
</button>
)}
{status === "contacted" && (
<>
<button onClick={() => onStatus("confirmed")} className="inline-flex items-center gap-1 rounded-full px-2.5 py-1 text-[10px] font-medium bg-emerald-500/10 text-emerald-400 border border-emerald-500/30 hover:bg-emerald-500/20 transition-all">
Подтвердить
</button>
<button onClick={() => onStatus("declined")} className="inline-flex items-center gap-1 rounded-full px-2.5 py-1 text-[10px] font-medium bg-red-500/10 text-red-400 border border-red-500/30 hover:bg-red-500/20 transition-all">
Отказ
</button>
</>
)}
{(status === "confirmed" || status === "declined") && (
<button onClick={() => onStatus("contacted")} className="inline-flex items-center gap-1 rounded-full px-2.5 py-1 text-[10px] font-medium bg-neutral-800/50 text-neutral-500 border border-transparent hover:border-white/10 hover:text-neutral-300 transition-all">
Вернуть
</button>
)}
</div>
);
}
export function BookingCard({ status, children }: { status: BookingStatus; children: React.ReactNode }) {
return (
<div
className={`rounded-lg border p-3 transition-colors ${
status === "declined" ? "border-red-500/15 bg-red-500/[0.02] opacity-50"
: status === "confirmed" ? "border-emerald-500/15 bg-emerald-500/[0.02]"
: status === "new" ? "border-gold/20 bg-gold/[0.03]"
: "border-white/10 bg-neutral-800/30"
}`}
>
{children}
</div>
);
}
export function fmtDate(iso: string): string {
return new Date(iso).toLocaleDateString("ru-RU");
}
export function countStatuses(items: { status: string }[]): Record<string, number> {
const c: Record<string, number> = { new: 0, contacted: 0, confirmed: 0, declined: 0 };
for (const i of items) c[i.status] = (c[i.status] || 0) + 1;
return c;
}
export function sortByStatus<T extends { status: string }>(items: T[]): T[] {
const order: Record<string, number> = { new: 0, contacted: 1, confirmed: 2, declined: 3 };
return [...items].sort((a, b) => (order[a.status] ?? 0) - (order[b.status] ?? 0));
}
+114 -285
View File
@@ -2,8 +2,17 @@
import { useState, useEffect, useMemo, useCallback, useRef } from "react";
import { createPortal } from "react-dom";
import { Loader2, Trash2, Phone, Instagram, Send, ChevronDown, ChevronRight, Bell, CheckCircle2, XCircle, Clock, Star, Calendar, DoorOpen, X } from "lucide-react";
import { Phone, Instagram, Send, ChevronDown, ChevronRight, Bell, CheckCircle2, XCircle, Clock, Star, Calendar, DoorOpen, X } from "lucide-react";
import { adminFetch } from "@/lib/csrf";
import {
type BookingStatus, type BookingFilter,
BOOKING_STATUSES, SHORT_DAYS,
LoadingSpinner, EmptyState, DeleteBtn, ContactLinks,
FilterTabs, StatusBadge, StatusActions, BookingCard,
fmtDate, countStatuses,
} from "./_shared";
import { McRegistrationsTab } from "./_McRegistrationsTab";
import { OpenDayBookingsTab } from "./_OpenDayBookingsTab";
// --- Types ---
@@ -23,50 +32,7 @@ interface GroupBooking {
createdAt: string;
}
interface McRegistration {
id: number;
masterClassTitle: string;
name: string;
phone?: 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;
}
const SHORT_DAYS: Record<string, string> = {
"Понедельник": "ПН", "Вторник": "ВТ", "Среда": "СР", "Четверг": "ЧТ",
"Пятница": "ПТ", "Суббота": "СБ", "Воскресенье": "ВС",
};
type Tab = "reminders" | "classes" | "master-classes" | "open-day";
type BookingStatus = "new" | "contacted" | "confirmed" | "declined";
type BookingFilter = "all" | BookingStatus;
const BOOKING_STATUSES: { key: BookingStatus; label: string; color: string; bg: string; border: string }[] = [
{ key: "new", label: "Новая", color: "text-gold", bg: "bg-gold/10", border: "border-gold/30" },
{ key: "contacted", label: "Связались", color: "text-blue-400", bg: "bg-blue-500/10", border: "border-blue-500/30" },
{ key: "confirmed", label: "Подтверждено", color: "text-emerald-400", bg: "bg-emerald-500/10", border: "border-emerald-500/30" },
{ key: "declined", label: "Отказ", color: "text-red-400", bg: "bg-red-500/10", border: "border-red-500/30" },
];
// --- Confirm Booking Modal ---
@@ -465,219 +431,6 @@ function GroupBookingsTab() {
);
}
// --- MC Registrations Tab ---
function McRegistrationsTab() {
const [regs, setRegs] = useState<McRegistration[]>([]);
const [loading, setLoading] = useState(true);
useEffect(() => {
adminFetch("/api/admin/mc-registrations")
.then((r) => r.json())
.then((data: McRegistration[]) => setRegs(data))
.catch(() => {})
.finally(() => setLoading(false));
}, []);
// Group by MC title
const grouped = useMemo(() => {
const map: Record<string, McRegistration[]> = {};
for (const r of regs) {
if (!map[r.masterClassTitle]) map[r.masterClassTitle] = [];
map[r.masterClassTitle].push(r);
}
return map;
}, [regs]);
const [expanded, setExpanded] = useState<Record<string, boolean>>({});
function toggleExpand(key: string) {
setExpanded((prev) => ({ ...prev, [key]: !prev[key] }));
}
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 (
<div className="space-y-2">
{Object.keys(grouped).length === 0 && <EmptyState total={regs.length} />}
{Object.entries(grouped).map(([title, items]) => {
const isOpen = expanded[title] ?? false;
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>
</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 border-white/5 bg-neutral-800/30 p-3"
>
<div className="flex items-center gap-2 flex-wrap text-sm">
<span className="font-medium text-white">{r.name}</span>
{r.phone && (
<a href={`tel:${r.phone.replace(/\D/g, "")}`} className="inline-flex items-center gap-1 text-emerald-400 hover:text-emerald-300 text-xs">
<Phone size={10} />{r.phone}
</a>
)}
{r.instagram && (
<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 text-xs"
>
<Instagram size={10} />{r.instagram}
</a>
)}
{r.telegram && (
<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 text-xs"
>
<Send size={10} />{r.telegram}
</a>
)}
<span className="text-neutral-600 text-xs ml-auto">{fmtDate(r.createdAt)}</span>
<DeleteBtn onClick={() => handleDelete(r.id)} />
</div>
</div>
))}
</div>
)}
</div>
);
})}
</div>
);
}
// --- Open Day Bookings Tab ---
function OpenDayBookingsTab() {
const [bookings, setBookings] = useState<OpenDayBooking[]>([]);
const [loading, setLoading] = useState(true);
useEffect(() => {
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];
return adminFetch(`/api/admin/open-day/bookings?eventId=${ev.id}`)
.then((r) => r.json())
.then((data: OpenDayBooking[]) => setBookings(data));
})
.catch(() => {})
.finally(() => setLoading(false));
}, []);
// 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 bookings) {
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);
});
}, [bookings]);
const [expanded, setExpanded] = useState<Record<string, boolean>>({});
function toggleExpand(key: string) {
setExpanded((prev) => ({ ...prev, [key]: !prev[key] }));
}
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 (
<div className="space-y-2">
{grouped.length === 0 && <EmptyState total={bookings.length} />}
{grouped.map(([key, group]) => {
const isOpen = expanded[key] ?? false;
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>
</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 border-white/5 bg-neutral-800/30 p-3"
>
<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>
</div>
))}
</div>
)}
</div>
);
})}
</div>
);
}
// --- Reminders Tab ---
interface ReminderItem {
@@ -891,40 +644,116 @@ function RemindersTab() {
);
}
// --- Shared helpers ---
// --- Dashboard Summary ---
interface DashboardCounts {
classesNew: number;
classesContacted: number;
mcNew: number;
mcContacted: number;
odNew: number;
odContacted: number;
remindersToday: number;
remindersTomorrow: number;
}
function DashboardSummary({ onNavigate }: { onNavigate: (tab: Tab) => void }) {
const [counts, setCounts] = useState<DashboardCounts | null>(null);
useEffect(() => {
Promise.all([
adminFetch("/api/admin/group-bookings").then((r) => r.json()),
adminFetch("/api/admin/mc-registrations").then((r) => r.json()),
adminFetch("/api/admin/open-day").then((r) => r.json()).then(async (events: { id: number }[]) => {
if (events.length === 0) return [];
return adminFetch(`/api/admin/open-day/bookings?eventId=${events[0].id}`).then((r) => r.json());
}),
adminFetch("/api/admin/reminders").then((r) => r.json()).catch(() => []),
]).then(([gb, mc, od, rem]: [{ status: string }[], { status: string }[], { status: string }[], { eventDate: string }[]]) => {
const today = new Date().toISOString().split("T")[0];
const tomorrow = new Date(Date.now() + 86400000).toISOString().split("T")[0];
setCounts({
classesNew: gb.filter((b) => b.status === "new").length,
classesContacted: gb.filter((b) => b.status === "contacted").length,
mcNew: mc.filter((b) => b.status === "new").length,
mcContacted: mc.filter((b) => b.status === "contacted").length,
odNew: od.filter((b) => b.status === "new").length,
odContacted: od.filter((b) => b.status === "contacted").length,
remindersToday: rem.filter((r) => r.eventDate === today).length,
remindersTomorrow: rem.filter((r) => r.eventDate === tomorrow).length,
});
}).catch(() => {});
}, []);
if (!counts) return null;
const cards: { tab: Tab; label: string; urgent: number; urgentLabel: string; pending: number; pendingLabel: string; color: string; urgentColor: string }[] = [
{
tab: "reminders", label: "Напоминания",
urgent: counts.remindersToday, urgentLabel: "сегодня",
pending: counts.remindersTomorrow, pendingLabel: "завтра",
color: "border-amber-500/20", urgentColor: "text-amber-400",
},
{
tab: "classes", label: "Занятия",
urgent: counts.classesNew, urgentLabel: "новых",
pending: counts.classesContacted, pendingLabel: "в работе",
color: "border-gold/20", urgentColor: "text-gold",
},
{
tab: "master-classes", label: "Мастер-классы",
urgent: counts.mcNew, urgentLabel: "новых",
pending: counts.mcContacted, pendingLabel: "в работе",
color: "border-purple-500/20", urgentColor: "text-purple-400",
},
{
tab: "open-day", label: "Open Day",
urgent: counts.odNew, urgentLabel: "новых",
pending: counts.odContacted, pendingLabel: "в работе",
color: "border-blue-500/20", urgentColor: "text-blue-400",
},
];
const hasWork = cards.some((c) => c.urgent > 0 || c.pending > 0);
if (!hasWork) return null;
function LoadingSpinner() {
return (
<div className="flex items-center gap-2 py-8 text-neutral-500 justify-center">
<Loader2 size={16} className="animate-spin" />
Загрузка...
<div className="grid grid-cols-2 lg:grid-cols-4 gap-3 mt-4">
{cards.map((c) => {
const total = c.urgent + c.pending;
if (total === 0) return (
<div key={c.tab} className="rounded-xl border border-white/5 bg-neutral-900/50 p-3 opacity-40">
<p className="text-xs text-neutral-500">{c.label}</p>
<p className="text-lg font-bold text-neutral-600 mt-1"></p>
</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="Удалить"
key={c.tab}
onClick={() => onNavigate(c.tab)}
className={`rounded-xl border ${c.color} bg-neutral-900 p-3 text-left transition-all hover:bg-neutral-800/80 hover:scale-[1.02]`}
>
<Trash2 size={14} />
<p className="text-xs text-neutral-400">{c.label}</p>
<div className="flex items-baseline gap-2 mt-1">
{c.urgent > 0 && (
<span className={`text-lg font-bold ${c.urgentColor}`}>{c.urgent}</span>
)}
{c.urgent > 0 && (
<span className="text-[10px] text-neutral-500">{c.urgentLabel}</span>
)}
{c.pending > 0 && (
<>
{c.urgent > 0 && <span className="text-neutral-700">·</span>}
<span className="text-sm font-medium text-neutral-400">{c.pending}</span>
<span className="text-[10px] text-neutral-500">{c.pendingLabel}</span>
</>
)}
</div>
</button>
);
}
function fmtDate(iso: string): string {
return new Date(iso).toLocaleDateString("ru-RU");
})}
</div>
);
}
// --- Main Page ---
@@ -942,9 +771,9 @@ export default function BookingsPage() {
return (
<div>
<h1 className="text-2xl font-bold">Записи</h1>
<p className="mt-1 text-neutral-400 text-sm">
Все заявки и записи в одном месте
</p>
{/* Dashboard — what needs attention */}
<DashboardSummary onNavigate={setTab} />
{/* Tabs */}
<div className="mt-5 flex border-b border-white/10">
+12 -1
View File
@@ -1,5 +1,5 @@
import { NextRequest, NextResponse } from "next/server";
import { getMcRegistrations, getAllMcRegistrations, addMcRegistration, updateMcRegistration, toggleMcNotification, deleteMcRegistration } from "@/lib/db";
import { getMcRegistrations, getAllMcRegistrations, addMcRegistration, updateMcRegistration, toggleMcNotification, deleteMcRegistration, setMcRegistrationStatus } from "@/lib/db";
export async function GET(request: NextRequest) {
const title = request.nextUrl.searchParams.get("title");
@@ -29,6 +29,17 @@ export async function PUT(request: NextRequest) {
try {
const body = await request.json();
// Set booking status
if (body.action === "set-status") {
const { id, status } = body;
if (!id || !status) return NextResponse.json({ error: "id, status required" }, { status: 400 });
if (!["new", "contacted", "confirmed", "declined"].includes(status)) {
return NextResponse.json({ error: "Invalid status" }, { status: 400 });
}
setMcRegistrationStatus(id, status);
return NextResponse.json({ ok: true });
}
// Toggle notification status
if (body.action === "toggle-notify") {
const { id, field, value } = body;
@@ -3,6 +3,7 @@ import {
getOpenDayBookings,
toggleOpenDayNotification,
deleteOpenDayBooking,
setOpenDayBookingStatus,
} from "@/lib/db";
export async function GET(request: NextRequest) {
@@ -16,6 +17,15 @@ export async function GET(request: NextRequest) {
export async function PUT(request: NextRequest) {
try {
const body = await request.json();
if (body.action === "set-status") {
const { id, status } = body;
if (!id || !status) return NextResponse.json({ error: "id, status required" }, { status: 400 });
if (!["new", "contacted", "confirmed", "declined"].includes(status)) {
return NextResponse.json({ error: "Invalid status" }, { status: 400 });
}
setOpenDayBookingStatus(id, status);
return NextResponse.json({ ok: true });
}
if (body.action === "toggle-notify") {
const { id, field, value } = body;
if (!id || !field || typeof value !== "boolean") {
+29
View File
@@ -229,6 +229,19 @@ const migrations: Migration[] = [
}
},
},
{
version: 12,
name: "add_status_to_mc_and_openday",
up: (db) => {
for (const table of ["mc_registrations", "open_day_bookings"]) {
const cols = db.prepare(`PRAGMA table_info(${table})`).all() as { name: string }[];
const colNames = new Set(cols.map((c) => c.name));
if (!colNames.has("status")) {
db.exec(`ALTER TABLE ${table} ADD COLUMN status TEXT NOT NULL DEFAULT 'new'`);
}
}
},
},
];
function runMigrations(db: Database.Database) {
@@ -510,6 +523,7 @@ interface McRegistrationRow {
notified_confirm: number;
notified_reminder: number;
reminder_status: string | null;
status: string;
}
export interface McRegistration {
@@ -523,6 +537,7 @@ export interface McRegistration {
notifiedConfirm: boolean;
notifiedReminder: boolean;
reminderStatus?: string;
status: string;
}
export function addMcRegistration(
@@ -572,9 +587,15 @@ function mapMcRow(r: McRegistrationRow): McRegistration {
notifiedConfirm: !!r.notified_confirm,
notifiedReminder: !!r.notified_reminder,
reminderStatus: r.reminder_status ?? undefined,
status: r.status || "new",
};
}
export function setMcRegistrationStatus(id: number, status: string): void {
const db = getDb();
db.prepare("UPDATE mc_registrations SET status = ? WHERE id = ?").run(status, id);
}
export function updateMcRegistration(
id: number,
name: string,
@@ -928,6 +949,7 @@ interface OpenDayBookingRow {
notified_confirm: number;
notified_reminder: number;
reminder_status: string | null;
status: string;
created_at: string;
class_style?: string;
class_trainer?: string;
@@ -946,6 +968,7 @@ export interface OpenDayBooking {
notifiedConfirm: boolean;
notifiedReminder: boolean;
reminderStatus?: string;
status: string;
createdAt: string;
classStyle?: string;
classTrainer?: string;
@@ -982,6 +1005,11 @@ function mapClassRow(r: OpenDayClassRow): OpenDayClass {
};
}
export function setOpenDayBookingStatus(id: number, status: string): void {
const db = getDb();
db.prepare("UPDATE open_day_bookings SET status = ? WHERE id = ?").run(status, id);
}
function mapBookingRow(r: OpenDayBookingRow): OpenDayBooking {
return {
id: r.id,
@@ -994,6 +1022,7 @@ function mapBookingRow(r: OpenDayBookingRow): OpenDayBooking {
notifiedConfirm: !!r.notified_confirm,
notifiedReminder: !!r.notified_reminder,
reminderStatus: r.reminder_status ?? undefined,
status: r.status || "new",
createdAt: r.created_at,
classStyle: r.class_style ?? undefined,
classTrainer: r.class_trainer ?? undefined,