refactor: move buildable .NET source into src/, update CI/doc paths
TaxBaik CI/CD / build-and-deploy (push) Successful in 2m7s
TaxBaik CI/CD / build-and-deploy (push) Successful in 2m7s
Groups the repo root into src (buildable source), docs (already existed), and everything else (db/, scripts/, tests/, deploy/ - deployment/ops/test assets that aren't compiled, already organized as their own folders). CI now only needs src/ to build: dotnet restore/build/test/publish all point at src/TaxBaik.sln, src/TaxBaik.Web/, src/TaxBaik.Proxy/. - git mv every project (Domain, Infrastructure, Application, Application.Tests, Web, Web.Client, Proxy) and TaxBaik.sln into src/ as a unit, so relative ProjectReference/.sln paths stay valid unchanged. - .gitea/workflows/deploy.yml: 6 dotnet restore/clean/build/test/publish invocations now point at src/. db/migrations and scripts/ stay at root (deploy_gb.sh and browser-e2e.yml only touch published output and the deployed URL, not source paths - verified, no changes needed there). - scripts/validate_admin_render.sh: admin render-mode file paths now src/TaxBaik.Web.Client/... - scripts/validate_kst_timestamps.sh: dropped deploy.sh from its target list - that script was removed in the prior cleanup commit (dead, no CI workflow referenced it) but this validator still expected it to exist. - CLAUDE.md, docs/ENGINEERING_HARNESS.md, docs/ADMIN_PATTERN_CRITIQUE_WBS.md: updated project-structure diagram, dotnet run/build commands, and grep targets to the new src/ paths (also fixed a pre-existing stale path in ADMIN_PATTERN_CRITIQUE_WBS.md that still said TaxBaik.Web/Components/Admin from before that ever moved to TaxBaik.Web.Client). - Added a Repo Root harness rule + Architecture Guardrail entries: new files belong under src/docs/tests/scripts/db/deploy, not loose at root; temp work stays outside the repo (or under a gitignored .scratch/) and is never committed. Verified locally: dotnet build/test src/TaxBaik.sln (26/26 tests), and all three scripts/validate_*.sh pass against the new layout. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
@@ -1,231 +0,0 @@
|
||||
using System.IdentityModel.Tokens.Jwt;
|
||||
using System.Security.Claims;
|
||||
using System.Text;
|
||||
using BCrypt.Net;
|
||||
using Microsoft.IdentityModel.Tokens;
|
||||
using TaxBaik.Domain.Entities;
|
||||
using TaxBaik.Domain.Interfaces;
|
||||
|
||||
namespace TaxBaik.Web.Services;
|
||||
|
||||
public class AuthService
|
||||
{
|
||||
private readonly IAdminUserRepository _adminUserRepository;
|
||||
private readonly ILogger<AuthService> _logger;
|
||||
private readonly ITelegramNotificationService _telegramService;
|
||||
private readonly string _jwtSecretKey;
|
||||
private readonly string? _passwordResetToken;
|
||||
private readonly int _accessTokenExpirationMinutes = 60; // Access Token: 1시간 (사용성 향상)
|
||||
private readonly int _refreshTokenExpirationMinutes = 10080; // Refresh Token: 7일
|
||||
|
||||
public AuthService(
|
||||
IAdminUserRepository adminUserRepository,
|
||||
ILogger<AuthService> logger,
|
||||
IConfiguration configuration,
|
||||
ITelegramNotificationService telegramService)
|
||||
{
|
||||
_adminUserRepository = adminUserRepository;
|
||||
_logger = logger;
|
||||
_telegramService = telegramService;
|
||||
_jwtSecretKey = configuration["Jwt:SecretKey"] ?? throw new InvalidOperationException("Missing 'Jwt:SecretKey' configuration.");
|
||||
_passwordResetToken = configuration["Admin:PasswordResetToken"];
|
||||
}
|
||||
|
||||
public async Task<AuthTokenPair?> AuthenticateAndGenerateTokenPairAsync(string username, string password)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(username) || string.IsNullOrWhiteSpace(password))
|
||||
return null;
|
||||
|
||||
var user = await _adminUserRepository.GetByUsernameAsync(username);
|
||||
if (user == null)
|
||||
{
|
||||
_logger.LogWarning("로그인 시도: 존재하지 않는 사용자 '{Username}'", username);
|
||||
return null;
|
||||
}
|
||||
|
||||
if (string.IsNullOrWhiteSpace(user.PasswordHash))
|
||||
{
|
||||
_logger.LogError("로그인 실패: 사용자 '{Username}'의 PasswordHash가 비어 있습니다.", username);
|
||||
return null;
|
||||
}
|
||||
|
||||
if (!BCrypt.Net.BCrypt.Verify(password, user.PasswordHash))
|
||||
{
|
||||
_logger.LogWarning("로그인 시도: 잘못된 비밀번호 '{Username}'", username);
|
||||
// 실패한 로그인은 알림하지 않음 (로그만 남김)
|
||||
return null;
|
||||
}
|
||||
|
||||
_logger.LogInformation("로그인 성공: {Username}", username);
|
||||
// 로그인 알림은 제거 (로그만 남김)
|
||||
await _adminUserRepository.UpdateLastLoginAtAsync(user.Id);
|
||||
return GenerateTokenPair(user);
|
||||
}
|
||||
|
||||
public async Task<AuthTokenPair?> RefreshAccessTokenAsync(string refreshToken)
|
||||
{
|
||||
try
|
||||
{
|
||||
var principal = ValidateRefreshToken(refreshToken);
|
||||
if (principal == null)
|
||||
{
|
||||
_logger.LogWarning("Refresh token 검증 실패");
|
||||
return null;
|
||||
}
|
||||
|
||||
var username = principal.FindFirstValue(ClaimTypes.Name);
|
||||
if (string.IsNullOrWhiteSpace(username))
|
||||
return null;
|
||||
|
||||
var user = await _adminUserRepository.GetByUsernameAsync(username);
|
||||
if (user == null)
|
||||
return null;
|
||||
|
||||
return GenerateTokenPair(user);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Refresh token 처리 중 오류");
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<bool> ChangePasswordAsync(string username, string currentPassword, string newPassword)
|
||||
{
|
||||
if (!IsValidPassword(newPassword))
|
||||
throw new ArgumentException("새 비밀번호는 12자 이상이어야 합니다.", nameof(newPassword));
|
||||
|
||||
var user = await _adminUserRepository.GetByUsernameAsync(username);
|
||||
if (user == null || string.IsNullOrWhiteSpace(user.PasswordHash))
|
||||
return false;
|
||||
|
||||
if (!BCrypt.Net.BCrypt.Verify(currentPassword, user.PasswordHash))
|
||||
return false;
|
||||
|
||||
await _adminUserRepository.UpdatePasswordHashAsync(user.Id, BCrypt.Net.BCrypt.HashPassword(newPassword));
|
||||
_logger.LogInformation("관리자 비밀번호 변경: {Username}", username);
|
||||
return true;
|
||||
}
|
||||
|
||||
public async Task<bool> ResetPasswordAsync(string username, string newPassword, string resetToken)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(_passwordResetToken))
|
||||
throw new InvalidOperationException("Admin:PasswordResetToken is not configured.");
|
||||
|
||||
if (!TimeConstantEquals(resetToken, _passwordResetToken))
|
||||
return false;
|
||||
|
||||
if (!IsValidPassword(newPassword))
|
||||
throw new ArgumentException("새 비밀번호는 12자 이상이어야 합니다.", nameof(newPassword));
|
||||
|
||||
var user = await _adminUserRepository.GetByUsernameAsync(username);
|
||||
if (user == null)
|
||||
return false;
|
||||
|
||||
await _adminUserRepository.UpdatePasswordHashAsync(user.Id, BCrypt.Net.BCrypt.HashPassword(newPassword));
|
||||
_logger.LogWarning("관리자 비밀번호 재설정 API 사용: {Username}", username);
|
||||
return true;
|
||||
}
|
||||
|
||||
private AuthTokenPair GenerateTokenPair(AdminUser user)
|
||||
{
|
||||
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_jwtSecretKey));
|
||||
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
|
||||
|
||||
var claims = new[]
|
||||
{
|
||||
new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()),
|
||||
new Claim(ClaimTypes.Name, user.Username),
|
||||
new Claim("username", user.Username)
|
||||
};
|
||||
|
||||
var accessToken = new JwtSecurityToken(
|
||||
issuer: "taxbaik-admin",
|
||||
audience: "taxbaik-admin-client",
|
||||
claims: claims,
|
||||
expires: DateTime.UtcNow.AddMinutes(_accessTokenExpirationMinutes),
|
||||
signingCredentials: creds);
|
||||
|
||||
var refreshToken = new JwtSecurityToken(
|
||||
issuer: "taxbaik-admin",
|
||||
audience: "taxbaik-admin-client",
|
||||
claims: claims,
|
||||
expires: DateTime.UtcNow.AddMinutes(_refreshTokenExpirationMinutes),
|
||||
signingCredentials: creds);
|
||||
|
||||
return new AuthTokenPair(
|
||||
new JwtSecurityTokenHandler().WriteToken(accessToken),
|
||||
new JwtSecurityTokenHandler().WriteToken(refreshToken),
|
||||
_accessTokenExpirationMinutes * 60
|
||||
);
|
||||
}
|
||||
|
||||
public ClaimsPrincipal? ValidateRefreshToken(string token)
|
||||
{
|
||||
try
|
||||
{
|
||||
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_jwtSecretKey));
|
||||
var handler = new JwtSecurityTokenHandler();
|
||||
var principal = handler.ValidateToken(token, new TokenValidationParameters
|
||||
{
|
||||
ValidateIssuerSigningKey = true,
|
||||
IssuerSigningKey = key,
|
||||
ValidateIssuer = true,
|
||||
ValidIssuer = "taxbaik-admin",
|
||||
ValidateAudience = true,
|
||||
ValidAudience = "taxbaik-admin-client",
|
||||
ValidateLifetime = true,
|
||||
ClockSkew = TimeSpan.Zero
|
||||
}, out SecurityToken validatedToken);
|
||||
|
||||
return principal;
|
||||
}
|
||||
catch
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public ClaimsPrincipal? ValidateToken(string token)
|
||||
{
|
||||
try
|
||||
{
|
||||
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_jwtSecretKey));
|
||||
var handler = new JwtSecurityTokenHandler();
|
||||
var principal = handler.ValidateToken(token, new TokenValidationParameters
|
||||
{
|
||||
ValidateIssuerSigningKey = true,
|
||||
IssuerSigningKey = key,
|
||||
ValidateIssuer = true,
|
||||
ValidIssuer = "taxbaik-admin",
|
||||
ValidateAudience = true,
|
||||
ValidAudience = "taxbaik-admin-client",
|
||||
ValidateLifetime = true,
|
||||
ClockSkew = TimeSpan.Zero
|
||||
}, out SecurityToken validatedToken);
|
||||
|
||||
return principal;
|
||||
}
|
||||
catch
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private static bool IsValidPassword(string password) => !string.IsNullOrWhiteSpace(password) && password.Length >= 12;
|
||||
|
||||
private static bool TimeConstantEquals(string value, string expected)
|
||||
{
|
||||
var valueBytes = Encoding.UTF8.GetBytes(value);
|
||||
var expectedBytes = Encoding.UTF8.GetBytes(expected);
|
||||
return valueBytes.Length == expectedBytes.Length
|
||||
&& System.Security.Cryptography.CryptographicOperations.FixedTimeEquals(valueBytes, expectedBytes);
|
||||
}
|
||||
}
|
||||
|
||||
public class AuthTokenPair(string accessToken, string refreshToken, int expiresIn)
|
||||
{
|
||||
public string AccessToken { get; } = accessToken;
|
||||
public string RefreshToken { get; } = refreshToken;
|
||||
public int ExpiresIn { get; } = expiresIn;
|
||||
}
|
||||
@@ -1,7 +0,0 @@
|
||||
namespace TaxBaik.Web.Services;
|
||||
|
||||
public static class PortalAuthDefaults
|
||||
{
|
||||
public const string Scheme = "PortalCookie";
|
||||
public const string CookieName = "TaxBaik.Portal.Auth";
|
||||
}
|
||||
@@ -1,14 +0,0 @@
|
||||
namespace TaxBaik.Web.Services;
|
||||
|
||||
public sealed class PortalAuthOptions
|
||||
{
|
||||
public ExternalProviderOptions Google { get; set; } = new();
|
||||
public ExternalProviderOptions Naver { get; set; } = new();
|
||||
public ExternalProviderOptions Kakao { get; set; } = new();
|
||||
|
||||
public sealed class ExternalProviderOptions
|
||||
{
|
||||
public string ClientId { get; set; } = "";
|
||||
public string ClientSecret { get; set; } = "";
|
||||
}
|
||||
}
|
||||
@@ -1,70 +0,0 @@
|
||||
namespace TaxBaik.Web.Services;
|
||||
|
||||
using System.Security.Claims;
|
||||
using Microsoft.AspNetCore.Authentication;
|
||||
using Microsoft.AspNetCore.Authentication.Cookies;
|
||||
using Microsoft.AspNetCore.Identity;
|
||||
using TaxBaik.Application.Services;
|
||||
using TaxBaik.Domain.Entities;
|
||||
|
||||
public class PortalAuthService(
|
||||
IHttpContextAccessor httpContextAccessor,
|
||||
PortalUserService portalUserService)
|
||||
{
|
||||
private static readonly PasswordHasher<PortalUser> Hasher = new();
|
||||
|
||||
public async Task<bool> SignInAsync(string email, string password, CancellationToken ct = default)
|
||||
{
|
||||
var httpContext = httpContextAccessor.HttpContext
|
||||
?? throw new InvalidOperationException("HTTP context is unavailable.");
|
||||
|
||||
var user = await portalUserService.GetByEmailAsync(email, ct);
|
||||
if (user is null)
|
||||
return false;
|
||||
|
||||
if (string.IsNullOrWhiteSpace(user.PasswordHash))
|
||||
return false;
|
||||
|
||||
var verify = Hasher.VerifyHashedPassword(user, user.PasswordHash, password);
|
||||
if (verify == PasswordVerificationResult.Failed)
|
||||
return false;
|
||||
|
||||
var claims = new List<Claim>
|
||||
{
|
||||
new(ClaimTypes.NameIdentifier, user.Id.ToString()),
|
||||
new(ClaimTypes.Name, user.Name),
|
||||
new(ClaimTypes.Email, user.Email),
|
||||
new("portal_user_id", user.Id.ToString())
|
||||
};
|
||||
|
||||
if (user.ClientId.HasValue)
|
||||
claims.Add(new("client_id", user.ClientId.Value.ToString()));
|
||||
|
||||
var identity = new ClaimsIdentity(claims, PortalAuthDefaults.Scheme);
|
||||
var principal = new ClaimsPrincipal(identity);
|
||||
|
||||
await httpContext.SignInAsync(
|
||||
PortalAuthDefaults.Scheme,
|
||||
principal,
|
||||
new AuthenticationProperties
|
||||
{
|
||||
IsPersistent = true
|
||||
});
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
public static string HashPassword(string password)
|
||||
{
|
||||
var tempUser = new PortalUser();
|
||||
return Hasher.HashPassword(tempUser, password);
|
||||
}
|
||||
|
||||
public async Task SignOutAsync()
|
||||
{
|
||||
var httpContext = httpContextAccessor.HttpContext
|
||||
?? throw new InvalidOperationException("HTTP context is unavailable.");
|
||||
|
||||
await httpContext.SignOutAsync(PortalAuthDefaults.Scheme);
|
||||
}
|
||||
}
|
||||
@@ -1,9 +0,0 @@
|
||||
namespace TaxBaik.Web.Services;
|
||||
|
||||
public static class PortalOAuthDefaults
|
||||
{
|
||||
public const string ExternalScheme = "PortalExternal";
|
||||
public const string GoogleScheme = "PortalGoogle";
|
||||
public const string NaverScheme = "PortalNaver";
|
||||
public const string KakaoScheme = "PortalKakao";
|
||||
}
|
||||
@@ -1,57 +0,0 @@
|
||||
using System.Collections.Concurrent;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
|
||||
namespace TaxBaik.Web.Services;
|
||||
|
||||
internal static class TelegramAlertGate
|
||||
{
|
||||
private sealed record GateEntry(DateTimeOffset WindowStart, int Count);
|
||||
|
||||
private static readonly ConcurrentDictionary<string, GateEntry> Gates = new();
|
||||
|
||||
public static bool ShouldSend(string category, string content, TimeSpan window, int maxPerWindow = 1)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(category))
|
||||
return false;
|
||||
|
||||
var now = DateTimeOffset.UtcNow;
|
||||
var key = $"{category}:{Fingerprint(content)}";
|
||||
|
||||
while (true)
|
||||
{
|
||||
if (!Gates.TryGetValue(key, out var current))
|
||||
{
|
||||
var initial = new GateEntry(now, 1);
|
||||
if (Gates.TryAdd(key, initial))
|
||||
return true;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (now - current.WindowStart >= window)
|
||||
{
|
||||
var reset = new GateEntry(now, 1);
|
||||
if (Gates.TryUpdate(key, reset, current))
|
||||
return true;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (current.Count >= maxPerWindow)
|
||||
return false;
|
||||
|
||||
var incremented = current with { Count = current.Count + 1 };
|
||||
if (Gates.TryUpdate(key, incremented, current))
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
private static string Fingerprint(string content)
|
||||
{
|
||||
if (string.IsNullOrEmpty(content))
|
||||
return "empty";
|
||||
|
||||
var normalized = content.Length > 1500 ? content[..1500] : content;
|
||||
var bytes = SHA256.HashData(Encoding.UTF8.GetBytes(normalized));
|
||||
return Convert.ToHexString(bytes);
|
||||
}
|
||||
}
|
||||
@@ -1,165 +0,0 @@
|
||||
using System.Net.Http.Json;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using TaxBaik.Application.Services;
|
||||
|
||||
namespace TaxBaik.Web.Services;
|
||||
|
||||
public class TelegramInquiryNotificationService : IInquiryNotificationService
|
||||
{
|
||||
private readonly IHttpClientFactory _httpClientFactory;
|
||||
private readonly IConfiguration _configuration;
|
||||
private readonly ILogger<TelegramInquiryNotificationService> _logger;
|
||||
private readonly string _baseUrl;
|
||||
|
||||
public TelegramInquiryNotificationService(IHttpClientFactory httpClientFactory, IConfiguration configuration, ILogger<TelegramInquiryNotificationService> logger)
|
||||
{
|
||||
_httpClientFactory = httpClientFactory;
|
||||
_configuration = configuration;
|
||||
_logger = logger;
|
||||
_baseUrl = (_configuration["App:PublicBaseUrl"] ?? "http://178.104.200.7/taxbaik").TrimEnd('/');
|
||||
}
|
||||
|
||||
public async Task NotifyCreatedAsync(int inquiryId, string name, string phone, string serviceType, string message, string? ipAddress, DateTime createdAtUtc, CancellationToken ct = default)
|
||||
{
|
||||
var botToken = _configuration["Telegram:BotToken"];
|
||||
var chatId = _configuration["Telegram:InquiryChatId"];
|
||||
if (string.IsNullOrWhiteSpace(chatId))
|
||||
chatId = _configuration["Telegram:ChatId"];
|
||||
if (string.IsNullOrWhiteSpace(botToken) || string.IsNullOrWhiteSpace(chatId))
|
||||
{
|
||||
_logger.LogWarning("텔레그램 새 문의 알림 설정이 누락되었습니다. Telegram:BotToken 또는 Telegram:InquiryChatId/ChatId를 확인하세요.");
|
||||
return;
|
||||
}
|
||||
|
||||
var adminLink = $"{_baseUrl}/admin/inquiries";
|
||||
var summary = message.Length > 180 ? message[..180] + "..." : message;
|
||||
var createdAtKst = createdAtUtc.AddHours(9);
|
||||
var text = new StringBuilder()
|
||||
.AppendLine("🆕 새 문의가 접수되었습니다.")
|
||||
.AppendLine()
|
||||
.AppendLine($"문의 번호: #{inquiryId}")
|
||||
.AppendLine($"제목: {serviceType}")
|
||||
.AppendLine($"이름: {name}")
|
||||
.AppendLine($"연락처: {phone}")
|
||||
.AppendLine($"접수 시각: {createdAtKst:yyyy-MM-dd HH:mm:ss} KST")
|
||||
.AppendLine($"IP: {(string.IsNullOrWhiteSpace(ipAddress) ? "-" : ipAddress)}")
|
||||
.AppendLine()
|
||||
.AppendLine("내용 요약:")
|
||||
.AppendLine(summary)
|
||||
.AppendLine()
|
||||
.AppendLine($"답변 목록 링크: {adminLink}")
|
||||
.ToString();
|
||||
|
||||
var client = _httpClientFactory.CreateClient();
|
||||
var url = $"https://api.telegram.org/bot{botToken}/sendMessage";
|
||||
var payload = new
|
||||
{
|
||||
chat_id = chatId,
|
||||
text,
|
||||
disable_web_page_preview = false
|
||||
};
|
||||
|
||||
try
|
||||
{
|
||||
var response = await client.PostAsJsonAsync(url, payload, ct);
|
||||
var responseBody = await response.Content.ReadAsStringAsync(ct);
|
||||
if (!response.IsSuccessStatusCode)
|
||||
{
|
||||
_logger.LogWarning("텔레그램 알림 전송 실패: {StatusCode} {ResponseBody}", response.StatusCode, Truncate(responseBody));
|
||||
}
|
||||
else
|
||||
{
|
||||
_logger.LogInformation("텔레그램 새 문의 알림 전송 성공: #{InquiryId}, message_id={MessageId}", inquiryId, TryGetMessageId(responseBody));
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogWarning(ex, "텔레그램 알림 전송 중 오류 발생");
|
||||
}
|
||||
}
|
||||
|
||||
public async Task NotifyStatusChangedAsync(int inquiryId, string name, string phone, string serviceType, string previousStatus, string newStatus, string? changedBy = null, CancellationToken ct = default)
|
||||
{
|
||||
var botToken = _configuration["Telegram:BotToken"];
|
||||
var chatId = _configuration["Telegram:InquiryChatId"];
|
||||
if (string.IsNullOrWhiteSpace(chatId))
|
||||
chatId = _configuration["Telegram:ChatId"];
|
||||
if (string.IsNullOrWhiteSpace(botToken) || string.IsNullOrWhiteSpace(chatId))
|
||||
{
|
||||
_logger.LogWarning("텔레그램 상태 변경 알림 설정이 누락되었습니다. Telegram:BotToken 또는 Telegram:InquiryChatId/ChatId를 확인하세요.");
|
||||
return;
|
||||
}
|
||||
|
||||
var adminLink = $"{_baseUrl}/admin/inquiries";
|
||||
var text = new StringBuilder()
|
||||
.AppendLine("✏️ 문의 상태가 변경되었습니다.")
|
||||
.AppendLine()
|
||||
.AppendLine($"문의 번호: #{inquiryId}")
|
||||
.AppendLine($"제목: {serviceType}")
|
||||
.AppendLine($"이름: {name}")
|
||||
.AppendLine($"연락처: {phone}")
|
||||
.AppendLine($"상태: {FormatStatus(previousStatus)} -> {FormatStatus(newStatus)}")
|
||||
.AppendLine($"변경자: {(string.IsNullOrWhiteSpace(changedBy) ? "-" : changedBy)}")
|
||||
.AppendLine()
|
||||
.AppendLine($"답변 목록 링크: {adminLink}")
|
||||
.ToString();
|
||||
|
||||
var client = _httpClientFactory.CreateClient();
|
||||
var url = $"https://api.telegram.org/bot{botToken}/sendMessage";
|
||||
var payload = new
|
||||
{
|
||||
chat_id = chatId,
|
||||
text,
|
||||
disable_web_page_preview = false
|
||||
};
|
||||
|
||||
try
|
||||
{
|
||||
var response = await client.PostAsJsonAsync(url, payload, ct);
|
||||
var responseBody = await response.Content.ReadAsStringAsync(ct);
|
||||
if (!response.IsSuccessStatusCode)
|
||||
{
|
||||
_logger.LogWarning("텔레그램 상태 변경 알림 실패: {StatusCode} {ResponseBody}", response.StatusCode, Truncate(responseBody));
|
||||
}
|
||||
else
|
||||
{
|
||||
_logger.LogInformation("텔레그램 상태 변경 알림 전송 성공: #{InquiryId}, message_id={MessageId}", inquiryId, TryGetMessageId(responseBody));
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogWarning(ex, "텔레그램 상태 변경 알림 중 오류 발생");
|
||||
}
|
||||
}
|
||||
|
||||
private static string FormatStatus(string status) => status switch
|
||||
{
|
||||
"new" => "신규",
|
||||
"contacted" => "연락함",
|
||||
"completed" => "완료",
|
||||
_ => status
|
||||
};
|
||||
|
||||
private static string TryGetMessageId(string responseBody)
|
||||
{
|
||||
try
|
||||
{
|
||||
using var document = JsonDocument.Parse(responseBody);
|
||||
if (document.RootElement.TryGetProperty("result", out var result)
|
||||
&& result.TryGetProperty("message_id", out var messageId))
|
||||
{
|
||||
return messageId.ToString();
|
||||
}
|
||||
}
|
||||
catch (JsonException)
|
||||
{
|
||||
return "unknown";
|
||||
}
|
||||
|
||||
return "unknown";
|
||||
}
|
||||
|
||||
private static string Truncate(string value)
|
||||
=> value.Length <= 500 ? value : value[..500] + "...";
|
||||
}
|
||||
@@ -1,130 +0,0 @@
|
||||
namespace TaxBaik.Web.Services;
|
||||
|
||||
using System.Net.Http.Json;
|
||||
|
||||
/// <summary>
|
||||
/// Telegram Bot 알림 서비스
|
||||
/// 중요 로깅 및 오류를 Telegram으로 전송
|
||||
/// </summary>
|
||||
public interface ITelegramNotificationService
|
||||
{
|
||||
Task SendMessageAsync(string message, CancellationToken ct = default);
|
||||
Task SendErrorAsync(string title, string details, CancellationToken ct = default);
|
||||
Task SendInfoAsync(string title, string message, CancellationToken ct = default);
|
||||
Task SendInquiryNotificationAsync(string message, CancellationToken ct = default);
|
||||
Task SendSystemNotificationAsync(string message, CancellationToken ct = default);
|
||||
Task SendReportAsync(string reportTitle, string reportContent, CancellationToken ct = default);
|
||||
}
|
||||
|
||||
public class TelegramNotificationService : ITelegramNotificationService
|
||||
{
|
||||
private readonly HttpClient _httpClient;
|
||||
private readonly ILogger<TelegramNotificationService> _logger;
|
||||
private readonly string _botToken;
|
||||
private readonly string _defaultChatId;
|
||||
private readonly string _inquiryChatId;
|
||||
private readonly string _systemChatId;
|
||||
private const string TelegramApiUrl = "https://api.telegram.org";
|
||||
|
||||
public TelegramNotificationService(
|
||||
HttpClient httpClient,
|
||||
ILogger<TelegramNotificationService> logger,
|
||||
IConfiguration config)
|
||||
{
|
||||
_httpClient = httpClient;
|
||||
_logger = logger;
|
||||
_botToken = config["Telegram:BotToken"] ?? "";
|
||||
_defaultChatId = config["Telegram:ChatId"] ?? "-5434691215";
|
||||
_inquiryChatId = config["Telegram:InquiryChatId"] ?? _defaultChatId;
|
||||
_systemChatId = config["Telegram:SystemChatId"] ?? "-5585148480";
|
||||
}
|
||||
|
||||
public async Task SendMessageAsync(string message, CancellationToken ct = default)
|
||||
{
|
||||
if (string.IsNullOrEmpty(_botToken) || string.IsNullOrEmpty(_defaultChatId))
|
||||
{
|
||||
_logger.LogWarning("Telegram credentials not configured");
|
||||
return;
|
||||
}
|
||||
|
||||
if (!TelegramAlertGate.ShouldSend("telegram:default", message, TimeSpan.FromMinutes(5)))
|
||||
return;
|
||||
|
||||
await SendToChat(_defaultChatId, message, ct);
|
||||
}
|
||||
|
||||
public async Task SendInquiryNotificationAsync(string message, CancellationToken ct = default)
|
||||
{
|
||||
var text = $"<b>📋 문의 사항</b>\n\n{message}";
|
||||
if (!TelegramAlertGate.ShouldSend("telegram:inquiry", text, TimeSpan.FromMinutes(10)))
|
||||
return;
|
||||
|
||||
await SendToChat(_inquiryChatId, text, ct);
|
||||
}
|
||||
|
||||
public async Task SendSystemNotificationAsync(string message, CancellationToken ct = default)
|
||||
{
|
||||
var text = $"<b>🔧 시스템 알림</b>\n\n{message}";
|
||||
if (!TelegramAlertGate.ShouldSend("telegram:system", text, TimeSpan.FromMinutes(10)))
|
||||
return;
|
||||
|
||||
await SendToChat(_systemChatId, text, ct);
|
||||
}
|
||||
|
||||
private async Task SendToChat(string chatId, string message, CancellationToken ct)
|
||||
{
|
||||
if (string.IsNullOrEmpty(_botToken) || string.IsNullOrEmpty(chatId))
|
||||
{
|
||||
_logger.LogWarning("Telegram credentials not configured for chatId {ChatId}", chatId);
|
||||
return;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
var url = $"{TelegramApiUrl}/bot{_botToken}/sendMessage";
|
||||
var payload = new
|
||||
{
|
||||
chat_id = chatId,
|
||||
text = message,
|
||||
parse_mode = "HTML"
|
||||
};
|
||||
|
||||
var response = await _httpClient.PostAsJsonAsync(url, payload, cancellationToken: ct);
|
||||
if (!response.IsSuccessStatusCode)
|
||||
{
|
||||
_logger.LogError("Failed to send Telegram message to {ChatId}: {StatusCode}", chatId, response.StatusCode);
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error sending Telegram message to {ChatId}", chatId);
|
||||
}
|
||||
}
|
||||
|
||||
public async Task SendErrorAsync(string title, string details, CancellationToken ct = default)
|
||||
{
|
||||
var message = $"<b>❌ {title}</b>\n\n{details}\n\n<i>{DateTime.UtcNow:yyyy-MM-dd HH:mm:ss} UTC</i>";
|
||||
if (!TelegramAlertGate.ShouldSend("telegram:error", message, TimeSpan.FromMinutes(15)))
|
||||
return;
|
||||
|
||||
await SendToChat(_systemChatId, message, ct);
|
||||
}
|
||||
|
||||
public async Task SendInfoAsync(string title, string message, CancellationToken ct = default)
|
||||
{
|
||||
var text = $"<b>ℹ️ {title}</b>\n\n{message}\n\n<i>{DateTime.UtcNow:yyyy-MM-dd HH:mm:ss} UTC</i>";
|
||||
if (!TelegramAlertGate.ShouldSend("telegram:info", text, TimeSpan.FromMinutes(30)))
|
||||
return;
|
||||
|
||||
await SendToChat(_defaultChatId, text, ct);
|
||||
}
|
||||
|
||||
public async Task SendReportAsync(string reportTitle, string reportContent, CancellationToken ct = default)
|
||||
{
|
||||
var text = $"<b>📊 {reportTitle}</b>\n\n{reportContent}\n\n<i>{DateTime.UtcNow:yyyy-MM-dd HH:mm:ss} UTC</i>";
|
||||
if (!TelegramAlertGate.ShouldSend("telegram:report", text, TimeSpan.FromHours(20)))
|
||||
return;
|
||||
|
||||
await SendToChat(_systemChatId, text, ct);
|
||||
}
|
||||
}
|
||||
@@ -1,93 +0,0 @@
|
||||
namespace TaxBaik.Web.Services;
|
||||
|
||||
using Microsoft.Extensions.Hosting;
|
||||
using TaxBaik.Application.Services;
|
||||
|
||||
public class TelegramReportBackgroundService(
|
||||
IServiceScopeFactory scopeFactory,
|
||||
ILogger<TelegramReportBackgroundService> logger) : BackgroundService
|
||||
{
|
||||
private static readonly TimeZoneInfo KoreaTimeZone = GetKoreaTimeZone();
|
||||
private DateOnly? _lastDailyReportDate;
|
||||
private DateOnly? _lastWeeklyReportWeekStart;
|
||||
|
||||
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
|
||||
{
|
||||
using var timer = new PeriodicTimer(TimeSpan.FromMinutes(30));
|
||||
|
||||
try
|
||||
{
|
||||
while (await timer.WaitForNextTickAsync(stoppingToken))
|
||||
{
|
||||
try
|
||||
{
|
||||
var now = TimeZoneInfo.ConvertTime(DateTimeOffset.UtcNow, KoreaTimeZone);
|
||||
await TrySendReportsAsync(now, stoppingToken);
|
||||
}
|
||||
catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested)
|
||||
{
|
||||
break;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
logger.LogError(ex, "Telegram report background loop failed");
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested)
|
||||
{
|
||||
// Normal shutdown path.
|
||||
}
|
||||
}
|
||||
|
||||
private async Task TrySendReportsAsync(DateTimeOffset nowKst, CancellationToken ct)
|
||||
{
|
||||
if (nowKst.Hour is 9 or 10)
|
||||
await SendDailyIfNeededAsync(DateOnly.FromDateTime(nowKst.DateTime), ct);
|
||||
|
||||
if (nowKst.DayOfWeek == DayOfWeek.Monday && nowKst.Hour is 9 or 10)
|
||||
await SendWeeklyIfNeededAsync(DateOnly.FromDateTime(nowKst.DateTime).AddDays(-7), ct);
|
||||
}
|
||||
|
||||
private async Task SendDailyIfNeededAsync(DateOnly date, CancellationToken ct)
|
||||
{
|
||||
if (_lastDailyReportDate == date)
|
||||
return;
|
||||
|
||||
using var scope = scopeFactory.CreateScope();
|
||||
var reportService = scope.ServiceProvider.GetRequiredService<TelegramReportService>();
|
||||
var telegram = scope.ServiceProvider.GetRequiredService<ITelegramNotificationService>();
|
||||
|
||||
var report = await reportService.BuildDailyReportAsync(date, ct);
|
||||
await telegram.SendReportAsync("일간 세무/상담 현황 리포트", TelegramReportService.FormatDailyMessage(report), ct);
|
||||
_lastDailyReportDate = date;
|
||||
logger.LogInformation("Daily telegram report sent for {Date}", date);
|
||||
}
|
||||
|
||||
private async Task SendWeeklyIfNeededAsync(DateOnly weekStart, CancellationToken ct)
|
||||
{
|
||||
if (_lastWeeklyReportWeekStart == weekStart)
|
||||
return;
|
||||
|
||||
using var scope = scopeFactory.CreateScope();
|
||||
var reportService = scope.ServiceProvider.GetRequiredService<TelegramReportService>();
|
||||
var telegram = scope.ServiceProvider.GetRequiredService<ITelegramNotificationService>();
|
||||
|
||||
var report = await reportService.BuildWeeklyReportAsync(weekStart, ct);
|
||||
await telegram.SendReportAsync("주간 세무/매출 종합 리포트", TelegramReportService.FormatWeeklyMessage(report), ct);
|
||||
_lastWeeklyReportWeekStart = weekStart;
|
||||
logger.LogInformation("Weekly telegram report sent for {WeekStart}", weekStart);
|
||||
}
|
||||
|
||||
private static TimeZoneInfo GetKoreaTimeZone()
|
||||
{
|
||||
try
|
||||
{
|
||||
return TimeZoneInfo.FindSystemTimeZoneById("Korea Standard Time");
|
||||
}
|
||||
catch (TimeZoneNotFoundException)
|
||||
{
|
||||
return TimeZoneInfo.FindSystemTimeZoneById("Asia/Seoul");
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user