import fs from 'fs'; import path from 'path'; export type UserRole = 'guest' | 'host' | 'couple' | 'admin'; export interface Guest { ticket_id: string; guest_name: string; team_id: string; team_name: string; role: UserRole; registered_at: number; } export interface KissCatch { id: number; ticket_id: string; guest_name: string; team_id: string; team_name: string; points: number; round_id: number; timestamp: number; } export interface ToastLog { id: number; ticket_id: string; guest_name: string; team_id: string; team_name: string; timestamp: number; photo_url?: string; detected_glasses?: number; confidence?: number; ai_cheer?: string; quest_id?: string; quest_title?: string; quest_completed?: boolean; status: 'pending' | 'verified' | 'rejected'; } export interface WeddingPhoto { id: string; ticket_id?: string; guest_name?: string; team_id?: string; team_name?: string; url: string; thumb_url?: string; caption?: string; uploaded_at: number; is_toast?: boolean; quest_title?: string; } export interface AppState { guests: Record; kiss_catches: KissCatch[]; toasts: ToastLog[]; photos: WeddingPhoto[]; current_round_id: number; round_active: boolean; round_start_time: number | null; round_first_catcher: { ticket_id: string; guest_name: string; team_name: string } | null; cooldown_until: number | null; cake_time_target: number; immich_url: string; immich_api_key: string; immich_album_id: string; immich_album_name: string; ollama_url: string; couples_names: string; wedding_date: string; } const DATA_DIR = path.join(process.cwd(), 'data'); const DATA_FILE = path.join(DATA_DIR, 'wedding_hub.json'); const DEFAULT_CAKE_TIME = Date.now() + 2 * 60 * 60 * 1000 + 45 * 60 * 1000; export const DEFAULT_TEAMS = [ { id: 'team_bride', name: '👰 Команда Невесты' }, { id: 'team_groom', name: '🤵 Команда Жениха' }, { id: 'team_witnesses', name: '🍸 Свидетели и Свита' }, { id: 'team_friends', name: '🎉 Команда Друзей' }, { id: 'team_family', name: '👑 Семья и Родные' }, ]; const DEFAULT_STATE: AppState = { guests: { 'ADMIN-001': { ticket_id: 'ADMIN-001', guest_name: 'Главный Администратор', team_id: 'team_witnesses', team_name: '🍸 Свидетели и Свита', role: 'admin', registered_at: Date.now() - 4000000 }, 'HOST-001': { ticket_id: 'HOST-001', guest_name: 'Ведущий Банкета (Александр)', team_id: 'team_friends', team_name: '🎉 Команда Друзей', role: 'host', registered_at: Date.now() - 3900000 }, 'COUPLE-001': { ticket_id: 'COUPLE-001', guest_name: 'Анна & Дмитрий (Молодожены)', team_id: 'team_bride', team_name: '👰 Команда Невесты', role: 'couple', registered_at: Date.now() - 3800000 }, 'LUCK-001': { ticket_id: 'LUCK-001', guest_name: 'Алексей Смирнов', team_id: 'team_groom', team_name: '🤵 Команда Жениха', role: 'guest', registered_at: Date.now() - 3600000 }, 'LUCK-002': { ticket_id: 'LUCK-002', guest_name: 'Елена Васильева', team_id: 'team_bride', team_name: '👰 Команда Невесты', role: 'guest', registered_at: Date.now() - 3500000 }, 'LUCK-003': { ticket_id: 'LUCK-003', guest_name: 'Дмитрий Ковалев', team_id: 'team_friends', team_name: '🎉 Команда Друзей', role: 'guest', registered_at: Date.now() - 3400000 }, 'LUCK-004': { ticket_id: 'LUCK-004', guest_name: 'Мария Соколова', team_id: 'team_bride', team_name: '👰 Команда Невесты', role: 'guest', registered_at: Date.now() - 3300000 }, 'LUCK-005': { ticket_id: 'LUCK-005', guest_name: 'Сергей Морозов', team_id: 'team_witnesses', team_name: '🍸 Свидетели и Свита', role: 'guest', registered_at: Date.now() - 3200000 }, 'LUCK-006': { ticket_id: 'LUCK-006', guest_name: 'Ольга Попова', team_id: 'team_family', team_name: '👑 Семья и Родные', role: 'guest', registered_at: Date.now() - 3100000 }, 'LUCK-007': { ticket_id: 'LUCK-007', guest_name: 'Михаил Новиков', team_id: 'team_groom', team_name: '🤵 Команда Жениха', role: 'guest', registered_at: Date.now() - 3000000 }, }, kiss_catches: [ { id: 1, ticket_id: 'LUCK-001', guest_name: 'Алексей Смирнов', team_id: 'team_groom', team_name: '🤵 Команда Жениха', points: 3, round_id: 1, timestamp: Date.now() - 2400000 }, { id: 2, ticket_id: 'LUCK-003', guest_name: 'Дмитрий Ковалев', team_id: 'team_friends', team_name: '🎉 Команда Друзей', points: 1, round_id: 1, timestamp: Date.now() - 2398000 }, { id: 3, ticket_id: 'LUCK-005', guest_name: 'Сергей Морозов', team_id: 'team_witnesses', team_name: '🍸 Свидетели и Свита', points: 1, round_id: 1, timestamp: Date.now() - 2396000 }, { id: 4, ticket_id: 'LUCK-004', guest_name: 'Мария Соколова', team_id: 'team_bride', team_name: '👰 Команда Невесты', points: 3, round_id: 2, timestamp: Date.now() - 1500000 }, { id: 5, ticket_id: 'LUCK-002', guest_name: 'Елена Васильева', team_id: 'team_bride', team_name: '👰 Команда Невесты', points: 1, round_id: 2, timestamp: Date.now() - 1497000 }, { id: 6, ticket_id: 'LUCK-007', guest_name: 'Михаил Новиков', team_id: 'team_groom', team_name: '🤵 Команда Жениха', points: 3, round_id: 3, timestamp: Date.now() - 700000 }, ], toasts: [ { id: 1, ticket_id: 'LUCK-001', guest_name: 'Алексей Смирнов', team_id: 'team_groom', team_name: '🤵 Команда Жениха', timestamp: Date.now() - 2800000, detected_glasses: 1, confidence: 0.96, quest_id: 'quest_fear', quest_title: 'Эмоция «СТРАХ»', quest_completed: true, ai_cheer: 'Эмоция ужаса от цен на свадьбу передана гениально! Бокал засчитан!', status: 'verified', photo_url: 'https://images.unsplash.com/photo-1519741497674-611481863552?w=800&auto=format&fit=crop&q=80' }, { id: 2, ticket_id: 'LUCK-002', guest_name: 'Елена Васильева', team_id: 'team_bride', team_name: '👰 Команда Невесты', timestamp: Date.now() - 2000000, detected_glasses: 1, confidence: 0.98, quest_id: 'quest_couple_bg', quest_title: 'На фоне Молодоженов', quest_completed: true, ai_cheer: 'Молодожены в фокусе, бокал шампанского сияет! За невесту!', status: 'verified', photo_url: 'https://images.unsplash.com/photo-1511285560929-80b456fea0bc?w=800&auto=format&fit=crop&q=80' }, { id: 3, ticket_id: 'LUCK-003', guest_name: 'Дмитрий Ковалев', team_id: 'team_friends', team_name: '🎉 Команда Друзей', timestamp: Date.now() - 1200000, detected_glasses: 2, confidence: 0.92, quest_id: 'quest_superhero', quest_title: 'Поза Супергероя', quest_completed: true, ai_cheer: 'Стойка Тора с бокалом виски! +1 напиток друзьям!', status: 'verified', photo_url: 'https://images.unsplash.com/photo-1465495976277-4387d4b0b4c6?w=800&auto=format&fit=crop&q=80' }, { id: 4, ticket_id: 'LUCK-005', guest_name: 'Сергей Морозов', team_id: 'team_witnesses', team_name: '🍸 Свидетели и Свита', timestamp: Date.now() - 600000, detected_glasses: 1, confidence: 0.95, quest_id: 'quest_serious', quest_title: 'Максимальная Серьезность', quest_completed: true, ai_cheer: 'Лицо министра финансов с бокалом! Безупречно!', status: 'verified', photo_url: 'https://images.unsplash.com/photo-1520854221256-17451cc331bf?w=800&auto=format&fit=crop&q=80' }, ], photos: [ { id: 'p1', ticket_id: 'LUCK-001', guest_name: 'Алексей Смирнов', team_id: 'team_groom', team_name: '🤵 Команда Жениха', url: 'https://images.unsplash.com/photo-1519741497674-611481863552?w=800&auto=format&fit=crop&q=80', uploaded_at: Date.now() - 2800000, caption: 'Квест «Страх» выполнен!', quest_title: 'Эмоция «СТРАХ»', is_toast: true }, { id: 'p2', ticket_id: 'LUCK-002', guest_name: 'Елена Васильева', team_id: 'team_bride', team_name: '👰 Команда Невесты', url: 'https://images.unsplash.com/photo-1511285560929-80b456fea0bc?w=800&auto=format&fit=crop&q=80', uploaded_at: Date.now() - 2000000, caption: 'Тост за молодых на фоне пары', quest_title: 'На фоне Молодоженов', is_toast: true }, { id: 'p3', ticket_id: 'LUCK-003', guest_name: 'Дмитрий Ковалев', team_id: 'team_friends', team_name: '🎉 Команда Друзей', url: 'https://images.unsplash.com/photo-1465495976277-4387d4b0b4c6?w=800&auto=format&fit=crop&q=80', uploaded_at: Date.now() - 1200000, caption: 'Супергерои вечера', quest_title: 'Поза Супергероя', is_toast: true }, { id: 'p4', ticket_id: 'LUCK-005', guest_name: 'Сергей Морозов', team_id: 'team_witnesses', team_name: '🍸 Свидетели и Свита', url: 'https://images.unsplash.com/photo-1520854221256-17451cc331bf?w=800&auto=format&fit=crop&q=80', uploaded_at: Date.now() - 600000, caption: 'Строгий свидетель', quest_title: 'Максимальная Серьезность', is_toast: true }, ], current_round_id: 3, round_active: false, round_start_time: null, round_first_catcher: null, cooldown_until: null, cake_time_target: DEFAULT_CAKE_TIME, immich_url: process.env.IMMICH_URL || '', immich_api_key: process.env.IMMICH_API_KEY || '', immich_album_id: process.env.IMMICH_ALBUM_ID || '', immich_album_name: process.env.IMMICH_ALBUM_NAME || '', ollama_url: process.env.OLLAMA_URL || '', couples_names: 'Анна & Дмитрий', wedding_date: '2026-08-27', }; class WeddingDatabase { private state: AppState; constructor() { this.state = this.loadState(); } private loadState(): AppState { try { if (!fs.existsSync(DATA_DIR)) { fs.mkdirSync(DATA_DIR, { recursive: true }); } if (fs.existsSync(DATA_FILE)) { const raw = fs.readFileSync(DATA_FILE, 'utf-8'); const parsed = JSON.parse(raw); return { ...DEFAULT_STATE, ...parsed }; } } catch (e) { console.warn('Could not load existing state file, using defaults:', e); } return { ...DEFAULT_STATE }; } public save(): void { try { if (!fs.existsSync(DATA_DIR)) { fs.mkdirSync(DATA_DIR, { recursive: true }); } const tmpFile = `${DATA_FILE}.tmp`; fs.writeFileSync(tmpFile, JSON.stringify(this.state, null, 2), 'utf-8'); fs.renameSync(tmpFile, DATA_FILE); } catch (e) { console.error('Failed to write database file:', e); } } public getState(): AppState { return this.state; } // Guests public registerGuest( ticket_id: string, guest_name: string, team_id: string, team_name?: string, role?: UserRole ): Guest { const cleanTicket = ticket_id.trim().toUpperCase(); const resolvedTeamName = team_name || DEFAULT_TEAMS.find((t) => t.id === team_id)?.name || '🎉 Команда Друзей'; // Auto-detect role from ticket prefix or explicit role let resolvedRole: UserRole = role || 'guest'; if (!role) { if (cleanTicket.startsWith('ADMIN')) resolvedRole = 'admin'; else if (cleanTicket.startsWith('HOST')) resolvedRole = 'host'; else if (cleanTicket.startsWith('COUPLE')) resolvedRole = 'couple'; } const guest: Guest = { ticket_id: cleanTicket, guest_name: guest_name.trim(), team_id: team_id || 'team_friends', team_name: resolvedTeamName, role: resolvedRole, registered_at: Date.now(), }; this.state.guests[cleanTicket] = guest; this.save(); return guest; } public getGuest(ticket_id: string): Guest | undefined { return this.state.guests[ticket_id.trim().toUpperCase()]; } public getAllGuests(): Guest[] { return Object.values(this.state.guests); } public removeGuest(ticket_id: string): boolean { const clean = ticket_id.trim().toUpperCase(); if (this.state.guests[clean]) { delete this.state.guests[clean]; this.save(); return true; } return false; } public batchRemoveGuests(ticket_ids: string[]): number { let count = 0; for (const tid of ticket_ids) { const clean = tid.trim().toUpperCase(); if (this.state.guests[clean]) { delete this.state.guests[clean]; count++; } } if (count > 0) { this.save(); } return count; } public updateGuest( ticket_id: string, updates: Partial> ): Guest | null { const clean = ticket_id.trim().toUpperCase(); const guest = this.state.guests[clean]; if (!guest) return null; if (updates.guest_name) guest.guest_name = updates.guest_name.trim(); if (updates.team_id) guest.team_id = updates.team_id; if (updates.team_name) guest.team_name = updates.team_name; if (updates.role) guest.role = updates.role; this.save(); return guest; } // Kisses logic public startKissRound(): { round_id: number; start_time: number } { this.state.current_round_id += 1; this.state.round_active = true; this.state.round_start_time = Date.now(); this.state.round_first_catcher = null; this.state.cooldown_until = null; this.save(); return { round_id: this.state.current_round_id, start_time: this.state.round_start_time }; } public endKissRound(): { cooldown_until: number } { this.state.round_active = false; this.state.round_start_time = null; this.state.cooldown_until = Date.now() + 30000; this.save(); return { cooldown_until: this.state.cooldown_until }; } public catchKiss(ticket_id: string): { success: boolean; points: number; is_golden: boolean; reason?: string; round_id: number; guest: Guest; catcher_info?: { ticket_id: string; guest_name: string; team_name: string }; } { const guest = this.getGuest(ticket_id); if (!guest) { return { success: false, points: 0, is_golden: false, reason: 'Гость не зарегистрирован', round_id: this.state.current_round_id, guest: null as any }; } const now = Date.now(); if (this.state.cooldown_until && now < this.state.cooldown_until) { const remaining = Math.ceil((this.state.cooldown_until - now) / 1000); return { success: false, points: 0, is_golden: false, reason: `Кулдаун! Подождите ${remaining} сек.`, round_id: this.state.current_round_id, guest }; } if (!this.state.round_active) { this.startKissRound(); const catchRecord: KissCatch = { id: this.state.kiss_catches.length + 1, ticket_id: guest.ticket_id, guest_name: guest.guest_name, team_id: guest.team_id, team_name: guest.team_name, points: 3, round_id: this.state.current_round_id, timestamp: now, }; this.state.kiss_catches.push(catchRecord); this.state.round_first_catcher = { ticket_id: guest.ticket_id, guest_name: guest.guest_name, team_name: guest.team_name, }; this.save(); return { success: true, points: 3, is_golden: true, round_id: this.state.current_round_id, guest, catcher_info: this.state.round_first_catcher, }; } const alreadyCaughtInThisRound = this.state.kiss_catches.some( (c) => c.round_id === this.state.current_round_id && c.ticket_id === guest.ticket_id ); if (alreadyCaughtInThisRound) { return { success: false, points: 0, is_golden: false, reason: 'Вы уже зафиксировали поцелуй в этом раунде!', round_id: this.state.current_round_id, guest }; } const elapsedMs = now - (this.state.round_start_time || now); if (elapsedMs <= 5500) { const catchRecord: KissCatch = { id: this.state.kiss_catches.length + 1, ticket_id: guest.ticket_id, guest_name: guest.guest_name, team_id: guest.team_id, team_name: guest.team_name, points: 1, round_id: this.state.current_round_id, timestamp: now, }; this.state.kiss_catches.push(catchRecord); this.save(); return { success: true, points: 1, is_golden: false, round_id: this.state.current_round_id, guest, catcher_info: this.state.round_first_catcher, }; } else { this.endKissRound(); return { success: false, points: 0, is_golden: false, reason: 'Раунд завершен! Не успели за 5 секунд.', round_id: this.state.current_round_id, guest }; } } // Toasts / Drinks with strange quests public addToast( ticket_id: string, photo_url?: string, detected_glasses: number = 1, confidence: number = 0.95, ai_cheer?: string, quest_id?: string, quest_title?: string, quest_completed: boolean = true ): ToastLog { const guest = this.getGuest(ticket_id); const toast: ToastLog = { id: this.state.toasts.length + 1, ticket_id: ticket_id.trim().toUpperCase(), guest_name: guest ? guest.guest_name : 'Гость', team_id: guest ? guest.team_id : 'team_friends', team_name: guest ? guest.team_name : '🎉 Команда Друзей', timestamp: Date.now(), photo_url, detected_glasses, confidence, ai_cheer: ai_cheer || 'Горько! За счастье молодых!', quest_id, quest_title, quest_completed, status: 'verified', }; this.state.toasts.push(toast); if (photo_url) { this.state.photos.unshift({ id: `toast-${toast.id}-${Date.now()}`, ticket_id: toast.ticket_id, guest_name: toast.guest_name, team_id: toast.team_id, team_name: toast.team_name, url: photo_url, uploaded_at: Date.now(), caption: quest_title ? `Квест «${quest_title}»: ${toast.ai_cheer}` : `Тост: ${toast.ai_cheer}`, quest_title, is_toast: true, }); } this.save(); return toast; } // Photos public addPhoto(photo: Omit): WeddingPhoto { const newPhoto: WeddingPhoto = { ...photo, id: `photo-${Date.now()}-${Math.random().toString(36).substring(2, 7)}`, uploaded_at: Date.now(), }; this.state.photos.unshift(newPhoto); this.save(); return newPhoto; } // Aggregated Stats with Personal and Team metrics public getAggregatedStats() { const totalKisses = this.state.kiss_catches.length; const totalToasts = this.state.toasts.length; const totalPhotos = this.state.photos.length; // 1. Top Paparazzi (Kiss Hunt Leaderboard) const guestKissPoints: Record = {}; for (const kc of this.state.kiss_catches) { if (!guestKissPoints[kc.ticket_id]) { guestKissPoints[kc.ticket_id] = { ticket_id: kc.ticket_id, guest_name: kc.guest_name, team_name: kc.team_name, points: 0, kisses_count: 0, }; } guestKissPoints[kc.ticket_id].points += kc.points; guestKissPoints[kc.ticket_id].kisses_count += 1; } const topPaparazzi = Object.values(guestKissPoints) .sort((a, b) => b.points - a.points || b.kisses_count - a.kisses_count) .slice(0, 5); // 2. Top Drinkers (Personal Drink Standings / Личный зачет по выпитому) const guestDrinkPoints: Record = {}; for (const t of this.state.toasts) { if (!guestDrinkPoints[t.ticket_id]) { guestDrinkPoints[t.ticket_id] = { ticket_id: t.ticket_id, guest_name: t.guest_name, team_name: t.team_name, drinks_count: 0, points: 0, }; } guestDrinkPoints[t.ticket_id].drinks_count += 1; guestDrinkPoints[t.ticket_id].points += 10; } const topDrinkers = Object.values(guestDrinkPoints) .sort((a, b) => b.drinks_count - a.drinks_count || b.points - a.points) .slice(0, 5); // 3. Team Battle Score (Командный зачет по выпитому и очкам) const teamStats: Record = {}; // Initialize preset teams for (const team of DEFAULT_TEAMS) { teamStats[team.id] = { team_id: team.id, team_name: team.name, drinks_count: 0, points: 0, guest_count: 0, kisses_count: 0, }; } // Count guests in teams for (const g of Object.values(this.state.guests)) { if (!teamStats[g.team_id]) { teamStats[g.team_id] = { team_id: g.team_id, team_name: g.team_name, drinks_count: 0, points: 0, guest_count: 0, kisses_count: 0, }; } teamStats[g.team_id].guest_count += 1; } // Count drinks / quests in teams (+10 pts per drink) for (const t of this.state.toasts) { if (!teamStats[t.team_id]) { teamStats[t.team_id] = { team_id: t.team_id, team_name: t.team_name, drinks_count: 0, points: 0, guest_count: 0, kisses_count: 0, }; } teamStats[t.team_id].drinks_count += 1; teamStats[t.team_id].points += 10; } // Count kisses in teams for (const kc of this.state.kiss_catches) { if (!teamStats[kc.team_id]) { teamStats[kc.team_id] = { team_id: kc.team_id, team_name: kc.team_name, drinks_count: 0, points: 0, guest_count: 0, kisses_count: 0, }; } teamStats[kc.team_id].kisses_count += 1; teamStats[kc.team_id].points += kc.points; } const teamBattle = Object.values(teamStats).sort((a, b) => b.points - a.points || b.drinks_count - a.drinks_count); // 4. Detailed Registered Users list for Admin const allGuests = Object.values(this.state.guests); const registeredUsers = allGuests.map((g) => { const kisses = this.state.kiss_catches.filter((k) => k.ticket_id === g.ticket_id); const kissPts = kisses.reduce((acc, k) => acc + k.points, 0); const drinks = this.state.toasts.filter((t) => t.ticket_id === g.ticket_id); const drinkPts = drinks.length * 10; const photos = this.state.photos.filter((p) => p.ticket_id === g.ticket_id); return { ...g, points: kissPts + drinkPts, kisses_count: kisses.length, drinks_count: drinks.length, photos_count: photos.length, }; }).sort((a, b) => b.registered_at - a.registered_at); // Format cake target time as HH:MM let cake_time_target_str = ''; try { const d = new Date(this.state.cake_time_target); const hours = String(d.getHours()).padStart(2, '0'); const mins = String(d.getMinutes()).padStart(2, '0'); cake_time_target_str = `${hours}:${mins}`; } catch { cake_time_target_str = '22:30'; } return { totalKisses, totalToasts, totalPhotos, topPaparazzi, topDrinkers, teamBattle, registeredUsers, round_active: this.state.round_active, round_start_time: this.state.round_start_time, round_first_catcher: this.state.round_first_catcher, cooldown_until: this.state.cooldown_until, cake_time_target: this.state.cake_time_target, cake_time_target_str, couples_names: this.state.couples_names, wedding_date: this.state.wedding_date, immich_url: this.state.immich_url, immich_album_id: this.state.immich_album_id, immich_album_name: this.state.immich_album_name, ollama_url: this.state.ollama_url, }; } public updateSettings(settings: Partial): AppState { this.state = { ...this.state, ...settings }; this.save(); return this.state; } public resetAllData(): void { this.state = { ...DEFAULT_STATE, guests: {}, kiss_catches: [], toasts: [], photos: [], current_round_id: 0, round_active: false, round_start_time: null, round_first_catcher: null, cooldown_until: null, cake_time_target: Date.now() + 3 * 3600000, }; this.save(); } public seedDemoData(): void { this.state = { ...DEFAULT_STATE, cake_time_target: Date.now() + 2 * 3600000 + 30 * 60000, }; this.save(); } } export const db = new WeddingDatabase();