feat: booking panel upgrade — refactor, notes, search, manual add, polling
Phase 1 — Refactor: - Split monolith _shared.tsx into types.ts, BookingComponents, InlineNotes, GenericBookingsList, AddBookingModal, SearchBar (no more _ prefix) - All 3 tabs use GenericBookingsList — shared status workflow, filters, archive Phase 2 — Features: - DB migration 13: add notes column to all booking tables - Inline notes with amber highlight, auto-save 800ms debounce - Confirm modal comment saves to notes field - Manual add: 2 tabs (Занятие / Мероприятие), filters expired MCs, Open Day support - Search bar: cross-table search by name/phone - 10s polling for real-time updates (bookings page + sidebar badge) - Status change marks booking as seen (fixes unread count on reset) - Confirm modal stores human-readable group label instead of raw groupId - Confirmed group bookings appear in Reminders tab Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
209
src/app/admin/bookings/AddBookingModal.tsx
Normal file
209
src/app/admin/bookings/AddBookingModal.tsx
Normal file
@@ -0,0 +1,209 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useState, useEffect } from "react";
|
||||||
|
import { createPortal } from "react-dom";
|
||||||
|
import { X } from "lucide-react";
|
||||||
|
import { adminFetch } from "@/lib/csrf";
|
||||||
|
|
||||||
|
type Tab = "classes" | "events";
|
||||||
|
type EventType = "master-class" | "open-day";
|
||||||
|
|
||||||
|
interface McOption { title: string; date: string }
|
||||||
|
interface OdClass { id: number; style: string; time: string; hall: string }
|
||||||
|
interface OdEvent { id: number; date: string; title?: string }
|
||||||
|
|
||||||
|
export function AddBookingModal({
|
||||||
|
open,
|
||||||
|
onClose,
|
||||||
|
onAdded,
|
||||||
|
}: {
|
||||||
|
open: boolean;
|
||||||
|
onClose: () => void;
|
||||||
|
onAdded: () => void;
|
||||||
|
}) {
|
||||||
|
const [tab, setTab] = useState<Tab>("classes");
|
||||||
|
const [eventType, setEventType] = useState<EventType>("master-class");
|
||||||
|
const [name, setName] = useState("");
|
||||||
|
const [phone, setPhone] = useState("");
|
||||||
|
const [mcTitle, setMcTitle] = useState("");
|
||||||
|
const [mcOptions, setMcOptions] = useState<McOption[]>([]);
|
||||||
|
const [odClasses, setOdClasses] = useState<OdClass[]>([]);
|
||||||
|
const [odEventId, setOdEventId] = useState<number | null>(null);
|
||||||
|
const [odClassId, setOdClassId] = useState("");
|
||||||
|
const [saving, setSaving] = useState(false);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!open) return;
|
||||||
|
setName(""); setPhone(""); setMcTitle(""); setOdClassId("");
|
||||||
|
|
||||||
|
// Fetch upcoming MCs (filter out expired)
|
||||||
|
adminFetch("/api/admin/sections/masterClasses").then((r) => r.json()).then((data: { items?: { title: string; slots: { date: string }[] }[] }) => {
|
||||||
|
const today = new Date().toISOString().split("T")[0];
|
||||||
|
const upcoming = (data.items || [])
|
||||||
|
.filter((mc) => mc.slots?.some((s) => s.date >= today))
|
||||||
|
.map((mc) => ({
|
||||||
|
title: mc.title,
|
||||||
|
date: mc.slots.reduce((latest, s) => s.date > latest ? s.date : latest, ""),
|
||||||
|
}));
|
||||||
|
setMcOptions(upcoming);
|
||||||
|
if (upcoming.length === 0 && tab === "events") setEventType("open-day");
|
||||||
|
}).catch(() => {});
|
||||||
|
|
||||||
|
// Fetch active Open Day event + classes
|
||||||
|
adminFetch("/api/admin/open-day").then((r) => r.json()).then(async (events: OdEvent[]) => {
|
||||||
|
const today = new Date().toISOString().split("T")[0];
|
||||||
|
const active = events.find((e) => e.date >= today);
|
||||||
|
if (!active) { setOdEventId(null); setOdClasses([]); return; }
|
||||||
|
setOdEventId(active.id);
|
||||||
|
const classes = await adminFetch(`/api/admin/open-day/classes?eventId=${active.id}`).then((r) => r.json());
|
||||||
|
setOdClasses(classes);
|
||||||
|
}).catch(() => {});
|
||||||
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||||
|
}, [open]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!open) return;
|
||||||
|
function onKey(e: KeyboardEvent) { if (e.key === "Escape") onClose(); }
|
||||||
|
document.addEventListener("keydown", onKey);
|
||||||
|
return () => document.removeEventListener("keydown", onKey);
|
||||||
|
}, [open, onClose]);
|
||||||
|
|
||||||
|
const hasUpcomingMc = mcOptions.length > 0;
|
||||||
|
const hasOpenDay = odEventId !== null && odClasses.length > 0;
|
||||||
|
const hasEvents = hasUpcomingMc || hasOpenDay;
|
||||||
|
|
||||||
|
async function handleSubmit() {
|
||||||
|
if (!name.trim() || !phone.trim()) return;
|
||||||
|
setSaving(true);
|
||||||
|
try {
|
||||||
|
if (tab === "classes") {
|
||||||
|
await adminFetch("/api/admin/group-bookings", {
|
||||||
|
method: "POST",
|
||||||
|
headers: { "Content-Type": "application/json" },
|
||||||
|
body: JSON.stringify({ name: name.trim(), phone: phone.trim() }),
|
||||||
|
});
|
||||||
|
} else if (eventType === "master-class") {
|
||||||
|
const title = mcTitle || mcOptions[0]?.title || "Мастер-класс";
|
||||||
|
await adminFetch("/api/admin/mc-registrations", {
|
||||||
|
method: "POST",
|
||||||
|
headers: { "Content-Type": "application/json" },
|
||||||
|
body: JSON.stringify({ masterClassTitle: title, name: name.trim(), instagram: "-", phone: phone.trim() }),
|
||||||
|
});
|
||||||
|
} else if (eventType === "open-day" && odClassId && odEventId) {
|
||||||
|
await adminFetch("/api/open-day-register", {
|
||||||
|
method: "POST",
|
||||||
|
headers: { "Content-Type": "application/json" },
|
||||||
|
body: JSON.stringify({ classId: Number(odClassId), eventId: odEventId, name: name.trim(), phone: phone.trim() }),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
onAdded();
|
||||||
|
onClose();
|
||||||
|
} finally {
|
||||||
|
setSaving(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!open) return null;
|
||||||
|
|
||||||
|
const inputClass = "w-full rounded-lg border border-white/[0.08] bg-white/[0.04] px-3 py-2 text-sm text-white outline-none focus:border-gold/40 placeholder-neutral-500";
|
||||||
|
const tabBtn = (key: Tab, label: string, disabled?: boolean) => (
|
||||||
|
<button
|
||||||
|
key={key}
|
||||||
|
onClick={() => !disabled && setTab(key)}
|
||||||
|
disabled={disabled}
|
||||||
|
className={`flex-1 rounded-lg py-2 text-xs font-medium transition-all ${
|
||||||
|
tab === key ? "bg-gold/20 text-gold border border-gold/40" : "bg-neutral-800 text-neutral-400 border border-white/10 hover:text-white disabled:opacity-30 disabled:cursor-not-allowed"
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
{label}
|
||||||
|
</button>
|
||||||
|
);
|
||||||
|
|
||||||
|
const canSubmit = name.trim() && phone.trim() && !saving
|
||||||
|
&& (tab === "classes" || (tab === "events" && eventType === "master-class" && hasUpcomingMc)
|
||||||
|
|| (tab === "events" && eventType === "open-day" && odClassId));
|
||||||
|
|
||||||
|
return createPortal(
|
||||||
|
<div className="fixed inset-0 z-50 flex items-center justify-center p-4" onClick={onClose}>
|
||||||
|
<div className="absolute inset-0 bg-black/70 backdrop-blur-sm" />
|
||||||
|
<div className="relative w-full max-w-sm rounded-2xl border border-white/[0.08] bg-[#0a0a0a] p-6 shadow-2xl" onClick={(e) => e.stopPropagation()}>
|
||||||
|
<button onClick={onClose} className="absolute right-3 top-3 flex h-7 w-7 items-center justify-center rounded-full text-neutral-500 hover:bg-white/[0.06] hover:text-white">
|
||||||
|
<X size={16} />
|
||||||
|
</button>
|
||||||
|
|
||||||
|
<h3 className="text-base font-bold text-white">Добавить запись</h3>
|
||||||
|
<p className="mt-1 text-xs text-neutral-400">Ручная запись (Instagram, звонок, лично)</p>
|
||||||
|
|
||||||
|
<div className="mt-4 space-y-3">
|
||||||
|
{/* Tab: Classes vs Events */}
|
||||||
|
<div className="flex gap-2">
|
||||||
|
{tabBtn("classes", "Занятие")}
|
||||||
|
{tabBtn("events", "Мероприятие", !hasEvents)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Events sub-selector */}
|
||||||
|
{tab === "events" && (
|
||||||
|
<div className="flex gap-2">
|
||||||
|
{hasUpcomingMc && (
|
||||||
|
<button
|
||||||
|
onClick={() => setEventType("master-class")}
|
||||||
|
className={`flex-1 rounded-lg py-1.5 text-[11px] font-medium transition-all ${
|
||||||
|
eventType === "master-class" ? "bg-purple-500/15 text-purple-400 border border-purple-500/30" : "bg-neutral-800/50 text-neutral-500 border border-white/5 hover:text-neutral-300"
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
Мастер-класс
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
{hasOpenDay && (
|
||||||
|
<button
|
||||||
|
onClick={() => setEventType("open-day")}
|
||||||
|
className={`flex-1 rounded-lg py-1.5 text-[11px] font-medium transition-all ${
|
||||||
|
eventType === "open-day" ? "bg-blue-500/15 text-blue-400 border border-blue-500/30" : "bg-neutral-800/50 text-neutral-500 border border-white/5 hover:text-neutral-300"
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
Open Day
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* MC selector */}
|
||||||
|
{tab === "events" && eventType === "master-class" && mcOptions.length > 0 && (
|
||||||
|
<select value={mcTitle} onChange={(e) => setMcTitle(e.target.value)} className={inputClass + " [color-scheme:dark]"}>
|
||||||
|
<option value="" className="bg-neutral-900">Выберите мастер-класс</option>
|
||||||
|
{mcOptions.map((mc) => (
|
||||||
|
<option key={mc.title} value={mc.title} className="bg-neutral-900">
|
||||||
|
{mc.title}
|
||||||
|
</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Open Day class selector */}
|
||||||
|
{tab === "events" && eventType === "open-day" && odClasses.length > 0 && (
|
||||||
|
<select value={odClassId} onChange={(e) => setOdClassId(e.target.value)} className={inputClass + " [color-scheme:dark]"}>
|
||||||
|
<option value="" className="bg-neutral-900">Выберите занятие</option>
|
||||||
|
{odClasses.map((c) => (
|
||||||
|
<option key={c.id} value={c.id} className="bg-neutral-900">
|
||||||
|
{c.time} · {c.style} · {c.hall}
|
||||||
|
</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<input type="text" value={name} onChange={(e) => setName(e.target.value)} placeholder="Имя" className={inputClass} />
|
||||||
|
<input type="tel" value={phone} onChange={(e) => setPhone(e.target.value)} placeholder="Телефон" className={inputClass} />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<button
|
||||||
|
onClick={handleSubmit}
|
||||||
|
disabled={!canSubmit}
|
||||||
|
className="mt-5 w-full rounded-lg bg-gold py-2.5 text-sm font-semibold text-black transition-all hover:bg-gold-light disabled:opacity-30 disabled:cursor-not-allowed"
|
||||||
|
>
|
||||||
|
{saving ? "Сохраняю..." : "Добавить"}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>,
|
||||||
|
document.body
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -1,25 +1,7 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import { Loader2, Trash2, Phone, Instagram, Send } from "lucide-react";
|
import { Loader2, Trash2, Phone, Instagram, Send } from "lucide-react";
|
||||||
|
import { type BookingStatus, type BookingFilter, BOOKING_STATUSES } from "./types";
|
||||||
// --- 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() {
|
export function LoadingSpinner() {
|
||||||
return (
|
return (
|
||||||
@@ -115,28 +97,21 @@ export function StatusBadge({ status }: { status: BookingStatus }) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export function StatusActions({ status, onStatus }: { status: BookingStatus; onStatus: (s: BookingStatus) => void }) {
|
export function StatusActions({ status, onStatus }: { status: BookingStatus; onStatus: (s: BookingStatus) => void }) {
|
||||||
|
const actionBtn = (label: string, onClick: () => void, cls: string) => (
|
||||||
|
<button onClick={onClick} className={`inline-flex items-center gap-1 rounded-full px-2.5 py-1 text-[10px] font-medium transition-all ${cls}`}>
|
||||||
|
{label}
|
||||||
|
</button>
|
||||||
|
);
|
||||||
return (
|
return (
|
||||||
<div className="flex gap-1 ml-auto">
|
<div className="flex gap-1 ml-auto">
|
||||||
{status === "new" && (
|
{status === "new" && actionBtn("Связались →", () => onStatus("contacted"), "bg-blue-500/10 text-blue-400 border border-blue-500/30 hover:bg-blue-500/20")}
|
||||||
<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" && (
|
{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">
|
{actionBtn("Подтвердить", () => onStatus("confirmed"), "bg-emerald-500/10 text-emerald-400 border border-emerald-500/30 hover:bg-emerald-500/20")}
|
||||||
Подтвердить
|
{actionBtn("Отказ", () => onStatus("declined"), "bg-red-500/10 text-red-400 border border-red-500/30 hover:bg-red-500/20")}
|
||||||
</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") && (
|
{(status === "confirmed" || status === "declined") && actionBtn("Вернуть", () => onStatus("contacted"), "bg-neutral-800/50 text-neutral-500 border border-transparent hover:border-white/10 hover:text-neutral-300")}
|
||||||
<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>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -155,18 +130,3 @@ export function BookingCard({ status, children }: { status: BookingStatus; child
|
|||||||
</div>
|
</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));
|
|
||||||
}
|
|
||||||
178
src/app/admin/bookings/GenericBookingsList.tsx
Normal file
178
src/app/admin/bookings/GenericBookingsList.tsx
Normal file
@@ -0,0 +1,178 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useState, useMemo } from "react";
|
||||||
|
import { ChevronDown, ChevronRight, Archive } from "lucide-react";
|
||||||
|
import { adminFetch } from "@/lib/csrf";
|
||||||
|
import { type BookingStatus, type BookingFilter, type BaseBooking, type BookingGroup, countStatuses, sortByStatus } from "./types";
|
||||||
|
import { FilterTabs, EmptyState, BookingCard, ContactLinks, StatusBadge, StatusActions, DeleteBtn } from "./BookingComponents";
|
||||||
|
import { fmtDate } from "./types";
|
||||||
|
import { InlineNotes } from "./InlineNotes";
|
||||||
|
|
||||||
|
interface GenericBookingsListProps<T extends BaseBooking> {
|
||||||
|
items: T[];
|
||||||
|
endpoint: string;
|
||||||
|
onItemsChange: (fn: (prev: T[]) => T[]) => void;
|
||||||
|
groups?: BookingGroup<T>[];
|
||||||
|
renderExtra?: (item: T) => React.ReactNode;
|
||||||
|
onConfirm?: (id: number) => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function GenericBookingsList<T extends BaseBooking>({
|
||||||
|
items,
|
||||||
|
endpoint,
|
||||||
|
onItemsChange,
|
||||||
|
groups,
|
||||||
|
renderExtra,
|
||||||
|
onConfirm,
|
||||||
|
}: GenericBookingsListProps<T>) {
|
||||||
|
const [filter, setFilter] = useState<BookingFilter>("all");
|
||||||
|
const [showArchived, setShowArchived] = useState(false);
|
||||||
|
const [expanded, setExpanded] = useState<Record<string, boolean>>({});
|
||||||
|
|
||||||
|
const counts = useMemo(() => countStatuses(items), [items]);
|
||||||
|
|
||||||
|
async function handleStatus(id: number, status: BookingStatus) {
|
||||||
|
if (status === "confirmed" && onConfirm) {
|
||||||
|
onConfirm(id);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
onItemsChange((prev) => prev.map((b) => b.id === id ? { ...b, status } : b));
|
||||||
|
await adminFetch(endpoint, {
|
||||||
|
method: "PUT",
|
||||||
|
headers: { "Content-Type": "application/json" },
|
||||||
|
body: JSON.stringify({ action: "set-status", id, status }),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async function handleDelete(id: number) {
|
||||||
|
await adminFetch(`${endpoint}?id=${id}`, { method: "DELETE" });
|
||||||
|
onItemsChange((prev) => prev.filter((b) => b.id !== id));
|
||||||
|
}
|
||||||
|
|
||||||
|
async function handleNotes(id: number, notes: string) {
|
||||||
|
onItemsChange((prev) => prev.map((b) => b.id === id ? { ...b, notes: notes || undefined } : b));
|
||||||
|
await adminFetch(endpoint, {
|
||||||
|
method: "PUT",
|
||||||
|
headers: { "Content-Type": "application/json" },
|
||||||
|
body: JSON.stringify({ action: "set-notes", id, notes }),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function renderItem(item: T, isArchived: boolean) {
|
||||||
|
return (
|
||||||
|
<BookingCard key={item.id} status={item.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">{item.name}</span>
|
||||||
|
<ContactLinks phone={item.phone} instagram={item.instagram} telegram={item.telegram} />
|
||||||
|
{renderExtra?.(item)}
|
||||||
|
</div>
|
||||||
|
<div className="flex items-center gap-2 shrink-0">
|
||||||
|
<span className="text-neutral-600 text-xs">{fmtDate(item.createdAt)}</span>
|
||||||
|
<DeleteBtn onClick={() => handleDelete(item.id)} />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className="flex items-center gap-2 mt-2 flex-wrap">
|
||||||
|
<StatusBadge status={item.status} />
|
||||||
|
{!isArchived && <StatusActions status={item.status} onStatus={(s) => handleStatus(item.id, s)} />}
|
||||||
|
</div>
|
||||||
|
<InlineNotes value={item.notes || ""} onSave={(notes) => handleNotes(item.id, notes)} />
|
||||||
|
</BookingCard>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (groups) {
|
||||||
|
const filteredGroups = groups.map((g) => ({
|
||||||
|
...g,
|
||||||
|
items: filter === "all" ? sortByStatus(g.items) : sortByStatus(g.items.filter((b) => b.status === filter)),
|
||||||
|
})).filter((g) => g.items.length > 0);
|
||||||
|
|
||||||
|
const activeGroups = filteredGroups.filter((g) => !g.isArchived);
|
||||||
|
const archivedGroups = filteredGroups.filter((g) => g.isArchived);
|
||||||
|
const archivedCount = archivedGroups.reduce((sum, g) => sum + g.items.length, 0);
|
||||||
|
|
||||||
|
function renderGroup(group: BookingGroup<T>) {
|
||||||
|
const isOpen = expanded[group.key] ?? !group.isArchived;
|
||||||
|
const groupCounts = countStatuses(group.items);
|
||||||
|
return (
|
||||||
|
<div key={group.key} className={`rounded-xl border overflow-hidden ${group.isArchived ? "border-white/5 opacity-60" : "border-white/10"}`}>
|
||||||
|
<button
|
||||||
|
onClick={() => setExpanded((p) => ({ ...p, [group.key]: !isOpen }))}
|
||||||
|
className={`w-full flex items-center gap-3 px-4 py-3 transition-colors text-left ${group.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" />}
|
||||||
|
{group.sublabel && (
|
||||||
|
<span className={`text-xs font-medium shrink-0 ${group.isArchived ? "text-neutral-500" : "text-gold"}`}>{group.sublabel}</span>
|
||||||
|
)}
|
||||||
|
<span className={`font-medium text-sm truncate ${group.isArchived ? "text-neutral-400" : "text-white"}`}>{group.label}</span>
|
||||||
|
{group.dateBadge && (
|
||||||
|
<span className={`text-[10px] rounded-full px-2 py-0.5 shrink-0 ${
|
||||||
|
group.isArchived ? "text-neutral-600 bg-neutral-800 line-through" : "text-gold bg-gold/10"
|
||||||
|
}`}>
|
||||||
|
{group.dateBadge}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
{group.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">{group.items.length} чел.</span>
|
||||||
|
{!group.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">
|
||||||
|
{group.items.map((item) => renderItem(item, group.isArchived))}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div>
|
||||||
|
<FilterTabs filter={filter} counts={counts} total={items.length} onFilter={setFilter} />
|
||||||
|
<div className="mt-3 space-y-2">
|
||||||
|
{activeGroups.length === 0 && archivedGroups.length === 0 && <EmptyState total={items.length} />}
|
||||||
|
{activeGroups.map(renderGroup)}
|
||||||
|
</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(renderGroup)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const filtered = useMemo(() => {
|
||||||
|
const list = filter === "all" ? items : items.filter((b) => b.status === filter);
|
||||||
|
return sortByStatus(list);
|
||||||
|
}, [items, filter]);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div>
|
||||||
|
<FilterTabs filter={filter} counts={counts} total={items.length} onFilter={setFilter} />
|
||||||
|
<div className="mt-3 space-y-2">
|
||||||
|
{filtered.length === 0 && <EmptyState total={items.length} />}
|
||||||
|
{filtered.map((item) => renderItem(item, false))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
68
src/app/admin/bookings/InlineNotes.tsx
Normal file
68
src/app/admin/bookings/InlineNotes.tsx
Normal file
@@ -0,0 +1,68 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useState, useRef, useCallback, useEffect } from "react";
|
||||||
|
import { StickyNote } from "lucide-react";
|
||||||
|
|
||||||
|
export function InlineNotes({ value, onSave }: { value: string; onSave: (notes: string) => void }) {
|
||||||
|
const [editing, setEditing] = useState(false);
|
||||||
|
const [text, setText] = useState(value);
|
||||||
|
const timerRef = useRef<ReturnType<typeof setTimeout>>(undefined);
|
||||||
|
const textareaRef = useRef<HTMLTextAreaElement>(null);
|
||||||
|
|
||||||
|
useEffect(() => { setText(value); }, [value]);
|
||||||
|
|
||||||
|
const save = useCallback((v: string) => {
|
||||||
|
clearTimeout(timerRef.current);
|
||||||
|
timerRef.current = setTimeout(() => onSave(v), 800);
|
||||||
|
}, [onSave]);
|
||||||
|
|
||||||
|
function handleChange(v: string) {
|
||||||
|
setText(v);
|
||||||
|
save(v);
|
||||||
|
}
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (editing && textareaRef.current) {
|
||||||
|
textareaRef.current.focus();
|
||||||
|
textareaRef.current.selectionStart = textareaRef.current.value.length;
|
||||||
|
}
|
||||||
|
}, [editing]);
|
||||||
|
|
||||||
|
if (!editing && !value) {
|
||||||
|
return (
|
||||||
|
<button
|
||||||
|
onClick={() => setEditing(true)}
|
||||||
|
className="mt-2 inline-flex items-center gap-1.5 text-[11px] text-neutral-600 hover:text-neutral-400 transition-colors"
|
||||||
|
>
|
||||||
|
<StickyNote size={11} />
|
||||||
|
Добавить заметку...
|
||||||
|
</button>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!editing) {
|
||||||
|
return (
|
||||||
|
<button
|
||||||
|
onClick={() => setEditing(true)}
|
||||||
|
className="mt-2 flex items-start gap-1.5 rounded-md bg-amber-500/[0.06] border border-amber-500/10 px-2.5 py-1.5 text-left transition-colors hover:bg-amber-500/10"
|
||||||
|
>
|
||||||
|
<StickyNote size={11} className="shrink-0 mt-0.5 text-amber-500/60" />
|
||||||
|
<span className="text-[11px] text-amber-200/70 leading-relaxed whitespace-pre-wrap">{value}</span>
|
||||||
|
</button>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="mt-2">
|
||||||
|
<textarea
|
||||||
|
ref={textareaRef}
|
||||||
|
value={text}
|
||||||
|
onChange={(e) => handleChange(e.target.value)}
|
||||||
|
onBlur={() => { if (!text.trim()) { onSave(""); } setEditing(false); }}
|
||||||
|
placeholder="Заметка..."
|
||||||
|
rows={2}
|
||||||
|
className="w-full rounded-md border border-amber-500/20 bg-amber-500/[0.06] px-2.5 py-1.5 text-[11px] text-amber-200/80 placeholder-neutral-600 outline-none focus:border-amber-500/40 resize-none"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
80
src/app/admin/bookings/McRegistrationsTab.tsx
Normal file
80
src/app/admin/bookings/McRegistrationsTab.tsx
Normal file
@@ -0,0 +1,80 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useState, useEffect, useMemo } from "react";
|
||||||
|
import { adminFetch } from "@/lib/csrf";
|
||||||
|
import { type BaseBooking, type BookingGroup } from "./types";
|
||||||
|
import { LoadingSpinner } from "./BookingComponents";
|
||||||
|
import { GenericBookingsList } from "./GenericBookingsList";
|
||||||
|
|
||||||
|
interface McRegistration extends BaseBooking {
|
||||||
|
masterClassTitle: 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>>({});
|
||||||
|
const [loading, setLoading] = useState(true);
|
||||||
|
|
||||||
|
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);
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
const regTitles = new Set(regData.map((r) => r.masterClassTitle));
|
||||||
|
for (const regTitle of regTitles) {
|
||||||
|
if (dates[regTitle]) continue;
|
||||||
|
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];
|
||||||
|
|
||||||
|
const groups = useMemo((): BookingGroup<McRegistration>[] => {
|
||||||
|
const map: Record<string, McRegistration[]> = {};
|
||||||
|
for (const r of regs) {
|
||||||
|
if (!map[r.masterClassTitle]) map[r.masterClassTitle] = [];
|
||||||
|
map[r.masterClassTitle].push(r);
|
||||||
|
}
|
||||||
|
return Object.entries(map).map(([title, items]) => {
|
||||||
|
const date = mcDates[title];
|
||||||
|
const isArchived = !date || date < today;
|
||||||
|
return {
|
||||||
|
key: title,
|
||||||
|
label: title,
|
||||||
|
dateBadge: date ? new Date(date + "T12:00").toLocaleDateString("ru-RU", { day: "numeric", month: "short" }) : undefined,
|
||||||
|
items,
|
||||||
|
isArchived,
|
||||||
|
};
|
||||||
|
});
|
||||||
|
}, [regs, mcDates, today]);
|
||||||
|
|
||||||
|
if (loading) return <LoadingSpinner />;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<GenericBookingsList<McRegistration>
|
||||||
|
items={regs}
|
||||||
|
endpoint="/api/admin/mc-registrations"
|
||||||
|
onItemsChange={setRegs}
|
||||||
|
groups={groups}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
86
src/app/admin/bookings/OpenDayBookingsTab.tsx
Normal file
86
src/app/admin/bookings/OpenDayBookingsTab.tsx
Normal file
@@ -0,0 +1,86 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useState, useEffect, useMemo } from "react";
|
||||||
|
import { adminFetch } from "@/lib/csrf";
|
||||||
|
import { type BaseBooking, type BookingGroup } from "./types";
|
||||||
|
import { LoadingSpinner } from "./BookingComponents";
|
||||||
|
import { GenericBookingsList } from "./GenericBookingsList";
|
||||||
|
|
||||||
|
interface OpenDayBooking extends BaseBooking {
|
||||||
|
classId: number;
|
||||||
|
eventId: number;
|
||||||
|
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);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
adminFetch("/api/admin/open-day")
|
||||||
|
.then((r) => r.json())
|
||||||
|
.then(async (evts: EventInfo[]) => {
|
||||||
|
setEvents(evts);
|
||||||
|
if (evts.length === 0) return;
|
||||||
|
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]);
|
||||||
|
|
||||||
|
const groups = useMemo((): BookingGroup<OpenDayBooking>[] => {
|
||||||
|
const map: Record<string, { hall: string; time: string; style: string; trainer: string; items: OpenDayBooking[]; eventId: number }> = {};
|
||||||
|
for (const b of bookings) {
|
||||||
|
const key = `${b.eventId}|${b.classHall}|${b.classTime}|${b.classStyle}`;
|
||||||
|
if (!map[key]) map[key] = { hall: b.classHall || "—", time: b.classTime || "—", style: b.classStyle || "—", trainer: b.classTrainer || "—", items: [], eventId: b.eventId };
|
||||||
|
map[key].items.push(b);
|
||||||
|
}
|
||||||
|
return Object.entries(map)
|
||||||
|
.sort(([, a], [, b]) => {
|
||||||
|
const hallCmp = a.hall.localeCompare(b.hall);
|
||||||
|
return hallCmp !== 0 ? hallCmp : a.time.localeCompare(b.time);
|
||||||
|
})
|
||||||
|
.map(([key, g]) => {
|
||||||
|
const eventDate = eventDateMap[g.eventId];
|
||||||
|
const isArchived = eventDate ? eventDate < today : false;
|
||||||
|
return {
|
||||||
|
key,
|
||||||
|
label: g.style,
|
||||||
|
sublabel: g.time,
|
||||||
|
dateBadge: isArchived && eventDate ? new Date(eventDate + "T12:00").toLocaleDateString("ru-RU", { day: "numeric", month: "short" }) : undefined,
|
||||||
|
items: g.items,
|
||||||
|
isArchived,
|
||||||
|
};
|
||||||
|
});
|
||||||
|
}, [bookings, eventDateMap, today]);
|
||||||
|
|
||||||
|
if (loading) return <LoadingSpinner />;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<GenericBookingsList<OpenDayBooking>
|
||||||
|
items={bookings}
|
||||||
|
endpoint="/api/admin/open-day/bookings"
|
||||||
|
onItemsChange={setBookings}
|
||||||
|
groups={groups}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
55
src/app/admin/bookings/SearchBar.tsx
Normal file
55
src/app/admin/bookings/SearchBar.tsx
Normal file
@@ -0,0 +1,55 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useState, useRef } from "react";
|
||||||
|
import { Search, X } from "lucide-react";
|
||||||
|
import { adminFetch } from "@/lib/csrf";
|
||||||
|
import type { SearchResult } from "./types";
|
||||||
|
|
||||||
|
export function SearchBar({
|
||||||
|
onResults,
|
||||||
|
onClear,
|
||||||
|
}: {
|
||||||
|
onResults: (results: SearchResult[]) => void;
|
||||||
|
onClear: () => void;
|
||||||
|
}) {
|
||||||
|
const [query, setQuery] = useState("");
|
||||||
|
const timerRef = useRef<ReturnType<typeof setTimeout>>(undefined);
|
||||||
|
|
||||||
|
function handleChange(q: string) {
|
||||||
|
setQuery(q);
|
||||||
|
clearTimeout(timerRef.current);
|
||||||
|
if (q.trim().length < 2) {
|
||||||
|
onClear();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
timerRef.current = setTimeout(() => {
|
||||||
|
adminFetch(`/api/admin/bookings/search?q=${encodeURIComponent(q.trim())}`)
|
||||||
|
.then((r) => r.json())
|
||||||
|
.then((data: SearchResult[]) => onResults(data))
|
||||||
|
.catch(() => {});
|
||||||
|
}, 400);
|
||||||
|
}
|
||||||
|
|
||||||
|
function clear() {
|
||||||
|
setQuery("");
|
||||||
|
onClear();
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="relative">
|
||||||
|
<Search size={14} className="absolute left-3 top-1/2 -translate-y-1/2 text-neutral-500" />
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
value={query}
|
||||||
|
onChange={(e) => handleChange(e.target.value)}
|
||||||
|
placeholder="Поиск по имени или телефону..."
|
||||||
|
className="w-full rounded-lg border border-white/[0.08] bg-white/[0.04] py-2 pl-9 pr-8 text-sm text-white placeholder-neutral-500 outline-none focus:border-gold/40"
|
||||||
|
/>
|
||||||
|
{query && (
|
||||||
|
<button onClick={clear} className="absolute right-2 top-1/2 -translate-y-1/2 text-neutral-500 hover:text-white">
|
||||||
|
<X size={14} />
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -1,198 +0,0 @@
|
|||||||
"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>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -1,202 +0,0 @@
|
|||||||
"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>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -2,17 +2,15 @@
|
|||||||
|
|
||||||
import { useState, useEffect, useMemo, useCallback, useRef } from "react";
|
import { useState, useEffect, useMemo, useCallback, useRef } from "react";
|
||||||
import { createPortal } from "react-dom";
|
import { createPortal } from "react-dom";
|
||||||
import { 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, Plus } from "lucide-react";
|
||||||
import { adminFetch } from "@/lib/csrf";
|
import { adminFetch } from "@/lib/csrf";
|
||||||
import {
|
import { type BookingStatus, type SearchResult, BOOKING_STATUSES, SHORT_DAYS, fmtDate } from "./types";
|
||||||
type BookingStatus, type BookingFilter,
|
import { LoadingSpinner, ContactLinks, BookingCard, StatusBadge, DeleteBtn } from "./BookingComponents";
|
||||||
BOOKING_STATUSES, SHORT_DAYS,
|
import { GenericBookingsList } from "./GenericBookingsList";
|
||||||
LoadingSpinner, EmptyState, DeleteBtn, ContactLinks,
|
import { AddBookingModal } from "./AddBookingModal";
|
||||||
FilterTabs, StatusBadge, StatusActions, BookingCard,
|
import { SearchBar } from "./SearchBar";
|
||||||
fmtDate, countStatuses,
|
import { McRegistrationsTab } from "./McRegistrationsTab";
|
||||||
} from "./_shared";
|
import { OpenDayBookingsTab } from "./OpenDayBookingsTab";
|
||||||
import { McRegistrationsTab } from "./_McRegistrationsTab";
|
|
||||||
import { OpenDayBookingsTab } from "./_OpenDayBookingsTab";
|
|
||||||
|
|
||||||
// --- Types ---
|
// --- Types ---
|
||||||
|
|
||||||
@@ -203,7 +201,8 @@ function ConfirmModal({
|
|||||||
<button
|
<button
|
||||||
onClick={() => {
|
onClick={() => {
|
||||||
if (group && date) {
|
if (group && date) {
|
||||||
onConfirm({ group, date, comment: comment.trim() || undefined });
|
const groupLabel = groups.find((g) => g.value === group)?.label || group;
|
||||||
|
onConfirm({ group: groupLabel, date, comment: comment.trim() || undefined });
|
||||||
}
|
}
|
||||||
}}
|
}}
|
||||||
disabled={!group || !date}
|
disabled={!group || !date}
|
||||||
@@ -226,7 +225,7 @@ function GroupBookingsTab() {
|
|||||||
const [bookings, setBookings] = useState<GroupBooking[]>([]);
|
const [bookings, setBookings] = useState<GroupBooking[]>([]);
|
||||||
const [allClasses, setAllClasses] = useState<ScheduleClassInfo[]>([]);
|
const [allClasses, setAllClasses] = useState<ScheduleClassInfo[]>([]);
|
||||||
const [loading, setLoading] = useState(true);
|
const [loading, setLoading] = useState(true);
|
||||||
const [filter, setFilter] = useState<BookingFilter>("all");
|
const [confirmingId, setConfirmingId] = useState<number | null>(null);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
Promise.all([
|
Promise.all([
|
||||||
@@ -240,15 +239,7 @@ function GroupBookingsTab() {
|
|||||||
const shortAddr = loc.address?.split(",")[0] || loc.name;
|
const shortAddr = loc.address?.split(",")[0] || loc.name;
|
||||||
for (const day of loc.days) {
|
for (const day of loc.days) {
|
||||||
for (const cls of day.classes) {
|
for (const cls of day.classes) {
|
||||||
classes.push({
|
classes.push({ type: cls.type, trainer: cls.trainer, time: cls.time, day: day.day, hall: loc.name, address: shortAddr, groupId: cls.groupId });
|
||||||
type: cls.type,
|
|
||||||
trainer: cls.trainer,
|
|
||||||
time: cls.time,
|
|
||||||
day: day.day,
|
|
||||||
hall: loc.name,
|
|
||||||
address: shortAddr,
|
|
||||||
groupId: cls.groupId,
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -258,163 +249,54 @@ function GroupBookingsTab() {
|
|||||||
.finally(() => setLoading(false));
|
.finally(() => setLoading(false));
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
const counts = useMemo(() => {
|
|
||||||
const c: Record<string, number> = { new: 0, contacted: 0, confirmed: 0, declined: 0 };
|
|
||||||
for (const b of bookings) c[b.status] = (c[b.status] || 0) + 1;
|
|
||||||
return c;
|
|
||||||
}, [bookings]);
|
|
||||||
|
|
||||||
const filtered = useMemo(() => {
|
|
||||||
const list = filter === "all" ? bookings : bookings.filter((b) => b.status === filter);
|
|
||||||
const order: Record<string, number> = { new: 0, contacted: 1, confirmed: 2, declined: 3 };
|
|
||||||
return [...list].sort((a, b) => (order[a.status] ?? 0) - (order[b.status] ?? 0));
|
|
||||||
}, [bookings, filter]);
|
|
||||||
|
|
||||||
const [confirmingId, setConfirmingId] = useState<number | null>(null);
|
|
||||||
const confirmingBooking = bookings.find((b) => b.id === confirmingId);
|
const confirmingBooking = bookings.find((b) => b.id === confirmingId);
|
||||||
|
|
||||||
async function handleStatus(id: number, status: BookingStatus, confirmation?: { group: string; date: string; comment?: string }) {
|
async function handleConfirm(data: { group: string; date: string; comment?: string }) {
|
||||||
setBookings((prev) => prev.map((b) => b.id === id ? {
|
if (!confirmingId) return;
|
||||||
...b, status,
|
const existing = bookings.find((b) => b.id === confirmingId);
|
||||||
confirmedDate: confirmation?.date,
|
const notes = data.comment
|
||||||
confirmedGroup: confirmation?.group,
|
? (existing?.notes ? `${existing.notes}\n${data.comment}` : data.comment)
|
||||||
confirmedComment: confirmation?.comment,
|
: existing?.notes;
|
||||||
|
setBookings((prev) => prev.map((b) => b.id === confirmingId ? {
|
||||||
|
...b, status: "confirmed" as BookingStatus,
|
||||||
|
confirmedDate: data.date, confirmedGroup: data.group, notes,
|
||||||
} : b));
|
} : b));
|
||||||
await adminFetch("/api/admin/group-bookings", {
|
await Promise.all([
|
||||||
|
adminFetch("/api/admin/group-bookings", {
|
||||||
method: "PUT",
|
method: "PUT",
|
||||||
headers: { "Content-Type": "application/json" },
|
headers: { "Content-Type": "application/json" },
|
||||||
body: JSON.stringify({ action: "set-status", id, status, confirmation }),
|
body: JSON.stringify({ action: "set-status", id: confirmingId, status: "confirmed", confirmation: { group: data.group, date: data.date } }),
|
||||||
});
|
}),
|
||||||
}
|
data.comment ? adminFetch("/api/admin/group-bookings", {
|
||||||
|
method: "PUT",
|
||||||
async function handleDelete(id: number) {
|
headers: { "Content-Type": "application/json" },
|
||||||
await adminFetch(`/api/admin/group-bookings?id=${id}`, { method: "DELETE" });
|
body: JSON.stringify({ action: "set-notes", id: confirmingId, notes: notes ?? "" }),
|
||||||
setBookings((prev) => prev.filter((b) => b.id !== id));
|
}) : Promise.resolve(),
|
||||||
|
]);
|
||||||
|
setConfirmingId(null);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (loading) return <LoadingSpinner />;
|
if (loading) return <LoadingSpinner />;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div>
|
<>
|
||||||
{/* Filter tabs */}
|
<GenericBookingsList<GroupBooking>
|
||||||
<div className="flex items-center gap-2 flex-wrap">
|
items={bookings}
|
||||||
<button
|
endpoint="/api/admin/group-bookings"
|
||||||
onClick={() => setFilter("all")}
|
onItemsChange={setBookings}
|
||||||
className={`rounded-full px-3 py-1.5 text-xs font-medium transition-all ${
|
onConfirm={(id) => setConfirmingId(id)}
|
||||||
filter === "all" ? "bg-gold/20 text-gold border border-gold/40" : "bg-neutral-800 text-neutral-400 border border-white/10 hover:text-white"
|
renderExtra={(b) => (
|
||||||
}`}
|
<>
|
||||||
>
|
{b.groupInfo && <span className="text-xs text-neutral-400 bg-neutral-800 rounded-full px-2 py-0.5">{b.groupInfo}</span>}
|
||||||
Все <span className="text-neutral-500 ml-1">{bookings.length}</span>
|
{b.status === "confirmed" && (b.confirmedGroup || b.confirmedDate) && (
|
||||||
</button>
|
|
||||||
{BOOKING_STATUSES.map((s) => (
|
|
||||||
<button
|
|
||||||
key={s.key}
|
|
||||||
onClick={() => setFilter(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>
|
|
||||||
|
|
||||||
{/* Bookings list */}
|
|
||||||
<div className="mt-3 space-y-2">
|
|
||||||
{filtered.length === 0 && <EmptyState total={bookings.length} />}
|
|
||||||
{filtered.map((b) => {
|
|
||||||
const statusConf = BOOKING_STATUSES.find((s) => s.key === b.status) || BOOKING_STATUSES[0];
|
|
||||||
return (
|
|
||||||
<div
|
|
||||||
key={b.id}
|
|
||||||
className={`rounded-xl border p-4 transition-colors ${
|
|
||||||
b.status === "declined" ? "border-red-500/15 bg-red-500/[0.02] opacity-50"
|
|
||||||
: b.status === "confirmed" ? "border-emerald-500/15 bg-emerald-500/[0.02]"
|
|
||||||
: b.status === "new" ? "border-gold/20 bg-gold/[0.03]"
|
|
||||||
: "border-white/10 bg-neutral-900"
|
|
||||||
}`}
|
|
||||||
>
|
|
||||||
<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>
|
|
||||||
<a href={`tel:${b.phone.replace(/\D/g, "")}`} 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>
|
|
||||||
)}
|
|
||||||
{b.groupInfo && (
|
|
||||||
<span className="text-xs text-neutral-400 bg-neutral-800 rounded-full px-2 py-0.5">{b.groupInfo}</span>
|
|
||||||
)}
|
|
||||||
</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>
|
|
||||||
{/* Linear status flow */}
|
|
||||||
<div className="flex items-center gap-2 mt-2 flex-wrap">
|
|
||||||
{/* Current status badge */}
|
|
||||||
<span className={`text-[10px] font-medium ${statusConf.bg} ${statusConf.color} border ${statusConf.border} rounded-full px-2.5 py-0.5`}>
|
|
||||||
{statusConf.label}
|
|
||||||
</span>
|
|
||||||
|
|
||||||
{b.status === "confirmed" && (
|
|
||||||
<span className="text-[10px] text-emerald-400/70">
|
<span className="text-[10px] text-emerald-400/70">
|
||||||
{b.confirmedGroup}
|
{b.confirmedGroup}
|
||||||
{b.confirmedDate && ` · ${new Date(b.confirmedDate + "T12:00").toLocaleDateString("ru-RU", { day: "numeric", month: "short" })}`}
|
{b.confirmedDate && ` · ${new Date(b.confirmedDate + "T12:00").toLocaleDateString("ru-RU", { day: "numeric", month: "short" })}`}
|
||||||
{b.confirmedComment && ` · ${b.confirmedComment}`}
|
|
||||||
</span>
|
</span>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{/* Action buttons based on current state */}
|
|
||||||
<div className="flex gap-1 ml-auto">
|
|
||||||
{b.status === "new" && (
|
|
||||||
<button
|
|
||||||
onClick={() => handleStatus(b.id, "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>
|
|
||||||
)}
|
|
||||||
{b.status === "contacted" && (
|
|
||||||
<>
|
|
||||||
<button
|
|
||||||
onClick={() => setConfirmingId(b.id)}
|
|
||||||
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={() => handleStatus(b.id, "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>
|
|
||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
{(b.status === "confirmed" || b.status === "declined") && (
|
/>
|
||||||
<button
|
|
||||||
onClick={() => handleStatus(b.id, "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>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
})}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<ConfirmModal
|
<ConfirmModal
|
||||||
open={confirmingId !== null}
|
open={confirmingId !== null}
|
||||||
@@ -422,12 +304,9 @@ function GroupBookingsTab() {
|
|||||||
groupInfo={confirmingBooking?.groupInfo}
|
groupInfo={confirmingBooking?.groupInfo}
|
||||||
allClasses={allClasses}
|
allClasses={allClasses}
|
||||||
onClose={() => setConfirmingId(null)}
|
onClose={() => setConfirmingId(null)}
|
||||||
onConfirm={(data) => {
|
onConfirm={handleConfirm}
|
||||||
if (confirmingId) handleStatus(confirmingId, "confirmed", data);
|
|
||||||
setConfirmingId(null);
|
|
||||||
}}
|
|
||||||
/>
|
/>
|
||||||
</div>
|
</>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -767,11 +646,77 @@ const TABS: { key: Tab; label: string }[] = [
|
|||||||
|
|
||||||
export default function BookingsPage() {
|
export default function BookingsPage() {
|
||||||
const [tab, setTab] = useState<Tab>("reminders");
|
const [tab, setTab] = useState<Tab>("reminders");
|
||||||
|
const [addOpen, setAddOpen] = useState(false);
|
||||||
|
const [searchResults, setSearchResults] = useState<SearchResult[] | null>(null);
|
||||||
|
const [refreshKey, setRefreshKey] = useState(0);
|
||||||
|
const lastTotalRef = useRef<number | null>(null);
|
||||||
|
|
||||||
|
// Poll for new bookings every 10s
|
||||||
|
useEffect(() => {
|
||||||
|
const id = setInterval(() => {
|
||||||
|
adminFetch("/api/admin/unread-counts")
|
||||||
|
.then((r) => r.json())
|
||||||
|
.then((data: { total: number }) => {
|
||||||
|
if (lastTotalRef.current !== null && data.total !== lastTotalRef.current) {
|
||||||
|
setRefreshKey((k) => k + 1);
|
||||||
|
}
|
||||||
|
lastTotalRef.current = data.total;
|
||||||
|
})
|
||||||
|
.catch(() => {});
|
||||||
|
}, 10000);
|
||||||
|
return () => clearInterval(id);
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const TYPE_LABELS: Record<string, string> = { class: "Занятие", mc: "Мастер-класс", "open-day": "Open Day" };
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div>
|
<div>
|
||||||
|
<div className="flex items-center gap-3">
|
||||||
<h1 className="text-2xl font-bold">Записи</h1>
|
<h1 className="text-2xl font-bold">Записи</h1>
|
||||||
|
<button
|
||||||
|
onClick={() => setAddOpen(true)}
|
||||||
|
className="flex h-8 w-8 items-center justify-center rounded-lg bg-gold/10 text-gold border border-gold/30 hover:bg-gold/20 transition-all"
|
||||||
|
title="Добавить запись"
|
||||||
|
>
|
||||||
|
<Plus size={16} />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Search */}
|
||||||
|
<div className="mt-3">
|
||||||
|
<SearchBar
|
||||||
|
onResults={setSearchResults}
|
||||||
|
onClear={() => setSearchResults(null)}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{searchResults ? (
|
||||||
|
/* Search results */
|
||||||
|
<div className="mt-4 space-y-2">
|
||||||
|
{searchResults.length === 0 ? (
|
||||||
|
<p className="text-sm text-neutral-500 py-8 text-center">Ничего не найдено</p>
|
||||||
|
) : (
|
||||||
|
searchResults.map((r) => (
|
||||||
|
<BookingCard key={`${r.type}-${r.id}`} status={r.status as BookingStatus}>
|
||||||
|
<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="text-[10px] text-neutral-500 bg-neutral-800 rounded-full px-2 py-0.5">{TYPE_LABELS[r.type] || r.type}</span>
|
||||||
|
<span className="font-medium text-white">{r.name}</span>
|
||||||
|
<ContactLinks phone={r.phone} instagram={r.instagram} telegram={r.telegram} />
|
||||||
|
{r.groupLabel && <span className="text-xs text-neutral-400 bg-neutral-800 rounded-full px-2 py-0.5">{r.groupLabel}</span>}
|
||||||
|
</div>
|
||||||
|
<span className="text-neutral-600 text-xs shrink-0">{fmtDate(r.createdAt)}</span>
|
||||||
|
</div>
|
||||||
|
<div className="flex items-center gap-2 mt-2">
|
||||||
|
<StatusBadge status={r.status as BookingStatus} />
|
||||||
|
{r.notes && <span className="text-[10px] text-neutral-500 truncate">{r.notes}</span>}
|
||||||
|
</div>
|
||||||
|
</BookingCard>
|
||||||
|
))
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
{/* Dashboard — what needs attention */}
|
{/* Dashboard — what needs attention */}
|
||||||
<DashboardSummary onNavigate={setTab} />
|
<DashboardSummary onNavigate={setTab} />
|
||||||
|
|
||||||
@@ -796,12 +741,20 @@ export default function BookingsPage() {
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Tab content */}
|
{/* Tab content */}
|
||||||
<div className="mt-4">
|
<div className="mt-4" key={refreshKey}>
|
||||||
{tab === "reminders" && <RemindersTab />}
|
{tab === "reminders" && <RemindersTab />}
|
||||||
{tab === "classes" && <GroupBookingsTab />}
|
{tab === "classes" && <GroupBookingsTab />}
|
||||||
{tab === "master-classes" && <McRegistrationsTab />}
|
{tab === "master-classes" && <McRegistrationsTab />}
|
||||||
{tab === "open-day" && <OpenDayBookingsTab />}
|
{tab === "open-day" && <OpenDayBookingsTab />}
|
||||||
</div>
|
</div>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<AddBookingModal
|
||||||
|
open={addOpen}
|
||||||
|
onClose={() => setAddOpen(false)}
|
||||||
|
onAdded={() => setRefreshKey((k) => k + 1)}
|
||||||
|
/>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
54
src/app/admin/bookings/types.ts
Normal file
54
src/app/admin/bookings/types.ts
Normal file
@@ -0,0 +1,54 @@
|
|||||||
|
export type BookingStatus = "new" | "contacted" | "confirmed" | "declined";
|
||||||
|
export type BookingFilter = "all" | BookingStatus;
|
||||||
|
|
||||||
|
export interface BaseBooking {
|
||||||
|
id: number;
|
||||||
|
name: string;
|
||||||
|
phone?: string;
|
||||||
|
instagram?: string;
|
||||||
|
telegram?: string;
|
||||||
|
status: BookingStatus;
|
||||||
|
notes?: string;
|
||||||
|
createdAt: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
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" },
|
||||||
|
];
|
||||||
|
|
||||||
|
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));
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface BookingGroup<T extends BaseBooking> {
|
||||||
|
key: string;
|
||||||
|
label: string;
|
||||||
|
sublabel?: string;
|
||||||
|
dateBadge?: string;
|
||||||
|
items: T[];
|
||||||
|
isArchived: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface SearchResult extends BaseBooking {
|
||||||
|
type: "class" | "mc" | "open-day";
|
||||||
|
groupLabel?: string;
|
||||||
|
}
|
||||||
@@ -53,7 +53,7 @@ export default function AdminLayout({
|
|||||||
const [unreadTotal, setUnreadTotal] = useState(0);
|
const [unreadTotal, setUnreadTotal] = useState(0);
|
||||||
const isLoginPage = pathname === "/admin/login";
|
const isLoginPage = pathname === "/admin/login";
|
||||||
|
|
||||||
// Fetch unread counts — poll every 30s
|
// Fetch unread counts — poll every 10s
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (isLoginPage) return;
|
if (isLoginPage) return;
|
||||||
function fetchCounts() {
|
function fetchCounts() {
|
||||||
@@ -63,7 +63,7 @@ export default function AdminLayout({
|
|||||||
.catch(() => {});
|
.catch(() => {});
|
||||||
}
|
}
|
||||||
fetchCounts();
|
fetchCounts();
|
||||||
const interval = setInterval(fetchCounts, 30000);
|
const interval = setInterval(fetchCounts, 10000);
|
||||||
return () => clearInterval(interval);
|
return () => clearInterval(interval);
|
||||||
}, [isLoginPage]);
|
}, [isLoginPage]);
|
||||||
|
|
||||||
|
|||||||
64
src/app/api/admin/bookings/search/route.ts
Normal file
64
src/app/api/admin/bookings/search/route.ts
Normal file
@@ -0,0 +1,64 @@
|
|||||||
|
import { NextRequest, NextResponse } from "next/server";
|
||||||
|
import { getDb } from "@/lib/db";
|
||||||
|
|
||||||
|
export async function GET(request: NextRequest) {
|
||||||
|
const q = request.nextUrl.searchParams.get("q")?.trim();
|
||||||
|
if (!q || q.length < 2) {
|
||||||
|
return NextResponse.json([]);
|
||||||
|
}
|
||||||
|
|
||||||
|
const db = getDb();
|
||||||
|
const like = `%${q}%`;
|
||||||
|
|
||||||
|
const groupRows = db.prepare(
|
||||||
|
"SELECT id, name, phone, instagram, telegram, status, notes, created_at, group_info FROM group_bookings WHERE name LIKE ? OR phone LIKE ? ORDER BY created_at DESC LIMIT 20"
|
||||||
|
).all(like, like) as { id: number; name: string; phone: string; instagram: string | null; telegram: string | null; status: string; notes: string | null; created_at: string; group_info: string | null }[];
|
||||||
|
|
||||||
|
const mcRows = db.prepare(
|
||||||
|
"SELECT id, name, phone, instagram, telegram, status, notes, created_at, master_class_title FROM mc_registrations WHERE name LIKE ? OR phone LIKE ? ORDER BY created_at DESC LIMIT 20"
|
||||||
|
).all(like, like) as { id: number; name: string; phone: string | null; instagram: string; telegram: string | null; status: string; notes: string | null; created_at: string; master_class_title: string }[];
|
||||||
|
|
||||||
|
const odRows = db.prepare(
|
||||||
|
"SELECT id, name, phone, instagram, telegram, status, notes, created_at FROM open_day_bookings WHERE name LIKE ? OR phone LIKE ? ORDER BY created_at DESC LIMIT 20"
|
||||||
|
).all(like, like) as { id: number; name: string; phone: string; instagram: string | null; telegram: string | null; status: string; notes: string | null; created_at: string }[];
|
||||||
|
|
||||||
|
const results = [
|
||||||
|
...groupRows.map((r) => ({
|
||||||
|
type: "class" as const,
|
||||||
|
id: r.id,
|
||||||
|
name: r.name,
|
||||||
|
phone: r.phone,
|
||||||
|
instagram: r.instagram ?? undefined,
|
||||||
|
telegram: r.telegram ?? undefined,
|
||||||
|
status: r.status || "new",
|
||||||
|
notes: r.notes ?? undefined,
|
||||||
|
createdAt: r.created_at,
|
||||||
|
groupLabel: r.group_info ?? undefined,
|
||||||
|
})),
|
||||||
|
...mcRows.map((r) => ({
|
||||||
|
type: "mc" as const,
|
||||||
|
id: r.id,
|
||||||
|
name: r.name,
|
||||||
|
phone: r.phone ?? undefined,
|
||||||
|
instagram: r.instagram ?? undefined,
|
||||||
|
telegram: r.telegram ?? undefined,
|
||||||
|
status: r.status || "new",
|
||||||
|
notes: r.notes ?? undefined,
|
||||||
|
createdAt: r.created_at,
|
||||||
|
groupLabel: r.master_class_title,
|
||||||
|
})),
|
||||||
|
...odRows.map((r) => ({
|
||||||
|
type: "open-day" as const,
|
||||||
|
id: r.id,
|
||||||
|
name: r.name,
|
||||||
|
phone: r.phone,
|
||||||
|
instagram: r.instagram ?? undefined,
|
||||||
|
telegram: r.telegram ?? undefined,
|
||||||
|
status: r.status || "new",
|
||||||
|
notes: r.notes ?? undefined,
|
||||||
|
createdAt: r.created_at,
|
||||||
|
})),
|
||||||
|
];
|
||||||
|
|
||||||
|
return NextResponse.json(results.slice(0, 50));
|
||||||
|
}
|
||||||
@@ -1,5 +1,5 @@
|
|||||||
import { NextRequest, NextResponse } from "next/server";
|
import { NextRequest, NextResponse } from "next/server";
|
||||||
import { getGroupBookings, toggleGroupBookingNotification, deleteGroupBooking, setGroupBookingStatus } from "@/lib/db";
|
import { getGroupBookings, addGroupBooking, toggleGroupBookingNotification, deleteGroupBooking, setGroupBookingStatus, updateBookingNotes } from "@/lib/db";
|
||||||
import type { BookingStatus } from "@/lib/db";
|
import type { BookingStatus } from "@/lib/db";
|
||||||
|
|
||||||
export async function GET() {
|
export async function GET() {
|
||||||
@@ -32,6 +32,12 @@ export async function PUT(request: NextRequest) {
|
|||||||
setGroupBookingStatus(id, status, confirmation);
|
setGroupBookingStatus(id, status, confirmation);
|
||||||
return NextResponse.json({ ok: true });
|
return NextResponse.json({ ok: true });
|
||||||
}
|
}
|
||||||
|
if (body.action === "set-notes") {
|
||||||
|
const { id, notes } = body;
|
||||||
|
if (!id) return NextResponse.json({ error: "id is required" }, { status: 400 });
|
||||||
|
updateBookingNotes("group_bookings", id, notes ?? "");
|
||||||
|
return NextResponse.json({ ok: true });
|
||||||
|
}
|
||||||
return NextResponse.json({ error: "Unknown action" }, { status: 400 });
|
return NextResponse.json({ error: "Unknown action" }, { status: 400 });
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.error("[admin/group-bookings] error:", err);
|
console.error("[admin/group-bookings] error:", err);
|
||||||
@@ -39,6 +45,21 @@ export async function PUT(request: NextRequest) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export async function POST(request: NextRequest) {
|
||||||
|
try {
|
||||||
|
const body = await request.json();
|
||||||
|
const { name, phone } = body;
|
||||||
|
if (!name?.trim() || !phone?.trim()) {
|
||||||
|
return NextResponse.json({ error: "name and phone are required" }, { status: 400 });
|
||||||
|
}
|
||||||
|
const id = addGroupBooking(name.trim(), phone.trim());
|
||||||
|
return NextResponse.json({ ok: true, id });
|
||||||
|
} catch (err) {
|
||||||
|
console.error("[admin/group-bookings] POST error:", err);
|
||||||
|
return NextResponse.json({ error: "Internal error" }, { status: 500 });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
export async function DELETE(request: NextRequest) {
|
export async function DELETE(request: NextRequest) {
|
||||||
const idStr = request.nextUrl.searchParams.get("id");
|
const idStr = request.nextUrl.searchParams.get("id");
|
||||||
if (!idStr) {
|
if (!idStr) {
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import { NextRequest, NextResponse } from "next/server";
|
import { NextRequest, NextResponse } from "next/server";
|
||||||
import { getMcRegistrations, getAllMcRegistrations, addMcRegistration, updateMcRegistration, toggleMcNotification, deleteMcRegistration, setMcRegistrationStatus } from "@/lib/db";
|
import { getMcRegistrations, getAllMcRegistrations, addMcRegistration, updateMcRegistration, toggleMcNotification, deleteMcRegistration, setMcRegistrationStatus, updateBookingNotes } from "@/lib/db";
|
||||||
|
|
||||||
export async function GET(request: NextRequest) {
|
export async function GET(request: NextRequest) {
|
||||||
const title = request.nextUrl.searchParams.get("title");
|
const title = request.nextUrl.searchParams.get("title");
|
||||||
@@ -40,6 +40,14 @@ export async function PUT(request: NextRequest) {
|
|||||||
return NextResponse.json({ ok: true });
|
return NextResponse.json({ ok: true });
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Set notes
|
||||||
|
if (body.action === "set-notes") {
|
||||||
|
const { id, notes } = body;
|
||||||
|
if (!id) return NextResponse.json({ error: "id is required" }, { status: 400 });
|
||||||
|
updateBookingNotes("mc_registrations", id, notes ?? "");
|
||||||
|
return NextResponse.json({ ok: true });
|
||||||
|
}
|
||||||
|
|
||||||
// Toggle notification status
|
// Toggle notification status
|
||||||
if (body.action === "toggle-notify") {
|
if (body.action === "toggle-notify") {
|
||||||
const { id, field, value } = body;
|
const { id, field, value } = body;
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ import {
|
|||||||
toggleOpenDayNotification,
|
toggleOpenDayNotification,
|
||||||
deleteOpenDayBooking,
|
deleteOpenDayBooking,
|
||||||
setOpenDayBookingStatus,
|
setOpenDayBookingStatus,
|
||||||
|
updateBookingNotes,
|
||||||
} from "@/lib/db";
|
} from "@/lib/db";
|
||||||
|
|
||||||
export async function GET(request: NextRequest) {
|
export async function GET(request: NextRequest) {
|
||||||
@@ -26,6 +27,12 @@ export async function PUT(request: NextRequest) {
|
|||||||
setOpenDayBookingStatus(id, status);
|
setOpenDayBookingStatus(id, status);
|
||||||
return NextResponse.json({ ok: true });
|
return NextResponse.json({ ok: true });
|
||||||
}
|
}
|
||||||
|
if (body.action === "set-notes") {
|
||||||
|
const { id, notes } = body;
|
||||||
|
if (!id) return NextResponse.json({ error: "id is required" }, { status: 400 });
|
||||||
|
updateBookingNotes("open_day_bookings", id, notes ?? "");
|
||||||
|
return NextResponse.json({ ok: true });
|
||||||
|
}
|
||||||
if (body.action === "toggle-notify") {
|
if (body.action === "toggle-notify") {
|
||||||
const { id, field, value } = body;
|
const { id, field, value } = body;
|
||||||
if (!id || !field || typeof value !== "boolean") {
|
if (!id || !field || typeof value !== "boolean") {
|
||||||
|
|||||||
@@ -3,6 +3,6 @@ import { getUnreadBookingCounts } from "@/lib/db";
|
|||||||
|
|
||||||
export async function GET() {
|
export async function GET() {
|
||||||
return NextResponse.json(getUnreadBookingCounts(), {
|
return NextResponse.json(getUnreadBookingCounts(), {
|
||||||
headers: { "Cache-Control": "private, max-age=15" },
|
headers: { "Cache-Control": "private, no-cache" },
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ const DB_PATH =
|
|||||||
|
|
||||||
let _db: Database.Database | null = null;
|
let _db: Database.Database | null = null;
|
||||||
|
|
||||||
function getDb(): Database.Database {
|
export function getDb(): Database.Database {
|
||||||
if (!_db) {
|
if (!_db) {
|
||||||
_db = new Database(DB_PATH);
|
_db = new Database(DB_PATH);
|
||||||
_db.pragma("journal_mode = WAL");
|
_db.pragma("journal_mode = WAL");
|
||||||
@@ -242,6 +242,18 @@ const migrations: Migration[] = [
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
version: 13,
|
||||||
|
name: "add_booking_notes",
|
||||||
|
up: (db) => {
|
||||||
|
for (const table of ["mc_registrations", "group_bookings", "open_day_bookings"]) {
|
||||||
|
const cols = db.prepare(`PRAGMA table_info(${table})`).all() as { name: string }[];
|
||||||
|
if (!cols.some((c) => c.name === "notes")) {
|
||||||
|
db.exec(`ALTER TABLE ${table} ADD COLUMN notes TEXT`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
},
|
||||||
];
|
];
|
||||||
|
|
||||||
function runMigrations(db: Database.Database) {
|
function runMigrations(db: Database.Database) {
|
||||||
@@ -524,6 +536,7 @@ interface McRegistrationRow {
|
|||||||
notified_reminder: number;
|
notified_reminder: number;
|
||||||
reminder_status: string | null;
|
reminder_status: string | null;
|
||||||
status: string;
|
status: string;
|
||||||
|
notes: string | null;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface McRegistration {
|
export interface McRegistration {
|
||||||
@@ -538,6 +551,7 @@ export interface McRegistration {
|
|||||||
notifiedReminder: boolean;
|
notifiedReminder: boolean;
|
||||||
reminderStatus?: string;
|
reminderStatus?: string;
|
||||||
status: string;
|
status: string;
|
||||||
|
notes?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function addMcRegistration(
|
export function addMcRegistration(
|
||||||
@@ -588,12 +602,13 @@ function mapMcRow(r: McRegistrationRow): McRegistration {
|
|||||||
notifiedReminder: !!r.notified_reminder,
|
notifiedReminder: !!r.notified_reminder,
|
||||||
reminderStatus: r.reminder_status ?? undefined,
|
reminderStatus: r.reminder_status ?? undefined,
|
||||||
status: r.status || "new",
|
status: r.status || "new",
|
||||||
|
notes: r.notes ?? undefined,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
export function setMcRegistrationStatus(id: number, status: string): void {
|
export function setMcRegistrationStatus(id: number, status: string): void {
|
||||||
const db = getDb();
|
const db = getDb();
|
||||||
db.prepare("UPDATE mc_registrations SET status = ? WHERE id = ?").run(status, id);
|
db.prepare("UPDATE mc_registrations SET status = ?, notified_confirm = 1 WHERE id = ?").run(status, id);
|
||||||
}
|
}
|
||||||
|
|
||||||
export function updateMcRegistration(
|
export function updateMcRegistration(
|
||||||
@@ -640,6 +655,7 @@ interface GroupBookingRow {
|
|||||||
confirmed_date: string | null;
|
confirmed_date: string | null;
|
||||||
confirmed_group: string | null;
|
confirmed_group: string | null;
|
||||||
confirmed_comment: string | null;
|
confirmed_comment: string | null;
|
||||||
|
notes: string | null;
|
||||||
created_at: string;
|
created_at: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -659,6 +675,7 @@ export interface GroupBooking {
|
|||||||
confirmedDate?: string;
|
confirmedDate?: string;
|
||||||
confirmedGroup?: string;
|
confirmedGroup?: string;
|
||||||
confirmedComment?: string;
|
confirmedComment?: string;
|
||||||
|
notes?: string;
|
||||||
createdAt: string;
|
createdAt: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -697,6 +714,7 @@ export function getGroupBookings(): GroupBooking[] {
|
|||||||
confirmedDate: r.confirmed_date ?? undefined,
|
confirmedDate: r.confirmed_date ?? undefined,
|
||||||
confirmedGroup: r.confirmed_group ?? undefined,
|
confirmedGroup: r.confirmed_group ?? undefined,
|
||||||
confirmedComment: r.confirmed_comment ?? undefined,
|
confirmedComment: r.confirmed_comment ?? undefined,
|
||||||
|
notes: r.notes ?? undefined,
|
||||||
createdAt: r.created_at,
|
createdAt: r.created_at,
|
||||||
}));
|
}));
|
||||||
}
|
}
|
||||||
@@ -709,11 +727,11 @@ export function setGroupBookingStatus(
|
|||||||
const db = getDb();
|
const db = getDb();
|
||||||
if (status === "confirmed" && confirmation) {
|
if (status === "confirmed" && confirmation) {
|
||||||
db.prepare(
|
db.prepare(
|
||||||
"UPDATE group_bookings SET status = ?, confirmed_date = ?, confirmed_group = ?, confirmed_comment = ? WHERE id = ?"
|
"UPDATE group_bookings SET status = ?, confirmed_date = ?, confirmed_group = ?, confirmed_comment = ?, notified_confirm = 1 WHERE id = ?"
|
||||||
).run(status, confirmation.date, confirmation.group, confirmation.comment || null, id);
|
).run(status, confirmation.date, confirmation.group, confirmation.comment || null, id);
|
||||||
} else {
|
} else {
|
||||||
db.prepare(
|
db.prepare(
|
||||||
"UPDATE group_bookings SET status = ?, confirmed_date = NULL, confirmed_group = NULL, confirmed_comment = NULL WHERE id = ?"
|
"UPDATE group_bookings SET status = ?, confirmed_date = NULL, confirmed_group = NULL, confirmed_comment = NULL, notified_confirm = 1 WHERE id = ?"
|
||||||
).run(status, id);
|
).run(status, id);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -769,6 +787,15 @@ export function setReminderStatus(
|
|||||||
db.prepare(`UPDATE ${table} SET reminder_status = ? WHERE id = ?`).run(status, id);
|
db.prepare(`UPDATE ${table} SET reminder_status = ? WHERE id = ?`).run(status, id);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function updateBookingNotes(
|
||||||
|
table: "mc_registrations" | "group_bookings" | "open_day_bookings",
|
||||||
|
id: number,
|
||||||
|
notes: string
|
||||||
|
): void {
|
||||||
|
const db = getDb();
|
||||||
|
db.prepare(`UPDATE ${table} SET notes = ? WHERE id = ?`).run(notes || null, id);
|
||||||
|
}
|
||||||
|
|
||||||
export interface ReminderItem {
|
export interface ReminderItem {
|
||||||
id: number;
|
id: number;
|
||||||
type: "class" | "master-class" | "open-day";
|
type: "class" | "master-class" | "open-day";
|
||||||
@@ -838,6 +865,27 @@ export function getUpcomingReminders(): ReminderItem[] {
|
|||||||
}
|
}
|
||||||
} catch { /* ignore */ }
|
} catch { /* ignore */ }
|
||||||
|
|
||||||
|
// Group bookings — confirmed with date today/tomorrow
|
||||||
|
try {
|
||||||
|
const gbRows = db.prepare(
|
||||||
|
"SELECT * FROM group_bookings WHERE status = 'confirmed' AND confirmed_date IN (?, ?)"
|
||||||
|
).all(today, tomorrow) as GroupBookingRow[];
|
||||||
|
for (const r of gbRows) {
|
||||||
|
items.push({
|
||||||
|
id: r.id,
|
||||||
|
type: "class",
|
||||||
|
table: "group_bookings",
|
||||||
|
name: r.name,
|
||||||
|
phone: r.phone ?? undefined,
|
||||||
|
instagram: r.instagram ?? undefined,
|
||||||
|
telegram: r.telegram ?? undefined,
|
||||||
|
reminderStatus: r.reminder_status ?? undefined,
|
||||||
|
eventLabel: r.confirmed_group || "Занятие",
|
||||||
|
eventDate: r.confirmed_date!,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
} catch { /* ignore */ }
|
||||||
|
|
||||||
// Open Day bookings — check event date
|
// Open Day bookings — check event date
|
||||||
try {
|
try {
|
||||||
const events = db.prepare(
|
const events = db.prepare(
|
||||||
@@ -1007,7 +1055,7 @@ function mapClassRow(r: OpenDayClassRow): OpenDayClass {
|
|||||||
|
|
||||||
export function setOpenDayBookingStatus(id: number, status: string): void {
|
export function setOpenDayBookingStatus(id: number, status: string): void {
|
||||||
const db = getDb();
|
const db = getDb();
|
||||||
db.prepare("UPDATE open_day_bookings SET status = ? WHERE id = ?").run(status, id);
|
db.prepare("UPDATE open_day_bookings SET status = ?, notified_confirm = 1 WHERE id = ?").run(status, id);
|
||||||
}
|
}
|
||||||
|
|
||||||
function mapBookingRow(r: OpenDayBookingRow): OpenDayBooking {
|
function mapBookingRow(r: OpenDayBookingRow): OpenDayBooking {
|
||||||
|
|||||||
Reference in New Issue
Block a user