diff --git a/Program.cs b/Program.cs index 8acf70b..b3e8cfb 100644 --- a/Program.cs +++ b/Program.cs @@ -64,6 +64,7 @@ class Program // Создание базы данных и таблицы, если они не существуют await CreateDatabaseIfNotExists(); + await CreateUserSettingsTableIfNotExists(); // Загрузка списка администраторов из базы данных await LoadAdminsFromDatabase(); @@ -105,7 +106,88 @@ class Program } } + private static async Task CreateUserSettingsTableIfNotExists() + { + try + { + using (var connection = new SqliteConnection("Data Source=bot.db")) + { + await connection.OpenAsync(); + var command = connection.CreateCommand(); + command.CommandText = @" + CREATE TABLE IF NOT EXISTS UserSettings ( + UserId INTEGER PRIMARY KEY, + NotificationsEnabled INTEGER NOT NULL DEFAULT 1 + );"; + await command.ExecuteNonQueryAsync(); + Log.Information("Таблица UserSettings успешно создана (если её не было)."); + } + } + catch (Exception ex) + { + Log.Error($"Ошибка при создании таблицы UserSettings: {ex.Message}"); + } + } + private static async Task ShowUserSettings(ITelegramBotClient botClient, long chatId) + { + try + { + // Получаем текущие настройки пользователя + bool notificationsEnabled = true; // По умолчанию уведомления включены + + using (var connection = new SqliteConnection("Data Source=bot.db")) + { + await connection.OpenAsync(); + var command = connection.CreateCommand(); + command.CommandText = "SELECT NotificationsEnabled FROM UserSettings WHERE UserId = @userId"; + command.Parameters.AddWithValue("@userId", chatId); + + var result = await command.ExecuteScalarAsync(); + if (result != null && result != DBNull.Value) + { + notificationsEnabled = Convert.ToInt32(result) == 1; + } + else + { + // Если запись для пользователя отсутствует, создаем ее + var insertCommand = connection.CreateCommand(); + insertCommand.CommandText = "INSERT INTO UserSettings (UserId, NotificationsEnabled) VALUES (@userId, 1)"; + insertCommand.Parameters.AddWithValue("@userId", chatId); + await insertCommand.ExecuteNonQueryAsync(); + } + } + + // Создаем клавиатуру с настройками + string notificationStatus = notificationsEnabled ? "✅ Включены" : "❌ Отключены"; + string toggleAction = notificationsEnabled ? "toggle_off" : "toggle_on"; + + var keyboard = new InlineKeyboardMarkup(new[] + { + new[] + { + InlineKeyboardButton.WithCallbackData($"Уведомления: {notificationStatus}", $"notifications_{toggleAction}") + }, + new[] + { + InlineKeyboardButton.WithCallbackData("🔙 Назад в меню", "main_menu") + } + }); + + await botClient.SendMessage( + chatId: chatId, + text: "⚙️ Настройки пользователя\n\n" + + "Здесь вы можете настроить параметры бота:", + parseMode: ParseMode.Html, + replyMarkup: keyboard + ); + } + catch (Exception ex) + { + Log.Error($"Ошибка при отображении настроек пользователя: {ex.Message}"); + await botClient.SendMessage(chatId, "Произошла ошибка при загрузке настроек."); + } + } private static async Task HandleUpdateAsync(ITelegramBotClient botClient, Update update, CancellationToken cancellationToken) { try @@ -380,6 +462,15 @@ class Program { await SendMainMenu(botClient, chatId); } + else if (data == "user_settings") + { + await ShowUserSettings(botClient, chatId); + } + else if (data != null && data.StartsWith("notifications_toggle_")) + { + string action = data.Substring(18); // "on" или "off" + await ToggleNotifications(botClient, chatId, action); + } else if (data != null && data.StartsWith("priority_")) { string priority = data.Substring(9); @@ -591,6 +682,30 @@ class Program { try { + // Проверяем настройки пользователя + bool notificationsEnabled = true; // По умолчанию уведомления включены + + using (var connection = new SqliteConnection("Data Source=bot.db")) + { + await connection.OpenAsync(); + var command = connection.CreateCommand(); + command.CommandText = "SELECT NotificationsEnabled FROM UserSettings WHERE UserId = @userId"; + command.Parameters.AddWithValue("@userId", chatId); + + var result = await command.ExecuteScalarAsync(); + if (result != null && result != DBNull.Value) + { + notificationsEnabled = Convert.ToInt32(result) == 1; + } + } + + // Если уведомления отключены, не отправляем сообщение + if (!notificationsEnabled) + { + Log.Information($"Уведомление о смене статуса заявки #{reportId} не отправлено пользователю {chatId} (уведомления отключены)"); + return; + } + string statusEmoji = GetStatusEmoji(newStatus); await _botClient.SendMessage( chatId: chatId, @@ -605,7 +720,39 @@ class Program } } + private static async Task ToggleNotifications(ITelegramBotClient botClient, long chatId, string action) + { + try + { + bool newValue = action == "toggle_on"; + int dbValue = newValue ? 1 : 0; + using (var connection = new SqliteConnection("Data Source=bot.db")) + { + await connection.OpenAsync(); + var command = connection.CreateCommand(); + command.CommandText = @" + INSERT INTO UserSettings (UserId, NotificationsEnabled) + VALUES (@userId, @value) + ON CONFLICT(UserId) + DO UPDATE SET NotificationsEnabled = @value"; + command.Parameters.AddWithValue("@userId", chatId); + command.Parameters.AddWithValue("@value", dbValue); + await command.ExecuteNonQueryAsync(); + } + + // Показываем обновленные настройки + await ShowUserSettings(botClient, chatId); + + string statusText = newValue ? "включены" : "отключены"; + Log.Information($"Пользователь {chatId} {statusText} уведомления о статусе заявок"); + } + catch (Exception ex) + { + Log.Error($"Ошибка при изменении настроек уведомлений: {ex.Message}"); + await botClient.SendMessage(chatId, "Произошла ошибка при обновлении настроек."); + } + } private static async Task SendMainMenu(ITelegramBotClient botClient, long chatId) @@ -615,6 +762,10 @@ class Program new[] { InlineKeyboardButton.WithCallbackData("📝 Подать заявку", "report"), + }, + new[] + { + InlineKeyboardButton.WithCallbackData("⚙️ Настройки", "user_settings"), InlineKeyboardButton.WithCallbackData("🔐 Панель администратора", "admin_panel") } });