diff --git a/README.md b/README.md
index e0fd9c9..feea3b8 100644
--- a/README.md
+++ b/README.md
@@ -64,6 +64,14 @@ Testy webové aplikace:
dotnet test --solution web/Helpdesk.Web.sln
```
+### Integrační testy backendu
+
+Vyžadují .NET SDK 10 a spuštěný Docker. Testcontainers vytvoří dočasnou MariaDB 11.4 a testy spustí skutečné migrace.
+
+```bash
+dotnet run --project backend/tests/Helpdesk.IntegrationTests/Helpdesk.IntegrationTests.csproj
+```
+
## Verzování databáze
Schéma se mění výhradně novými číslovanými skripty `db/migrations/V{NNN}__{popis}.sql`. Provedený skript se nikdy neupravuje. Migrace spouští DbUp (`Helpdesk.Migrator`) před startem API a eviduje je v tabulce `schema_version`.
diff --git a/backend/Directory.Packages.props b/backend/Directory.Packages.props
index f0f39c6..42d1815 100644
--- a/backend/Directory.Packages.props
+++ b/backend/Directory.Packages.props
@@ -22,7 +22,9 @@
+
+
diff --git a/backend/Helpdesk.sln b/backend/Helpdesk.sln
index 61e2772..21919ef 100644
--- a/backend/Helpdesk.sln
+++ b/backend/Helpdesk.sln
@@ -15,6 +15,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Helpdesk.Migrator", "src\He
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Helpdesk.UnitTests", "tests\Helpdesk.UnitTests\Helpdesk.UnitTests.csproj", "{AB40F473-EB15-47C7-B179-A8EB066325EC}"
EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Helpdesk.IntegrationTests", "tests\Helpdesk.IntegrationTests\Helpdesk.IntegrationTests.csproj", "{B8A0D31B-C086-4E70-942C-FA0B3B7D9906}"
+EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
@@ -97,6 +99,18 @@ Global
{AB40F473-EB15-47C7-B179-A8EB066325EC}.Release|x64.Build.0 = Release|Any CPU
{AB40F473-EB15-47C7-B179-A8EB066325EC}.Release|x86.ActiveCfg = Release|Any CPU
{AB40F473-EB15-47C7-B179-A8EB066325EC}.Release|x86.Build.0 = Release|Any CPU
+ {B8A0D31B-C086-4E70-942C-FA0B3B7D9906}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {B8A0D31B-C086-4E70-942C-FA0B3B7D9906}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {B8A0D31B-C086-4E70-942C-FA0B3B7D9906}.Debug|x64.ActiveCfg = Debug|Any CPU
+ {B8A0D31B-C086-4E70-942C-FA0B3B7D9906}.Debug|x64.Build.0 = Debug|Any CPU
+ {B8A0D31B-C086-4E70-942C-FA0B3B7D9906}.Debug|x86.ActiveCfg = Debug|Any CPU
+ {B8A0D31B-C086-4E70-942C-FA0B3B7D9906}.Debug|x86.Build.0 = Debug|Any CPU
+ {B8A0D31B-C086-4E70-942C-FA0B3B7D9906}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {B8A0D31B-C086-4E70-942C-FA0B3B7D9906}.Release|Any CPU.Build.0 = Release|Any CPU
+ {B8A0D31B-C086-4E70-942C-FA0B3B7D9906}.Release|x64.ActiveCfg = Release|Any CPU
+ {B8A0D31B-C086-4E70-942C-FA0B3B7D9906}.Release|x64.Build.0 = Release|Any CPU
+ {B8A0D31B-C086-4E70-942C-FA0B3B7D9906}.Release|x86.ActiveCfg = Release|Any CPU
+ {B8A0D31B-C086-4E70-942C-FA0B3B7D9906}.Release|x86.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
diff --git a/backend/tests/Helpdesk.IntegrationTests/AuthTests.cs b/backend/tests/Helpdesk.IntegrationTests/AuthTests.cs
new file mode 100644
index 0000000..ac6aaab
--- /dev/null
+++ b/backend/tests/Helpdesk.IntegrationTests/AuthTests.cs
@@ -0,0 +1,77 @@
+using System.Net;
+using System.Net.Http.Json;
+using Helpdesk.Application.Auth;
+using Helpdesk.Domain.Auth;
+using Helpdesk.Infrastructure.Persistence;
+using Microsoft.EntityFrameworkCore;
+using Microsoft.Extensions.DependencyInjection;
+using Microsoft.IdentityModel.JsonWebTokens;
+using static Helpdesk.IntegrationTests.BackendFixture;
+
+namespace Helpdesk.IntegrationTests;
+
+public sealed class AuthTests(BackendFixture fixture) : IClassFixture
+{
+ [Fact]
+ public async Task LogoutRevokesOnlyTheCurrentSession()
+ {
+ using var anonymous = fixture.CreateClient();
+ var user = await fixture.RegisterAsync(anonymous);
+ var session = await LoginAsync(anonymous, user.Email);
+ var otherSession = await LoginAsync(anonymous, user.Email);
+ using var client = fixture.CreateClient(session.AccessToken);
+ using var otherClient = fixture.CreateClient(otherSession.AccessToken);
+ var refresh = new RefreshTokenRequest(session.RefreshToken);
+
+ await ExpectAsync(client.PostAsJsonAsync("/api/v1/auth/logout", refresh, Cancellation), HttpStatusCode.NoContent);
+
+ await ExpectAsync(client.GetAsync("/api/v1/users/me", Cancellation), HttpStatusCode.Unauthorized);
+ await ExpectAsync(otherClient.GetAsync("/api/v1/users/me", Cancellation), HttpStatusCode.OK);
+ var accessId = new JsonWebToken(session.AccessToken).Id;
+ var refreshId = new JsonWebToken(session.RefreshToken).Id;
+ await using var scope = fixture.Services.CreateAsyncScope();
+ var db = scope.ServiceProvider.GetRequiredService();
+ Assert.Equal(2, await db.AuthTokens.CountAsync(token =>
+ token.UserId == user.Id && (token.Jti == accessId || token.Jti == refreshId) &&
+ token.RevokeReason == RevokeReason.Logout, Cancellation));
+ }
+
+ [Fact]
+ public async Task ConcurrentRefreshRevokesTheNewPairAndOtherSessions()
+ {
+ using var anonymous = fixture.CreateClient();
+ var user = await fixture.RegisterAsync(anonymous);
+ var session = await LoginAsync(anonymous, user.Email);
+ var otherSession = await LoginAsync(anonymous, user.Email);
+ var refresh = new RefreshTokenRequest(session.RefreshToken);
+
+ var pause = fixture.TokenSaves.PauseNextSave();
+ Task first;
+ Task duplicate;
+ try
+ {
+ first = anonymous.PostAsJsonAsync("/api/v1/auth/refresh", refresh, Cancellation);
+ await pause.Entered.Task.WaitAsync(TimeSpan.FromSeconds(15), Cancellation);
+ await using var scope = fixture.Services.CreateAsyncScope();
+ var db = scope.ServiceProvider.GetRequiredService();
+ Assert.Equal(2, await db.AuthTokens.CountAsync(token =>
+ token.UserId == user.Id && token.TokenType == TokenType.Refresh && token.RevokedAt == null, Cancellation));
+ duplicate = anonymous.PostAsJsonAsync("/api/v1/auth/refresh", refresh, Cancellation);
+ }
+ finally
+ {
+ pause.Release();
+ }
+
+ var renewed = await ReadAsync(first);
+ await ExpectAsync(duplicate, HttpStatusCode.Unauthorized);
+ await using var after = fixture.Services.CreateAsyncScope();
+ var tokens = after.ServiceProvider.GetRequiredService().AuthTokens;
+ Assert.False(await tokens.AnyAsync(token => token.UserId == user.Id && token.RevokedAt == null, Cancellation));
+
+ using var renewedClient = fixture.CreateClient(renewed.AccessToken);
+ using var otherClient = fixture.CreateClient(otherSession.AccessToken);
+ await ExpectAsync(renewedClient.GetAsync("/api/v1/users/me", Cancellation), HttpStatusCode.Unauthorized);
+ await ExpectAsync(otherClient.GetAsync("/api/v1/users/me", Cancellation), HttpStatusCode.Unauthorized);
+ }
+}
diff --git a/backend/tests/Helpdesk.IntegrationTests/BackendFixture.cs b/backend/tests/Helpdesk.IntegrationTests/BackendFixture.cs
new file mode 100644
index 0000000..d14b510
--- /dev/null
+++ b/backend/tests/Helpdesk.IntegrationTests/BackendFixture.cs
@@ -0,0 +1,179 @@
+using System.Collections.Concurrent;
+using System.Diagnostics;
+using System.Net;
+using System.Net.Http.Headers;
+using System.Net.Http.Json;
+using System.Security.Cryptography;
+using Helpdesk.Application.Abstractions;
+using Helpdesk.Application.Auth;
+using Helpdesk.Application.Users;
+using Helpdesk.Infrastructure.Persistence;
+using Microsoft.AspNetCore.Hosting;
+using Microsoft.AspNetCore.Mvc.Testing;
+using Microsoft.AspNetCore.TestHost;
+using Microsoft.AspNetCore.WebUtilities;
+using Microsoft.EntityFrameworkCore;
+using Microsoft.Extensions.Configuration;
+using Microsoft.Extensions.DependencyInjection;
+using Microsoft.Extensions.DependencyInjection.Extensions;
+using Microsoft.Extensions.Hosting;
+using Testcontainers.MariaDb;
+
+namespace Helpdesk.IntegrationTests;
+
+public sealed class BackendFixture : IAsyncLifetime
+{
+ internal const string AdminEmail = "admin@example.test";
+ internal const string Password = "Integration-test-password";
+ internal static string MigrationsPath => Path.Combine(AppContext.BaseDirectory, "migrations");
+ internal static CancellationToken Cancellation => TestContext.Current.CancellationToken;
+
+ private readonly MariaDbContainer database = new MariaDbBuilder("mariadb:11.4")
+ .WithDatabase("helpdesk")
+ .WithPassword(Convert.ToHexString(RandomNumberGenerator.GetBytes(24)))
+ .WithCommand("--character-set-server=utf8mb4")
+ .Build();
+ private readonly TestEmailSender email = new();
+ private ApiFactory? factory;
+
+ internal TokenSaveGate TokenSaves { get; } = new();
+ internal IServiceProvider Services => factory!.Services;
+
+ public async ValueTask InitializeAsync()
+ {
+ await database.StartAsync(Cancellation);
+ await RunMigratorAsync(database.GetConnectionString());
+ factory = new ApiFactory(database.GetConnectionString(), email, TokenSaves);
+ }
+
+ public async ValueTask DisposeAsync()
+ {
+ try
+ {
+ if (factory is not null)
+ await factory.DisposeAsync();
+ }
+ finally
+ {
+ await database.DisposeAsync();
+ }
+ }
+
+ internal HttpClient CreateClient(string? accessToken = null)
+ {
+ var client = factory!.CreateClient();
+ if (accessToken is not null)
+ client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
+ return client;
+ }
+
+ internal async Task RegisterAsync(HttpClient client)
+ {
+ var address = $"{Guid.NewGuid():N}@student.example.test";
+ var user = await ReadAsync(client.PostAsJsonAsync("/api/v1/auth/register",
+ new RegisterRequest(address, Password, "Test", "User"), Cancellation), HttpStatusCode.Created);
+ await ExpectAsync(client.PostAsJsonAsync("/api/v1/auth/confirm-email",
+ new EmailTokenRequest(email.TakeConfirmationToken(address)), Cancellation), HttpStatusCode.NoContent);
+ return user;
+ }
+
+ internal static Task LoginAsync(HttpClient client, string address) =>
+ ReadAsync(client.PostAsJsonAsync("/api/v1/auth/login",
+ new LoginRequest(address, Password), Cancellation));
+
+ internal static async Task ReadAsync(Task request, HttpStatusCode expected = HttpStatusCode.OK)
+ where T : class
+ {
+ using var response = await request;
+ Assert.Equal(expected, response.StatusCode);
+ return Assert.IsType(await response.Content.ReadFromJsonAsync(Cancellation));
+ }
+
+ internal static async Task ExpectAsync(Task request, HttpStatusCode expected)
+ {
+ using var response = await request;
+ Assert.Equal(expected, response.StatusCode);
+ }
+
+ private static async Task RunMigratorAsync(string connectionString)
+ {
+ var startInfo = new ProcessStartInfo(Environment.GetEnvironmentVariable("DOTNET_HOST_PATH") ?? "dotnet")
+ {
+ RedirectStandardOutput = true,
+ RedirectStandardError = true,
+ };
+ startInfo.ArgumentList.Add(Path.Combine(AppContext.BaseDirectory, "Helpdesk.Migrator.dll"));
+ startInfo.Environment["ConnectionStrings__Migrator"] = connectionString;
+ startInfo.Environment["MIGRATIONS_PATH"] = MigrationsPath;
+ using var process = Process.Start(startInfo) ?? throw new InvalidOperationException("Could not start the migrator.");
+ var output = process.StandardOutput.ReadToEndAsync(Cancellation);
+ var errors = process.StandardError.ReadToEndAsync(Cancellation);
+ try
+ {
+ await process.WaitForExitAsync(Cancellation);
+ Assert.True(process.ExitCode == 0, $"Migrator failed with exit code {process.ExitCode}.\n{await output}\n{await errors}");
+ }
+ finally
+ {
+ if (!process.HasExited)
+ {
+ process.Kill();
+ await process.WaitForExitAsync();
+ }
+ }
+ }
+
+ private sealed class ApiFactory(string connectionString, TestEmailSender email, TokenSaveGate tokenSaves)
+ : WebApplicationFactory
+ {
+ private readonly Dictionary settings = new()
+ {
+ ["ConnectionStrings:Helpdesk"] = connectionString,
+ ["Jwt:SigningKey"] = Convert.ToHexString(RandomNumberGenerator.GetBytes(32)),
+ ["Encryption:Key"] = Convert.ToBase64String(RandomNumberGenerator.GetBytes(32)),
+ ["Registration:StudentEmailDomains:0"] = "student.example.test",
+ ["Registration:WebBaseUrl"] = "https://helpdesk.example.test",
+ ["ADMIN_EMAIL"] = AdminEmail,
+ ["ADMIN_PASSWORD"] = Password,
+ ["Firebase:ServiceAccountJson"] = "",
+ ["Smtp:Mailbox"] = "",
+ ["Smtp:Password"] = "",
+ ["ReverseProxy:TrustedIp"] = "",
+ };
+
+ protected override IHost CreateHost(IHostBuilder builder)
+ {
+ // Program čte konfiguraci před Build(), proto musí hodnoty dostat už při startu.
+ builder.UseEnvironment(Environments.Development)
+ .ConfigureHostConfiguration(config => config.AddInMemoryCollection(settings));
+ return base.CreateHost(builder);
+ }
+
+ protected override void ConfigureWebHost(IWebHostBuilder builder) =>
+ builder.ConfigureTestServices(services =>
+ {
+ services.RemoveAll();
+ services.AddSingleton(email);
+ services.AddDbContext((_, options) => options.AddInterceptors(tokenSaves));
+ });
+ }
+
+ private sealed class TestEmailSender : IEmailSender
+ {
+ private readonly ConcurrentDictionary tokens = new();
+
+ public Task SendAsync(string to, string subject, string body, CancellationToken cancellationToken = default)
+ {
+ if (Uri.TryCreate(body[(body.LastIndexOf('\n') + 1)..], UriKind.Absolute, out var link) &&
+ link.AbsolutePath == "/confirm-email")
+ tokens[to] = QueryHelpers.ParseQuery(link.Query)["token"].ToString();
+ return Task.CompletedTask;
+ }
+
+ internal string TakeConfirmationToken(string address)
+ {
+ Assert.True(tokens.TryRemove(address, out var token), "Registration did not send a confirmation link.");
+ return token;
+ }
+ }
+}
diff --git a/backend/tests/Helpdesk.IntegrationTests/DatabaseTests.cs b/backend/tests/Helpdesk.IntegrationTests/DatabaseTests.cs
new file mode 100644
index 0000000..3a985e5
--- /dev/null
+++ b/backend/tests/Helpdesk.IntegrationTests/DatabaseTests.cs
@@ -0,0 +1,59 @@
+using Helpdesk.Api.Controllers;
+using Helpdesk.Infrastructure.Persistence;
+using Microsoft.EntityFrameworkCore;
+using Microsoft.Extensions.DependencyInjection;
+using MySqlConnector;
+using static Helpdesk.IntegrationTests.BackendFixture;
+
+namespace Helpdesk.IntegrationTests;
+
+public sealed class DatabaseTests(BackendFixture fixture) : IClassFixture
+{
+ [Fact]
+ public async Task MigratorAppliesEveryScriptAndEfCanReadTheSchema()
+ {
+ using var client = fixture.CreateClient();
+ await using var scope = fixture.Services.CreateAsyncScope();
+ var db = scope.ServiceProvider.GetRequiredService();
+ var expected = Directory.EnumerateFiles(MigrationsPath, "V*__*.sql")
+ .Select(Path.GetFileName).Order(StringComparer.Ordinal).ToArray();
+ var applied = await db.Database
+ .SqlQueryRaw("SELECT scriptname AS Value FROM schema_version ORDER BY schemaversionid")
+ .ToListAsync(Cancellation);
+ Assert.Equal(expected, applied);
+ var health = await ReadAsync(client.GetAsync("/health", Cancellation));
+ Assert.Equal(new HealthResponse("Healthy", expected[^1]), health);
+
+ await db.Users.AsNoTracking().ToListAsync(Cancellation);
+ await db.AuthTokens.AsNoTracking().ToListAsync(Cancellation);
+ await db.Buildings.AsNoTracking().ToListAsync(Cancellation);
+ await db.IssueCategories.AsNoTracking().ToListAsync(Cancellation);
+ await db.ProposalCategories.AsNoTracking().ToListAsync(Cancellation);
+ await db.Issues.AsNoTracking().ToListAsync(Cancellation);
+ await db.IssueEvents.AsNoTracking().ToListAsync(Cancellation);
+ await db.IssueTimings.ToListAsync(Cancellation);
+ await db.Attachments.AsNoTracking().ToListAsync(Cancellation);
+ await db.Proposals.AsNoTracking().ToListAsync(Cancellation);
+ await db.ProposalEvents.AsNoTracking().ToListAsync(Cancellation);
+ await db.ProposalVotes.AsNoTracking().ToListAsync(Cancellation);
+ await db.ProposalScores.ToListAsync(Cancellation);
+ await db.Notifications.AsNoTracking().ToListAsync(Cancellation);
+ await db.NotificationDeliveries.AsNoTracking().ToListAsync(Cancellation);
+ await db.PushDevices.AsNoTracking().ToListAsync(Cancellation);
+ }
+
+ [Fact]
+ public async Task DatabaseRejectsAnAssignedIssueWithoutAnAssignee()
+ {
+ await using var scope = fixture.Services.CreateAsyncScope();
+ var db = scope.ServiceProvider.GetRequiredService();
+ var reporterId = await db.Users.Select(user => user.Id).SingleAsync(Cancellation);
+ var categoryId = await db.IssueCategories.MinAsync(category => category.Id, Cancellation);
+
+ var error = await Assert.ThrowsAsync(() => db.Database.ExecuteSqlInterpolatedAsync($"""
+ INSERT INTO issue (title, description, category_id, reporter_id, status)
+ VALUES ('Test', 'Test', {categoryId}, {reporterId}, 'ASSIGNED')
+ """, Cancellation));
+ Assert.Contains("ck_issue_assignee", error.Message);
+ }
+}
diff --git a/backend/tests/Helpdesk.IntegrationTests/Helpdesk.IntegrationTests.csproj b/backend/tests/Helpdesk.IntegrationTests/Helpdesk.IntegrationTests.csproj
new file mode 100644
index 0000000..818b90f
--- /dev/null
+++ b/backend/tests/Helpdesk.IntegrationTests/Helpdesk.IntegrationTests.csproj
@@ -0,0 +1,23 @@
+
+
+
+ false
+ Exe
+ true
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/backend/tests/Helpdesk.IntegrationTests/IssueWorkflowTests.cs b/backend/tests/Helpdesk.IntegrationTests/IssueWorkflowTests.cs
new file mode 100644
index 0000000..8d446af
--- /dev/null
+++ b/backend/tests/Helpdesk.IntegrationTests/IssueWorkflowTests.cs
@@ -0,0 +1,124 @@
+using System.Net;
+using System.Net.Http.Json;
+using Helpdesk.Application.Auth;
+using Helpdesk.Application.Catalogs;
+using Helpdesk.Application.Common;
+using Helpdesk.Application.Issues;
+using Helpdesk.Application.Notifications;
+using Helpdesk.Application.Statistics;
+using Helpdesk.Application.Users;
+using static Helpdesk.IntegrationTests.BackendFixture;
+
+namespace Helpdesk.IntegrationTests;
+
+public sealed class IssueWorkflowTests(BackendFixture fixture) : IClassFixture
+{
+ [Fact]
+ public async Task ReporterAndAssigneesCanResolveAnIssueAndManagementCanReportOnIt()
+ {
+ using var anonymous = fixture.CreateClient();
+ using var admin = fixture.CreateClient((await LoginAsync(anonymous, AdminEmail)).AccessToken);
+ var author = await fixture.RegisterAsync(anonymous);
+ using var reporter = fixture.CreateClient((await LoginAsync(anonymous, author.Email)).AccessToken);
+ var management = await CreateStaffAsync(anonymous, admin, "MANAGEMENT");
+ var firstAssignee = await CreateStaffAsync(anonymous, admin, "FACILITY_MANAGER");
+ var secondAssignee = await CreateStaffAsync(anonymous, admin, "FACILITY_MANAGER");
+ using var manager = fixture.CreateClient(management.AccessToken);
+ using var firstSolver = fixture.CreateClient(firstAssignee.AccessToken);
+ using var secondSolver = fixture.CreateClient(secondAssignee.AccessToken);
+
+ var categories = await ReadAsync(reporter.GetAsync("/api/v1/issue-categories", Cancellation));
+ var buildings = await ReadAsync(reporter.GetAsync("/api/v1/buildings", Cancellation));
+ var request = new CreateIssueRequest("Nefunkční projektor", "Projektor se nezapne.", categories[0].Id, buildings[0].Id, "A101");
+ var issue = await PostIssueAsync(reporter, "/api/v1/issues", request, HttpStatusCode.Created);
+ var path = $"/api/v1/issues/{issue.Id}";
+ Assert.Equal("RECEIVED", issue.Status);
+ await ExpectAsync(anonymous.GetAsync(path, Cancellation), HttpStatusCode.Unauthorized);
+
+ var assign = new AssignIssueRequest(firstAssignee.User.Id, null, issue.RowVersion);
+ await ExpectAsync(reporter.PostAsJsonAsync(path + "/assign", assign, Cancellation), HttpStatusCode.Forbidden);
+ issue = await PostIssueAsync(manager, path + "/assign", assign);
+ await ExpectAsync(firstSolver.PostAsJsonAsync(path + "/start",
+ new IssueVersionRequest(assign.RowVersion), Cancellation), HttpStatusCode.Conflict);
+
+ var reporterNotifications = await InboxAsync(reporter, issue.Id);
+ Assert.Equal("ISSUE_STATUS_CHANGED", Assert.Single(reporterNotifications).Type);
+ issue = await PostIssueAsync(manager, path + "/assign", new AssignIssueRequest(secondAssignee.User.Id, null, issue.RowVersion));
+ Assert.Equal("ISSUE_ASSIGNED", Assert.Single(await InboxAsync(secondSolver, issue.Id)).Type);
+ Assert.Equal(reporterNotifications, await InboxAsync(reporter, issue.Id));
+
+ issue = await PostIssueAsync(secondSolver, path + "/start", new IssueVersionRequest(issue.RowVersion));
+ Assert.Equal("IN_PROGRESS", issue.Status);
+ reporterNotifications = await InboxAsync(reporter, issue.Id);
+ issue = await PostIssueAsync(manager, path + "/assign", new AssignIssueRequest(firstAssignee.User.Id, null, issue.RowVersion));
+ Assert.Equal("ASSIGNED", issue.Status);
+ var reassignment = Assert.Single((await InboxAsync(reporter, issue.Id)).Except(reporterNotifications));
+ Assert.Equal("ISSUE_STATUS_CHANGED", reassignment.Type);
+ Assert.Equal(2, (await InboxAsync(firstSolver, issue.Id)).Count(notification => notification.Type == "ISSUE_ASSIGNED"));
+
+ issue = await PostIssueAsync(firstSolver, path + "/start", new IssueVersionRequest(issue.RowVersion));
+ const string commentText = "Porucha stále trvá.";
+ var comment = await ReadAsync(reporter.PostAsJsonAsync(path + "/comments",
+ new CommentRequest(commentText), Cancellation));
+ issue = await ReadAsync(firstSolver.GetAsync(path, Cancellation));
+ issue = await PostIssueAsync(firstSolver, path + "/submit-for-verification", new VerifyIssueRequest(issue.RowVersion, null));
+ Assert.Equal("PENDING_VERIFICATION", issue.Status);
+ issue = await PostIssueAsync(reporter, path + "/confirm", new IssueVersionRequest(issue.RowVersion));
+ Assert.Equal("RESOLVED", issue.Status);
+ var events = await ReadAsync(reporter.GetAsync(path + "/events", Cancellation));
+ Assert.Equal(commentText, Assert.Single(events, entry => entry.Id == comment.Id).Note);
+ Assert.Equal("RESOLVED", events[^1].ToStatus);
+
+ var openIssue = await PostIssueAsync(reporter, "/api/v1/issues",
+ request with { Title = "Porucha osvětlení" }, HttpStatusCode.Created);
+ await VerifyReadsAsync(reporter, manager, issue, openIssue);
+ }
+
+ private async Task CreateStaffAsync(HttpClient anonymous, HttpClient admin, string role)
+ {
+ var user = await fixture.RegisterAsync(anonymous);
+ await ExpectAsync(admin.PutAsJsonAsync($"/api/v1/admin/users/{user.Id}/role",
+ new ChangeRoleRequest(role), Cancellation), HttpStatusCode.NoContent);
+ return await LoginAsync(anonymous, user.Email);
+ }
+
+ private static async Task VerifyReadsAsync(HttpClient reporter, HttpClient manager, IssueDetail resolved, IssueDetail open)
+ {
+ var query = $"/api/v1/issues?categoryId={resolved.CategoryId}&buildingId={resolved.BuildingId}&pageSize=1";
+ var first = await ReadAsync>(manager.GetAsync(query + "&page=1", Cancellation));
+ var second = await ReadAsync>(manager.GetAsync(query + "&page=2", Cancellation));
+ var filtered = await ReadAsync>(manager.GetAsync(query + "&status=RESOLVED", Cancellation));
+ Assert.Equal(2, first.TotalCount);
+ Assert.Equal(open.Id, Assert.Single(first.Items).Id);
+ Assert.Equal(resolved.Id, Assert.Single(second.Items).Id);
+ Assert.Equal(1, filtered.TotalCount);
+ Assert.Equal(resolved.Id, Assert.Single(filtered.Items).Id);
+
+ const string overview = "/api/v1/statistics/overview";
+ await ExpectAsync(reporter.GetAsync(overview, Cancellation), HttpStatusCode.Forbidden);
+ var from = Uri.EscapeDataString(resolved.CreatedAt.AddMinutes(-1).ToString("O"));
+ var to = Uri.EscapeDataString(open.CreatedAt.AddMinutes(1).ToString("O"));
+ var period = $"?from={from}&to={to}";
+ var statistics = await ReadAsync(manager.GetAsync(overview + period, Cancellation));
+ Assert.Equal(2, statistics.TotalIssues);
+ Assert.Equal(1, statistics.IssuesByStatus["RESOLVED"]);
+ Assert.Equal(1, statistics.IssuesByStatus["RECEIVED"]);
+ Assert.NotNull(statistics.AverageHoursToAssignment);
+ Assert.NotNull(statistics.AverageHoursToClosure);
+ var trend = await ReadAsync(manager.GetAsync("/api/v1/statistics/issues/trend" + period, Cancellation));
+ Assert.Equal(2, trend.Sum(point => point.CreatedIssues));
+ Assert.Equal(1, trend.Sum(point => point.ClosedIssues));
+ var after = await ReadAsync(manager.GetAsync(overview + $"?from={to}", Cancellation));
+ Assert.Equal(0, after.TotalIssues);
+ }
+
+ private static Task PostIssueAsync(
+ HttpClient client, string path, T request, HttpStatusCode expected = HttpStatusCode.OK) =>
+ ReadAsync(client.PostAsJsonAsync(path, request, Cancellation), expected);
+
+ private static async Task InboxAsync(HttpClient client, int issueId)
+ {
+ var notifications = await ReadAsync>(client.GetAsync("/api/v1/notifications", Cancellation));
+ return notifications.Items.Where(notification => notification.IssueId == issueId).ToArray();
+ }
+}
diff --git a/backend/tests/Helpdesk.IntegrationTests/TokenSaveGate.cs b/backend/tests/Helpdesk.IntegrationTests/TokenSaveGate.cs
new file mode 100644
index 0000000..abed69c
--- /dev/null
+++ b/backend/tests/Helpdesk.IntegrationTests/TokenSaveGate.cs
@@ -0,0 +1,40 @@
+using Helpdesk.Domain.Auth;
+using Microsoft.EntityFrameworkCore;
+using Microsoft.EntityFrameworkCore.Diagnostics;
+
+namespace Helpdesk.IntegrationTests;
+
+internal sealed class TokenSaveGate : SaveChangesInterceptor
+{
+ private Pause? next;
+
+ internal Pause PauseNextSave()
+ {
+ var pause = new Pause();
+ if (Interlocked.CompareExchange(ref next, pause, null) is not null)
+ throw new InvalidOperationException("A save is already scheduled to pause.");
+ return pause;
+ }
+
+ public override async ValueTask> SavingChangesAsync(
+ DbContextEventData eventData, InterceptionResult result, CancellationToken cancellationToken = default)
+ {
+ if (Volatile.Read(ref next) is not null &&
+ eventData.Context!.ChangeTracker.Entries()
+ .Any(entry => entry.State == EntityState.Added && entry.Entity.TokenType == TokenType.Refresh) &&
+ Interlocked.Exchange(ref next, null) is { } pause)
+ {
+ pause.Entered.TrySetResult();
+ await pause.Released.Task.WaitAsync(cancellationToken);
+ }
+ return result;
+ }
+
+ internal sealed class Pause
+ {
+ internal TaskCompletionSource Entered { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
+ internal TaskCompletionSource Released { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
+
+ internal void Release() => Released.TrySetResult();
+ }
+}