From b1e0638979d8032fec0bae71f51b7a3c137506ef Mon Sep 17 00:00:00 2001 From: GonnaHetzMe Date: Thu, 19 Nov 2026 12:58:03 +0100 Subject: [PATCH 1/4] backend: Add management statistics endpoints --- .../Controllers/StatisticsController.cs | 61 ++++++++ .../Abstractions/Abstractions.cs | 2 + .../DependencyInjection.cs | 2 + .../Statistics/StatisticsDtos.cs | 26 ++++ .../Statistics/StatisticsService.cs | 141 ++++++++++++++++++ .../Persistence/HelpdeskDbContext.cs | 8 + 6 files changed, 240 insertions(+) create mode 100644 backend/src/Helpdesk.Api/Controllers/StatisticsController.cs create mode 100644 backend/src/Helpdesk.Application/Statistics/StatisticsDtos.cs create mode 100644 backend/src/Helpdesk.Application/Statistics/StatisticsService.cs diff --git a/backend/src/Helpdesk.Api/Controllers/StatisticsController.cs b/backend/src/Helpdesk.Api/Controllers/StatisticsController.cs new file mode 100644 index 0000000..dbc8e4d --- /dev/null +++ b/backend/src/Helpdesk.Api/Controllers/StatisticsController.cs @@ -0,0 +1,61 @@ +using System.ComponentModel.DataAnnotations; +using Helpdesk.Api.Infrastructure; +using Helpdesk.Application.Statistics; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Mvc; + +namespace Helpdesk.Api.Controllers; + +/// Statistiky pro vedení školy. Období v UTC zahrnuje začátek a vylučuje konec. +[ApiController] +[Authorize(Roles = Roles.Management)] +[ResponseCache(NoStore = true, Location = ResponseCacheLocation.None)] +[Route("api/statistics")] +[ProducesResponseType(StatusCodes.Status400BadRequest)] +[ProducesResponseType(StatusCodes.Status401Unauthorized)] +[ProducesResponseType(StatusCodes.Status403Forbidden)] +public sealed class StatisticsController(StatisticsService statistics) : ControllerBase +{ + /// Počty podle aktuálního stavu a průměrné časy pro závady nahlášené v období. + [HttpGet("overview")] + public Task GetOverview([FromQuery] StatisticsQuery query, CancellationToken ct) => + statistics.GetOverviewAsync(query.ToPeriod(), ct); + + /// Počty nahlášených závad a průměrná doba vyřešení podle kategorie. + [HttpGet("issues/by-category")] + public Task> GetByCategory([FromQuery] StatisticsQuery query, CancellationToken ct) => + statistics.GetByCategoryAsync(query.ToPeriod(), ct); + + /// Počty nahlášených závad podle budovy včetně závad bez budovy. + [HttpGet("issues/by-building")] + public Task> GetByBuilding([FromQuery] StatisticsQuery query, CancellationToken ct) => + statistics.GetByBuildingAsync(query.ToPeriod(), ct); + + /// Otevřené, vyřešené a zamítnuté závady podle aktuálního řešitele. + [HttpGet("issues/by-assignee")] + public Task> GetByAssignee([FromQuery] StatisticsQuery query, CancellationToken ct) => + statistics.GetByAssigneeAsync(query.ToPeriod(), ct); + + /// Počty vytvoření a uzavření závad po měsících podle data události. + [HttpGet("issues/trend")] + public Task> GetTrend([FromQuery] StatisticsQuery query, CancellationToken ct, + [FromQuery, AllowedValues("month")] string granularity = "month") => + statistics.GetTrendAsync(query.ToPeriod(), ct); + + /// Návrhy podané v období podle aktuálního skóre, počtu hlasů pro a data podání. + [HttpGet("proposals/top")] + public Task> GetTopProposals([FromQuery] StatisticsQuery query, CancellationToken ct, + [FromQuery, Range(1, 100)] int limit = 10) => + statistics.GetTopProposalsAsync(query.ToPeriod(), limit, ct); +} + +public sealed class StatisticsQuery +{ + [FromQuery(Name = "from")] + public DateTimeOffset? From { get; init; } + + [FromQuery(Name = "to")] + public DateTimeOffset? To { get; init; } + + internal StatisticsPeriod ToPeriod() => new(From, To); +} diff --git a/backend/src/Helpdesk.Application/Abstractions/Abstractions.cs b/backend/src/Helpdesk.Application/Abstractions/Abstractions.cs index 81f767d..abcdb58 100644 --- a/backend/src/Helpdesk.Application/Abstractions/Abstractions.cs +++ b/backend/src/Helpdesk.Application/Abstractions/Abstractions.cs @@ -1,3 +1,4 @@ +using Helpdesk.Application.Statistics; using Helpdesk.Domain.Auth; using Helpdesk.Domain.Catalogs; using Helpdesk.Domain.Issues; @@ -18,6 +19,7 @@ public interface IAppDbContext DbSet ProposalCategories { get; } DbSet Issues { get; } DbSet IssueEvents { get; } + IQueryable IssueTimings { get; } DbSet Attachments { get; } DbSet Proposals { get; } DbSet ProposalEvents { get; } diff --git a/backend/src/Helpdesk.Application/DependencyInjection.cs b/backend/src/Helpdesk.Application/DependencyInjection.cs index 462c29b..290ea91 100644 --- a/backend/src/Helpdesk.Application/DependencyInjection.cs +++ b/backend/src/Helpdesk.Application/DependencyInjection.cs @@ -4,6 +4,7 @@ using Helpdesk.Application.Catalogs; using Helpdesk.Application.Issues; using Helpdesk.Application.Notifications; using Helpdesk.Application.Proposals; +using Helpdesk.Application.Statistics; using Helpdesk.Application.Users; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; @@ -25,6 +26,7 @@ public static class DependencyInjection services.AddScoped(); services.AddScoped(); services.AddScoped(); + services.AddScoped(); return services; } } diff --git a/backend/src/Helpdesk.Application/Statistics/StatisticsDtos.cs b/backend/src/Helpdesk.Application/Statistics/StatisticsDtos.cs new file mode 100644 index 0000000..1fcf6c0 --- /dev/null +++ b/backend/src/Helpdesk.Application/Statistics/StatisticsDtos.cs @@ -0,0 +1,26 @@ +using Helpdesk.Application.Common; + +namespace Helpdesk.Application.Statistics; + +public sealed record StatisticsPeriod(DateTimeOffset? From, DateTimeOffset? To) +{ + internal (DateTime? From, DateTime? To) UtcBounds() + { + if (From >= To) + throw new BadRequestException("Začátek období musí předcházet jeho konci."); + + return (From?.UtcDateTime, To?.UtcDateTime); + } +} + +public sealed record IssueTiming(int IssueId, long? MicrosecondsToAssignment, long? MicrosecondsToClosure); + +public sealed record StatisticsOverview( + int TotalIssues, IReadOnlyDictionary IssuesByStatus, + decimal? AverageHoursToAssignment, decimal? AverageHoursToClosure); + +public sealed record IssueCategoryStatistics(int CategoryId, string Name, int IssueCount, decimal? AverageHoursToResolution); +public sealed record IssueBuildingStatistics(int? BuildingId, string? Name, int IssueCount); +public sealed record IssueAssigneeStatistics(int AssigneeId, string Name, int OpenIssues, int ResolvedIssues, int RejectedIssues); +public sealed record IssueTrendPoint(DateOnly Month, int CreatedIssues, int ClosedIssues); +public sealed record TopProposal(int Id, string Title, string Status, long VotesFor, long VotesAgainst, long Score); diff --git a/backend/src/Helpdesk.Application/Statistics/StatisticsService.cs b/backend/src/Helpdesk.Application/Statistics/StatisticsService.cs new file mode 100644 index 0000000..ad8f4be --- /dev/null +++ b/backend/src/Helpdesk.Application/Statistics/StatisticsService.cs @@ -0,0 +1,141 @@ +using Helpdesk.Application.Abstractions; +using Helpdesk.Application.Common; +using Helpdesk.Domain; +using Helpdesk.Domain.Issues; +using Microsoft.EntityFrameworkCore; + +namespace Helpdesk.Application.Statistics; + +public sealed class StatisticsService(IAppDbContext db) +{ + private const decimal MicrosecondsPerHour = 3_600_000_000m; + + public async Task GetOverviewAsync(StatisticsPeriod period, CancellationToken ct) + { + var byStatus = await ( + from issue in IssuesInPeriod(period) + join timing in db.IssueTimings on issue.Id equals timing.IssueId into timings + from timing in timings.DefaultIfEmpty() + group timing by issue.Status into rows + select new + { + Status = rows.Key, + Count = rows.Count(), + AssignedCount = rows.Count(t => t.MicrosecondsToAssignment != null), + ClosedCount = rows.Count(t => t.MicrosecondsToClosure != null), + AssignmentTime = rows.Sum(t => (decimal?)t.MicrosecondsToAssignment), + ClosureTime = rows.Sum(t => (decimal?)t.MicrosecondsToClosure), + }).ToDictionaryAsync(row => row.Status, ct); + + var counts = Enum.GetValues() + .ToDictionary(status => status.ToCode(), status => byStatus.GetValueOrDefault(status)?.Count ?? 0); + return new StatisticsOverview( + counts.Values.Sum(), + counts, + AverageHours(byStatus.Values.Sum(row => row.AssignmentTime), byStatus.Values.Sum(row => row.AssignedCount)), + AverageHours(byStatus.Values.Sum(row => row.ClosureTime), byStatus.Values.Sum(row => row.ClosedCount))); + } + + public async Task> GetByCategoryAsync(StatisticsPeriod period, CancellationToken ct) + { + var groups = await ( + from issue in IssuesInPeriod(period) + join category in db.IssueCategories on issue.CategoryId equals category.Id + join timing in db.IssueTimings on issue.Id equals timing.IssueId into timings + from timing in timings.DefaultIfEmpty() + group new { issue.Status, timing.MicrosecondsToClosure } by new { category.Id, category.Name } into rows + orderby rows.Key.Id + select new + { + rows.Key.Id, + rows.Key.Name, + Count = rows.Count(), + ResolutionTime = rows.Average(row => row.Status == IssueStatus.Resolved + ? (decimal?)row.MicrosecondsToClosure : null), + }).ToListAsync(ct); + + return groups.Select(row => new IssueCategoryStatistics( + row.Id, row.Name, row.Count, row.ResolutionTime / MicrosecondsPerHour)).ToArray(); + } + + public async Task> GetByBuildingAsync(StatisticsPeriod period, CancellationToken ct) => + await ( + from issue in IssuesInPeriod(period) + join building in db.Buildings on issue.BuildingId equals building.Id into buildings + from building in buildings.DefaultIfEmpty() + group issue by new { issue.BuildingId, building.Name } into rows + orderby rows.Key.BuildingId + select new IssueBuildingStatistics(rows.Key.BuildingId, rows.Key.Name, rows.Count())).ToListAsync(ct); + + public async Task> GetByAssigneeAsync(StatisticsPeriod period, CancellationToken ct) => + await ( + from issue in IssuesInPeriod(period) + join assignee in db.Users on issue.AssigneeId equals assignee.Id + group issue by new { assignee.Id, assignee.FirstName, assignee.LastName } into rows + orderby rows.Key.LastName, rows.Key.FirstName, rows.Key.Id + select new IssueAssigneeStatistics( + rows.Key.Id, + rows.Key.FirstName + " " + rows.Key.LastName, + rows.Count(i => i.Status == IssueStatus.Assigned || i.Status == IssueStatus.InProgress || + i.Status == IssueStatus.PendingVerification), + rows.Count(i => i.Status == IssueStatus.Resolved), + rows.Count(i => i.Status == IssueStatus.Rejected))).ToListAsync(ct); + + public async Task> GetTrendAsync(StatisticsPeriod period, CancellationToken ct) + { + var (from, to) = period.UtcBounds(); + var created = await CountByMonthAsync(db.Issues.Select(i => i.CreatedAt), from, to, ct); + var closed = await CountByMonthAsync( + db.IssueEvents.Where(e => e.EventType == IssueEventType.StatusChanged && + (e.ToStatus == IssueStatus.Resolved || e.ToStatus == IssueStatus.Rejected)).Select(e => e.OccurredAt), + from, to, ct); + + var observed = created.Keys.Concat(closed.Keys).ToArray(); + if (observed.Length == 0 && (from is null || to is null)) + return []; + + var first = from is DateTime start ? MonthIndex(start) : observed.Min(); + var last = to is DateTime end ? MonthIndex(end.AddTicks(-1)) : observed.Max(); + var result = new List(); + for (var month = first; month <= last; month++) + { + var date = new DateOnly(month / 12 + 1, month % 12 + 1, 1); + result.Add(new IssueTrendPoint(date, created.GetValueOrDefault(month), closed.GetValueOrDefault(month))); + } + + return result; + } + + public async Task> GetTopProposalsAsync(StatisticsPeriod period, int limit, CancellationToken ct) + { + var (start, end) = period.UtcBounds(); + var top = await ( + from proposal in db.Proposals + where (start == null || proposal.CreatedAt >= start) && (end == null || proposal.CreatedAt < end) + join score in db.ProposalScores on proposal.Id equals score.ProposalId + orderby score.Score descending, score.VotesFor descending, proposal.CreatedAt, proposal.Id + select new { proposal.Id, proposal.Title, proposal.Status, score.VotesFor, score.VotesAgainst, score.Score }) + .Take(limit).ToListAsync(ct); + + return top.Select(row => new TopProposal(row.Id, row.Title, row.Status.ToCode(), + (long)row.VotesFor, (long)row.VotesAgainst, (long)row.Score)).ToArray(); + } + + private IQueryable IssuesInPeriod(StatisticsPeriod period) + { + var (from, to) = period.UtcBounds(); + return db.Issues.Where(i => (from == null || i.CreatedAt >= from) && (to == null || i.CreatedAt < to)); + } + + private static Task> CountByMonthAsync( + IQueryable dates, DateTime? from, DateTime? to, CancellationToken ct) => + dates.Where(date => (from == null || date >= from) && (to == null || date < to)) + .GroupBy(date => (date.Year - 1) * 12 + date.Month - 1) + .Select(rows => new { Month = rows.Key, Count = rows.Count() }) + .ToDictionaryAsync(row => row.Month, row => row.Count, ct); + + private static int MonthIndex(DateTime date) => (date.Year - 1) * 12 + date.Month - 1; + + private static decimal? AverageHours(decimal? microseconds, int count) => + count == 0 ? null : microseconds / count / MicrosecondsPerHour; +} diff --git a/backend/src/Helpdesk.Infrastructure/Persistence/HelpdeskDbContext.cs b/backend/src/Helpdesk.Infrastructure/Persistence/HelpdeskDbContext.cs index 2645811..5bd2548 100644 --- a/backend/src/Helpdesk.Infrastructure/Persistence/HelpdeskDbContext.cs +++ b/backend/src/Helpdesk.Infrastructure/Persistence/HelpdeskDbContext.cs @@ -1,5 +1,6 @@ using System.Data; using Helpdesk.Application.Abstractions; +using Helpdesk.Application.Statistics; using Helpdesk.Domain.Auth; using Helpdesk.Domain.Catalogs; using Helpdesk.Domain.Issues; @@ -27,6 +28,7 @@ public sealed class HelpdeskDbContext(DbContextOptions option public DbSet ProposalCategories => Set(); public DbSet Issues => Set(); public DbSet IssueEvents => Set(); + public IQueryable IssueTimings => Set(); public DbSet Attachments => Set(); public DbSet Proposals => Set(); public DbSet ProposalEvents => Set(); @@ -55,6 +57,12 @@ public sealed class HelpdeskDbContext(DbContextOptions option modelBuilder.ApplyConfiguration(new ProposalCategoryConfiguration()); modelBuilder.ApplyConfiguration(new IssueConfiguration()); modelBuilder.ApplyConfiguration(new IssueEventConfiguration()); + modelBuilder.Entity().HasNoKey().ToSqlQuery(""" + SELECT issue_id, + TIMESTAMPDIFF(MICROSECOND, created_at, first_assigned_at) AS microseconds_to_assignment, + TIMESTAMPDIFF(MICROSECOND, created_at, closed_at) AS microseconds_to_closure + FROM v_issue_lifecycle + """); modelBuilder.ApplyConfiguration(new AttachmentConfiguration()); modelBuilder.ApplyConfiguration(new ProposalConfiguration()); modelBuilder.ApplyConfiguration(new ProposalEventConfiguration()); From 28fc49ea39e7d6ae5b4f062e09a3650e745d9fab Mon Sep 17 00:00:00 2001 From: GonnaHetzMe Date: Thu, 19 Nov 2026 13:07:48 +0100 Subject: [PATCH 2/4] Add category catalog management --- .../Controllers/CatalogsController.cs | 78 ++++++++++++++++-- .../Catalogs/CatalogService.cs | 82 +++++++++++++++++-- .../src/Helpdesk.Domain/Catalogs/Catalogs.cs | 20 +++++ .../Persistence/HelpdeskDbContext.cs | 16 ++++ 4 files changed, 185 insertions(+), 11 deletions(-) diff --git a/backend/src/Helpdesk.Api/Controllers/CatalogsController.cs b/backend/src/Helpdesk.Api/Controllers/CatalogsController.cs index 9461546..da8242d 100644 --- a/backend/src/Helpdesk.Api/Controllers/CatalogsController.cs +++ b/backend/src/Helpdesk.Api/Controllers/CatalogsController.cs @@ -17,12 +17,6 @@ public sealed class CatalogsController(CatalogService catalogs) : ControllerBase public Task> GetBuildings([FromQuery] bool includeInactive = false, CancellationToken ct = default) => catalogs.GetBuildingsAsync(includeInactive && User.IsInRole(Roles.Admin), ct); - [HttpGet("issue-categories")] - public Task> GetIssueCategories(CancellationToken ct) => catalogs.GetIssueCategoriesAsync(ct); - - [HttpGet("proposal-categories")] - public Task> GetProposalCategories(CancellationToken ct) => catalogs.GetProposalCategoriesAsync(ct); - [Authorize(Roles = Roles.Admin)] [HttpPost("buildings")] [ProducesResponseType(StatusCodes.Status201Created)] @@ -51,4 +45,76 @@ public sealed class CatalogsController(CatalogService catalogs) : ControllerBase await catalogs.DeactivateBuildingAsync(id, ct); return NoContent(); } + + /// Kategorie závad. Administrátor může zobrazit i deaktivované pomocí includeInactive=true. + [HttpGet("issue-categories")] + public Task> GetIssueCategories([FromQuery] bool includeInactive = false, CancellationToken ct = default) => + catalogs.GetIssueCategoriesAsync(includeInactive && User.IsInRole(Roles.Admin), ct); + + [Authorize(Roles = Roles.Admin)] + [HttpPost("issue-categories")] + [ProducesResponseType(StatusCodes.Status201Created)] + [ProducesResponseType(StatusCodes.Status400BadRequest)] + [ProducesResponseType(StatusCodes.Status409Conflict)] + public async Task> CreateIssueCategory(SaveCategoryRequest request, CancellationToken ct) + { + var category = await catalogs.CreateIssueCategoryAsync(request, ct); + return Created($"/api/issue-categories/{category.Id}", category); + } + + [Authorize(Roles = Roles.Admin)] + [HttpPut("issue-categories/{id:int}")] + [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(StatusCodes.Status400BadRequest)] + [ProducesResponseType(StatusCodes.Status404NotFound)] + [ProducesResponseType(StatusCodes.Status409Conflict)] + public Task UpdateIssueCategory(int id, SaveCategoryRequest request, CancellationToken ct) => + catalogs.UpdateIssueCategoryAsync(id, request, ct); + + /// Deaktivuje kategorii závad. + [Authorize(Roles = Roles.Admin)] + [HttpDelete("issue-categories/{id:int}")] + [ProducesResponseType(StatusCodes.Status204NoContent)] + [ProducesResponseType(StatusCodes.Status404NotFound)] + public async Task DeactivateIssueCategory(int id, CancellationToken ct) + { + await catalogs.DeactivateIssueCategoryAsync(id, ct); + return NoContent(); + } + + /// Kategorie návrhů. Administrátor může zobrazit i deaktivované pomocí includeInactive=true. + [HttpGet("proposal-categories")] + public Task> GetProposalCategories([FromQuery] bool includeInactive = false, CancellationToken ct = default) => + catalogs.GetProposalCategoriesAsync(includeInactive && User.IsInRole(Roles.Admin), ct); + + [Authorize(Roles = Roles.Admin)] + [HttpPost("proposal-categories")] + [ProducesResponseType(StatusCodes.Status201Created)] + [ProducesResponseType(StatusCodes.Status400BadRequest)] + [ProducesResponseType(StatusCodes.Status409Conflict)] + public async Task> CreateProposalCategory(SaveCategoryRequest request, CancellationToken ct) + { + var category = await catalogs.CreateProposalCategoryAsync(request, ct); + return Created($"/api/proposal-categories/{category.Id}", category); + } + + [Authorize(Roles = Roles.Admin)] + [HttpPut("proposal-categories/{id:int}")] + [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(StatusCodes.Status400BadRequest)] + [ProducesResponseType(StatusCodes.Status404NotFound)] + [ProducesResponseType(StatusCodes.Status409Conflict)] + public Task UpdateProposalCategory(int id, SaveCategoryRequest request, CancellationToken ct) => + catalogs.UpdateProposalCategoryAsync(id, request, ct); + + /// Deaktivuje kategorii návrhů. + [Authorize(Roles = Roles.Admin)] + [HttpDelete("proposal-categories/{id:int}")] + [ProducesResponseType(StatusCodes.Status204NoContent)] + [ProducesResponseType(StatusCodes.Status404NotFound)] + public async Task DeactivateProposalCategory(int id, CancellationToken ct) + { + await catalogs.DeactivateProposalCategoryAsync(id, ct); + return NoContent(); + } } diff --git a/backend/src/Helpdesk.Application/Catalogs/CatalogService.cs b/backend/src/Helpdesk.Application/Catalogs/CatalogService.cs index a30a1be..8481f9c 100644 --- a/backend/src/Helpdesk.Application/Catalogs/CatalogService.cs +++ b/backend/src/Helpdesk.Application/Catalogs/CatalogService.cs @@ -12,6 +12,8 @@ public sealed record CategoryDto(int Id, string Name, string? Description, bool public sealed record SaveBuildingRequest(string Code, string Name, string? Address); +public sealed record SaveCategoryRequest(string Name, string? Description); + public sealed class SaveBuildingRequestValidator : AbstractValidator { public SaveBuildingRequestValidator() @@ -22,8 +24,18 @@ public sealed class SaveBuildingRequestValidator : AbstractValidator +{ + public SaveCategoryRequestValidator() + { + RuleFor(x => x.Name).NotEmpty().MaximumLength(100); + RuleFor(x => x.Description).MaximumLength(500); + } +} + /// Číselníky pro formuláře a jejich správa administrátorem. Mazání = deaktivace. -public sealed class CatalogService(IAppDbContext db, IValidator buildingValidator) +public sealed class CatalogService( + IAppDbContext db, IValidator buildingValidator, IValidator categoryValidator) { public async Task> GetBuildingsAsync(bool includeInactive, CancellationToken ct) => await db.Buildings.AsNoTracking() @@ -32,16 +44,16 @@ public sealed class CatalogService(IAppDbContext db, IValidator new BuildingDto(b.Id, b.Code, b.Name, b.Address, b.IsActive)) .ToListAsync(ct); - public async Task> GetIssueCategoriesAsync(CancellationToken ct) => + public async Task> GetIssueCategoriesAsync(bool includeInactive, CancellationToken ct) => await db.IssueCategories.AsNoTracking() - .Where(c => c.IsActive) + .Where(c => includeInactive || c.IsActive) .OrderBy(c => c.Id) .Select(c => new CategoryDto(c.Id, c.Name, c.Description, c.IsActive)) .ToListAsync(ct); - public async Task> GetProposalCategoriesAsync(CancellationToken ct) => + public async Task> GetProposalCategoriesAsync(bool includeInactive, CancellationToken ct) => await db.ProposalCategories.AsNoTracking() - .Where(c => c.IsActive) + .Where(c => includeInactive || c.IsActive) .OrderBy(c => c.Id) .Select(c => new CategoryDto(c.Id, c.Name, c.Description, c.IsActive)) .ToListAsync(ct); @@ -75,10 +87,68 @@ public sealed class CatalogService(IAppDbContext db, IValidator CreateIssueCategoryAsync(SaveCategoryRequest request, CancellationToken ct) + { + await categoryValidator.ValidateAndThrowAsync(request, ct); + var category = new IssueCategory(request.Name, request.Description); + db.IssueCategories.Add(category); + await db.SaveChangesAsync(ct); + return ToDto(category); + } + + public async Task UpdateIssueCategoryAsync(int id, SaveCategoryRequest request, CancellationToken ct) + { + await categoryValidator.ValidateAndThrowAsync(request, ct); + var category = await GetIssueCategoryAsync(id, ct); + category.Update(request.Name, request.Description); + await db.SaveChangesAsync(ct); + return ToDto(category); + } + + public async Task DeactivateIssueCategoryAsync(int id, CancellationToken ct) + { + var category = await GetIssueCategoryAsync(id, ct); + category.Deactivate(); + await db.SaveChangesAsync(ct); + } + + public async Task CreateProposalCategoryAsync(SaveCategoryRequest request, CancellationToken ct) + { + await categoryValidator.ValidateAndThrowAsync(request, ct); + var category = new ProposalCategory(request.Name, request.Description); + db.ProposalCategories.Add(category); + await db.SaveChangesAsync(ct); + return ToDto(category); + } + + public async Task UpdateProposalCategoryAsync(int id, SaveCategoryRequest request, CancellationToken ct) + { + await categoryValidator.ValidateAndThrowAsync(request, ct); + var category = await GetProposalCategoryAsync(id, ct); + category.Update(request.Name, request.Description); + await db.SaveChangesAsync(ct); + return ToDto(category); + } + + public async Task DeactivateProposalCategoryAsync(int id, CancellationToken ct) + { + var category = await GetProposalCategoryAsync(id, ct); + category.Deactivate(); + await db.SaveChangesAsync(ct); + } + private async Task GetBuildingAsync(int id, CancellationToken ct) => await db.Buildings.SingleOrDefaultAsync(b => b.Id == id, ct) ?? throw new NotFoundException($"Budova {id} neexistuje."); + private async Task GetIssueCategoryAsync(int id, CancellationToken ct) => + await db.IssueCategories.SingleOrDefaultAsync(c => c.Id == id, ct) + ?? throw new NotFoundException($"Kategorie závad {id} neexistuje."); + + private async Task GetProposalCategoryAsync(int id, CancellationToken ct) => + await db.ProposalCategories.SingleOrDefaultAsync(c => c.Id == id, ct) + ?? throw new NotFoundException($"Kategorie návrhů {id} neexistuje."); + private async Task EnsureUniqueCodeAsync(string code, int? exceptId, CancellationToken ct) { var trimmed = code.Trim(); @@ -87,4 +157,6 @@ public sealed class CatalogService(IAppDbContext db, IValidator new(b.Id, b.Code, b.Name, b.Address, b.IsActive); + private static CategoryDto ToDto(IssueCategory c) => new(c.Id, c.Name, c.Description, c.IsActive); + private static CategoryDto ToDto(ProposalCategory c) => new(c.Id, c.Name, c.Description, c.IsActive); } diff --git a/backend/src/Helpdesk.Domain/Catalogs/Catalogs.cs b/backend/src/Helpdesk.Domain/Catalogs/Catalogs.cs index 086fc73..04d398d 100644 --- a/backend/src/Helpdesk.Domain/Catalogs/Catalogs.cs +++ b/backend/src/Helpdesk.Domain/Catalogs/Catalogs.cs @@ -31,10 +31,20 @@ public sealed class IssueCategory { private IssueCategory() { } // EF Core + public IssueCategory(string name, string? description) => Update(name, description); + public int Id { get; private set; } public string Name { get; private set; } = null!; public string? Description { get; private set; } public bool IsActive { get; private set; } = true; + + public void Update(string name, string? description) + { + Name = name.Trim(); + Description = string.IsNullOrWhiteSpace(description) ? null : description.Trim(); + } + + public void Deactivate() => IsActive = false; } /// Oblast návrhu na zlepšení (tabulka proposal_category). @@ -42,8 +52,18 @@ public sealed class ProposalCategory { private ProposalCategory() { } // EF Core + public ProposalCategory(string name, string? description) => Update(name, description); + public int Id { get; private set; } public string Name { get; private set; } = null!; public string? Description { get; private set; } public bool IsActive { get; private set; } = true; + + public void Update(string name, string? description) + { + Name = name.Trim(); + Description = string.IsNullOrWhiteSpace(description) ? null : description.Trim(); + } + + public void Deactivate() => IsActive = false; } diff --git a/backend/src/Helpdesk.Infrastructure/Persistence/HelpdeskDbContext.cs b/backend/src/Helpdesk.Infrastructure/Persistence/HelpdeskDbContext.cs index 5bd2548..0d8f000 100644 --- a/backend/src/Helpdesk.Infrastructure/Persistence/HelpdeskDbContext.cs +++ b/backend/src/Helpdesk.Infrastructure/Persistence/HelpdeskDbContext.cs @@ -1,5 +1,6 @@ using System.Data; using Helpdesk.Application.Abstractions; +using Helpdesk.Application.Common; using Helpdesk.Application.Statistics; using Helpdesk.Domain.Auth; using Helpdesk.Domain.Catalogs; @@ -11,6 +12,7 @@ using Helpdesk.Infrastructure.Security; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Storage; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using MySqlConnector; namespace Helpdesk.Infrastructure.Persistence; @@ -38,6 +40,20 @@ public sealed class HelpdeskDbContext(DbContextOptions option public DbSet NotificationDeliveries => Set(); public DbSet PushDevices => Set(); + public override async Task SaveChangesAsync(CancellationToken cancellationToken = default) + { + try + { + return await base.SaveChangesAsync(cancellationToken); + } + catch (DbUpdateException exception) when ( + exception.InnerException is MySqlException { ErrorCode: MySqlErrorCode.DuplicateKeyEntry } && + exception.Entries is [var entry] && entry.Entity is (IssueCategory or ProposalCategory)) + { + throw new ConflictException("Kategorie se stejným názvem již existuje."); + } + } + public Task BeginProposalWriteAsync(CancellationToken ct) => Database.BeginTransactionAsync(IsolationLevel.ReadCommitted, ct); From c96eb155aec9809f7008c01ec9d1a76bf80b2af0 Mon Sep 17 00:00:00 2001 From: GonnaHetzMe Date: Thu, 19 Nov 2026 13:41:42 +0100 Subject: [PATCH 3/4] Add SMTP email delivery and deployment config --- README.md | 6 +- backend/Directory.Packages.props | 1 + .../Controllers/AuthController.cs | 6 +- backend/src/Helpdesk.Api/Program.cs | 9 ++- .../Helpdesk.Application/Auth/AuthService.cs | 26 +++++++-- .../src/Helpdesk.Application/Common/Errors.cs | 5 ++ .../DependencyInjection.cs | 28 ++++++++- .../Email/LoggingEmailSender.cs | 14 +---- .../Email/SmtpEmailSender.cs | 57 +++++++++++++++++++ .../Helpdesk.Infrastructure.csproj | 1 + deploy/.env.example | 23 +++++++- deploy/docker-compose.yml | 12 +++- 12 files changed, 160 insertions(+), 28 deletions(-) create mode 100644 backend/src/Helpdesk.Infrastructure/Email/SmtpEmailSender.cs diff --git a/README.md b/README.md index 34720be..eae53f4 100644 --- a/README.md +++ b/README.md @@ -31,7 +31,11 @@ Potřeba je jen Docker Desktop. 3. Swagger UI: · stav a verze schématu: -Při prvním startu se vytvoří účet administrátora z `ADMIN_EMAIL` / `ADMIN_PASSWORD`. Odesílání e-mailů je zatím jen do logu – odkaz pro ověření e-mailu po registraci najdete v `docker compose -f deploy/docker-compose.yml logs api`. +Při prvním startu se vytvoří účet administrátora, pokud vyplníte `ADMIN_EMAIL` a `ADMIN_PASSWORD`. V režimu `Development` s prázdnými hodnotami `SMTP_MAILBOX` a `SMTP_PASSWORD` najdete ověřovací odkazy a odkazy pro obnovu hesla v logu služby `api`. + +Pro nasazení nastavte v `deploy/.env` režim `Production`, veřejnou HTTPS adresu webu v `PUBLIC_BASE_URL` a skutečné univerzitní domény v `STUDENT_EMAIL_DOMAIN` a `TEACHER_EMAIL_DOMAIN`. Pro Email Profi vyplňte `SMTP_MAILBOX` celou adresou schránky a nastavte `SMTP_PASSWORD`. API odesílá přes `smtp.seznam.cz:465` s TLS. + +Reverse proxy ukončuje HTTPS a předává požadavky přes HTTP na adresu `PROXY_UPSTREAM_BIND_ADDRESS` a port `API_HTTP_PORT`. Výchozí hodnoty `127.0.0.1` a `8080` odpovídají proxy běžící přímo na stejném hostiteli. ### Vývoj bez Dockeru diff --git a/backend/Directory.Packages.props b/backend/Directory.Packages.props index 235fb47..ee2454d 100644 --- a/backend/Directory.Packages.props +++ b/backend/Directory.Packages.props @@ -17,6 +17,7 @@ + diff --git a/backend/src/Helpdesk.Api/Controllers/AuthController.cs b/backend/src/Helpdesk.Api/Controllers/AuthController.cs index 760e483..dce9ef1 100644 --- a/backend/src/Helpdesk.Api/Controllers/AuthController.cs +++ b/backend/src/Helpdesk.Api/Controllers/AuthController.cs @@ -21,6 +21,7 @@ public sealed class AuthController(AuthService auth) : ControllerBase [ProducesResponseType(StatusCodes.Status201Created)] [ProducesResponseType(StatusCodes.Status400BadRequest)] [ProducesResponseType(StatusCodes.Status409Conflict)] + [ProducesResponseType(StatusCodes.Status503ServiceUnavailable)] public async Task> Register(RegisterRequest request, CancellationToken ct) { var user = await auth.RegisterAsync(request, ct); @@ -74,9 +75,10 @@ public sealed class AuthController(AuthService auth) : ControllerBase /// Odešle e-mail s odkazem pro nastavení nového hesla. Odpověď je stejná, ať účet existuje, nebo ne. [HttpPost("forgot-password")] [ProducesResponseType(StatusCodes.Status204NoContent)] - public async Task ForgotPassword(ForgotPasswordRequest request, CancellationToken ct) + public IActionResult ForgotPassword(ForgotPasswordRequest request, [FromServices] IHostApplicationLifetime lifetime) { - await auth.ForgotPasswordAsync(request, ct); + // Doba vyhledání účtu a doručení přes SMTP se nesmí projevit v době odpovědi. + Response.OnCompleted(() => auth.ForgotPasswordAsync(request, lifetime.ApplicationStopping)); return NoContent(); } diff --git a/backend/src/Helpdesk.Api/Program.cs b/backend/src/Helpdesk.Api/Program.cs index c6f7309..88dd819 100644 --- a/backend/src/Helpdesk.Api/Program.cs +++ b/backend/src/Helpdesk.Api/Program.cs @@ -2,13 +2,20 @@ using System.Threading.RateLimiting; using Helpdesk.Api.Infrastructure; using Helpdesk.Application; using Helpdesk.Application.Abstractions; +using Helpdesk.Application.Auth; using Helpdesk.Infrastructure; using Microsoft.IdentityModel.JsonWebTokens; var builder = WebApplication.CreateBuilder(args); builder.Services.AddApplication(builder.Configuration); -builder.Services.AddInfrastructure(builder.Configuration); +builder.Services.AddInfrastructure(builder.Configuration, builder.Environment); +builder.Services.AddOptions() + .Validate(options => Uri.TryCreate(options.WebBaseUrl, UriKind.Absolute, out var url) && + (url.Scheme == Uri.UriSchemeHttps || (builder.Environment.IsDevelopment() && url.Scheme == Uri.UriSchemeHttp)) && + string.IsNullOrEmpty(url.UserInfo) && string.IsNullOrEmpty(url.Query) && string.IsNullOrEmpty(url.Fragment), + "Nastavte Registration:WebBaseUrl na veřejnou HTTPS adresu webové aplikace bez parametrů.") + .ValidateOnStart(); builder.Services.AddHttpContextAccessor(); builder.Services.AddScoped(); diff --git a/backend/src/Helpdesk.Application/Auth/AuthService.cs b/backend/src/Helpdesk.Application/Auth/AuthService.cs index 869419b..86c31fb 100644 --- a/backend/src/Helpdesk.Application/Auth/AuthService.cs +++ b/backend/src/Helpdesk.Application/Auth/AuthService.cs @@ -32,12 +32,17 @@ public sealed class AuthService( ?? throw new BadRequestException("Registrace je možná jen s univerzitním e-mailem."); var normalized = User.NormalizeEmail(request.Email); - if (await db.Users.AnyAsync(u => u.EmailNormalized == normalized, ct)) + var user = await db.Users.SingleOrDefaultAsync(u => u.EmailNormalized == normalized, ct); + if (user is null) + { + user = User.Create(request.Email, passwordHasher.Hash(request.Password), request.FirstName, request.LastName, role); + db.Users.Add(user); + await db.SaveChangesAsync(ct); + } + else if (!user.IsActive || user.EmailConfirmed || !passwordHasher.Verify(request.Password, user.PasswordHash)) + { throw new ConflictException("Účet s tímto e-mailem už existuje."); - - var user = User.Create(request.Email, passwordHasher.Hash(request.Password), request.FirstName, request.LastName, role); - db.Users.Add(user); - await db.SaveChangesAsync(ct); + } await SendEmailTokenAsync(user, TokenType.EmailConfirm, ct); return UserDto.From(user); @@ -123,8 +128,17 @@ public sealed class AuthService( { var normalized = User.NormalizeEmail(request.Email ?? ""); var user = await db.Users.SingleOrDefaultAsync(u => u.EmailNormalized == normalized && u.IsActive, ct); - if (user is not null) + if (user is null) + return; + + try + { await SendEmailTokenAsync(user, TokenType.PasswordReset, ct); + } + catch (EmailDeliveryException) + { + // SMTP zapisuje typ chyby. Odpověď na obnovu hesla zůstává pro všechny adresy stejná. + } } public async Task ResetPasswordAsync(ResetPasswordRequest request, CancellationToken ct) diff --git a/backend/src/Helpdesk.Application/Common/Errors.cs b/backend/src/Helpdesk.Application/Common/Errors.cs index 39e5b29..bf94d77 100644 --- a/backend/src/Helpdesk.Application/Common/Errors.cs +++ b/backend/src/Helpdesk.Application/Common/Errors.cs @@ -31,4 +31,9 @@ public sealed class BadRequestException(string message) : AppException(message) public override int StatusCode => 400; } +public sealed class EmailDeliveryException() : AppException("E-mail se nepodařilo odeslat. Zkuste požadavek později.") +{ + public override int StatusCode => 503; +} + public sealed record PagedResult(IReadOnlyList Items, int TotalCount, int Page, int PageSize); diff --git a/backend/src/Helpdesk.Infrastructure/DependencyInjection.cs b/backend/src/Helpdesk.Infrastructure/DependencyInjection.cs index 40b6693..748944e 100644 --- a/backend/src/Helpdesk.Infrastructure/DependencyInjection.cs +++ b/backend/src/Helpdesk.Infrastructure/DependencyInjection.cs @@ -8,12 +8,15 @@ using Helpdesk.Infrastructure.Security; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using MimeKit; namespace Helpdesk.Infrastructure; public static class DependencyInjection { - public static IServiceCollection AddInfrastructure(this IServiceCollection services, IConfiguration configuration) + public static IServiceCollection AddInfrastructure( + this IServiceCollection services, IConfiguration configuration, IHostEnvironment environment) { var connectionString = configuration.GetConnectionString("Helpdesk") ?? throw new InvalidOperationException("Chybí připojovací řetězec ConnectionStrings:Helpdesk."); @@ -33,7 +36,7 @@ public static class DependencyInjection services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); - services.AddSingleton(); + AddEmailSender(services, configuration.GetSection("Smtp"), environment); services.AddSingleton(); services.AddHostedService(); @@ -41,4 +44,25 @@ public static class DependencyInjection services.AddHostedService(); return services; } + + private static void AddEmailSender(IServiceCollection services, IConfigurationSection configuration, IHostEnvironment environment) + { + if (environment.IsDevelopment() && string.IsNullOrWhiteSpace(configuration["Mailbox"]) && + string.IsNullOrWhiteSpace(configuration["Password"])) + { + services.AddSingleton(); + return; + } + + services.AddOptions() + .Bind(configuration) + .Validate(options => !string.IsNullOrWhiteSpace(options.Host) && options.Port is >= 1 and <= 65535, + "Nastavte platný SMTP server a port.") + .Validate(options => MailboxAddress.TryParse(options.Mailbox, out var mailbox) && + mailbox.Address == options.Mailbox && mailbox.Address.Contains('@'), + "Nastavte celou e-mailovou adresu SMTP schránky.") + .Validate(options => !string.IsNullOrWhiteSpace(options.Password), "Nastavte heslo SMTP schránky.") + .ValidateOnStart(); + services.AddSingleton(); + } } diff --git a/backend/src/Helpdesk.Infrastructure/Email/LoggingEmailSender.cs b/backend/src/Helpdesk.Infrastructure/Email/LoggingEmailSender.cs index 6b269b5..036678b 100644 --- a/backend/src/Helpdesk.Infrastructure/Email/LoggingEmailSender.cs +++ b/backend/src/Helpdesk.Infrastructure/Email/LoggingEmailSender.cs @@ -1,27 +1,19 @@ using Helpdesk.Application.Abstractions; -using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; namespace Helpdesk.Infrastructure.Email; /// -/// Vývojová náhrada odesílání e-mailů – obsah zapíše do logu (odkaz pro ověření e-mailu je tak vidět -/// v docker compose logs api). Odesílání přes SMTP (MailKit + Mailpit) přijde s notifikacemi. +/// Vývojová náhrada odesílání e-mailů, pokud schránka SMTP není nakonfigurována. /// -internal sealed partial class LoggingEmailSender(ILogger logger, IHostEnvironment environment) : IEmailSender +internal sealed partial class LoggingEmailSender(ILogger logger) : IEmailSender { public Task SendAsync(string to, string subject, string body, CancellationToken cancellationToken = default) { - if (environment.IsDevelopment()) - LogEmail(to, subject, body); - else - LogMissingTransport(); + LogEmail(to, subject, body); return Task.CompletedTask; } [LoggerMessage(Level = LogLevel.Information, Message = "E-mail pro {To} – {Subject}:\n{Body}")] private partial void LogEmail(string to, string subject, string body); - - [LoggerMessage(Level = LogLevel.Warning, Message = "E-mail nebyl odeslán. Pro toto prostředí není nakonfigurován poštovní transport.")] - private partial void LogMissingTransport(); } diff --git a/backend/src/Helpdesk.Infrastructure/Email/SmtpEmailSender.cs b/backend/src/Helpdesk.Infrastructure/Email/SmtpEmailSender.cs new file mode 100644 index 0000000..28ced30 --- /dev/null +++ b/backend/src/Helpdesk.Infrastructure/Email/SmtpEmailSender.cs @@ -0,0 +1,57 @@ +using System.Net.Sockets; +using Helpdesk.Application.Abstractions; +using Helpdesk.Application.Common; +using MailKit; +using MailKit.Net.Smtp; +using MailKit.Security; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; +using MimeKit; + +namespace Helpdesk.Infrastructure.Email; + +internal sealed class SmtpOptions +{ + public string Host { get; set; } = "smtp.seznam.cz"; + public int Port { get; set; } = 465; + public string Mailbox { get; set; } = ""; + public string Password { get; set; } = ""; +} + +internal sealed partial class SmtpEmailSender(IOptions options, ILogger logger) : IEmailSender +{ + public async Task SendAsync(string to, string subject, string body, CancellationToken cancellationToken = default) + { + if (!MailboxAddress.TryParse(to, out var recipient)) + { + LogDeliveryFailure("InvalidRecipient"); + throw new EmailDeliveryException(); + } + + var settings = options.Value; + using var message = new MimeMessage { Subject = subject, Body = new TextPart("plain") { Text = body } }; + message.From.Add(MailboxAddress.Parse(settings.Mailbox)); + message.To.Add(recipient); + + using var timeout = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); + timeout.CancelAfter(TimeSpan.FromSeconds(15)); + using var client = new SmtpClient(); + try + { + await client.ConnectAsync(settings.Host, settings.Port, SecureSocketOptions.SslOnConnect, timeout.Token); + await client.AuthenticateAsync(settings.Mailbox, settings.Password, timeout.Token); + await client.SendAsync(message, timeout.Token); + } + catch (Exception exception) when (!cancellationToken.IsCancellationRequested && + exception is (IOException or SocketException or CommandException or ProtocolException or + AuthenticationException or SslHandshakeException or NotSupportedException or TimeoutException or + OperationCanceledException)) + { + LogDeliveryFailure(exception.GetType().Name); + throw new EmailDeliveryException(); + } + } + + [LoggerMessage(Level = LogLevel.Warning, Message = "Doručení e-mailu přes SMTP selhalo ({FailureType}).")] + private partial void LogDeliveryFailure(string failureType); +} diff --git a/backend/src/Helpdesk.Infrastructure/Helpdesk.Infrastructure.csproj b/backend/src/Helpdesk.Infrastructure/Helpdesk.Infrastructure.csproj index 3fd70f6..593292c 100644 --- a/backend/src/Helpdesk.Infrastructure/Helpdesk.Infrastructure.csproj +++ b/backend/src/Helpdesk.Infrastructure/Helpdesk.Infrastructure.csproj @@ -10,6 +10,7 @@ + diff --git a/deploy/.env.example b/deploy/.env.example index 803ec70..cf5178d 100644 --- a/deploy/.env.example +++ b/deploy/.env.example @@ -11,8 +11,27 @@ APP_DB_PASSWORD=change-me-app JWT_SIGNING_KEY=change-me-to-a-random-string-of-at-least-32-bytes ENCRYPTION_KEY=AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA= -# Účet administrátora – vytvoří se při prvním startu API, pokud neexistuje. -ADMIN_EMAIL=admin@univerzita.cz +# Volitelný účet administrátora vytvořený při prvním startu API. +ADMIN_EMAIL=admin@domain.local ADMIN_PASSWORD=change-me-admin +# HTTP adresa a port API na hostiteli, kam se reverse proxy připojuje. +# Loopback použijte pro reverse proxy běžící přímo na stejném hostiteli. +PROXY_UPSTREAM_BIND_ADDRESS=127.0.0.1 +API_HTTP_PORT=8080 + +# Veřejná HTTPS adresa webu pro odkazy v e-mailech a povolené univerzitní domény. +PUBLIC_BASE_URL= #https://helpdesk.domain.local +STUDENT_EMAIL_DOMAIN= #student.domain.local +TEACHER_EMAIL_DOMAIN= #domain.local + +# Email Profi. V Production vyplňte celou adresu schránky a její heslo. +SMTP_HOST=smtp.seznam.cz +SMTP_PORT=465 +SMTP_MAILBOX= +# Jednoduché uvozovky zachovají ve skutečném hesle např. znak $. +SMTP_PASSWORD='' + +# Development = bez proxy +# Production = s reverse proxy ASPNETCORE_ENVIRONMENT=Development diff --git a/deploy/docker-compose.yml b/deploy/docker-compose.yml index 204cdea..d977619 100644 --- a/deploy/docker-compose.yml +++ b/deploy/docker-compose.yml @@ -1,5 +1,5 @@ # Vývojové spuštění backendu: docker compose -f deploy/docker-compose.yml --env-file deploy/.env up --build -# Topologie odpovídá kap. 15 návrhu; proxy (nginx + HTTPS), web a mailpit přibudou v dalších fázích. +# Reverse proxy ukončuje HTTPS a připojuje se k API přes HTTP. name: helpdesk @@ -44,6 +44,13 @@ services: ConnectionStrings__Helpdesk: "Server=db;Database=helpdesk;User=helpdesk_app;Password=${APP_DB_PASSWORD}" Jwt__SigningKey: ${JWT_SIGNING_KEY:?} Encryption__Key: ${ENCRYPTION_KEY:?} + Registration__WebBaseUrl: ${PUBLIC_BASE_URL:-https://helpdesk.localhost} + Registration__StudentEmailDomains__0: ${STUDENT_EMAIL_DOMAIN:-student.univerzita.cz} + Registration__TeacherEmailDomains__0: ${TEACHER_EMAIL_DOMAIN:-univerzita.cz} + Smtp__Host: ${SMTP_HOST:-smtp.seznam.cz} + Smtp__Port: ${SMTP_PORT:-465} + Smtp__Mailbox: ${SMTP_MAILBOX:-} + Smtp__Password: ${SMTP_PASSWORD:-} ADMIN_EMAIL: ${ADMIN_EMAIL:-} ADMIN_PASSWORD: ${ADMIN_PASSWORD:-} volumes: @@ -51,9 +58,8 @@ services: depends_on: migrator: condition: service_completed_successfully - # Dočasně publikováno přímo; po přidání nginx proxy bude API dostupné jen přes ni. ports: - - "8080:8080" + - "${PROXY_UPSTREAM_BIND_ADDRESS:-127.0.0.1}:${API_HTTP_PORT:-8080}:8080" networks: [frontend, backend] networks: From 599237dd2c010fb05321bb3f2e8a44ba6873b5a0 Mon Sep 17 00:00:00 2001 From: GonnaHetzMe Date: Thu, 19 Nov 2026 14:02:02 +0100 Subject: [PATCH 4/4] Add queued email and Firebase push delivery --- README.md | 6 +- backend/Directory.Packages.props | 1 + .../AdminNotificationDeliveriesController.cs | 32 +++++ .../Controllers/DevicesController.cs | 33 +++++ backend/src/Helpdesk.Api/Program.cs | 20 +++ .../Abstractions/Abstractions.cs | 1 + .../src/Helpdesk.Application/Common/Errors.cs | 5 +- .../DependencyInjection.cs | 2 + .../NotificationDeliveryService.cs | 53 ++++++++ .../Notifications/PushDeviceService.cs | 27 ++++ .../Notifications/Notification.cs | 39 +++++- .../Background/NotificationDispatcher.cs | 121 +++++++++++++++++ .../DependencyInjection.cs | 5 + .../Email/SmtpEmailSender.cs | 10 +- .../Helpdesk.Infrastructure.csproj | 1 + .../Notifications/FirebasePushSender.cs | 122 ++++++++++++++++++ .../Persistence/HelpdeskDbContext.cs | 11 +- .../Persistence/IssueConfigurations.cs | 1 + .../V003__push_device_token_collation.sql | 3 + deploy/.env.example | 5 + deploy/db-init/Dockerfile | 2 + deploy/docker-compose.yml | 5 +- 22 files changed, 497 insertions(+), 8 deletions(-) create mode 100644 backend/src/Helpdesk.Api/Controllers/AdminNotificationDeliveriesController.cs create mode 100644 backend/src/Helpdesk.Api/Controllers/DevicesController.cs create mode 100644 backend/src/Helpdesk.Application/Notifications/NotificationDeliveryService.cs create mode 100644 backend/src/Helpdesk.Application/Notifications/PushDeviceService.cs create mode 100644 backend/src/Helpdesk.Infrastructure/Background/NotificationDispatcher.cs create mode 100644 backend/src/Helpdesk.Infrastructure/Notifications/FirebasePushSender.cs create mode 100644 db/migrations/V003__push_device_token_collation.sql create mode 100644 deploy/db-init/Dockerfile diff --git a/README.md b/README.md index eae53f4..5cc6ed0 100644 --- a/README.md +++ b/README.md @@ -9,7 +9,7 @@ Univerzitní helpdesk a portál návrhů na zlepšení – semestrální práce | Složka / soubor | Obsah | |---|---| | [docs/navrh-aplikace.md](docs/navrh-aplikace.md) | Návrhový dokument (v1.1 – včetně zapracovaných připomínek z obhajoby) | -| [db/migrations/](db/migrations/) | Verzované SQL migrace (MariaDB 11) – `V001` schéma, `V002` číselníky | +| [db/migrations/](db/migrations/) | Verzované SQL migrace (MariaDB 11) – schéma, číselníky a porovnávání FCM tokenů | | [backend/](backend/) | ASP.NET Core Web API, DbUp migrator, unit testy (.NET 10) | | [deploy/](deploy/) | Docker Compose, inicializace DB účtů, šablona `.env` | @@ -37,6 +37,10 @@ Pro nasazení nastavte v `deploy/.env` režim `Production`, veřejnou HTTPS adre Reverse proxy ukončuje HTTPS a předává požadavky přes HTTP na adresu `PROXY_UPSTREAM_BIND_ADDRESS` a port `API_HTTP_PORT`. Výchozí hodnoty `127.0.0.1` a `8080` odpovídají proxy běžící přímo na stejném hostiteli. +Pro zpracování `X-Forwarded-For` a `X-Forwarded-Proto` nastavte `TRUSTED_REVERSE_PROXY_IP` na IP bezprostředního protějšku, kterou vidí API. Tato IP se může při průchodu Docker sítí lišit od adresy, na kterou je API vázáno. + +S nakonfigurovaným SMTP odesílá backend i e-mailové notifikace z databázové fronty. Pro mobilní push nastavte `FIREBASE_SERVICE_ACCOUNT_JSON` na jednořádkový JSON klíče servisního účtu Firebase. + ### Vývoj bez Dockeru Vyžaduje .NET SDK 10. Unit testy: diff --git a/backend/Directory.Packages.props b/backend/Directory.Packages.props index ee2454d..f0f39c6 100644 --- a/backend/Directory.Packages.props +++ b/backend/Directory.Packages.props @@ -18,6 +18,7 @@ + diff --git a/backend/src/Helpdesk.Api/Controllers/AdminNotificationDeliveriesController.cs b/backend/src/Helpdesk.Api/Controllers/AdminNotificationDeliveriesController.cs new file mode 100644 index 0000000..bdacc59 --- /dev/null +++ b/backend/src/Helpdesk.Api/Controllers/AdminNotificationDeliveriesController.cs @@ -0,0 +1,32 @@ +using Helpdesk.Api.Infrastructure; +using Helpdesk.Application.Common; +using Helpdesk.Application.Notifications; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Mvc; + +namespace Helpdesk.Api.Controllers; + +[ApiController] +[Authorize(Roles = Roles.Admin)] +[Route("api/admin/notification-deliveries")] +public sealed class AdminNotificationDeliveriesController(NotificationDeliveryService deliveries) : ControllerBase +{ + /// Přehled doručení podle stavu, výchozí stav je FAILED. + [HttpGet] + [ProducesResponseType>(StatusCodes.Status200OK)] + [ProducesResponseType(StatusCodes.Status400BadRequest)] + public Task> List( + CancellationToken ct, [FromQuery] string status = "FAILED", [FromQuery] int page = 1, [FromQuery] int pageSize = 20) => + deliveries.ListAsync(status, page, pageSize, ct); + + /// Vrátí neúspěšné doručení do fronty s novým počtem pokusů. + [HttpPost("{id:int}/retry")] + [ProducesResponseType(StatusCodes.Status204NoContent)] + [ProducesResponseType(StatusCodes.Status404NotFound)] + [ProducesResponseType(StatusCodes.Status409Conflict)] + public async Task Retry(int id, CancellationToken ct) + { + await deliveries.RetryAsync(id, ct); + return NoContent(); + } +} diff --git a/backend/src/Helpdesk.Api/Controllers/DevicesController.cs b/backend/src/Helpdesk.Api/Controllers/DevicesController.cs new file mode 100644 index 0000000..56fc6b7 --- /dev/null +++ b/backend/src/Helpdesk.Api/Controllers/DevicesController.cs @@ -0,0 +1,33 @@ +using Helpdesk.Application.Notifications; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Mvc; + +namespace Helpdesk.Api.Controllers; + +public sealed record RegisterDeviceRequest(string Token); + +[ApiController] +[Authorize] +[Route("api/devices")] +public sealed class DevicesController(PushDeviceService devices) : ControllerBase +{ + /// Zaregistruje FCM token pro právě přihlášeného uživatele. + [HttpPost] + [ProducesResponseType(StatusCodes.Status204NoContent)] + [ProducesResponseType(StatusCodes.Status400BadRequest)] + public async Task Register(RegisterDeviceRequest request, CancellationToken ct) + { + await devices.RegisterAsync(request.Token, ct); + return NoContent(); + } + + /// Odregistruje token právě přihlášeného uživatele. + [HttpDelete("{token}")] + [ProducesResponseType(StatusCodes.Status204NoContent)] + [ProducesResponseType(StatusCodes.Status400BadRequest)] + public async Task Unregister(string token, CancellationToken ct) + { + await devices.UnregisterAsync(token, ct); + return NoContent(); + } +} diff --git a/backend/src/Helpdesk.Api/Program.cs b/backend/src/Helpdesk.Api/Program.cs index 88dd819..ef09b00 100644 --- a/backend/src/Helpdesk.Api/Program.cs +++ b/backend/src/Helpdesk.Api/Program.cs @@ -1,9 +1,11 @@ +using System.Net; using System.Threading.RateLimiting; using Helpdesk.Api.Infrastructure; using Helpdesk.Application; using Helpdesk.Application.Abstractions; using Helpdesk.Application.Auth; using Helpdesk.Infrastructure; +using Microsoft.AspNetCore.HttpOverrides; using Microsoft.IdentityModel.JsonWebTokens; var builder = WebApplication.CreateBuilder(args); @@ -28,6 +30,21 @@ builder.Services.AddProblemDetails(); builder.Services.AddExceptionHandler(); builder.Services.AddHelpdeskSwagger(); +var trustedProxy = builder.Configuration["ReverseProxy:TrustedIp"]; +if (!string.IsNullOrWhiteSpace(trustedProxy)) +{ + if (!IPAddress.TryParse(trustedProxy, out var proxyAddress)) + throw new InvalidOperationException("Nastavte platnou IP adresu důvěryhodné reverse proxy."); + + builder.Services.Configure(options => + { + options.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto; + options.KnownIPNetworks.Clear(); + options.KnownProxies.Clear(); + options.KnownProxies.Add(proxyAddress); + }); +} + // Ochrana přihlášení a zápisů závad proti zahlcení (kap. 10). builder.Services.AddRateLimiter(options => { @@ -47,6 +64,9 @@ builder.Services.AddRateLimiter(options => var app = builder.Build(); +if (!string.IsNullOrWhiteSpace(trustedProxy)) + app.UseForwardedHeaders(); + app.UseExceptionHandler(); app.UseStatusCodePages(); diff --git a/backend/src/Helpdesk.Application/Abstractions/Abstractions.cs b/backend/src/Helpdesk.Application/Abstractions/Abstractions.cs index abcdb58..aa3f044 100644 --- a/backend/src/Helpdesk.Application/Abstractions/Abstractions.cs +++ b/backend/src/Helpdesk.Application/Abstractions/Abstractions.cs @@ -32,6 +32,7 @@ public interface IAppDbContext Task SaveChangesAsync(CancellationToken cancellationToken = default); Task BeginProposalWriteAsync(CancellationToken ct); Task LockProposalAsync(int id, CancellationToken ct); + Task RegisterPushDeviceAsync(int userId, string token, CancellationToken ct); } public interface IPasswordHasher diff --git a/backend/src/Helpdesk.Application/Common/Errors.cs b/backend/src/Helpdesk.Application/Common/Errors.cs index bf94d77..56eaafb 100644 --- a/backend/src/Helpdesk.Application/Common/Errors.cs +++ b/backend/src/Helpdesk.Application/Common/Errors.cs @@ -31,8 +31,11 @@ public sealed class BadRequestException(string message) : AppException(message) public override int StatusCode => 400; } -public sealed class EmailDeliveryException() : AppException("E-mail se nepodařilo odeslat. Zkuste požadavek později.") +public sealed class EmailDeliveryException(string reason, bool retryable) + : AppException("E-mail se nepodařilo odeslat. Zkuste požadavek později.") { + public string Reason { get; } = reason; + public bool Retryable { get; } = retryable; public override int StatusCode => 503; } diff --git a/backend/src/Helpdesk.Application/DependencyInjection.cs b/backend/src/Helpdesk.Application/DependencyInjection.cs index 290ea91..f58039f 100644 --- a/backend/src/Helpdesk.Application/DependencyInjection.cs +++ b/backend/src/Helpdesk.Application/DependencyInjection.cs @@ -24,7 +24,9 @@ public static class DependencyInjection services.AddScoped(); services.AddScoped(); services.AddScoped(); + services.AddScoped(); services.AddScoped(); + services.AddScoped(); services.AddScoped(); services.AddScoped(); return services; diff --git a/backend/src/Helpdesk.Application/Notifications/NotificationDeliveryService.cs b/backend/src/Helpdesk.Application/Notifications/NotificationDeliveryService.cs new file mode 100644 index 0000000..028ef12 --- /dev/null +++ b/backend/src/Helpdesk.Application/Notifications/NotificationDeliveryService.cs @@ -0,0 +1,53 @@ +using Helpdesk.Application.Abstractions; +using Helpdesk.Application.Common; +using Helpdesk.Domain; +using Helpdesk.Domain.Notifications; +using Microsoft.EntityFrameworkCore; + +namespace Helpdesk.Application.Notifications; + +public sealed record NotificationDeliveryDto( + int Id, int NotificationId, string Channel, string Status, int AttemptCount, + string? LastError, DateTime? NextAttemptAt, DateTime? SentAt); + +public sealed class NotificationDeliveryService(IAppDbContext db, TimeProvider clock) +{ + public async Task> ListAsync(string status, int page, int pageSize, CancellationToken ct) + { + if (!EnumCode.TryParse(status, out var deliveryStatus)) + throw new BadRequestException("Neplatný stav doručení."); + + page = Math.Max(1, page); + pageSize = Math.Clamp(pageSize, 1, 100); + var query = db.NotificationDeliveries.AsNoTracking().Where(d => d.Status == deliveryStatus); + var count = await query.CountAsync(ct); + var offset = (long)(page - 1) * pageSize; + if (offset >= count) + return new PagedResult([], count, page, pageSize); + + var rows = await query.OrderByDescending(d => d.Id).Skip((int)offset).Take(pageSize).ToListAsync(ct); + var items = rows.Select(d => new NotificationDeliveryDto(d.Id, d.NotificationId, d.Channel.ToCode(), + d.Status.ToCode(), d.AttemptCount, d.LastError, d.NextAttemptAt, d.SentAt)).ToArray(); + return new PagedResult(items, count, page, pageSize); + } + + public async Task RetryAsync(int id, CancellationToken ct) + { + var now = clock.GetUtcNow().UtcDateTime; + var delivery = db.NotificationDeliveries.Where(d => d.Id == id); + var updated = await delivery.Where(d => d.Status == DeliveryStatus.Failed) + .ExecuteUpdateAsync(setters => setters + .SetProperty(d => d.Status, DeliveryStatus.Pending) + .SetProperty(d => d.AttemptCount, 0) + .SetProperty(d => d.NextAttemptAt, now) + .SetProperty(d => d.LastError, (string?)null) + .SetProperty(d => d.SentAt, (DateTime?)null), ct); + if (updated == 1) + return; + + if (!await delivery.AnyAsync(ct)) + throw new NotFoundException("Doručení neexistuje."); + + throw new ConflictException("Zopakovat lze pouze neúspěšné doručení."); + } +} diff --git a/backend/src/Helpdesk.Application/Notifications/PushDeviceService.cs b/backend/src/Helpdesk.Application/Notifications/PushDeviceService.cs new file mode 100644 index 0000000..ef804c8 --- /dev/null +++ b/backend/src/Helpdesk.Application/Notifications/PushDeviceService.cs @@ -0,0 +1,27 @@ +using Helpdesk.Application.Abstractions; +using Helpdesk.Application.Common; +using Microsoft.EntityFrameworkCore; + +namespace Helpdesk.Application.Notifications; + +public sealed class PushDeviceService(IAppDbContext db, ICurrentUser currentUser) +{ + public Task RegisterAsync(string token, CancellationToken ct) + { + ValidateToken(token); + return db.RegisterPushDeviceAsync(currentUser.Id, token, ct); + } + + public async Task UnregisterAsync(string token, CancellationToken ct) + { + ValidateToken(token); + var userId = currentUser.Id; + await db.PushDevices.Where(d => d.UserId == userId && d.FcmToken == token).ExecuteDeleteAsync(ct); + } + + private static void ValidateToken(string? token) + { + if (string.IsNullOrEmpty(token) || token.Length > 512 || token.Any(c => char.IsWhiteSpace(c) || char.IsControl(c))) + throw new BadRequestException("Neplatný registrační token zařízení."); + } +} diff --git a/backend/src/Helpdesk.Domain/Notifications/Notification.cs b/backend/src/Helpdesk.Domain/Notifications/Notification.cs index 53b1b46..45963cf 100644 --- a/backend/src/Helpdesk.Domain/Notifications/Notification.cs +++ b/backend/src/Helpdesk.Domain/Notifications/Notification.cs @@ -5,7 +5,7 @@ namespace Helpdesk.Domain.Notifications; public enum NotificationType { IssueCreated, IssueAssigned, IssueStatusChanged, IssueCommentAdded, IssueReopened, ProposalStatusChanged } public enum DeliveryChannel { Email, Push } -public enum DeliveryStatus { Pending, Skipped } +public enum DeliveryStatus { Pending, Sent, Failed, Skipped } public sealed class Notification : IHasCreatedAt { @@ -46,6 +46,9 @@ public sealed class Notification : IHasCreatedAt public sealed class NotificationDelivery( Notification notification, DeliveryChannel channel, bool enabled, DateTime now) { + private static readonly TimeSpan[] RetryDelays = + [TimeSpan.FromMinutes(1), TimeSpan.FromMinutes(5), TimeSpan.FromMinutes(30), TimeSpan.FromHours(2)]; + private NotificationDelivery() : this(null!, default, false, default) { } public int Id { get; private set; } @@ -53,11 +56,45 @@ public sealed class NotificationDelivery( public Notification Notification { get; private set; } = notification; public DeliveryChannel Channel { get; private set; } = channel; public DeliveryStatus Status { get; private set; } = enabled ? DeliveryStatus.Pending : DeliveryStatus.Skipped; + public int AttemptCount { get; private set; } public DateTime? NextAttemptAt { get; private set; } = enabled ? now : null; + public string? LastError { get; private set; } + public DateTime? SentAt { get; private set; } + + public void RecordSent(DateTime now) + { + AttemptCount++; + Status = DeliveryStatus.Sent; + SentAt = now; + NextAttemptAt = null; + LastError = null; + } + + public void RecordFailure(DateTime now, string reason, bool retryable) + { + AttemptCount++; + LastError = reason; + if (retryable && AttemptCount <= RetryDelays.Length) + { + NextAttemptAt = now + RetryDelays[AttemptCount - 1]; + return; + } + + Status = DeliveryStatus.Failed; + NextAttemptAt = null; + } + + public void Skip() + { + Status = DeliveryStatus.Skipped; + NextAttemptAt = null; + LastError = null; + } } public sealed class PushDevice { public int Id { get; private set; } public int UserId { get; private set; } + public string FcmToken { get; private set; } = null!; } diff --git a/backend/src/Helpdesk.Infrastructure/Background/NotificationDispatcher.cs b/backend/src/Helpdesk.Infrastructure/Background/NotificationDispatcher.cs new file mode 100644 index 0000000..e2d072f --- /dev/null +++ b/backend/src/Helpdesk.Infrastructure/Background/NotificationDispatcher.cs @@ -0,0 +1,121 @@ +using System.Data; +using Helpdesk.Application.Abstractions; +using Helpdesk.Application.Common; +using Helpdesk.Domain.Notifications; +using Helpdesk.Infrastructure.Email; +using Helpdesk.Infrastructure.Notifications; +using Helpdesk.Infrastructure.Persistence; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Logging; + +namespace Helpdesk.Infrastructure.Background; + +internal sealed partial class NotificationDispatcher( + IServiceScopeFactory scopes, IEmailSender email, TimeProvider clock, ILogger logger, + FirebasePushSender? push = null) : BackgroundService +{ + private static readonly TimeSpan PollInterval = TimeSpan.FromSeconds(2); + private readonly bool emailEnabled = email is not LoggingEmailSender; + + protected override async Task ExecuteAsync(CancellationToken stoppingToken) + { + if (!emailEnabled && push is null) + return; + + while (!stoppingToken.IsCancellationRequested) + { + try + { + if (await DeliverNextAsync(stoppingToken)) + continue; + } + catch (Exception failure) when (!stoppingToken.IsCancellationRequested) + { + LogDispatchFailure(failure.GetType().Name); + } + + await Task.Delay(PollInterval, clock, stoppingToken); + } + } + + private async Task DeliverNextAsync(CancellationToken ct) + { + using var scope = scopes.CreateScope(); + var db = scope.ServiceProvider.GetRequiredService(); + await using var transaction = await db.Database.BeginTransactionAsync(IsolationLevel.ReadCommitted, ct); + var now = clock.GetUtcNow().UtcDateTime; + var rows = await db.NotificationDeliveries.FromSql($""" + SELECT * FROM notification_delivery + WHERE status = 'PENDING' AND next_attempt_at <= {now} + AND (({emailEnabled} AND channel = 'EMAIL') OR ({push is not null} AND channel = 'PUSH')) + ORDER BY next_attempt_at, id LIMIT 1 FOR UPDATE SKIP LOCKED + """).ToListAsync(ct); + if (rows.SingleOrDefault() is not { } delivery) + return false; + + var recipient = await ( + from notification in db.Notifications.AsNoTracking() + join user in db.Users on notification.UserId equals user.Id + where notification.Id == delivery.NotificationId + select new { Notification = notification, user.Id, user.Email, user.IsActive, user.EmailConfirmed, user.EmailNotificationsEnabled } + ).SingleAsync(ct); + + if (!recipient.IsActive) + delivery.Skip(); + else if (delivery.Channel == DeliveryChannel.Email) + { + if (recipient.EmailConfirmed && recipient.EmailNotificationsEnabled) + await SendEmailAsync(delivery, recipient.Notification, recipient.Email, ct); + else + delivery.Skip(); + } + else + { + await SendPushAsync(db, delivery, recipient.Notification, recipient.Id, ct); + } + + await db.SaveChangesAsync(ct); + await transaction.CommitAsync(ct); + return true; + } + + private async Task SendEmailAsync(NotificationDelivery delivery, Notification notification, string address, CancellationToken ct) + { + try + { + await email.SendAsync(address, notification.Title, notification.Message, ct); + delivery.RecordSent(clock.GetUtcNow().UtcDateTime); + } + catch (EmailDeliveryException failure) + { + delivery.RecordFailure(clock.GetUtcNow().UtcDateTime, failure.Reason, failure.Retryable); + } + } + + private async Task SendPushAsync( + HelpdeskDbContext db, NotificationDelivery delivery, Notification notification, int userId, CancellationToken ct) + { + var devices = db.PushDevices.Where(d => d.UserId == userId); + var tokens = await devices.Select(d => d.FcmToken).ToArrayAsync(ct); + if (tokens.Length == 0) + { + delivery.Skip(); + return; + } + + var result = await push!.SendAsync(notification, tokens, ct); + foreach (var invalidToken in result.InvalidTokens) + await devices.Where(d => d.FcmToken == invalidToken).ExecuteDeleteAsync(ct); + + var now = clock.GetUtcNow().UtcDateTime; + if (result.Sent) + delivery.RecordSent(now); + else + delivery.RecordFailure(now, result.FailureReason, result.Retryable); + } + + [LoggerMessage(Level = LogLevel.Error, Message = "Zpracování notifikační fronty selhalo ({FailureType}).")] + private partial void LogDispatchFailure(string failureType); +} diff --git a/backend/src/Helpdesk.Infrastructure/DependencyInjection.cs b/backend/src/Helpdesk.Infrastructure/DependencyInjection.cs index 748944e..a9004d0 100644 --- a/backend/src/Helpdesk.Infrastructure/DependencyInjection.cs +++ b/backend/src/Helpdesk.Infrastructure/DependencyInjection.cs @@ -3,6 +3,7 @@ using Helpdesk.Application.Issues; using Helpdesk.Infrastructure.Background; using Helpdesk.Infrastructure.Email; using Helpdesk.Infrastructure.Files; +using Helpdesk.Infrastructure.Notifications; using Helpdesk.Infrastructure.Persistence; using Helpdesk.Infrastructure.Security; using Microsoft.EntityFrameworkCore; @@ -37,11 +38,15 @@ public static class DependencyInjection services.AddSingleton(); services.AddSingleton(); AddEmailSender(services, configuration.GetSection("Smtp"), environment); + var firebaseCredentials = configuration["Firebase:ServiceAccountJson"]; + if (!string.IsNullOrWhiteSpace(firebaseCredentials)) + services.AddSingleton(_ => FirebasePushSender.Create(firebaseCredentials)); services.AddSingleton(); services.AddHostedService(); services.AddHostedService(); services.AddHostedService(); + services.AddHostedService(); return services; } diff --git a/backend/src/Helpdesk.Infrastructure/Email/SmtpEmailSender.cs b/backend/src/Helpdesk.Infrastructure/Email/SmtpEmailSender.cs index 28ced30..f97b48d 100644 --- a/backend/src/Helpdesk.Infrastructure/Email/SmtpEmailSender.cs +++ b/backend/src/Helpdesk.Infrastructure/Email/SmtpEmailSender.cs @@ -25,7 +25,7 @@ internal sealed partial class SmtpEmailSender(IOptions options, ILo if (!MailboxAddress.TryParse(to, out var recipient)) { LogDeliveryFailure("InvalidRecipient"); - throw new EmailDeliveryException(); + throw new EmailDeliveryException("SMTP_INVALID_RECIPIENT", retryable: false); } var settings = options.Value; @@ -48,7 +48,13 @@ internal sealed partial class SmtpEmailSender(IOptions options, ILo OperationCanceledException)) { LogDeliveryFailure(exception.GetType().Name); - throw new EmailDeliveryException(); + if (exception is SmtpCommandException command) + { + var status = (int)command.StatusCode; + throw new EmailDeliveryException($"SMTP_{status}", retryable: status is < 500 or >= 600); + } + + throw new EmailDeliveryException($"SMTP_{exception.GetType().Name}", retryable: true); } } diff --git a/backend/src/Helpdesk.Infrastructure/Helpdesk.Infrastructure.csproj b/backend/src/Helpdesk.Infrastructure/Helpdesk.Infrastructure.csproj index 593292c..caa7357 100644 --- a/backend/src/Helpdesk.Infrastructure/Helpdesk.Infrastructure.csproj +++ b/backend/src/Helpdesk.Infrastructure/Helpdesk.Infrastructure.csproj @@ -11,6 +11,7 @@ + diff --git a/backend/src/Helpdesk.Infrastructure/Notifications/FirebasePushSender.cs b/backend/src/Helpdesk.Infrastructure/Notifications/FirebasePushSender.cs new file mode 100644 index 0000000..0821254 --- /dev/null +++ b/backend/src/Helpdesk.Infrastructure/Notifications/FirebasePushSender.cs @@ -0,0 +1,122 @@ +using System.Globalization; +using System.Security.Cryptography; +using FirebaseAdmin; +using FirebaseAdmin.Messaging; +using Google.Apis.Auth.OAuth2; +using Google.Apis.Auth.OAuth2.Responses; +using Helpdesk.Domain; +using Notification = Helpdesk.Domain.Notifications.Notification; + +namespace Helpdesk.Infrastructure.Notifications; + +internal sealed record PushDeliveryResult(bool Sent, bool Retryable, string FailureReason, IReadOnlyList InvalidTokens); + +internal sealed class FirebasePushSender(FirebaseApp app) : IDisposable +{ + public static FirebasePushSender Create(string serviceAccountJson) + { + ServiceAccountCredential credential; + try + { + credential = CredentialFactory.FromJson(serviceAccountJson); + } + catch (Exception exception) when ( + exception is ArgumentException or InvalidOperationException or CryptographicException or Newtonsoft.Json.JsonException) + { + throw new InvalidOperationException("Nastavte platný JSON klíče servisního účtu Firebase."); + } + + if (string.IsNullOrWhiteSpace(credential.ProjectId)) + throw new InvalidOperationException("Klíč servisního účtu Firebase musí obsahovat project_id."); + + var app = FirebaseApp.Create(new AppOptions + { + Credential = credential.ToGoogleCredential(), + ProjectId = credential.ProjectId, + }); + return new FirebasePushSender(app); + } + + public async Task SendAsync(Notification notification, string[] tokens, CancellationToken ct) + { + var data = new Dictionary + { + ["notificationId"] = notification.Id.ToString(CultureInfo.InvariantCulture), + }; + if (notification.IssueId is int issueId) + data["issueId"] = issueId.ToString(CultureInfo.InvariantCulture); + if (notification.ProposalId is int proposalId) + data["proposalId"] = proposalId.ToString(CultureInfo.InvariantCulture); + + var messaging = FirebaseMessaging.GetMessaging(app); + using var timeout = CancellationTokenSource.CreateLinkedTokenSource(ct); + timeout.CancelAfter(TimeSpan.FromSeconds(15)); + var invalidTokens = new List(); + var sent = false; + var retryable = false; + var reason = "FCM_NO_ACCEPTED_DEVICE"; + + foreach (var batch in tokens.Chunk(500)) + { + try + { + var result = await messaging.SendEachForMulticastAsync(new MulticastMessage + { +#pragma warning disable CS0618 // API zařízení podle návrhu přijímá registrační tokeny FCM. + Tokens = batch, +#pragma warning restore CS0618 + Notification = new FirebaseAdmin.Messaging.Notification + { + Title = notification.Title, + Body = notification.Message, + }, + Data = data, + }, timeout.Token); + + sent |= result.SuccessCount > 0; + for (var i = 0; i < result.Responses.Count; i++) + { + if (result.Responses[i].Exception is not { } failure) + continue; + if (IsInvalidToken(failure)) + invalidTokens.Add(batch[i]); + + if (!retryable) + reason = FailureReason(failure); + retryable |= IsRetryable(failure); + } + } + catch (FirebaseMessagingException failure) + { + if (!retryable) + reason = FailureReason(failure); + retryable |= IsRetryable(failure); + } + catch (TokenResponseException) + { + return new PushDeliveryResult(sent, true, "FCM_AUTHENTICATION_FAILED", invalidTokens); + } + catch (Exception failure) when (!ct.IsCancellationRequested && + failure is HttpRequestException or IOException or OperationCanceledException) + { + return new PushDeliveryResult(sent, true, $"FCM_{failure.GetType().Name}", invalidTokens); + } + } + + return new PushDeliveryResult(sent, retryable, reason, invalidTokens); + } + + private static bool IsInvalidToken(FirebaseMessagingException failure) => + failure.MessagingErrorCode == MessagingErrorCode.Unregistered || + (failure.MessagingErrorCode == MessagingErrorCode.InvalidArgument && + failure.Message.Contains("registration token", StringComparison.OrdinalIgnoreCase)); + + private static bool IsRetryable(FirebaseMessagingException failure) => + failure.MessagingErrorCode is MessagingErrorCode.Unavailable or MessagingErrorCode.Internal or MessagingErrorCode.QuotaExceeded || + failure.ErrorCode is ErrorCode.Unavailable or ErrorCode.Internal or ErrorCode.ResourceExhausted or ErrorCode.DeadlineExceeded; + + private static string FailureReason(FirebaseMessagingException failure) => + $"FCM_{failure.MessagingErrorCode?.ToCode() ?? failure.ErrorCode.ToCode()}"; + + public void Dispose() => app.Delete(); +} diff --git a/backend/src/Helpdesk.Infrastructure/Persistence/HelpdeskDbContext.cs b/backend/src/Helpdesk.Infrastructure/Persistence/HelpdeskDbContext.cs index 0d8f000..4edcdbd 100644 --- a/backend/src/Helpdesk.Infrastructure/Persistence/HelpdeskDbContext.cs +++ b/backend/src/Helpdesk.Infrastructure/Persistence/HelpdeskDbContext.cs @@ -86,9 +86,18 @@ public sealed class HelpdeskDbContext(DbContextOptions option modelBuilder.Entity().HasNoKey().ToView("v_proposal_score"); modelBuilder.ApplyConfiguration(new NotificationConfiguration()); modelBuilder.ApplyConfiguration(new NotificationDeliveryConfiguration()); - modelBuilder.Entity().ToTable("push_device"); + var pushDevice = modelBuilder.Entity(); + pushDevice.ToTable("push_device"); + pushDevice.Property(x => x.FcmToken).HasMaxLength(512); + pushDevice.HasIndex(x => x.FcmToken).IsUnique(); } + public Task RegisterPushDeviceAsync(int userId, string token, CancellationToken ct) => + Database.ExecuteSqlInterpolatedAsync($""" + INSERT INTO push_device (user_id, fcm_token) VALUES ({userId}, {token}) + ON DUPLICATE KEY UPDATE user_id = VALUES(user_id) + """, ct); + protected override void ConfigureConventions(ModelConfigurationBuilder configurationBuilder) { // Všechny časy jsou v DB v UTC; při čtení jim nastavíme Kind = Utc, aby se v JSON serializovaly se "Z". diff --git a/backend/src/Helpdesk.Infrastructure/Persistence/IssueConfigurations.cs b/backend/src/Helpdesk.Infrastructure/Persistence/IssueConfigurations.cs index 6186dcd..6eb07aa 100644 --- a/backend/src/Helpdesk.Infrastructure/Persistence/IssueConfigurations.cs +++ b/backend/src/Helpdesk.Infrastructure/Persistence/IssueConfigurations.cs @@ -73,6 +73,7 @@ internal sealed class NotificationDeliveryConfiguration : IEntityTypeConfigurati b.ToTable("notification_delivery"); b.Property(x => x.Channel).HasConversion>().HasMaxLength(10); b.Property(x => x.Status).HasConversion>().HasMaxLength(10); + b.Property(x => x.LastError).HasMaxLength(1000); b.HasOne(x => x.Notification).WithMany().HasForeignKey(x => x.NotificationId); } } diff --git a/db/migrations/V003__push_device_token_collation.sql b/db/migrations/V003__push_device_token_collation.sql new file mode 100644 index 0000000..1847e40 --- /dev/null +++ b/db/migrations/V003__push_device_token_collation.sql @@ -0,0 +1,3 @@ +-- Registrační token FCM rozlišuje velikost písmen. +ALTER TABLE push_device + MODIFY fcm_token VARCHAR(512) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NOT NULL; diff --git a/deploy/.env.example b/deploy/.env.example index cf5178d..2b3a300 100644 --- a/deploy/.env.example +++ b/deploy/.env.example @@ -19,6 +19,8 @@ ADMIN_PASSWORD=change-me-admin # Loopback použijte pro reverse proxy běžící přímo na stejném hostiteli. PROXY_UPSTREAM_BIND_ADDRESS=127.0.0.1 API_HTTP_PORT=8080 +# Adresa reverse proxy tak, jak ji API vidí jako bezprostředního klienta. +TRUSTED_REVERSE_PROXY_IP= # Veřejná HTTPS adresa webu pro odkazy v e-mailech a povolené univerzitní domény. PUBLIC_BASE_URL= #https://helpdesk.domain.local @@ -32,6 +34,9 @@ SMTP_MAILBOX= # Jednoduché uvozovky zachovají ve skutečném hesle např. znak $. SMTP_PASSWORD='' +# Jednořádkový JSON klíče servisního účtu Firebase v jednoduchých uvozovkách. +FIREBASE_SERVICE_ACCOUNT_JSON='' + # Development = bez proxy # Production = s reverse proxy ASPNETCORE_ENVIRONMENT=Development diff --git a/deploy/db-init/Dockerfile b/deploy/db-init/Dockerfile new file mode 100644 index 0000000..20e7473 --- /dev/null +++ b/deploy/db-init/Dockerfile @@ -0,0 +1,2 @@ +FROM mariadb:11.4 +COPY --chmod=0644 01-accounts.sh /docker-entrypoint-initdb.d/01-accounts.sh diff --git a/deploy/docker-compose.yml b/deploy/docker-compose.yml index d977619..24d829d 100644 --- a/deploy/docker-compose.yml +++ b/deploy/docker-compose.yml @@ -5,7 +5,7 @@ name: helpdesk services: db: - image: mariadb:11.4 + build: ./db-init environment: MARIADB_ROOT_PASSWORD: ${DB_ROOT_PASSWORD:?} MARIADB_DATABASE: helpdesk @@ -14,7 +14,6 @@ services: APP_DB_PASSWORD: ${APP_DB_PASSWORD:?} volumes: - db-data:/var/lib/mysql - - ./db-init:/docker-entrypoint-initdb.d:ro healthcheck: test: ["CMD", "healthcheck.sh", "--connect", "--innodb_initialized"] interval: 5s @@ -51,6 +50,8 @@ services: Smtp__Port: ${SMTP_PORT:-465} Smtp__Mailbox: ${SMTP_MAILBOX:-} Smtp__Password: ${SMTP_PASSWORD:-} + Firebase__ServiceAccountJson: ${FIREBASE_SERVICE_ACCOUNT_JSON:-} + ReverseProxy__TrustedIp: ${TRUSTED_REVERSE_PROXY_IP:-} ADMIN_EMAIL: ${ADMIN_EMAIL:-} ADMIN_PASSWORD: ${ADMIN_PASSWORD:-} volumes: