'use client'; import React, { useState, useEffect } from 'react'; import { useAuth } from '@/contexts/AuthContext'; import { Switch } from '@/components/common/Switch'; import { getParentDashboard } from '@/api/dashboard'; import { getParentChildNotificationSettingsForChild, updateParentChildNotificationSettings, type ParentChildNotificationSettings, } from '@/api/notifications'; const NOTIFICATION_TYPES = [ { value: 'lesson_created', label: 'Создано занятие' }, { value: 'lesson_updated', label: 'Занятие обновлено' }, { value: 'lesson_cancelled', label: 'Занятие отменено' }, { value: 'lesson_rescheduled', label: 'Занятие перенесено' }, { value: 'lesson_reminder', label: 'Напоминание о занятии' }, { value: 'lesson_completed', label: 'Занятие завершено' }, { value: 'homework_assigned', label: 'Назначено домашнее задание' }, { value: 'homework_submitted', label: 'ДЗ сдано' }, { value: 'homework_reviewed', label: 'ДЗ проверено' }, { value: 'homework_returned', label: 'ДЗ возвращено на доработку' }, { value: 'homework_deadline_reminder', label: 'Напоминание о дедлайне ДЗ' }, { value: 'material_added', label: 'Добавлен материал' }, ]; function getAvatarUrl(child: { avatar_url?: string | null; avatar?: string | null }): string | null { const url = child.avatar_url || child.avatar; if (!url) return null; if (url.startsWith('http')) return url; const base = typeof window !== 'undefined' ? `${window.location.protocol}//${window.location.hostname}:8123` : ''; return url.startsWith('/') ? `${base}${url}` : `${base}/${url}`; } export function ParentChildNotificationSettings() { const { user } = useAuth(); const [children, setChildren] = useState<{ id: string; name: string; avatar?: string | null; avatar_url?: string | null }[]>([]); const [settings, setSettings] = useState>({}); const [loading, setLoading] = useState(true); const [saving, setSaving] = useState>({}); const [error, setError] = useState(null); const [expandedChild, setExpandedChild] = useState(null); useEffect(() => { const load = async () => { if (user?.role !== 'parent') { setLoading(false); return; } try { setLoading(true); setError(null); const stats = await getParentDashboard(); const rawChildren = (stats as any).children || (stats as any).children_stats || []; const list = rawChildren.map((item: any) => { const c = item.child || item; return { id: String(c.id), name: c.name || `${c.first_name || ''} ${c.last_name || ''}`.trim() || 'Ребёнок', avatar: c.avatar, avatar_url: c.avatar_url, }; }); setChildren(list); const settingsMap: Record = {}; for (const child of list) { try { const s = await getParentChildNotificationSettingsForChild(child.id); settingsMap[child.id] = s; } catch (e: any) { if (e?.response?.status === 404 || e?.status === 404) { settingsMap[child.id] = { child_id: parseInt(child.id), child_name: child.name, enabled: true, type_settings: {}, }; } } } setSettings(settingsMap); } catch (e) { console.error(e); setError('Не удалось загрузить настройки'); } finally { setLoading(false); } }; load(); }, [user?.role]); const handleToggleEnabled = async (childId: string, enabled: boolean) => { try { setSaving((p) => ({ ...p, [childId]: true })); const updated = await updateParentChildNotificationSettings(childId, { enabled }); setSettings((p) => ({ ...p, [childId]: updated })); } catch (e) { setError('Не удалось обновить'); } finally { setSaving((p) => ({ ...p, [childId]: false })); } }; const handleToggleType = async (childId: string, type: string, enabled: boolean) => { try { setSaving((p) => ({ ...p, [childId]: true })); const curr = settings[childId] || { enabled: true, type_settings: {} }; const newTypeSettings = { ...curr.type_settings, [type]: enabled }; const updated = await updateParentChildNotificationSettings(childId, { type_settings: newTypeSettings, }); setSettings((p) => ({ ...p, [childId]: updated })); } catch (e) { setError('Не удалось обновить'); } finally { setSaving((p) => ({ ...p, [childId]: false })); } }; if (user?.role !== 'parent') return null; if (loading) { return (
Загрузка настроек для детей…
); } if (children.length === 0) { return (
Уведомления которые хотите получать вместе с учеником

Добавьте детей на странице «Мои дети», чтобы настроить уведомления для каждого ребёнка.

); } return (
Уведомления которые хотите получать вместе с учеником
{error && (

{error}

)}
{children.map((child) => { const childSettings = settings[child.id] || { enabled: true, type_settings: {} }; const isExpanded = expandedChild === child.id; const isSaving = saving[child.id]; return (
setExpandedChild(isExpanded ? null : child.id)} style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '10px 12px', cursor: 'pointer', }} >
{getAvatarUrl(child) ? ( ) : ( child.name.charAt(0) || '?' )}
{child.name}
{childSettings.enabled ? 'Включены' : 'Выключены'}
e.stopPropagation()}> handleToggleEnabled(child.id, v)} disabled={isSaving} size="compact" />
expand_more
{isExpanded && (
{NOTIFICATION_TYPES.map((type) => { const isEnabled = childSettings.type_settings[type.value] !== false; return (
{type.label} handleToggleType(child.id, type.value, v)} disabled={isSaving || !childSettings.enabled} size="compact" />
); })}
)}
); })}
); }