/** * Управление настройками уведомлений */ class NotificationSettingsManager { constructor() { this.settings = {}; this.init(); } init() { this.loadSettings(); this.setupSoundToggle(); } async loadSettings() { const container = document.getElementById("settingsContainer"); if (!container) return; try { const response = await fetch("/api/v1/notifications/settings/", { credentials: "same-origin", headers: { Accept: "application/json", }, }); if (!response.ok) { throw new Error(`HTTP error! status: ${response.status}`); } const data = await response.json(); this.settings = data.settings || {}; this.renderSettings(); } catch (error) { console.error("[Settings] Error loading:", error); container.innerHTML = `
Ошибка загрузки настроек: ${error.message}
`; } } renderSettings() { const container = document.getElementById("settingsContainer"); if (!container) return; const categories = [ { code: "communications", name: "Коммуникации", icon: "bi-chat-dots", description: "Сообщения, упоминания, ответы в чатах", }, { code: "documents", name: "Документы", icon: "bi-file-earmark-text", description: "Новые документы, ознакомления", }, { code: "requests", name: "Заявления", icon: "bi-clipboard-check", description: "Заявки, согласования, комментарии", }, { code: "calendar", name: "Календарь", icon: "bi-calendar-event", description: "События, напоминания, изменения", }, { code: "department", name: "Отдел", icon: "bi-people", description: "Изменения в структуре отдела", }, { code: "profile", name: "Профиль", icon: "bi-person", description: "Изменения профиля и безопасности", }, { code: "feed", name: "Новости", icon: "bi-newspaper", description: "Публикации, комментарии, реакции", }, { code: "system", name: "Система", icon: "bi-gear", description: "Системные уведомления и обновления", }, ]; let html = '
'; categories.forEach((cat) => { const setting = this.settings[cat.code] || { is_enabled: true, web_enabled: true, email_enabled: false, email_frequency: "instant", telegram_enabled: false, }; html += `
${cat.name}

${ cat.description }

${ setting.email_enabled ? `
` : "" }
`; }); html += "
"; container.innerHTML = html; // Добавить обработчики this.attachEventHandlers(); } attachEventHandlers() { // Обработчики для главных переключателей document.querySelectorAll(".setting-toggle").forEach((toggle) => { toggle.addEventListener("change", async (e) => { const category = toggle.dataset.category; const field = toggle.dataset.field; const value = toggle.checked; // Показать/скрыть каналы const channels = document.getElementById(`channels_${category}`); if (channels) { if (value) { channels.classList.remove("d-none"); } else { channels.classList.add("d-none"); } } await this.updateSetting(category, field, value); }); }); // Обработчики для каналов document.querySelectorAll(".channel-toggle").forEach((toggle) => { toggle.addEventListener("change", async (e) => { const category = toggle.dataset.category; const field = toggle.dataset.field; const value = toggle.checked; // Если включили email, перерисовать карточку для показа частоты if (field === "email_enabled") { await this.updateSetting(category, field, value); this.renderSettings(); // Перерисовать для показа select } else { await this.updateSetting(category, field, value); } }); }); // Обработчики для частоты email document.querySelectorAll(".email-frequency-select").forEach((select) => { select.addEventListener("change", async (e) => { const category = select.dataset.category; const value = select.value; await this.updateSetting(category, "email_frequency", value); }); }); } async updateSetting(category, field, value) { try { const response = await fetch( "/api/v1/notifications/settings/category/update/", { method: "PUT", credentials: "same-origin", headers: { "Content-Type": "application/json", "X-CSRFToken": this.getCsrfToken(), }, body: JSON.stringify({ category: category, [field]: value, }), } ); if (!response.ok) { throw new Error("Failed to update setting"); } // Обновить локальные настройки if (!this.settings[category]) { this.settings[category] = {}; } this.settings[category][field] = value; // Показать уведомление об успехе this.showToast("Настройки сохранены", "success"); } catch (error) { console.error("[Settings] Error updating:", error); this.showToast("Ошибка сохранения настроек", "danger"); } } setupSoundToggle() { const soundToggle = document.getElementById("soundToggle"); if (soundToggle && window.notificationManager) { soundToggle.checked = window.notificationManager.soundEnabled; soundToggle.addEventListener("change", (e) => { window.notificationManager.saveSoundPreference(e.target.checked); this.showToast( e.target.checked ? "Звук включен" : "Звук выключен", "info" ); }); } } getCsrfToken() { return document.querySelector("[name=csrfmiddlewaretoken]")?.value || ""; } showToast(message, type = "info") { // Создать toast уведомление const toastContainer = document.getElementById("toastContainer") || this.createToastContainer(); const toast = document.createElement("div"); toast.className = `toast align-items-center text-white bg-${type} border-0`; toast.setAttribute("role", "alert"); toast.innerHTML = `
${message}
`; toastContainer.appendChild(toast); const bsToast = new bootstrap.Toast(toast, { delay: 3000 }); bsToast.show(); toast.addEventListener("hidden.bs.toast", () => { toast.remove(); }); } createToastContainer() { const container = document.createElement("div"); container.id = "toastContainer"; container.className = "toast-container position-fixed bottom-0 end-0 p-3"; document.body.appendChild(container); return container; } } /** * Управление привязкой Telegram (упрощенная версия) */ class TelegramLinkManager { constructor() { this.container = document.getElementById("telegramLinkContainer"); if (!this.container) return; this.init(); } async init() { this.renderInstructions(); } renderInstructions() { const botUsername = window.TELEGRAM_BOT_USERNAME || "eusrr_bot"; this.container.innerHTML = `
Настройка Telegram уведомлений
📱 Как получать уведомления в Telegram:
  1. Откройте бота @userinfobot в Telegram
    Это официальный бот для получения информации о вашем аккаунте
  2. Отправьте любое сообщение боту
    Бот ответит вам информацией, включая ваш Chat ID (число)
  3. Скопируйте ваш Chat ID
    Например: 123456789
  4. Добавьте Chat ID в ваш профиль
    Откройте профиль → Редактировать → вставьте Chat ID в поле "Telegram"
  5. Включите галочки "Telegram" для нужных категорий ниже
    Выберите категории уведомлений, которые хотите получать в Telegram
  6. ⚠️ ВАЖНО: Отправьте /start нашему боту @${botUsername}
    Иначе бот не сможет отправлять вам сообщения из-за ограничений Telegram API
`; } } // Инициализация document.addEventListener("DOMContentLoaded", () => { if (document.getElementById("settingsContainer")) { window.notificationSettingsManager = new NotificationSettingsManager(); } if (document.getElementById("telegramLinkContainer")) { window.telegramLinkManager = new TelegramLinkManager(); } });