krona-staff/apps/KronaStaffTerminal/Services/NotificationService.cs
Ochenstarik efd5bd5c60
Some checks are pending
ci / verify (push) Waiting to run
feat: add SLK20R attendance terminal
2026-09-17 20:51:20 +07:00

79 lines
2.8 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using System.Net.Http.Json;
using System.Text;
using System.Text.Json;
using KronaStaffTerminal.Models;
namespace KronaStaffTerminal.Services;
public sealed class NotificationService
{
private readonly HttpClient _httpClient = new() { Timeout = TimeSpan.FromSeconds(15) };
public async Task<(bool Delivered, string? Error)> SendArrivalAsync(TerminalSettings settings, string employeeName, DateTimeOffset localTime)
{
return await SendAsync(settings, $"{employeeName} пришёл(а) в {localTime:HH:mm}");
}
public async Task<(bool Delivered, string? Error)> SendTestAsync(TerminalSettings settings)
{
return await SendAsync(settings, "Krona Staff: тестовое сообщение доставлено.");
}
private async Task<(bool Delivered, string? Error)> SendAsync(TerminalSettings settings, string text)
{
var errors = new List<string>();
var sent = false;
if (settings.TelegramEnabled)
{
try
{
var url = $"https://api.telegram.org/bot{settings.TelegramBotToken}/sendMessage";
using var response = await _httpClient.PostAsJsonAsync(url, new { chat_id = settings.TelegramChatId, text });
if (!response.IsSuccessStatusCode)
{
errors.Add($"Telegram: HTTP {(int)response.StatusCode}");
}
else
{
sent = true;
}
}
catch (Exception exception)
{
errors.Add($"Telegram: {exception.Message}");
}
}
if (settings.MaxEnabled)
{
try
{
var url = $"https://platform-api.max.ru/messages?chat_id={Uri.EscapeDataString(settings.MaxChatId)}";
using var request = new HttpRequestMessage(HttpMethod.Post, url);
request.Headers.TryAddWithoutValidation("Authorization", settings.MaxBotToken);
request.Content = new StringContent(JsonSerializer.Serialize(new { text }), Encoding.UTF8, "application/json");
using var response = await _httpClient.SendAsync(request);
if (!response.IsSuccessStatusCode)
{
errors.Add($"MAX: HTTP {(int)response.StatusCode}");
}
else
{
sent = true;
}
}
catch (Exception exception)
{
errors.Add($"MAX: {exception.Message}");
}
}
if (!settings.TelegramEnabled && !settings.MaxEnabled)
{
return (false, null);
}
return (sent && errors.Count == 0, errors.Count == 0 ? null : string.Join("; ", errors));
}
}