Compare commits
36
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
91d0c06c83 | ||
|
|
fcf7cd0596 | ||
|
|
232d48c7fc | ||
|
|
0865831746 | ||
|
|
1550c0343b | ||
|
|
ea3de2e444 | ||
|
|
34f2d57bd3 | ||
|
|
eddf5837eb | ||
|
|
d8de714481 | ||
|
|
ac3ec6aff7 | ||
|
|
32bc5a4691 | ||
|
|
ce04c8beb3 | ||
|
|
def23d306e | ||
|
|
fd37986f5e | ||
|
|
483bb10fbd | ||
|
|
5d8b71c435 | ||
|
|
946ff5ce12 | ||
|
|
2fe939ba5c | ||
|
|
6208fd3baf | ||
|
|
6e742b4029 | ||
|
|
08ca55dd6b | ||
|
|
36f1078b0a | ||
|
|
3965a8a2a1 | ||
|
|
d3a1b1cb17 | ||
|
|
abd075287c | ||
|
|
b402d9f92c | ||
|
|
bbbbca95fa | ||
|
|
599237dd2c | ||
|
|
c96eb155ae | ||
|
|
28fc49ea39 | ||
|
|
b1e0638979 | ||
|
|
1ff4a0a814 | ||
|
|
9ca23a2c15 | ||
|
|
33b6864d3b | ||
|
|
b80ec57589 | ||
|
|
6ad3d5bbaa |
No files matched your search
@@ -0,0 +1,16 @@
|
||||
**
|
||||
!backend/Directory.Build.props
|
||||
!backend/Directory.Packages.props
|
||||
!backend/src/
|
||||
!db/migrations/
|
||||
!web/Directory.Build.props
|
||||
!web/Directory.Packages.props
|
||||
!web/Helpdesk.Web/
|
||||
backend/**/bin
|
||||
backend/**/obj
|
||||
web/**/bin
|
||||
web/**/obj
|
||||
**/.env
|
||||
**/*.env
|
||||
**/*.pem
|
||||
**/*.pfx
|
||||
@@ -9,11 +9,12 @@ 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) |
|
||||
| [web/](web/) | Webová aplikace ASP.NET Core MVC – tenký klient REST API |
|
||||
| [deploy/](deploy/) | Docker Compose, inicializace DB účtů, šablona `.env` |
|
||||
|
||||
## Spuštění backendu (Docker)
|
||||
## Spuštění (Docker)
|
||||
|
||||
Potřeba je jen Docker Desktop.
|
||||
|
||||
@@ -23,28 +24,71 @@ Potřeba je jen Docker Desktop.
|
||||
cp deploy/.env.example deploy/.env
|
||||
```
|
||||
|
||||
2. Spusťte databázi, migrace a API:
|
||||
2. Spusťte databázi, migrace, API a web:
|
||||
|
||||
```bash
|
||||
docker compose -f deploy/docker-compose.yml --env-file deploy/.env up --build
|
||||
```
|
||||
|
||||
3. Swagger UI: <http://localhost:8080/swagger> · stav a verze schématu: <http://localhost:8080/health>
|
||||
3. Webová aplikace: <http://localhost:8081> · Swagger UI po přihlášení administrátora: <http://localhost:8081/swagger> · stav a verze schématu: <http://localhost:8080/health>
|
||||
|
||||
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`.
|
||||
Lokálně bez reverse proxy nastavte `PUBLIC_BASE_URL=http://localhost:8081`, aby odkazy pro ověření e-mailu a obnovu hesla vedly na web v Dockeru.
|
||||
|
||||
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`: `/api/*` na port `API_HTTP_PORT` (výchozí `8080`) a ostatní cesty včetně `/swagger` na web na port `WEB_HTTP_PORT` (výchozí `8081`). Výchozí adresa `127.0.0.1` odpovídá proxy běžící přímo na stejném hostiteli. Swagger UI ověřuje administrátorskou relaci webu. Funkce **Try it out** vyžaduje, aby stejná adresa přes proxy směrovala i `/api/*`, a chráněná volání autorizuje access tokenem.
|
||||
|
||||
Serverová reverse proxy předává IP klienta v `X-Forwarded-For` a schéma v `X-Forwarded-Proto`. Nastavte `TRUSTED_REVERSE_PROXY_IP` na IP bezprostředního protějšku, kterou vidí API a web. Tato IP se může při průchodu Docker sítí lišit od adresy, na kterou je API vázáno. Compose automaticky nastaví privátní síť a důvěryhodnou adresu webu, přes kterou web předává IP klienta dál do API.
|
||||
|
||||
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:
|
||||
|
||||
```bash
|
||||
dotnet test --solution backend/Helpdesk.sln
|
||||
dotnet run --project backend/tests/Helpdesk.UnitTests/Helpdesk.UnitTests.csproj
|
||||
```
|
||||
|
||||
Webová aplikace proti API běžícímu v Dockeru (otevře se na <http://localhost:5080>):
|
||||
|
||||
```bash
|
||||
dotnet run --project web/Helpdesk.Web
|
||||
```
|
||||
|
||||
Testy webové aplikace:
|
||||
|
||||
```bash
|
||||
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
|
||||
```
|
||||
|
||||
Pokrytí backendu integračními testy se ukládá jako Cobertura XML do `TestResults` ve výstupu testovacího projektu.
|
||||
|
||||
```bash
|
||||
dotnet run --project backend/tests/Helpdesk.IntegrationTests/Helpdesk.IntegrationTests.csproj -- \
|
||||
--coverage --coverage-output-format cobertura --coverage-output backend-coverage.cobertura.xml \
|
||||
--coverage-settings "$PWD/backend/tests/Helpdesk.IntegrationTests/coverage.settings.xml"
|
||||
```
|
||||
|
||||
## 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`.
|
||||
|
||||
## Verzování webové aplikace
|
||||
|
||||
- **Verze API:** web volá REST API `/api/v1`. Verze je na jednom místě, `ApiOptions.ApiVersion` v `web/Helpdesk.Web/Api/ApiOptions.cs`. Klienti API používají jen relativní cesty (`issues`, `auth/login`), takže přechod na `/api/v2` znamená změnit tuto konstantu a upravit DTO, která se ve v2 změnila.
|
||||
- **Verze webu:** `<Version>` v `web/Helpdesk.Web/Helpdesk.Web.csproj` podle semver – před vydáním 1.0 zvyšujeme MINOR za novou část aplikace (závady, návrhy, …) a PATCH za opravy. Verze se zobrazuje v patičce webu spolu s krátkým hashem commitu, ze kterého byl web sestaven.
|
||||
|
||||
## Technologie
|
||||
|
||||
Backend C# / ASP.NET Core Web API · EF Core + Pomelo (MariaDB) · DbUp · JWT (RFC 7519) · Swagger · Web ASP.NET Core MVC · Mobil Kotlin + Jetpack Compose · Docker
|
||||
|
||||
@@ -15,12 +15,17 @@
|
||||
<PackageVersion Include="Microsoft.Extensions.Caching.Memory" Version="10.0.14" />
|
||||
<PackageVersion Include="Microsoft.Extensions.Hosting.Abstractions" Version="10.0.14" />
|
||||
<PackageVersion Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="10.0.14" />
|
||||
<PackageVersion Include="Swashbuckle.AspNetCore" Version="10.3.1" />
|
||||
<PackageVersion Include="Swashbuckle.AspNetCore.SwaggerGen" Version="10.3.1" />
|
||||
<PackageVersion Include="BCrypt.Net-Next" Version="4.2.0" />
|
||||
<PackageVersion Include="MailKit" Version="5.0.0" />
|
||||
<PackageVersion Include="FirebaseAdmin" Version="3.7.1" />
|
||||
<PackageVersion Include="FluentValidation" Version="12.2.0" />
|
||||
<PackageVersion Include="FluentValidation.DependencyInjectionExtensions" Version="12.2.0" />
|
||||
<!-- testy -->
|
||||
<PackageVersion Include="Microsoft.AspNetCore.Mvc.Testing" Version="10.0.14" />
|
||||
<PackageVersion Include="Microsoft.NET.Test.Sdk" Version="18.11.0" />
|
||||
<PackageVersion Include="Microsoft.Testing.Extensions.CodeCoverage" Version="18.12.0" />
|
||||
<PackageVersion Include="Testcontainers.MariaDb" Version="4.16.0" />
|
||||
<PackageVersion Include="xunit.v3" Version="4.0.2" />
|
||||
<PackageVersion Include="xunit.runner.visualstudio" Version="4.0.1" />
|
||||
</ItemGroup>
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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(ApiRoutes.V1 + "/admin/notification-deliveries")]
|
||||
public sealed class AdminNotificationDeliveriesController(NotificationDeliveryService deliveries) : ControllerBase
|
||||
{
|
||||
/// <summary>Přehled doručení podle stavu, výchozí stav je FAILED.</summary>
|
||||
[HttpGet]
|
||||
[ProducesResponseType<PagedResult<NotificationDeliveryDto>>(StatusCodes.Status200OK)]
|
||||
[ProducesResponseType<ProblemDetails>(StatusCodes.Status400BadRequest)]
|
||||
public Task<PagedResult<NotificationDeliveryDto>> List(
|
||||
CancellationToken ct, [FromQuery] string status = "FAILED", [FromQuery] int page = 1, [FromQuery] int pageSize = 20) =>
|
||||
deliveries.ListAsync(status, page, pageSize, ct);
|
||||
|
||||
/// <summary>Vrátí neúspěšné doručení do fronty s novým počtem pokusů.</summary>
|
||||
[HttpPost("{id:int}/retry")]
|
||||
[ProducesResponseType(StatusCodes.Status204NoContent)]
|
||||
[ProducesResponseType<ProblemDetails>(StatusCodes.Status404NotFound)]
|
||||
[ProducesResponseType<ProblemDetails>(StatusCodes.Status409Conflict)]
|
||||
public async Task<IActionResult> Retry(int id, CancellationToken ct)
|
||||
{
|
||||
await deliveries.RetryAsync(id, ct);
|
||||
return NoContent();
|
||||
}
|
||||
}
|
||||
@@ -10,7 +10,7 @@ namespace Helpdesk.Api.Controllers;
|
||||
/// <summary>Správa uživatelů a rolí (jen administrátor).</summary>
|
||||
[ApiController]
|
||||
[Authorize(Roles = Roles.Admin)]
|
||||
[Route("api/admin/users")]
|
||||
[Route(ApiRoutes.V1 + "/admin/users")]
|
||||
[Produces("application/json")]
|
||||
public sealed class AdminUsersController(UserService users, ICurrentUser currentUser) : ControllerBase
|
||||
{
|
||||
@@ -22,6 +22,50 @@ public sealed class AdminUsersController(UserService users, ICurrentUser current
|
||||
CancellationToken ct = default) =>
|
||||
users.SearchAsync(q, role, page, pageSize, ct);
|
||||
|
||||
[HttpGet("{id:int}")]
|
||||
public Task<AdminUserDetailsDto> Get(int id, CancellationToken ct) => users.GetAdminAsync(id, ct);
|
||||
|
||||
[HttpPost]
|
||||
[ProducesResponseType<AdminUserDetailsDto>(StatusCodes.Status201Created)]
|
||||
public async Task<ActionResult<AdminUserDetailsDto>> Create(SaveAdminUserRequest request, CancellationToken ct)
|
||||
{
|
||||
var user = await users.CreateAsync(currentUser, request, ct);
|
||||
return CreatedAtAction(nameof(Get), new { id = user.Id }, user);
|
||||
}
|
||||
|
||||
[HttpPut("{id:int}")]
|
||||
[ProducesResponseType<AdminUserDetailsDto>(StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(StatusCodes.Status204NoContent)]
|
||||
public async Task<IActionResult> Update(int id, SaveAdminUserRequest request, CancellationToken ct)
|
||||
{
|
||||
var result = await users.UpdateAsync(currentUser, id, request, ct);
|
||||
return result is null ? NoContent() : Ok(result);
|
||||
}
|
||||
|
||||
[HttpPost("{id:int}/email-confirmation")]
|
||||
[ProducesResponseType(StatusCodes.Status204NoContent)]
|
||||
public async Task<IActionResult> SendEmailConfirmation(int id, CancellationToken ct)
|
||||
{
|
||||
await users.SendEmailConfirmationAsync(id, ct);
|
||||
return NoContent();
|
||||
}
|
||||
|
||||
[HttpDelete("{id:int}")]
|
||||
[ProducesResponseType(StatusCodes.Status204NoContent)]
|
||||
public async Task<IActionResult> Delete(int id, CancellationToken ct)
|
||||
{
|
||||
await users.DeleteAsync(currentUser, id, ct);
|
||||
return NoContent();
|
||||
}
|
||||
|
||||
[HttpPost("bulk")]
|
||||
[ProducesResponseType(StatusCodes.Status204NoContent)]
|
||||
public async Task<IActionResult> Bulk(BulkAdminUsersRequest request, CancellationToken ct)
|
||||
{
|
||||
await users.BulkUpdateAsync(currentUser, request, ct);
|
||||
return NoContent();
|
||||
}
|
||||
|
||||
/// <summary>Změna role – uživatel bude odhlášen a po přihlášení dostane token s novou rolí.</summary>
|
||||
[HttpPut("{id:int}/role")]
|
||||
[ProducesResponseType(StatusCodes.Status204NoContent)]
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
using Helpdesk.Api.Infrastructure;
|
||||
using Helpdesk.Application.Issues;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
|
||||
namespace Helpdesk.Api.Controllers;
|
||||
|
||||
[ApiController]
|
||||
[Authorize]
|
||||
[ResponseCache(NoStore = true, Location = ResponseCacheLocation.None)]
|
||||
[Route(ApiRoutes.V1 + "/attachments")]
|
||||
public sealed class AttachmentsController(IssueService issues) : ControllerBase
|
||||
{
|
||||
[HttpGet("{id:int}")]
|
||||
[ProducesResponseType<FileStreamResult>(StatusCodes.Status200OK, "application/octet-stream")]
|
||||
[ProducesResponseType<ProblemDetails>(StatusCodes.Status403Forbidden)]
|
||||
[ProducesResponseType<ProblemDetails>(StatusCodes.Status404NotFound)]
|
||||
public async Task<IActionResult> Download(int id, CancellationToken ct)
|
||||
{
|
||||
var file = await issues.DownloadAsync(id, ct);
|
||||
Response.Headers["X-Content-Type-Options"] = "nosniff";
|
||||
return File(file.Content, file.ContentType, file.FileName);
|
||||
}
|
||||
}
|
||||
@@ -10,7 +10,7 @@ namespace Helpdesk.Api.Controllers;
|
||||
|
||||
/// <summary>Registrace, přihlášení a správa tokenů.</summary>
|
||||
[ApiController]
|
||||
[Route("api/auth")]
|
||||
[Route(ApiRoutes.V1 + "/auth")]
|
||||
[EnableRateLimiting(RateLimitPolicies.Auth)]
|
||||
[Produces("application/json")]
|
||||
public sealed class AuthController(AuthService auth) : ControllerBase
|
||||
@@ -21,10 +21,11 @@ public sealed class AuthController(AuthService auth) : ControllerBase
|
||||
[ProducesResponseType<UserDto>(StatusCodes.Status201Created)]
|
||||
[ProducesResponseType<ValidationProblemDetails>(StatusCodes.Status400BadRequest)]
|
||||
[ProducesResponseType<ProblemDetails>(StatusCodes.Status409Conflict)]
|
||||
[ProducesResponseType<ProblemDetails>(StatusCodes.Status503ServiceUnavailable)]
|
||||
public async Task<ActionResult<UserDto>> Register(RegisterRequest request, CancellationToken ct)
|
||||
{
|
||||
var user = await auth.RegisterAsync(request, ct);
|
||||
return Created("/api/users/me", user);
|
||||
return Created($"/{ApiRoutes.V1}/users/me", user);
|
||||
}
|
||||
|
||||
/// <summary>Ověření e-mailu tokenem z registračního e-mailu (jednorázový).</summary>
|
||||
@@ -74,9 +75,10 @@ public sealed class AuthController(AuthService auth) : ControllerBase
|
||||
/// <summary>Odešle e-mail s odkazem pro nastavení nového hesla. Odpověď je stejná, ať účet existuje, nebo ne.</summary>
|
||||
[HttpPost("forgot-password")]
|
||||
[ProducesResponseType(StatusCodes.Status204NoContent)]
|
||||
public async Task<IActionResult> 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();
|
||||
}
|
||||
|
||||
|
||||
@@ -8,7 +8,7 @@ namespace Helpdesk.Api.Controllers;
|
||||
/// <summary>Číselníky pro formuláře (budovy, kategorie závad a návrhů) a jejich správa.</summary>
|
||||
[ApiController]
|
||||
[Authorize]
|
||||
[Route("api")]
|
||||
[Route(ApiRoutes.V1)]
|
||||
[Produces("application/json")]
|
||||
public sealed class CatalogsController(CatalogService catalogs) : ControllerBase
|
||||
{
|
||||
@@ -17,12 +17,6 @@ public sealed class CatalogsController(CatalogService catalogs) : ControllerBase
|
||||
public Task<IReadOnlyList<BuildingDto>> GetBuildings([FromQuery] bool includeInactive = false, CancellationToken ct = default) =>
|
||||
catalogs.GetBuildingsAsync(includeInactive && User.IsInRole(Roles.Admin), ct);
|
||||
|
||||
[HttpGet("issue-categories")]
|
||||
public Task<IReadOnlyList<CategoryDto>> GetIssueCategories(CancellationToken ct) => catalogs.GetIssueCategoriesAsync(ct);
|
||||
|
||||
[HttpGet("proposal-categories")]
|
||||
public Task<IReadOnlyList<CategoryDto>> GetProposalCategories(CancellationToken ct) => catalogs.GetProposalCategoriesAsync(ct);
|
||||
|
||||
[Authorize(Roles = Roles.Admin)]
|
||||
[HttpPost("buildings")]
|
||||
[ProducesResponseType<BuildingDto>(StatusCodes.Status201Created)]
|
||||
@@ -30,7 +24,7 @@ public sealed class CatalogsController(CatalogService catalogs) : ControllerBase
|
||||
public async Task<ActionResult<BuildingDto>> CreateBuilding(SaveBuildingRequest request, CancellationToken ct)
|
||||
{
|
||||
var building = await catalogs.CreateBuildingAsync(request, ct);
|
||||
return Created($"/api/buildings/{building.Id}", building);
|
||||
return Created($"/{ApiRoutes.V1}/buildings/{building.Id}", building);
|
||||
}
|
||||
|
||||
[Authorize(Roles = Roles.Admin)]
|
||||
@@ -51,4 +45,76 @@ public sealed class CatalogsController(CatalogService catalogs) : ControllerBase
|
||||
await catalogs.DeactivateBuildingAsync(id, ct);
|
||||
return NoContent();
|
||||
}
|
||||
|
||||
/// <summary>Kategorie závad. Administrátor může zobrazit i deaktivované pomocí <c>includeInactive=true</c>.</summary>
|
||||
[HttpGet("issue-categories")]
|
||||
public Task<IReadOnlyList<CategoryDto>> GetIssueCategories([FromQuery] bool includeInactive = false, CancellationToken ct = default) =>
|
||||
catalogs.GetIssueCategoriesAsync(includeInactive && User.IsInRole(Roles.Admin), ct);
|
||||
|
||||
[Authorize(Roles = Roles.Admin)]
|
||||
[HttpPost("issue-categories")]
|
||||
[ProducesResponseType<CategoryDto>(StatusCodes.Status201Created)]
|
||||
[ProducesResponseType<ValidationProblemDetails>(StatusCodes.Status400BadRequest)]
|
||||
[ProducesResponseType<ProblemDetails>(StatusCodes.Status409Conflict)]
|
||||
public async Task<ActionResult<CategoryDto>> CreateIssueCategory(SaveCategoryRequest request, CancellationToken ct)
|
||||
{
|
||||
var category = await catalogs.CreateIssueCategoryAsync(request, ct);
|
||||
return Created($"/{ApiRoutes.V1}/issue-categories/{category.Id}", category);
|
||||
}
|
||||
|
||||
[Authorize(Roles = Roles.Admin)]
|
||||
[HttpPut("issue-categories/{id:int}")]
|
||||
[ProducesResponseType<CategoryDto>(StatusCodes.Status200OK)]
|
||||
[ProducesResponseType<ValidationProblemDetails>(StatusCodes.Status400BadRequest)]
|
||||
[ProducesResponseType<ProblemDetails>(StatusCodes.Status404NotFound)]
|
||||
[ProducesResponseType<ProblemDetails>(StatusCodes.Status409Conflict)]
|
||||
public Task<CategoryDto> UpdateIssueCategory(int id, SaveCategoryRequest request, CancellationToken ct) =>
|
||||
catalogs.UpdateIssueCategoryAsync(id, request, ct);
|
||||
|
||||
/// <summary>Deaktivuje kategorii závad.</summary>
|
||||
[Authorize(Roles = Roles.Admin)]
|
||||
[HttpDelete("issue-categories/{id:int}")]
|
||||
[ProducesResponseType(StatusCodes.Status204NoContent)]
|
||||
[ProducesResponseType<ProblemDetails>(StatusCodes.Status404NotFound)]
|
||||
public async Task<IActionResult> DeactivateIssueCategory(int id, CancellationToken ct)
|
||||
{
|
||||
await catalogs.DeactivateIssueCategoryAsync(id, ct);
|
||||
return NoContent();
|
||||
}
|
||||
|
||||
/// <summary>Kategorie návrhů. Administrátor může zobrazit i deaktivované pomocí <c>includeInactive=true</c>.</summary>
|
||||
[HttpGet("proposal-categories")]
|
||||
public Task<IReadOnlyList<CategoryDto>> GetProposalCategories([FromQuery] bool includeInactive = false, CancellationToken ct = default) =>
|
||||
catalogs.GetProposalCategoriesAsync(includeInactive && User.IsInRole(Roles.Admin), ct);
|
||||
|
||||
[Authorize(Roles = Roles.Admin)]
|
||||
[HttpPost("proposal-categories")]
|
||||
[ProducesResponseType<CategoryDto>(StatusCodes.Status201Created)]
|
||||
[ProducesResponseType<ValidationProblemDetails>(StatusCodes.Status400BadRequest)]
|
||||
[ProducesResponseType<ProblemDetails>(StatusCodes.Status409Conflict)]
|
||||
public async Task<ActionResult<CategoryDto>> CreateProposalCategory(SaveCategoryRequest request, CancellationToken ct)
|
||||
{
|
||||
var category = await catalogs.CreateProposalCategoryAsync(request, ct);
|
||||
return Created($"/{ApiRoutes.V1}/proposal-categories/{category.Id}", category);
|
||||
}
|
||||
|
||||
[Authorize(Roles = Roles.Admin)]
|
||||
[HttpPut("proposal-categories/{id:int}")]
|
||||
[ProducesResponseType<CategoryDto>(StatusCodes.Status200OK)]
|
||||
[ProducesResponseType<ValidationProblemDetails>(StatusCodes.Status400BadRequest)]
|
||||
[ProducesResponseType<ProblemDetails>(StatusCodes.Status404NotFound)]
|
||||
[ProducesResponseType<ProblemDetails>(StatusCodes.Status409Conflict)]
|
||||
public Task<CategoryDto> UpdateProposalCategory(int id, SaveCategoryRequest request, CancellationToken ct) =>
|
||||
catalogs.UpdateProposalCategoryAsync(id, request, ct);
|
||||
|
||||
/// <summary>Deaktivuje kategorii návrhů.</summary>
|
||||
[Authorize(Roles = Roles.Admin)]
|
||||
[HttpDelete("proposal-categories/{id:int}")]
|
||||
[ProducesResponseType(StatusCodes.Status204NoContent)]
|
||||
[ProducesResponseType<ProblemDetails>(StatusCodes.Status404NotFound)]
|
||||
public async Task<IActionResult> DeactivateProposalCategory(int id, CancellationToken ct)
|
||||
{
|
||||
await catalogs.DeactivateProposalCategoryAsync(id, ct);
|
||||
return NoContent();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
using Helpdesk.Api.Infrastructure;
|
||||
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(ApiRoutes.V1 + "/devices")]
|
||||
public sealed class DevicesController(PushDeviceService devices) : ControllerBase
|
||||
{
|
||||
/// <summary>Zaregistruje FCM token pro právě přihlášeného uživatele.</summary>
|
||||
[HttpPost]
|
||||
[ProducesResponseType(StatusCodes.Status204NoContent)]
|
||||
[ProducesResponseType<ProblemDetails>(StatusCodes.Status400BadRequest)]
|
||||
public async Task<IActionResult> Register(RegisterDeviceRequest request, CancellationToken ct)
|
||||
{
|
||||
await devices.RegisterAsync(request.Token, ct);
|
||||
return NoContent();
|
||||
}
|
||||
|
||||
/// <summary>Odregistruje token právě přihlášeného uživatele.</summary>
|
||||
[HttpDelete("{token}")]
|
||||
[ProducesResponseType(StatusCodes.Status204NoContent)]
|
||||
[ProducesResponseType<ProblemDetails>(StatusCodes.Status400BadRequest)]
|
||||
public async Task<IActionResult> Unregister(string token, CancellationToken ct)
|
||||
{
|
||||
await devices.UnregisterAsync(token, ct);
|
||||
return NoContent();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,188 @@
|
||||
using System.Globalization;
|
||||
using System.Text.Json;
|
||||
using Helpdesk.Api.Infrastructure;
|
||||
using Helpdesk.Application.Common;
|
||||
using Helpdesk.Application.Issues;
|
||||
using Helpdesk.Domain.Issues;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Http.Features;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.AspNetCore.Mvc.Filters;
|
||||
using Microsoft.AspNetCore.Mvc.ModelBinding;
|
||||
using Microsoft.AspNetCore.RateLimiting;
|
||||
|
||||
namespace Helpdesk.Api.Controllers;
|
||||
|
||||
[ApiController]
|
||||
[Authorize]
|
||||
[ResponseCache(NoStore = true, Location = ResponseCacheLocation.None)]
|
||||
[Route(ApiRoutes.V1 + "/issues")]
|
||||
[ProducesResponseType<ProblemDetails>(StatusCodes.Status400BadRequest)]
|
||||
[ProducesResponseType<ProblemDetails>(StatusCodes.Status401Unauthorized)]
|
||||
[ProducesResponseType<ProblemDetails>(StatusCodes.Status403Forbidden)]
|
||||
[ProducesResponseType<ProblemDetails>(StatusCodes.Status404NotFound)]
|
||||
[ProducesResponseType<ProblemDetails>(StatusCodes.Status409Conflict)]
|
||||
public sealed class IssuesController(IssueService issues) : ControllerBase
|
||||
{
|
||||
// Pro popis o velikosti 65 535 bajtů ponechá prostor i při JSON escapování znaků.
|
||||
private const int MaxJsonCreateBytes = 1024 * 1024;
|
||||
|
||||
[HttpGet]
|
||||
public Task<PagedResult<IssueSummary>> List([FromQuery] IssueQuery query, CancellationToken ct) =>
|
||||
issues.ListAsync(query, ct);
|
||||
|
||||
[HttpGet("{id:int}")]
|
||||
public Task<IssueDetail> Get(int id, CancellationToken ct) => issues.GetAsync(id, ct);
|
||||
|
||||
[HttpPost]
|
||||
[ReadIssueBodyManually]
|
||||
[EnableRateLimiting(RateLimitPolicies.IssueWrites)]
|
||||
[Consumes("application/json", "multipart/form-data")]
|
||||
[RequestSizeLimit(AttachmentLimits.MaxRequestBytes)]
|
||||
[RequestFormLimits(MultipartBodyLengthLimit = AttachmentLimits.MaxRequestBytes)]
|
||||
[ProducesResponseType<IssueDetail>(StatusCodes.Status201Created)]
|
||||
[ProducesResponseType<ProblemDetails>(StatusCodes.Status413PayloadTooLarge)]
|
||||
[ProducesResponseType<ProblemDetails>(StatusCodes.Status415UnsupportedMediaType)]
|
||||
[ProducesResponseType<ProblemDetails>(StatusCodes.Status429TooManyRequests)]
|
||||
public async Task<ActionResult<IssueDetail>> Create(CancellationToken ct)
|
||||
{
|
||||
CreateIssueRequest request;
|
||||
AttachmentUpload[] uploads = [];
|
||||
try
|
||||
{
|
||||
if (Request.HasFormContentType)
|
||||
{
|
||||
var form = await ReadFormAsync(ct);
|
||||
request = new CreateIssueRequest(
|
||||
form["title"].ToString(), form["description"].ToString(),
|
||||
ReadId(form, "categoryId") ?? throw new BadRequestException("Kategorie je povinná."),
|
||||
ReadId(form, "buildingId"), form["locationDetail"].ToString());
|
||||
uploads = ReadUploads(form.Files);
|
||||
}
|
||||
else
|
||||
{
|
||||
if (Request.ContentType is null && Request.ContentLength is null or 0)
|
||||
throw new BadRequestException("Vyplňte údaje závady.");
|
||||
if (!Request.HasJsonContentType())
|
||||
return Problem(statusCode: StatusCodes.Status415UnsupportedMediaType);
|
||||
|
||||
var contentType = Request.GetTypedHeaders().ContentType;
|
||||
if (contentType is { Charset.HasValue: true, Encoding: null })
|
||||
return Problem(statusCode: StatusCodes.Status415UnsupportedMediaType);
|
||||
|
||||
if (HttpContext.Features.Get<IHttpMaxRequestBodySizeFeature>() is { IsReadOnly: false } sizeLimit)
|
||||
sizeLimit.MaxRequestBodySize = MaxJsonCreateBytes;
|
||||
|
||||
request = await Request.ReadFromJsonAsync<CreateIssueRequest>(ct)
|
||||
?? throw new BadRequestException("Vyplňte údaje závady.");
|
||||
}
|
||||
}
|
||||
catch (JsonException)
|
||||
{
|
||||
throw new BadRequestException("Neplatný formát požadavku.");
|
||||
}
|
||||
|
||||
var result = await issues.CreateAsync(request, uploads, ct);
|
||||
return CreatedAtAction(nameof(Get), new { id = result.Id }, result);
|
||||
}
|
||||
|
||||
[HttpPut("{id:int}")]
|
||||
public Task<IssueDetail> Edit(int id, EditIssueRequest request, CancellationToken ct) =>
|
||||
issues.EditAsync(id, request, ct);
|
||||
|
||||
[HttpPost("{id:int}/assign")]
|
||||
public Task<IssueDetail> Assign(int id, AssignIssueRequest request, CancellationToken ct) =>
|
||||
issues.AssignAsync(id, request, ct);
|
||||
|
||||
[HttpPost("{id:int}/start")]
|
||||
public Task<IssueDetail> Start(int id, IssueVersionRequest request, CancellationToken ct) =>
|
||||
issues.TransitionAsync(id, IssueAction.StartWork, request.RowVersion, null, ct);
|
||||
|
||||
[HttpPost("{id:int}/submit-for-verification")]
|
||||
public Task<IssueDetail> SubmitForVerification(int id, VerifyIssueRequest request, CancellationToken ct) =>
|
||||
issues.TransitionAsync(id, IssueAction.SubmitForVerification, request.RowVersion, request.Note, ct);
|
||||
|
||||
[HttpPost("{id:int}/confirm")]
|
||||
public Task<IssueDetail> Confirm(int id, IssueVersionRequest request, CancellationToken ct) =>
|
||||
issues.TransitionAsync(id, IssueAction.Confirm, request.RowVersion, null, ct);
|
||||
|
||||
[HttpPost("{id:int}/reopen")]
|
||||
public Task<IssueDetail> Reopen(int id, IssueReasonRequest request, CancellationToken ct) =>
|
||||
issues.TransitionAsync(id, IssueAction.Reopen, request.RowVersion, request.Reason, ct);
|
||||
|
||||
[HttpPost("{id:int}/reject")]
|
||||
public Task<IssueDetail> Reject(int id, IssueReasonRequest request, CancellationToken ct) =>
|
||||
issues.TransitionAsync(id, IssueAction.Reject, request.RowVersion, request.Reason, ct);
|
||||
|
||||
[HttpGet("{id:int}/events")]
|
||||
public Task<IReadOnlyList<IssueEventDto>> Events(int id, CancellationToken ct) => issues.GetEventsAsync(id, ct);
|
||||
|
||||
[HttpPost("{id:int}/comments")]
|
||||
[EnableRateLimiting(RateLimitPolicies.IssueWrites)]
|
||||
[ProducesResponseType<ProblemDetails>(StatusCodes.Status429TooManyRequests)]
|
||||
public Task<IssueEventDto> Comment(int id, CommentRequest request, CancellationToken ct) =>
|
||||
issues.CommentAsync(id, request, ct);
|
||||
|
||||
[HttpPost("{id:int}/attachments")]
|
||||
[ReadIssueBodyManually]
|
||||
[EnableRateLimiting(RateLimitPolicies.IssueWrites)]
|
||||
[Consumes("multipart/form-data")]
|
||||
[RequestSizeLimit(AttachmentLimits.MaxRequestBytes)]
|
||||
[RequestFormLimits(MultipartBodyLengthLimit = AttachmentLimits.MaxRequestBytes)]
|
||||
[ProducesResponseType<ProblemDetails>(StatusCodes.Status413PayloadTooLarge)]
|
||||
[ProducesResponseType<ProblemDetails>(StatusCodes.Status415UnsupportedMediaType)]
|
||||
[ProducesResponseType<ProblemDetails>(StatusCodes.Status429TooManyRequests)]
|
||||
public async Task<ActionResult<IReadOnlyList<AttachmentDto>>> Upload(int id, CancellationToken ct)
|
||||
{
|
||||
if (!Request.HasFormContentType)
|
||||
return Problem(statusCode: StatusCodes.Status415UnsupportedMediaType);
|
||||
|
||||
var attachments = await issues.AddAttachmentsAsync(id, async token =>
|
||||
ReadUploads((await ReadFormAsync(token)).Files), ct);
|
||||
return Ok(attachments);
|
||||
}
|
||||
|
||||
private async Task<IFormCollection> ReadFormAsync(CancellationToken ct)
|
||||
{
|
||||
try
|
||||
{
|
||||
return await Request.ReadFormAsync(ct);
|
||||
}
|
||||
catch (InvalidDataException)
|
||||
{
|
||||
throw new BadRequestException("Neplatný formát požadavku.");
|
||||
}
|
||||
}
|
||||
|
||||
private static int? ReadId(IFormCollection form, string key)
|
||||
{
|
||||
var value = form[key].ToString();
|
||||
if (string.IsNullOrWhiteSpace(value))
|
||||
return null;
|
||||
if (!int.TryParse(value, NumberStyles.None, CultureInfo.InvariantCulture, out var id))
|
||||
throw new BadRequestException($"Neplatná hodnota {key}.");
|
||||
return id;
|
||||
}
|
||||
|
||||
private static AttachmentUpload[] ReadUploads(IFormFileCollection files)
|
||||
{
|
||||
if (files.Count > AttachmentLimits.MaxFiles)
|
||||
throw new BadRequestException("Najednou lze přiložit nejvýše pět souborů.");
|
||||
if (files.Any(file => file.Name != "files"))
|
||||
throw new BadRequestException("Přílohy patří do pole files.");
|
||||
|
||||
return files.Select(file => new AttachmentUpload(file.FileName, file.Length, file.OpenReadStream)).ToArray();
|
||||
}
|
||||
}
|
||||
|
||||
internal sealed class ReadIssueBodyManuallyAttribute : Attribute, IResourceFilter
|
||||
{
|
||||
public void OnResourceExecuting(ResourceExecutingContext context)
|
||||
{
|
||||
context.ValueProviderFactories.RemoveType<FormValueProviderFactory>();
|
||||
context.ValueProviderFactories.RemoveType<FormFileValueProviderFactory>();
|
||||
context.ValueProviderFactories.RemoveType<JQueryFormValueProviderFactory>();
|
||||
}
|
||||
|
||||
public void OnResourceExecuted(ResourceExecutedContext context) { }
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
using Helpdesk.Application.Common;
|
||||
using Helpdesk.Api.Infrastructure;
|
||||
using Helpdesk.Application.Notifications;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
|
||||
namespace Helpdesk.Api.Controllers;
|
||||
|
||||
[ApiController]
|
||||
[Authorize]
|
||||
[Route(ApiRoutes.V1 + "/notifications")]
|
||||
[ResponseCache(NoStore = true, Location = ResponseCacheLocation.None)]
|
||||
[ProducesResponseType<ProblemDetails>(StatusCodes.Status401Unauthorized)]
|
||||
public sealed class NotificationsController(NotificationService notifications) : ControllerBase
|
||||
{
|
||||
[HttpGet]
|
||||
public Task<PagedResult<NotificationDto>> List(
|
||||
[FromQuery] bool unreadOnly = false, [FromQuery] int page = 1, [FromQuery] int pageSize = 20,
|
||||
CancellationToken ct = default) => notifications.ListAsync(unreadOnly, page, pageSize, ct);
|
||||
|
||||
[HttpGet("unread-count")]
|
||||
public Task<UnreadCountDto> CountUnread(CancellationToken ct) => notifications.CountUnreadAsync(ct);
|
||||
|
||||
[HttpPost("{id:int}/read")]
|
||||
[ProducesResponseType(StatusCodes.Status204NoContent)]
|
||||
[ProducesResponseType<ProblemDetails>(StatusCodes.Status404NotFound)]
|
||||
public async Task<IActionResult> MarkRead(int id, CancellationToken ct)
|
||||
{
|
||||
await notifications.MarkReadAsync(id, ct);
|
||||
return NoContent();
|
||||
}
|
||||
|
||||
[HttpPost("read-all")]
|
||||
[ProducesResponseType(StatusCodes.Status204NoContent)]
|
||||
public async Task<IActionResult> MarkAllRead(CancellationToken ct)
|
||||
{
|
||||
await notifications.MarkAllReadAsync(ct);
|
||||
return NoContent();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
using Helpdesk.Api.Infrastructure;
|
||||
using Helpdesk.Application.Common;
|
||||
using Helpdesk.Application.Proposals;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
|
||||
namespace Helpdesk.Api.Controllers;
|
||||
|
||||
[ApiController]
|
||||
[Authorize]
|
||||
[ResponseCache(NoStore = true, Location = ResponseCacheLocation.None)]
|
||||
[Route(ApiRoutes.V1 + "/proposals")]
|
||||
[ProducesResponseType<ProblemDetails>(StatusCodes.Status400BadRequest)]
|
||||
[ProducesResponseType<ProblemDetails>(StatusCodes.Status401Unauthorized)]
|
||||
[ProducesResponseType<ProblemDetails>(StatusCodes.Status403Forbidden)]
|
||||
[ProducesResponseType<ProblemDetails>(StatusCodes.Status404NotFound)]
|
||||
[ProducesResponseType<ProblemDetails>(StatusCodes.Status409Conflict)]
|
||||
public sealed class ProposalsController(ProposalService proposals) : ControllerBase
|
||||
{
|
||||
/// <summary>Seznam návrhů s volitelným filtrem podle data podání.</summary>
|
||||
/// <param name="query">Filtry, řazení a stránkování.</param>
|
||||
/// <param name="from">Dolní hranice data podání včetně.</param>
|
||||
/// <param name="to">Horní hranice data podání bez uvedeného okamžiku.</param>
|
||||
/// <param name="ct">Token pro zrušení požadavku.</param>
|
||||
[HttpGet]
|
||||
public Task<PagedResult<ProposalSummary>> List([FromQuery] ProposalQuery query,
|
||||
[FromQuery] DateTimeOffset? from, [FromQuery] DateTimeOffset? to, CancellationToken ct) =>
|
||||
proposals.ListAsync(query, from, to, ct);
|
||||
|
||||
[HttpGet("{id:int}")]
|
||||
public Task<ProposalDetail> Get(int id, CancellationToken ct) => proposals.GetAsync(id, ct);
|
||||
|
||||
[HttpPost]
|
||||
[RequestSizeLimit(1024 * 1024)]
|
||||
[ProducesResponseType<ProposalDetail>(StatusCodes.Status201Created)]
|
||||
public async Task<ActionResult<ProposalDetail>> Create(SaveProposalRequest request, CancellationToken ct)
|
||||
{
|
||||
var proposal = await proposals.CreateAsync(request, ct);
|
||||
return CreatedAtAction(nameof(Get), new { id = proposal.Id }, proposal);
|
||||
}
|
||||
|
||||
[HttpPut("{id:int}")]
|
||||
[RequestSizeLimit(1024 * 1024)]
|
||||
public Task<ProposalDetail> Edit(int id, SaveProposalRequest request, CancellationToken ct) =>
|
||||
proposals.EditAsync(id, request, ct);
|
||||
|
||||
[HttpPut("{id:int}/vote")]
|
||||
[RequestSizeLimit(1024 * 1024)]
|
||||
[ProducesResponseType(StatusCodes.Status204NoContent)]
|
||||
public async Task<IActionResult> SetVote(int id, VoteRequest request, CancellationToken ct)
|
||||
{
|
||||
await proposals.SetVoteAsync(id, request.Value, ct);
|
||||
return NoContent();
|
||||
}
|
||||
|
||||
[HttpDelete("{id:int}/vote")]
|
||||
[ProducesResponseType(StatusCodes.Status204NoContent)]
|
||||
public async Task<IActionResult> RemoveVote(int id, CancellationToken ct)
|
||||
{
|
||||
await proposals.RemoveVoteAsync(id, ct);
|
||||
return NoContent();
|
||||
}
|
||||
|
||||
[HttpPost("{id:int}/status")]
|
||||
[Authorize(Roles = Roles.ManagementOrAdmin)]
|
||||
[RequestSizeLimit(1024 * 1024)]
|
||||
public Task<ProposalDetail> ChangeStatus(int id, ChangeProposalStatusRequest request, CancellationToken ct) =>
|
||||
proposals.ChangeStatusAsync(id, request, ct);
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
/// <summary>Statistiky pro vedení školy a administrátory. Období v UTC zahrnuje začátek a vylučuje konec.</summary>
|
||||
[ApiController]
|
||||
[Authorize(Roles = Roles.ManagementOrAdmin)]
|
||||
[ResponseCache(NoStore = true, Location = ResponseCacheLocation.None)]
|
||||
[Route(ApiRoutes.V1 + "/statistics")]
|
||||
[ProducesResponseType<ProblemDetails>(StatusCodes.Status400BadRequest)]
|
||||
[ProducesResponseType<ProblemDetails>(StatusCodes.Status401Unauthorized)]
|
||||
[ProducesResponseType<ProblemDetails>(StatusCodes.Status403Forbidden)]
|
||||
public sealed class StatisticsController(StatisticsService statistics) : ControllerBase
|
||||
{
|
||||
/// <summary>Počty podle aktuálního stavu a průměrné časy pro závady nahlášené v období.</summary>
|
||||
[HttpGet("overview")]
|
||||
public Task<StatisticsOverview> GetOverview([FromQuery] StatisticsQuery query, CancellationToken ct) =>
|
||||
statistics.GetOverviewAsync(query.ToPeriod(), ct);
|
||||
|
||||
/// <summary>Počty nahlášených závad a průměrná doba vyřešení podle kategorie.</summary>
|
||||
[HttpGet("issues/by-category")]
|
||||
public Task<IReadOnlyList<IssueCategoryStatistics>> GetByCategory([FromQuery] StatisticsQuery query, CancellationToken ct) =>
|
||||
statistics.GetByCategoryAsync(query.ToPeriod(), ct);
|
||||
|
||||
/// <summary>Počty nahlášených závad podle budovy včetně závad bez budovy.</summary>
|
||||
[HttpGet("issues/by-building")]
|
||||
public Task<IReadOnlyList<IssueBuildingStatistics>> GetByBuilding([FromQuery] StatisticsQuery query, CancellationToken ct) =>
|
||||
statistics.GetByBuildingAsync(query.ToPeriod(), ct);
|
||||
|
||||
/// <summary>Otevřené, vyřešené a zamítnuté závady podle aktuálního řešitele.</summary>
|
||||
[HttpGet("issues/by-assignee")]
|
||||
public Task<IReadOnlyList<IssueAssigneeStatistics>> GetByAssignee([FromQuery] StatisticsQuery query, CancellationToken ct) =>
|
||||
statistics.GetByAssigneeAsync(query.ToPeriod(), ct);
|
||||
|
||||
/// <summary>Počty vytvoření a uzavření závad po měsících podle data události.</summary>
|
||||
[HttpGet("issues/trend")]
|
||||
public Task<IReadOnlyList<IssueTrendPoint>> GetTrend([FromQuery] StatisticsQuery query, CancellationToken ct,
|
||||
[FromQuery, AllowedValues("month")] string granularity = "month") =>
|
||||
statistics.GetTrendAsync(query.ToPeriod(), ct);
|
||||
|
||||
/// <summary>Návrhy podané v období podle aktuálního skóre, počtu hlasů pro a data podání.</summary>
|
||||
[HttpGet("proposals/top")]
|
||||
public Task<IReadOnlyList<TopProposal>> 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);
|
||||
}
|
||||
@@ -1,5 +1,7 @@
|
||||
using Helpdesk.Application.Abstractions;
|
||||
using Helpdesk.Application.Issues;
|
||||
using Helpdesk.Application.Users;
|
||||
using Helpdesk.Api.Infrastructure;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
|
||||
@@ -8,9 +10,9 @@ namespace Helpdesk.Api.Controllers;
|
||||
/// <summary>Profil přihlášeného uživatele.</summary>
|
||||
[ApiController]
|
||||
[Authorize]
|
||||
[Route("api/users")]
|
||||
[Route(ApiRoutes.V1 + "/users")]
|
||||
[Produces("application/json")]
|
||||
public sealed class UsersController(UserService users, ICurrentUser currentUser) : ControllerBase
|
||||
public sealed class UsersController(UserService users, ICurrentUser currentUser, IssueService issues) : ControllerBase
|
||||
{
|
||||
/// <summary>Můj profil.</summary>
|
||||
[HttpGet("me")]
|
||||
@@ -21,4 +23,11 @@ public sealed class UsersController(UserService users, ICurrentUser currentUser)
|
||||
[ProducesResponseType<UserDto>(StatusCodes.Status200OK)]
|
||||
[ProducesResponseType<ValidationProblemDetails>(StatusCodes.Status400BadRequest)]
|
||||
public Task<UserDto> UpdateMe(UpdateProfileRequest request, CancellationToken ct) => users.UpdateMeAsync(currentUser, request, ct);
|
||||
|
||||
/// <summary>Aktivní řešitelé s počtem otevřených závad.</summary>
|
||||
[HttpGet("assignable")]
|
||||
[Authorize(Roles = Roles.ManagementOrAdmin)]
|
||||
[ResponseCache(NoStore = true, Location = ResponseCacheLocation.None)]
|
||||
[ProducesResponseType<ProblemDetails>(StatusCodes.Status403Forbidden)]
|
||||
public Task<IReadOnlyList<AssignableUserDto>> GetAssignable(CancellationToken ct) => issues.GetAssignableAsync(ct);
|
||||
}
|
||||
@@ -13,7 +13,7 @@
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" />
|
||||
<PackageReference Include="Swashbuckle.AspNetCore" />
|
||||
<PackageReference Include="Swashbuckle.AspNetCore.SwaggerGen" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -0,0 +1,6 @@
|
||||
namespace Helpdesk.Api.Infrastructure;
|
||||
|
||||
internal static class ApiRoutes
|
||||
{
|
||||
public const string V1 = "api/v1";
|
||||
}
|
||||
@@ -21,6 +21,7 @@ internal sealed class AppExceptionHandler(IProblemDetailsService problemDetails)
|
||||
Title = "Neplatná vstupní data.",
|
||||
},
|
||||
AppException app => new ProblemDetails { Status = app.StatusCode, Title = app.Message },
|
||||
BadHttpRequestException request => new ProblemDetails { Status = request.StatusCode },
|
||||
_ => null,
|
||||
};
|
||||
|
||||
|
||||
@@ -42,4 +42,5 @@ public static class AuthenticationSetup
|
||||
public static class RateLimitPolicies
|
||||
{
|
||||
public const string Auth = "auth";
|
||||
public const string IssueWrites = "issue-writes";
|
||||
}
|
||||
@@ -8,4 +8,5 @@ public static class Roles
|
||||
public const string FacilityManager = "FACILITY_MANAGER";
|
||||
public const string Management = "MANAGEMENT";
|
||||
public const string Admin = "ADMIN";
|
||||
public const string ManagementOrAdmin = Management + "," + Admin;
|
||||
}
|
||||
@@ -1,4 +1,7 @@
|
||||
using Microsoft.OpenApi;
|
||||
using Swashbuckle.AspNetCore.SwaggerGen;
|
||||
using Helpdesk.Api.Controllers;
|
||||
using Helpdesk.Application.Issues;
|
||||
|
||||
namespace Helpdesk.Api.Infrastructure;
|
||||
|
||||
@@ -6,7 +9,7 @@ public static class SwaggerSetup
|
||||
{
|
||||
private const string SchemeId = "Bearer";
|
||||
|
||||
/// <summary>Swagger UI na <c>/swagger</c> včetně přihlášení access tokenem (NFR-04).</summary>
|
||||
/// <summary>Generování OpenAPI dokumentu pro administrátorské Swagger UI (NFR-04).</summary>
|
||||
public static IServiceCollection AddHelpdeskSwagger(this IServiceCollection services)
|
||||
{
|
||||
services.AddEndpointsApiExplorer();
|
||||
@@ -16,7 +19,7 @@ public static class SwaggerSetup
|
||||
{
|
||||
Title = "Univerzitní helpdesk – API",
|
||||
Version = "v1",
|
||||
Description = "REST API pro webovou a mobilní aplikaci. Access token získáte přes POST /api/auth/login.",
|
||||
Description = $"REST API pro webovou a mobilní aplikaci. Access token získáte přes POST /{ApiRoutes.V1}/auth/login.",
|
||||
});
|
||||
|
||||
options.AddSecurityDefinition(SchemeId, new OpenApiSecurityScheme
|
||||
@@ -30,6 +33,7 @@ public static class SwaggerSetup
|
||||
{
|
||||
[new OpenApiSecuritySchemeReference(SchemeId, document)] = [],
|
||||
});
|
||||
options.OperationFilter<IssueRequestBody>();
|
||||
|
||||
var xml = Path.Combine(AppContext.BaseDirectory, "Helpdesk.Api.xml");
|
||||
if (File.Exists(xml))
|
||||
@@ -38,3 +42,63 @@ public static class SwaggerSetup
|
||||
return services;
|
||||
}
|
||||
}
|
||||
|
||||
internal sealed class IssueRequestBody : IOperationFilter
|
||||
{
|
||||
public void Apply(OpenApiOperation operation, OperationFilterContext context)
|
||||
{
|
||||
if (context.MethodInfo.DeclaringType != typeof(IssuesController))
|
||||
return;
|
||||
|
||||
var create = context.MethodInfo.Name == nameof(IssuesController.Create);
|
||||
if (!create && context.MethodInfo.Name != nameof(IssuesController.Upload))
|
||||
return;
|
||||
|
||||
var properties = new Dictionary<string, IOpenApiSchema>
|
||||
{
|
||||
["files"] = new OpenApiSchema
|
||||
{
|
||||
Type = JsonSchemaType.Array,
|
||||
MinItems = 1,
|
||||
MaxItems = AttachmentLimits.MaxFiles,
|
||||
Items = new OpenApiSchema { Type = JsonSchemaType.String, Format = "binary" },
|
||||
},
|
||||
};
|
||||
var required = new HashSet<string> { "files" };
|
||||
if (create)
|
||||
{
|
||||
required = ["title", "description", "categoryId"];
|
||||
properties["title"] = new OpenApiSchema { Type = JsonSchemaType.String, MaxLength = 200 };
|
||||
properties["description"] = new OpenApiSchema { Type = JsonSchemaType.String };
|
||||
properties["categoryId"] = new OpenApiSchema { Type = JsonSchemaType.Integer };
|
||||
properties["buildingId"] = new OpenApiSchema { Type = JsonSchemaType.Integer };
|
||||
properties["locationDetail"] = new OpenApiSchema { Type = JsonSchemaType.String, MaxLength = 255 };
|
||||
}
|
||||
|
||||
var content = new Dictionary<string, OpenApiMediaType>
|
||||
{
|
||||
["multipart/form-data"] = new()
|
||||
{
|
||||
Schema = new OpenApiSchema
|
||||
{
|
||||
Type = JsonSchemaType.Object,
|
||||
Required = required,
|
||||
Properties = properties,
|
||||
},
|
||||
},
|
||||
};
|
||||
if (create)
|
||||
{
|
||||
content["application/json"] = new OpenApiMediaType
|
||||
{
|
||||
Schema = context.SchemaGenerator.GenerateSchema(typeof(CreateIssueRequest), context.SchemaRepository),
|
||||
};
|
||||
}
|
||||
|
||||
operation.RequestBody = new OpenApiRequestBody
|
||||
{
|
||||
Required = true,
|
||||
Content = content,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -1,13 +1,23 @@
|
||||
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);
|
||||
|
||||
builder.Services.AddApplication(builder.Configuration);
|
||||
builder.Services.AddInfrastructure(builder.Configuration);
|
||||
builder.Services.AddInfrastructure(builder.Configuration, builder.Environment);
|
||||
builder.Services.AddOptions<RegistrationOptions>()
|
||||
.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<ICurrentUser, HttpCurrentUser>();
|
||||
@@ -20,31 +30,60 @@ builder.Services.AddProblemDetails();
|
||||
builder.Services.AddExceptionHandler<AppExceptionHandler>();
|
||||
builder.Services.AddHelpdeskSwagger();
|
||||
|
||||
// Ochrana /api/auth/* proti hádání hesel a zahlcení (kap. 10).
|
||||
var trustedProxies = new[] { "ReverseProxy:TrustedIp", "ReverseProxy:TrustedWebIp" }
|
||||
.Where(key => !string.IsNullOrWhiteSpace(builder.Configuration[key]))
|
||||
.Select(key => IPAddress.TryParse(builder.Configuration[key], out var address) ? address
|
||||
: throw new InvalidOperationException($"Nastavte platnou IP adresu v {key}."))
|
||||
.ToArray();
|
||||
|
||||
if (trustedProxies.Length > 0)
|
||||
{
|
||||
builder.Services.Configure<ForwardedHeadersOptions>(options =>
|
||||
{
|
||||
options.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto;
|
||||
options.KnownIPNetworks.Clear();
|
||||
options.KnownProxies.Clear();
|
||||
foreach (var address in trustedProxies)
|
||||
options.KnownProxies.Add(address);
|
||||
});
|
||||
}
|
||||
|
||||
// Ochrana přihlášení a zápisů závad proti zahlcení (kap. 10).
|
||||
builder.Services.AddRateLimiter(options =>
|
||||
{
|
||||
options.RejectionStatusCode = StatusCodes.Status429TooManyRequests;
|
||||
options.AddPolicy(RateLimitPolicies.Auth, http => RateLimitPartition.GetFixedWindowLimiter(
|
||||
http.Connection.RemoteIpAddress?.ToString() ?? "unknown",
|
||||
_ => new FixedWindowRateLimiterOptions { PermitLimit = 20, Window = TimeSpan.FromMinutes(1) }));
|
||||
options.AddPolicy(RateLimitPolicies.Auth, http =>
|
||||
{
|
||||
var address = http.Connection.RemoteIpAddress;
|
||||
if (address is { IsIPv4MappedToIPv6: true })
|
||||
address = address.MapToIPv4();
|
||||
return RateLimitPartition.GetFixedWindowLimiter(address?.ToString() ?? "unknown",
|
||||
_ => new FixedWindowRateLimiterOptions { PermitLimit = 20, Window = TimeSpan.FromMinutes(1) });
|
||||
});
|
||||
options.AddPolicy(RateLimitPolicies.IssueWrites, http => RateLimitPartition.GetSlidingWindowLimiter(
|
||||
http.User.FindFirst(JwtRegisteredClaimNames.Sub)?.Value ?? "unknown",
|
||||
_ => new SlidingWindowRateLimiterOptions
|
||||
{
|
||||
PermitLimit = 10,
|
||||
Window = TimeSpan.FromMinutes(1),
|
||||
SegmentsPerWindow = 6,
|
||||
}));
|
||||
});
|
||||
|
||||
var app = builder.Build();
|
||||
|
||||
if (trustedProxies.Length > 0)
|
||||
app.UseForwardedHeaders();
|
||||
|
||||
app.UseExceptionHandler();
|
||||
app.UseStatusCodePages();
|
||||
|
||||
app.UseSwagger();
|
||||
app.UseSwaggerUI(options =>
|
||||
{
|
||||
options.SwaggerEndpoint("/swagger/v1/swagger.json", "Helpdesk API v1");
|
||||
options.DocumentTitle = "Helpdesk API";
|
||||
});
|
||||
|
||||
app.UseRateLimiter();
|
||||
app.UseAuthentication();
|
||||
app.UseAuthorization();
|
||||
app.UseRateLimiter();
|
||||
|
||||
app.MapSwagger(ApiRoutes.V1 + "/admin/openapi/{documentName}.json")
|
||||
.RequireAuthorization(policy => policy.RequireRole(Roles.Admin));
|
||||
app.MapControllers();
|
||||
|
||||
app.Run();
|
||||
|
||||
@@ -1,7 +1,12 @@
|
||||
using Helpdesk.Application.Statistics;
|
||||
using Helpdesk.Domain.Auth;
|
||||
using Helpdesk.Domain.Catalogs;
|
||||
using Helpdesk.Domain.Issues;
|
||||
using Helpdesk.Domain.Notifications;
|
||||
using Helpdesk.Domain.Proposals;
|
||||
using Helpdesk.Domain.Users;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Storage;
|
||||
|
||||
namespace Helpdesk.Application.Abstractions;
|
||||
|
||||
@@ -12,8 +17,23 @@ public interface IAppDbContext
|
||||
DbSet<Building> Buildings { get; }
|
||||
DbSet<IssueCategory> IssueCategories { get; }
|
||||
DbSet<ProposalCategory> ProposalCategories { get; }
|
||||
DbSet<Issue> Issues { get; }
|
||||
DbSet<IssueEvent> IssueEvents { get; }
|
||||
IQueryable<IssueTiming> IssueTimings { get; }
|
||||
DbSet<Attachment> Attachments { get; }
|
||||
DbSet<Proposal> Proposals { get; }
|
||||
DbSet<ProposalEvent> ProposalEvents { get; }
|
||||
DbSet<ProposalVote> ProposalVotes { get; }
|
||||
DbSet<ProposalScore> ProposalScores { get; }
|
||||
DbSet<Notification> Notifications { get; }
|
||||
DbSet<NotificationDelivery> NotificationDeliveries { get; }
|
||||
DbSet<PushDevice> PushDevices { get; }
|
||||
|
||||
Task<int> SaveChangesAsync(CancellationToken cancellationToken = default);
|
||||
Task<IDbContextTransaction> BeginWriteAsync(CancellationToken ct);
|
||||
Task<User?> LockUserAsync(int id, CancellationToken ct);
|
||||
Task<Proposal?> LockProposalAsync(int id, CancellationToken ct);
|
||||
Task RegisterPushDeviceAsync(int userId, string token, CancellationToken ct);
|
||||
}
|
||||
|
||||
public interface IPasswordHasher
|
||||
|
||||
@@ -32,36 +32,52 @@ 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);
|
||||
await SendEmailConfirmationAsync(user, ct);
|
||||
return UserDto.From(user);
|
||||
}
|
||||
|
||||
internal Task<bool> SendEmailConfirmationAsync(User user, CancellationToken ct) =>
|
||||
SendEmailTokenAsync(user, TokenType.EmailConfirm, ct);
|
||||
|
||||
public async Task ConfirmEmailAsync(EmailTokenRequest request, CancellationToken ct)
|
||||
{
|
||||
await using var transaction = await db.BeginWriteAsync(ct);
|
||||
var user = await ConsumeEmailTokenAsync(request.Token, TokenType.EmailConfirm, ct);
|
||||
user.ConfirmEmail();
|
||||
await db.SaveChangesAsync(ct);
|
||||
await transaction.CommitAsync(ct);
|
||||
}
|
||||
|
||||
public async Task<AuthResponse> LoginAsync(LoginRequest request, CancellationToken ct)
|
||||
{
|
||||
await loginValidator.ValidateAndThrowAsync(request, ct);
|
||||
|
||||
var now = clock.GetUtcNow().UtcDateTime;
|
||||
var normalized = User.NormalizeEmail(request.Email);
|
||||
var user = await db.Users.SingleOrDefaultAsync(u => u.EmailNormalized == normalized, ct);
|
||||
var account = await db.Users.Where(u => u.EmailNormalized == normalized)
|
||||
.Select(u => new { u.Id, u.EmailNormalized }).SingleOrDefaultAsync(ct);
|
||||
|
||||
// Neexistující účet a špatné heslo vracejí stejnou chybu – nelze tak zjišťovat registrované e-maily.
|
||||
const string invalidCredentials = "Neplatný e-mail nebo heslo.";
|
||||
if (user is null)
|
||||
if (account is null)
|
||||
throw new UnauthorizedException(invalidCredentials);
|
||||
|
||||
await using var transaction = await db.BeginWriteAsync(ct);
|
||||
var user = await db.LockUserAsync(account.Id, ct);
|
||||
if (user is null || user.IsDeleted || user.EmailNormalized != account.EmailNormalized)
|
||||
throw new UnauthorizedException(invalidCredentials);
|
||||
var now = clock.GetUtcNow().UtcDateTime;
|
||||
if (user.IsLockedOut(now))
|
||||
throw new UnauthorizedException("Účet je po opakovaných neúspěšných pokusech dočasně zamčen. Zkuste to později.");
|
||||
|
||||
@@ -69,16 +85,19 @@ public sealed class AuthService(
|
||||
{
|
||||
user.RegisterFailedLogin(now);
|
||||
await db.SaveChangesAsync(ct);
|
||||
await transaction.CommitAsync(ct);
|
||||
throw new UnauthorizedException(invalidCredentials);
|
||||
}
|
||||
|
||||
if (!user.IsActive)
|
||||
throw new ForbiddenException("Účet je deaktivován.");
|
||||
if (!user.EmailConfirmed)
|
||||
throw new ForbiddenException("E-mail ještě nebyl ověřen. Použijte odkaz z registračního e-mailu.");
|
||||
throw new ForbiddenException("E-mail ještě nebyl ověřen. Použijte odkaz z ověřovacího e-mailu.");
|
||||
|
||||
user.RegisterSuccessfulLogin();
|
||||
return await IssueTokenPairAsync(user, ct);
|
||||
var response = await IssueTokenPairAsync(user, ct);
|
||||
await transaction.CommitAsync(ct);
|
||||
return response;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -90,17 +109,23 @@ public sealed class AuthService(
|
||||
var token = await tokens.ValidateAsync(request.RefreshToken, TokenType.Refresh)
|
||||
?? throw new UnauthorizedException("Neplatný refresh token.");
|
||||
|
||||
if (!await revocation.TryConsumeAsync(token.Jti, TokenType.Refresh, ct))
|
||||
// Stejný zámek účtu používá jeho správa, takže během zneplatnění nevznikne nová relace.
|
||||
await using var transaction = await db.BeginWriteAsync(ct);
|
||||
var user = await db.LockUserAsync(token.UserId, ct);
|
||||
if (user is null || !user.IsActive || !user.EmailConfirmed)
|
||||
throw new UnauthorizedException("Účet neexistuje, je deaktivován nebo nemá ověřený e-mail.");
|
||||
|
||||
if (await revocation.TryConsumeAsync(token.Jti, TokenType.Refresh, ct))
|
||||
{
|
||||
await revocation.RevokeAllAsync(token.UserId, RevokeReason.ReuseDetected, ct);
|
||||
throw new UnauthorizedException("Refresh token už byl použit. Přihlaste se znovu.");
|
||||
var response = await IssueTokenPairAsync(user, ct);
|
||||
await transaction.CommitAsync(ct);
|
||||
return response;
|
||||
}
|
||||
|
||||
var user = await db.Users.SingleOrDefaultAsync(u => u.Id == token.UserId, ct);
|
||||
if (user is null || !user.IsActive)
|
||||
throw new UnauthorizedException("Účet neexistuje nebo je deaktivován.");
|
||||
|
||||
return await IssueTokenPairAsync(user, ct);
|
||||
var revoked = await revocation.StageRevokeAllAsync([user.Id], RevokeReason.ReuseDetected, ct);
|
||||
await transaction.CommitAsync(ct);
|
||||
revocation.Publish(revoked);
|
||||
throw new UnauthorizedException("Refresh token už byl použit. Přihlaste se znovu.");
|
||||
}
|
||||
|
||||
/// <summary>Odhlášení jednoho zařízení – zneplatní aktuální access token a k němu předaný refresh token.</summary>
|
||||
@@ -123,20 +148,30 @@ 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)
|
||||
{
|
||||
await resetPasswordValidator.ValidateAndThrowAsync(request, ct);
|
||||
|
||||
await using var transaction = await db.BeginWriteAsync(ct);
|
||||
var user = await ConsumeEmailTokenAsync(request.Token, TokenType.PasswordReset, ct);
|
||||
|
||||
// Nejdřív zneplatnit stará přihlášení – kdyby uložení hesla selhalo, nic se tím neotevře.
|
||||
await revocation.RevokeAllAsync(user.Id, RevokeReason.PasswordChanged, ct);
|
||||
var revoked = await revocation.StageRevokeAllAsync([user.Id], RevokeReason.PasswordChanged, ct);
|
||||
user.ChangePasswordHash(passwordHasher.Hash(request.NewPassword));
|
||||
await db.SaveChangesAsync(ct);
|
||||
await transaction.CommitAsync(ct);
|
||||
revocation.Publish(revoked);
|
||||
}
|
||||
|
||||
private async Task<AuthResponse> IssueTokenPairAsync(User user, CancellationToken ct)
|
||||
@@ -152,21 +187,33 @@ public sealed class AuthService(
|
||||
UserDto.From(user));
|
||||
}
|
||||
|
||||
private async Task SendEmailTokenAsync(User user, TokenType type, CancellationToken ct)
|
||||
private async Task<bool> SendEmailTokenAsync(User user, TokenType type, CancellationToken ct)
|
||||
{
|
||||
var issued = tokens.Issue(user, type);
|
||||
db.AuthTokens.Add(issued.Record);
|
||||
await db.SaveChangesAsync(ct);
|
||||
IssuedToken issued;
|
||||
await using (var transaction = await db.BeginWriteAsync(ct))
|
||||
{
|
||||
await db.LockUserAsync(user.Id, ct);
|
||||
var current = await db.Users.AsNoTracking().SingleOrDefaultAsync(u => u.Id == user.Id, ct);
|
||||
if (current is null || !current.IsActive || current.EmailNormalized != user.EmailNormalized ||
|
||||
(type == TokenType.EmailConfirm && current.EmailConfirmed))
|
||||
return false;
|
||||
|
||||
issued = tokens.Issue(current, type);
|
||||
db.AuthTokens.Add(issued.Record);
|
||||
await db.SaveChangesAsync(ct);
|
||||
await transaction.CommitAsync(ct);
|
||||
}
|
||||
|
||||
var baseUrl = _registration.WebBaseUrl.TrimEnd('/');
|
||||
var (subject, path, text) = type switch
|
||||
{
|
||||
TokenType.EmailConfirm => ("Ověření e-mailu", "confirm-email", "Pro dokončení registrace ověřte svůj e-mail"),
|
||||
TokenType.EmailConfirm => ("Ověření e-mailu", "confirm-email", "Ověřte svůj e-mail"),
|
||||
TokenType.PasswordReset => ("Obnova hesla", "reset-password", "Nové heslo nastavíte"),
|
||||
_ => throw new ArgumentOutOfRangeException(nameof(type)),
|
||||
};
|
||||
var link = $"{baseUrl}/{path}?token={Uri.EscapeDataString(issued.Token)}";
|
||||
await emailSender.SendAsync(user.Email, subject, $"{text} na adrese:\n{link}", ct);
|
||||
return true;
|
||||
}
|
||||
|
||||
private async Task<User> ConsumeEmailTokenAsync(string token, TokenType type, CancellationToken ct)
|
||||
@@ -174,10 +221,10 @@ public sealed class AuthService(
|
||||
const string invalid = "Odkaz je neplatný, už byl použit nebo vypršel.";
|
||||
|
||||
var validated = await tokens.ValidateAsync(token ?? "", type) ?? throw new BadRequestException(invalid);
|
||||
if (!await revocation.TryConsumeAsync(validated.Jti, type, ct))
|
||||
var user = await db.LockUserAsync(validated.UserId, ct);
|
||||
if (user is null || !user.IsActive || !await revocation.TryConsumeAsync(validated.Jti, type, ct))
|
||||
throw new BadRequestException(invalid);
|
||||
|
||||
return await db.Users.SingleOrDefaultAsync(u => u.Id == validated.UserId && u.IsActive, ct)
|
||||
?? throw new BadRequestException(invalid);
|
||||
return user;
|
||||
}
|
||||
}
|
||||
@@ -31,35 +31,41 @@ public sealed class TokenRevocationService(IAppDbContext db, IRevokedTokenStore
|
||||
.ExecuteUpdateAsync(s => s
|
||||
.SetProperty(t => t.RevokedAt, now)
|
||||
.SetProperty(t => t.RevokeReason, reason), ct);
|
||||
await AddRevokedAccessTokensToStoreAsync(userId, now, ct);
|
||||
Publish(await LoadRevokedAccessTokensAsync([userId], now, ct));
|
||||
}
|
||||
|
||||
/// <summary>Zneplatní všechny platné tokeny uživatele – jeden UPDATE (kap. 10.1).</summary>
|
||||
public async Task RevokeAllAsync(int userId, RevokeReason reason, CancellationToken ct)
|
||||
public async Task RevokeAllAsync(int userId, RevokeReason reason, CancellationToken ct) =>
|
||||
Publish(await StageRevokeAllAsync([userId], reason, ct));
|
||||
|
||||
internal async Task<List<RevokedAccessToken>> StageRevokeAllAsync(int[] userIds, RevokeReason reason, CancellationToken ct)
|
||||
{
|
||||
var now = Now();
|
||||
await db.AuthTokens
|
||||
.Where(t => t.UserId == userId && t.RevokedAt == null)
|
||||
.Where(t => userIds.Contains(t.UserId) && t.RevokedAt == null)
|
||||
.ExecuteUpdateAsync(s => s
|
||||
.SetProperty(t => t.RevokedAt, now)
|
||||
.SetProperty(t => t.RevokeReason, reason), ct);
|
||||
await AddRevokedAccessTokensToStoreAsync(userId, now, ct);
|
||||
return await LoadRevokedAccessTokensAsync(userIds, now, ct);
|
||||
}
|
||||
|
||||
// Access tokeny se ověřují proti paměťové evidenci, aby API nemuselo při každém
|
||||
// požadavku dotazovat DB. Zneplatněné řádky poznáme podle právě zapsaného revoked_at.
|
||||
private async Task AddRevokedAccessTokensToStoreAsync(int userId, DateTime revokedAt, CancellationToken ct)
|
||||
{
|
||||
var revoked = await db.AuthTokens
|
||||
private Task<List<RevokedAccessToken>> LoadRevokedAccessTokensAsync(int[] userIds, DateTime revokedAt, CancellationToken ct) =>
|
||||
db.AuthTokens
|
||||
.AsNoTracking()
|
||||
.Where(t => t.UserId == userId && t.TokenType == TokenType.Access && t.RevokedAt == revokedAt)
|
||||
.Select(t => new { t.Jti, t.ExpiresAt })
|
||||
.Where(t => userIds.Contains(t.UserId) && t.TokenType == TokenType.Access && t.RevokedAt == revokedAt)
|
||||
.Select(t => new RevokedAccessToken(t.Jti, t.ExpiresAt))
|
||||
.ToListAsync(ct);
|
||||
|
||||
internal void Publish(IEnumerable<RevokedAccessToken> revoked)
|
||||
{
|
||||
foreach (var token in revoked)
|
||||
store.Add(token.Jti, token.ExpiresAt);
|
||||
}
|
||||
|
||||
internal sealed record RevokedAccessToken(string Jti, DateTime ExpiresAt);
|
||||
|
||||
// DATETIME(6) má přesnost na mikrosekundy – zaokrouhlením zajistíme, že hodnota
|
||||
// zapsaná do DB je stejná jako ta, podle které pak hledáme.
|
||||
private DateTime Now()
|
||||
|
||||
@@ -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<SaveBuildingRequest>
|
||||
{
|
||||
public SaveBuildingRequestValidator()
|
||||
@@ -22,8 +24,18 @@ public sealed class SaveBuildingRequestValidator : AbstractValidator<SaveBuildin
|
||||
}
|
||||
}
|
||||
|
||||
public sealed class SaveCategoryRequestValidator : AbstractValidator<SaveCategoryRequest>
|
||||
{
|
||||
public SaveCategoryRequestValidator()
|
||||
{
|
||||
RuleFor(x => x.Name).NotEmpty().MaximumLength(100);
|
||||
RuleFor(x => x.Description).MaximumLength(500);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Číselníky pro formuláře a jejich správa administrátorem. Mazání = deaktivace.</summary>
|
||||
public sealed class CatalogService(IAppDbContext db, IValidator<SaveBuildingRequest> buildingValidator)
|
||||
public sealed class CatalogService(
|
||||
IAppDbContext db, IValidator<SaveBuildingRequest> buildingValidator, IValidator<SaveCategoryRequest> categoryValidator)
|
||||
{
|
||||
public async Task<IReadOnlyList<BuildingDto>> GetBuildingsAsync(bool includeInactive, CancellationToken ct) =>
|
||||
await db.Buildings.AsNoTracking()
|
||||
@@ -32,16 +44,16 @@ public sealed class CatalogService(IAppDbContext db, IValidator<SaveBuildingRequ
|
||||
.Select(b => new BuildingDto(b.Id, b.Code, b.Name, b.Address, b.IsActive))
|
||||
.ToListAsync(ct);
|
||||
|
||||
public async Task<IReadOnlyList<CategoryDto>> GetIssueCategoriesAsync(CancellationToken ct) =>
|
||||
public async Task<IReadOnlyList<CategoryDto>> 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<IReadOnlyList<CategoryDto>> GetProposalCategoriesAsync(CancellationToken ct) =>
|
||||
public async Task<IReadOnlyList<CategoryDto>> 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<SaveBuildingRequ
|
||||
await db.SaveChangesAsync(ct);
|
||||
}
|
||||
|
||||
public async Task<CategoryDto> 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<CategoryDto> 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<CategoryDto> 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<CategoryDto> 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<Building> GetBuildingAsync(int id, CancellationToken ct) =>
|
||||
await db.Buildings.SingleOrDefaultAsync(b => b.Id == id, ct)
|
||||
?? throw new NotFoundException($"Budova {id} neexistuje.");
|
||||
|
||||
private async Task<IssueCategory> 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<ProposalCategory> 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<SaveBuildingRequ
|
||||
}
|
||||
|
||||
private static BuildingDto ToDto(Building b) => 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);
|
||||
}
|
||||
@@ -31,4 +31,12 @@ public sealed class BadRequestException(string message) : AppException(message)
|
||||
public override int StatusCode => 400;
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
public sealed record PagedResult<T>(IReadOnlyList<T> Items, int TotalCount, int Page, int PageSize);
|
||||
@@ -1,6 +1,10 @@
|
||||
using FluentValidation;
|
||||
using Helpdesk.Application.Auth;
|
||||
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;
|
||||
@@ -18,6 +22,13 @@ public static class DependencyInjection
|
||||
services.AddScoped<AuthService>();
|
||||
services.AddScoped<UserService>();
|
||||
services.AddScoped<CatalogService>();
|
||||
services.AddScoped<IssueService>();
|
||||
services.AddScoped<NotificationService>();
|
||||
services.AddScoped<NotificationDeliveryService>();
|
||||
services.AddScoped<NotificationWriter>();
|
||||
services.AddScoped<PushDeviceService>();
|
||||
services.AddScoped<ProposalService>();
|
||||
services.AddScoped<StatisticsService>();
|
||||
return services;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
using Helpdesk.Domain;
|
||||
using Helpdesk.Domain.Issues;
|
||||
|
||||
namespace Helpdesk.Application.Issues;
|
||||
|
||||
public record CreateIssueRequest(
|
||||
[Required, StringLength(200)] string Title,
|
||||
[Required] string Description,
|
||||
[Range(1, int.MaxValue)] int CategoryId,
|
||||
[Range(1, int.MaxValue)] int? BuildingId,
|
||||
[StringLength(255)] string? LocationDetail);
|
||||
|
||||
public sealed record EditIssueRequest(
|
||||
string Title, string Description, int CategoryId, int? BuildingId, string? LocationDetail,
|
||||
[Required, Range(0, int.MaxValue)] int? RowVersion)
|
||||
: CreateIssueRequest(Title, Description, CategoryId, BuildingId, LocationDetail);
|
||||
|
||||
public sealed record AssignIssueRequest(
|
||||
int AssigneeId, string? Priority, [Required, Range(0, int.MaxValue)] int? RowVersion);
|
||||
|
||||
public record IssueVersionRequest([Required, Range(0, int.MaxValue)] int? RowVersion);
|
||||
public sealed record VerifyIssueRequest(int? RowVersion, string? Note) : IssueVersionRequest(RowVersion);
|
||||
public sealed record IssueReasonRequest(int? RowVersion, string Reason) : IssueVersionRequest(RowVersion);
|
||||
public sealed record CommentRequest(string Text);
|
||||
|
||||
public sealed class IssueQuery
|
||||
{
|
||||
public string? Status { get; init; }
|
||||
public int? CategoryId { get; init; }
|
||||
public int? BuildingId { get; init; }
|
||||
public int? AssigneeId { get; init; }
|
||||
public int? ReporterId { get; init; }
|
||||
public DateTimeOffset? From { get; init; }
|
||||
public DateTimeOffset? To { get; init; }
|
||||
public string? Q { get; init; }
|
||||
public bool Mine { get; init; }
|
||||
public string? Sort { get; init; }
|
||||
public int Page { get; init; } = 1;
|
||||
public int PageSize { get; init; } = 20;
|
||||
}
|
||||
|
||||
public sealed record IssueSummary(
|
||||
int Id, string Title, int CategoryId, int? BuildingId, string? LocationDetail, string Status,
|
||||
string Priority, int ReporterId, int? AssigneeId, DateTime CreatedAt)
|
||||
{
|
||||
internal static IssueSummary From(Issue issue) => new(
|
||||
issue.Id, issue.Title, issue.CategoryId, issue.BuildingId, issue.LocationDetail, issue.Status.ToCode(),
|
||||
issue.Priority.ToCode(), issue.ReporterId, issue.AssigneeId, issue.CreatedAt);
|
||||
}
|
||||
|
||||
public sealed record IssueDetail(
|
||||
int Id, string Title, string Description, int CategoryId, int? BuildingId, string? LocationDetail, string Status,
|
||||
string Priority, int ReporterId, int? AssigneeId, DateTime CreatedAt, int RowVersion,
|
||||
IReadOnlyList<string> AllowedActions, IReadOnlyList<AttachmentDto> Attachments);
|
||||
|
||||
public sealed record IssueEventDto(
|
||||
int Id, string EventType, string? FromStatus, string ToStatus, int ActorId, string ActorName, string? Note,
|
||||
DateTime OccurredAt);
|
||||
|
||||
public sealed record AssignableUserDto(int Id, string FirstName, string LastName, string Role, int OpenIssues);
|
||||
|
||||
public sealed record AttachmentDto(int Id, string FileName, string ContentType, long SizeBytes, DateTime CreatedAt)
|
||||
{
|
||||
internal static AttachmentDto From(Attachment attachment) => new(
|
||||
attachment.Id, attachment.OriginalFileName, attachment.ContentType, attachment.SizeBytes, attachment.CreatedAt);
|
||||
}
|
||||
|
||||
public sealed record AttachmentUpload(string FileName, long SizeBytes, Func<Stream> OpenRead);
|
||||
public sealed record StoredAttachment(string OriginalFileName, string StoredFileName, string ContentType, long SizeBytes);
|
||||
public sealed record AttachmentDownload(Stream Content, string FileName, string ContentType);
|
||||
|
||||
public interface IAttachmentStore
|
||||
{
|
||||
Task<StoredAttachment> SaveAsync(AttachmentUpload upload, CancellationToken ct);
|
||||
Stream OpenRead(string storedFileName);
|
||||
void Delete(string storedFileName);
|
||||
}
|
||||
|
||||
public static class AttachmentLimits
|
||||
{
|
||||
public const int MaxFiles = 5;
|
||||
public const int MaxFileBytes = 10 * 1024 * 1024;
|
||||
public const int MaxRequestBytes = MaxFiles * MaxFileBytes + 1024 * 1024;
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
using Helpdesk.Application.Common;
|
||||
using Helpdesk.Domain;
|
||||
using Helpdesk.Domain.Issues;
|
||||
using Helpdesk.Domain.Users;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace Helpdesk.Application.Issues;
|
||||
|
||||
public sealed partial class IssueService
|
||||
{
|
||||
public async Task<PagedResult<IssueSummary>> ListAsync(IssueQuery filters, CancellationToken ct)
|
||||
{
|
||||
var actor = await GetActorAsync(ct);
|
||||
var issues = db.Issues.AsNoTracking();
|
||||
if (filters.Mine || !Issue.CanReadAll(actor.Role))
|
||||
issues = issues.Where(i => i.ReporterId == actor.Id);
|
||||
|
||||
if (filters.Status is { } statusCode)
|
||||
{
|
||||
var status = ParseCode<IssueStatus>(statusCode);
|
||||
issues = issues.Where(i => i.Status == status);
|
||||
}
|
||||
if (filters.CategoryId is int categoryId)
|
||||
issues = issues.Where(i => i.CategoryId == categoryId);
|
||||
if (filters.BuildingId is int buildingId)
|
||||
issues = issues.Where(i => i.BuildingId == buildingId);
|
||||
if (filters.AssigneeId is int assigneeId)
|
||||
issues = issues.Where(i => i.AssigneeId == assigneeId);
|
||||
if (filters.ReporterId is int reporterId)
|
||||
issues = issues.Where(i => i.ReporterId == reporterId);
|
||||
if (filters.From >= filters.To)
|
||||
throw new BadRequestException("Začátek období musí předcházet jeho konci.");
|
||||
if (filters.From?.UtcDateTime is DateTime from)
|
||||
issues = issues.Where(i => i.CreatedAt >= from);
|
||||
if (filters.To?.UtcDateTime is DateTime to)
|
||||
issues = issues.Where(i => i.CreatedAt < to);
|
||||
if (!string.IsNullOrWhiteSpace(filters.Q))
|
||||
{
|
||||
var term = filters.Q.Trim();
|
||||
issues = issues.Where(i => i.Title.Contains(term) || i.Description.Contains(term));
|
||||
}
|
||||
|
||||
var ordered = filters.Sort switch
|
||||
{
|
||||
null or "newest" => issues.OrderByDescending(i => i.CreatedAt).ThenByDescending(i => i.Id),
|
||||
"oldest" => issues.OrderBy(i => i.CreatedAt).ThenBy(i => i.Id),
|
||||
_ => throw new BadRequestException("Řazení musí být newest nebo oldest."),
|
||||
};
|
||||
var page = Math.Max(1, filters.Page);
|
||||
var pageSize = Math.Clamp(filters.PageSize, 1, 100);
|
||||
var total = await issues.CountAsync(ct);
|
||||
var offset = (long)(page - 1) * pageSize;
|
||||
if (offset >= total)
|
||||
return new PagedResult<IssueSummary>([], total, page, pageSize);
|
||||
|
||||
var pageItems = await ordered.Skip((int)offset).Take(pageSize).ToListAsync(ct);
|
||||
return new PagedResult<IssueSummary>(pageItems.Select(IssueSummary.From).ToArray(), total, page, pageSize);
|
||||
}
|
||||
|
||||
public async Task<IssueDetail> GetAsync(int id, CancellationToken ct)
|
||||
{
|
||||
var actor = await GetActorAsync(ct);
|
||||
var issue = await LoadIssueAsync(id, actor, tracking: false, ct);
|
||||
return await LoadDetailAsync(issue, actor, ct);
|
||||
}
|
||||
|
||||
public async Task<IReadOnlyList<IssueEventDto>> GetEventsAsync(int id, CancellationToken ct)
|
||||
{
|
||||
var actor = await GetActorAsync(ct);
|
||||
await LoadIssueAsync(id, actor, tracking: false, ct);
|
||||
var entries = await (
|
||||
from entry in db.IssueEvents.AsNoTracking()
|
||||
join user in db.Users on entry.ActorId equals user.Id
|
||||
where entry.IssueId == id
|
||||
orderby entry.OccurredAt, entry.Id
|
||||
select new { Entry = entry, user.FirstName, user.LastName }).ToListAsync(ct);
|
||||
return entries.Select(entry => ToEvent(entry.Entry, $"{entry.FirstName} {entry.LastName}")).ToArray();
|
||||
}
|
||||
|
||||
public async Task<IReadOnlyList<AssignableUserDto>> GetAssignableAsync(CancellationToken ct)
|
||||
{
|
||||
var actor = await GetActorAsync(ct);
|
||||
if (!Issue.CanAssign(actor.Role))
|
||||
throw new ForbiddenException("Přehled řešitelů je určen vedení a administrátorům.");
|
||||
|
||||
var users = await db.Users.Where(u => u.IsActive &&
|
||||
(u.Role == UserRole.Management || u.Role == UserRole.FacilityManager || u.Role == UserRole.Admin))
|
||||
.OrderBy(u => u.LastName).ThenBy(u => u.FirstName).ThenBy(u => u.Id)
|
||||
.Select(u => new
|
||||
{
|
||||
u.Id, u.FirstName, u.LastName, u.Role,
|
||||
OpenIssues = db.Issues.Count(i => i.AssigneeId == u.Id &&
|
||||
(i.Status == IssueStatus.Assigned || i.Status == IssueStatus.InProgress || i.Status == IssueStatus.PendingVerification)),
|
||||
}).ToListAsync(ct);
|
||||
return users.Select(u => new AssignableUserDto(u.Id, u.FirstName, u.LastName, u.Role.ToCode(), u.OpenIssues)).ToArray();
|
||||
}
|
||||
|
||||
public async Task<AttachmentDownload> DownloadAsync(int id, CancellationToken ct)
|
||||
{
|
||||
var actor = await GetActorAsync(ct);
|
||||
var attachment = await db.Attachments.AsNoTracking().Include(a => a.Issue).SingleOrDefaultAsync(a => a.Id == id, ct)
|
||||
?? throw new NotFoundException("Příloha neexistuje.");
|
||||
if (!attachment.Issue.CanRead(actor.Id, actor.Role))
|
||||
throw new ForbiddenException("K příloze nemáte přístup.");
|
||||
return new AttachmentDownload(files.OpenRead(attachment.StoredFileName), attachment.OriginalFileName, attachment.ContentType);
|
||||
}
|
||||
|
||||
private async Task<IssueDetail> LoadDetailAsync(Issue issue, User actor, CancellationToken ct)
|
||||
{
|
||||
var attachments = await db.Attachments.AsNoTracking().Where(a => a.IssueId == issue.Id).OrderBy(a => a.Id)
|
||||
.Select(a => new AttachmentDto(a.Id, a.OriginalFileName, a.ContentType, a.SizeBytes, a.CreatedAt)).ToListAsync(ct);
|
||||
return ToDetail(issue, actor, attachments);
|
||||
}
|
||||
|
||||
private static IssueDetail ToDetail(Issue issue, User actor, IReadOnlyList<AttachmentDto> attachments)
|
||||
{
|
||||
var actions = Enum.GetValues<IssueAction>()
|
||||
.Where(action => issue.Availability(action, actor.Id, actor.Role) == IssueActionAvailability.Allowed)
|
||||
.Select(action => action.ToCode()).ToArray();
|
||||
|
||||
return new IssueDetail(issue.Id, issue.Title, issue.Description, issue.CategoryId, issue.BuildingId, issue.LocationDetail,
|
||||
issue.Status.ToCode(), issue.Priority.ToCode(), issue.ReporterId, issue.AssigneeId, issue.CreatedAt,
|
||||
issue.RowVersion, actions, attachments);
|
||||
}
|
||||
|
||||
private static IssueEventDto ToEvent(IssueEvent entry, string actorName) =>
|
||||
new(entry.Id, entry.EventType.ToCode(), entry.FromStatus?.ToCode(), entry.ToStatus.ToCode(),
|
||||
entry.ActorId, actorName, entry.Note, entry.OccurredAt);
|
||||
}
|
||||
@@ -0,0 +1,235 @@
|
||||
using System.Text;
|
||||
using Helpdesk.Application.Abstractions;
|
||||
using Helpdesk.Application.Common;
|
||||
using Helpdesk.Application.Notifications;
|
||||
using Helpdesk.Domain;
|
||||
using Helpdesk.Domain.Issues;
|
||||
using Helpdesk.Domain.Notifications;
|
||||
using Helpdesk.Domain.Users;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace Helpdesk.Application.Issues;
|
||||
|
||||
public sealed partial class IssueService(
|
||||
IAppDbContext db, ICurrentUser currentUser, IAttachmentStore files, TimeProvider clock, NotificationWriter notificationWriter)
|
||||
{
|
||||
public async Task<IssueDetail> CreateAsync(CreateIssueRequest request, IReadOnlyList<AttachmentUpload> uploads, CancellationToken ct)
|
||||
{
|
||||
var actor = await GetActorAsync(ct);
|
||||
await ValidateDetailsAsync(request, null, ct);
|
||||
var issue = new Issue(actor.Id, request.Title, request.Description, request.CategoryId, request.BuildingId, request.LocationDetail);
|
||||
db.Issues.Add(issue);
|
||||
AddEvent(issue, IssueEventType.Created, null, actor, null);
|
||||
var managementIds = await db.Users.Where(u => u.IsActive && u.Role == UserRole.Management)
|
||||
.Select(u => u.Id).ToArrayAsync(ct);
|
||||
await notificationWriter.ForIssueAsync(issue, actor.Id, managementIds, NotificationType.IssueCreated, "Nové hlášení závady", ct);
|
||||
var attachments = await SaveWithAttachmentsAsync(issue, uploads, ct);
|
||||
return ToDetail(issue, actor, attachments.Select(AttachmentDto.From).ToArray());
|
||||
}
|
||||
|
||||
public async Task<IssueDetail> EditAsync(int id, EditIssueRequest request, CancellationToken ct)
|
||||
{
|
||||
var (issue, actor) = await LoadActionAsync(id, IssueAction.Edit, ct);
|
||||
CheckVersion(issue, request.RowVersion);
|
||||
await ValidateDetailsAsync(request, issue, ct);
|
||||
issue.Edit(actor.Id, actor.Role, request.Title, request.Description, request.CategoryId, request.BuildingId, request.LocationDetail);
|
||||
AddEvent(issue, IssueEventType.Updated, null, actor, null);
|
||||
await SaveAsync(ct);
|
||||
return await LoadDetailAsync(issue, actor, ct);
|
||||
}
|
||||
|
||||
public async Task<IssueDetail> AssignAsync(int id, AssignIssueRequest request, CancellationToken ct)
|
||||
{
|
||||
var (issue, actor) = await LoadActionAsync(id, IssueAction.Assign, ct);
|
||||
CheckVersion(issue, request.RowVersion);
|
||||
var assignee = await db.Users.AsNoTracking().SingleOrDefaultAsync(u => u.Id == request.AssigneeId && u.IsActive, ct);
|
||||
if (assignee is null || !Issue.CanBeAssigned(assignee.Role))
|
||||
throw new BadRequestException("Vyberte aktivního správce budov, člena vedení nebo administrátora.");
|
||||
if (issue.AssigneeId == assignee.Id)
|
||||
throw new ConflictException("Závada je již přiřazena tomuto řešiteli.");
|
||||
|
||||
IssuePriority? priority = request.Priority is null ? null : ParseCode<IssuePriority>(request.Priority);
|
||||
var from = issue.Status;
|
||||
issue.Assign(actor.Id, actor.Role, assignee.Id, assignee.Role, priority);
|
||||
AddEvent(issue, IssueEventType.Assigned, from, actor, assignee.FullName);
|
||||
await notificationWriter.ForIssueAsync(issue, actor.Id, [assignee.Id], NotificationType.IssueAssigned, "Závada byla přiřazena", ct);
|
||||
if (from != issue.Status && issue.ReporterId != assignee.Id)
|
||||
await notificationWriter.ForIssueAsync(issue, actor.Id, [issue.ReporterId], NotificationType.IssueStatusChanged, "Závada byla přiřazena", ct);
|
||||
|
||||
await SaveAsync(ct);
|
||||
return await LoadDetailAsync(issue, actor, ct);
|
||||
}
|
||||
|
||||
public async Task<IssueDetail> TransitionAsync(int id, IssueAction action, int? version, string? note, CancellationToken ct)
|
||||
{
|
||||
var (issue, actor) = await LoadActionAsync(id, action, ct);
|
||||
CheckVersion(issue, version);
|
||||
note = action is IssueAction.Reopen or IssueAction.Reject
|
||||
? RequiredText(note, "Důvod", MaxTextBytes)
|
||||
: OptionalText(note, "Poznámka", MaxTextBytes);
|
||||
|
||||
var from = issue.Status;
|
||||
issue.Transition(action, actor.Id, actor.Role, note);
|
||||
AddEvent(issue, IssueEventType.StatusChanged, from, actor, note);
|
||||
int? recipient = action is IssueAction.Confirm or IssueAction.Reopen ? issue.AssigneeId : issue.ReporterId;
|
||||
if (recipient is int recipientId)
|
||||
{
|
||||
var (type, title) = action == IssueAction.Reopen
|
||||
? (NotificationType.IssueReopened, "Závada byla znovu otevřena")
|
||||
: (NotificationType.IssueStatusChanged, "Stav závady se změnil");
|
||||
await notificationWriter.ForIssueAsync(issue, actor.Id, [recipientId], type, title, ct);
|
||||
}
|
||||
|
||||
await SaveAsync(ct);
|
||||
return await LoadDetailAsync(issue, actor, ct);
|
||||
}
|
||||
|
||||
public async Task<IssueEventDto> CommentAsync(int id, CommentRequest request, CancellationToken ct)
|
||||
{
|
||||
var (issue, actor) = await LoadActionAsync(id, IssueAction.Comment, ct);
|
||||
var text = RequiredText(request.Text, "Komentář", MaxTextBytes);
|
||||
issue.RecordParticipation(IssueAction.Comment, actor.Id, actor.Role);
|
||||
var entry = AddEvent(issue, IssueEventType.Commented, null, actor, text);
|
||||
int[] recipients = issue.AssigneeId is int assignee ? [issue.ReporterId, assignee] : [issue.ReporterId];
|
||||
await notificationWriter.ForIssueAsync(issue, actor.Id, recipients, NotificationType.IssueCommentAdded, "Nový komentář k závadě", ct);
|
||||
await SaveAsync(ct);
|
||||
return ToEvent(entry, actor.FullName);
|
||||
}
|
||||
|
||||
public async Task<IReadOnlyList<AttachmentDto>> AddAttachmentsAsync(
|
||||
int id, Func<CancellationToken, Task<AttachmentUpload[]>> readUploads, CancellationToken ct)
|
||||
{
|
||||
var (issue, actor) = await LoadActionAsync(id, IssueAction.AddAttachments, ct);
|
||||
var uploads = await readUploads(ct);
|
||||
if (uploads.Length == 0)
|
||||
throw new BadRequestException("Vyberte alespoň jeden soubor.");
|
||||
|
||||
issue.RecordParticipation(IssueAction.AddAttachments, actor.Id, actor.Role);
|
||||
var attachments = await SaveWithAttachmentsAsync(issue, uploads, ct);
|
||||
return attachments.Select(AttachmentDto.From).ToArray();
|
||||
}
|
||||
|
||||
private async Task<IReadOnlyList<Attachment>> SaveWithAttachmentsAsync(
|
||||
Issue issue, IReadOnlyList<AttachmentUpload> uploads, CancellationToken ct)
|
||||
{
|
||||
if (uploads.Count > AttachmentLimits.MaxFiles)
|
||||
throw new BadRequestException("Najednou lze přiložit nejvýše pět souborů.");
|
||||
|
||||
var attachments = new List<Attachment>(uploads.Count);
|
||||
var saving = false;
|
||||
try
|
||||
{
|
||||
foreach (var upload in uploads)
|
||||
{
|
||||
var stored = await files.SaveAsync(upload, ct);
|
||||
var attachment = new Attachment(issue, stored.OriginalFileName, stored.StoredFileName,
|
||||
stored.ContentType, stored.SizeBytes);
|
||||
attachments.Add(attachment);
|
||||
db.Attachments.Add(attachment);
|
||||
}
|
||||
|
||||
ct.ThrowIfCancellationRequested();
|
||||
saving = true;
|
||||
await SaveAsync(ct);
|
||||
return attachments;
|
||||
}
|
||||
catch (Exception exception) when (!saving || exception is ConflictException)
|
||||
{
|
||||
// Po chybě s neznámým výsledkem commitu soubory ponecháme, aby metadata nemohla odkazovat na smazaná data.
|
||||
foreach (var attachment in attachments)
|
||||
files.Delete(attachment.StoredFileName);
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
private async Task<User> GetActorAsync(CancellationToken ct) =>
|
||||
await db.Users.AsNoTracking().SingleOrDefaultAsync(u => u.Id == currentUser.Id && u.IsActive, ct)
|
||||
?? throw new UnauthorizedException("Účet není aktivní.");
|
||||
|
||||
private async Task<Issue> LoadIssueAsync(int id, User actor, bool tracking, CancellationToken ct)
|
||||
{
|
||||
var query = tracking ? db.Issues : db.Issues.AsNoTracking();
|
||||
var issue = await query.SingleOrDefaultAsync(i => i.Id == id, ct)
|
||||
?? throw new NotFoundException("Závada neexistuje.");
|
||||
if (!issue.CanRead(actor.Id, actor.Role))
|
||||
throw new ForbiddenException("K závadě nemáte přístup.");
|
||||
return issue;
|
||||
}
|
||||
|
||||
private async Task<(Issue Issue, User Actor)> LoadActionAsync(int id, IssueAction action, CancellationToken ct)
|
||||
{
|
||||
var actor = await GetActorAsync(ct);
|
||||
var issue = await LoadIssueAsync(id, actor, tracking: true, ct);
|
||||
switch (issue.Availability(action, actor.Id, actor.Role))
|
||||
{
|
||||
case IssueActionAvailability.Forbidden:
|
||||
throw new ForbiddenException("Tuto akci nemůžete provést.");
|
||||
case IssueActionAvailability.InvalidState:
|
||||
throw new ConflictException("Akce není v aktuálním stavu závady možná.");
|
||||
}
|
||||
return (issue, actor);
|
||||
}
|
||||
|
||||
private async Task ValidateDetailsAsync(CreateIssueRequest request, Issue? original, CancellationToken ct)
|
||||
{
|
||||
var title = RequiredText(request.Title, "Název", MaxTextBytes);
|
||||
RequiredText(request.Description, "Popis", MaxTextBytes);
|
||||
if (title.Length > 200 || request.LocationDetail?.Trim().Length > 255)
|
||||
throw new BadRequestException("Název smí mít nejvýše 200 znaků a upřesnění místa 255 znaků.");
|
||||
|
||||
if (original?.CategoryId != request.CategoryId &&
|
||||
!await db.IssueCategories.AnyAsync(c => c.Id == request.CategoryId && c.IsActive, ct))
|
||||
throw new BadRequestException("Vyberte aktivní kategorii závady.");
|
||||
|
||||
if (request.BuildingId is int buildingId && original?.BuildingId != buildingId &&
|
||||
!await db.Buildings.AnyAsync(b => b.Id == buildingId && b.IsActive, ct))
|
||||
throw new BadRequestException("Vyberte aktivní budovu.");
|
||||
}
|
||||
|
||||
private IssueEvent AddEvent(Issue issue, IssueEventType type, IssueStatus? fromStatus, User actor, string? note)
|
||||
{
|
||||
var entry = new IssueEvent(issue, type, fromStatus, actor.Id, note, clock.GetUtcNow().UtcDateTime);
|
||||
db.IssueEvents.Add(entry);
|
||||
return entry;
|
||||
}
|
||||
|
||||
private async Task SaveAsync(CancellationToken ct)
|
||||
{
|
||||
try
|
||||
{
|
||||
await db.SaveChangesAsync(ct);
|
||||
}
|
||||
catch (DbUpdateConcurrencyException)
|
||||
{
|
||||
throw new ConflictException("Závada se mezitím změnila. Načtěte aktuální stav.");
|
||||
}
|
||||
}
|
||||
|
||||
private static void CheckVersion(Issue issue, int? supplied)
|
||||
{
|
||||
if (supplied is null or < 0)
|
||||
throw new BadRequestException("Zadejte platnou hodnotu rowVersion.");
|
||||
if (issue.RowVersion != supplied)
|
||||
throw new ConflictException("Závada se mezitím změnila. Načtěte aktuální stav.");
|
||||
}
|
||||
|
||||
private const int MaxTextBytes = 65_535;
|
||||
|
||||
private static string RequiredText(string? input, string name, int maxBytes) =>
|
||||
OptionalText(input, name, maxBytes) ?? throw new BadRequestException($"{name}: hodnota je povinná.");
|
||||
|
||||
private static string? OptionalText(string? input, string name, int maxBytes)
|
||||
{
|
||||
var text = input?.Trim();
|
||||
if (string.IsNullOrEmpty(text))
|
||||
return null;
|
||||
if (Encoding.UTF8.GetByteCount(text) > maxBytes)
|
||||
throw new BadRequestException($"{name}: hodnota je příliš dlouhá.");
|
||||
return text;
|
||||
}
|
||||
|
||||
private static T ParseCode<T>(string code) where T : struct, Enum =>
|
||||
EnumCode.TryParse<T>(code, out var result)
|
||||
? result
|
||||
: throw new BadRequestException($"Neplatný kód '{code}'.");
|
||||
}
|
||||
@@ -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<PagedResult<NotificationDeliveryDto>> ListAsync(string status, int page, int pageSize, CancellationToken ct)
|
||||
{
|
||||
if (!EnumCode.TryParse<DeliveryStatus>(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<NotificationDeliveryDto>([], 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<NotificationDeliveryDto>(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í.");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
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 NotificationDto(
|
||||
int Id, string Type, string Title, string Message, int? IssueId, int? ProposalId, DateTime CreatedAt, DateTime? ReadAt);
|
||||
|
||||
public sealed record UnreadCountDto(int Count);
|
||||
|
||||
public sealed class NotificationService(IAppDbContext db, ICurrentUser currentUser, TimeProvider clock)
|
||||
{
|
||||
public async Task<PagedResult<NotificationDto>> ListAsync(bool unreadOnly, int page, int pageSize, CancellationToken ct)
|
||||
{
|
||||
page = Math.Max(1, page);
|
||||
pageSize = Math.Clamp(pageSize, 1, 100);
|
||||
|
||||
var query = Inbox().AsNoTracking();
|
||||
if (unreadOnly)
|
||||
query = query.Where(n => n.ReadAt == null);
|
||||
|
||||
var total = await query.CountAsync(ct);
|
||||
var offset = (long)(page - 1) * pageSize;
|
||||
if (offset >= total)
|
||||
return new PagedResult<NotificationDto>([], total, page, pageSize);
|
||||
|
||||
var rows = await query.OrderByDescending(n => n.CreatedAt).ThenByDescending(n => n.Id)
|
||||
.Skip((int)offset).Take(pageSize).ToListAsync(ct);
|
||||
var items = rows.Select(n => new NotificationDto(
|
||||
n.Id, n.Type.ToCode(), n.Title, n.Message, n.IssueId, n.ProposalId, n.CreatedAt, n.ReadAt)).ToArray();
|
||||
return new PagedResult<NotificationDto>(items, total, page, pageSize);
|
||||
}
|
||||
|
||||
public async Task<UnreadCountDto> CountUnreadAsync(CancellationToken ct) =>
|
||||
new(await Inbox().CountAsync(n => n.ReadAt == null, ct));
|
||||
|
||||
public async Task MarkReadAsync(int id, CancellationToken ct)
|
||||
{
|
||||
var match = Inbox().Where(n => n.Id == id);
|
||||
if (await MarkUnreadRowsAsync(match, ct) == 0 && !await match.AnyAsync(ct))
|
||||
throw new NotFoundException("Notifikace neexistuje.");
|
||||
}
|
||||
|
||||
public async Task MarkAllReadAsync(CancellationToken ct) => await MarkUnreadRowsAsync(Inbox(), ct);
|
||||
|
||||
private IQueryable<Notification> Inbox()
|
||||
{
|
||||
var userId = currentUser.Id;
|
||||
return db.Notifications.Where(n => n.UserId == userId);
|
||||
}
|
||||
|
||||
private Task<int> MarkUnreadRowsAsync(IQueryable<Notification> query, CancellationToken ct)
|
||||
{
|
||||
var now = clock.GetUtcNow().UtcDateTime;
|
||||
return query.Where(n => n.ReadAt == null)
|
||||
.ExecuteUpdateAsync(update => update.SetProperty(n => n.ReadAt, now), ct);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
using Helpdesk.Application.Abstractions;
|
||||
using Helpdesk.Domain.Issues;
|
||||
using Helpdesk.Domain.Notifications;
|
||||
using Helpdesk.Domain.Proposals;
|
||||
using Helpdesk.Domain.Users;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace Helpdesk.Application.Notifications;
|
||||
|
||||
/// <summary>Připraví notifikace a záznamy outboxu pro uložení spolu s událostí.</summary>
|
||||
public sealed class NotificationWriter(IAppDbContext db, TimeProvider clock)
|
||||
{
|
||||
public Task ForIssueAsync(Issue issue, int actorId, int[] recipientIds, NotificationType type, string title,
|
||||
CancellationToken ct)
|
||||
{
|
||||
var reporterId = issue.ReporterId;
|
||||
var eligibleUsers = db.Users.Where(u =>
|
||||
u.Id == reporterId || u.Role == UserRole.FacilityManager || u.Role == UserRole.Management ||
|
||||
u.Role == UserRole.Admin);
|
||||
return QueueAsync(eligibleUsers, actorId, recipientIds,
|
||||
id => new Notification(issue, id, type, title, issue.Title), ct);
|
||||
}
|
||||
|
||||
public Task ForProposalStatusAsync(Proposal proposal, int actorId, CancellationToken ct) =>
|
||||
QueueAsync(db.Users, actorId, [proposal.AuthorId],
|
||||
id => new Notification(proposal, id, "Stav návrhu se změnil"), ct);
|
||||
|
||||
private async Task QueueAsync(IQueryable<User> eligibleUsers, int actorId, int[] recipientIds,
|
||||
Func<int, Notification> create, CancellationToken ct)
|
||||
{
|
||||
var ids = recipientIds.Where(id => id != actorId).Distinct().ToArray();
|
||||
if (ids.Length == 0)
|
||||
return;
|
||||
|
||||
var recipients = await eligibleUsers.Where(u => u.IsActive && ids.Contains(u.Id))
|
||||
.Select(u => new
|
||||
{
|
||||
u.Id,
|
||||
Email = u.EmailNotificationsEnabled && u.EmailConfirmed,
|
||||
Push = db.PushDevices.Any(device => device.UserId == u.Id),
|
||||
}).ToListAsync(ct);
|
||||
|
||||
var now = clock.GetUtcNow().UtcDateTime;
|
||||
foreach (var recipient in recipients)
|
||||
{
|
||||
var notification = create(recipient.Id);
|
||||
db.Notifications.Add(notification);
|
||||
db.NotificationDeliveries.AddRange(
|
||||
new NotificationDelivery(notification, DeliveryChannel.Email, recipient.Email, now),
|
||||
new NotificationDelivery(notification, DeliveryChannel.Push, recipient.Push, now));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
using Helpdesk.Application.Abstractions;
|
||||
using Helpdesk.Application.Common;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace Helpdesk.Application.Notifications;
|
||||
|
||||
public sealed class PushDeviceService(IAppDbContext db, ICurrentUser currentUser)
|
||||
{
|
||||
public async Task RegisterAsync(string token, CancellationToken ct)
|
||||
{
|
||||
ValidateToken(token);
|
||||
await using var transaction = await db.BeginWriteAsync(ct);
|
||||
var user = await db.LockUserAsync(currentUser.Id, ct);
|
||||
if (user is not { IsActive: true, IsDeleted: false })
|
||||
throw new UnauthorizedException("Účet není aktivní.");
|
||||
|
||||
await db.RegisterPushDeviceAsync(user.Id, token, ct);
|
||||
await transaction.CommitAsync(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í.");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
namespace Helpdesk.Application.Proposals;
|
||||
|
||||
public sealed record SaveProposalRequest(string Title, string Description, int CategoryId);
|
||||
public sealed record ChangeProposalStatusRequest(string Status, string? Note);
|
||||
public sealed record VoteRequest(int Value);
|
||||
|
||||
public sealed class ProposalQuery
|
||||
{
|
||||
public string? Status { get; init; }
|
||||
public int? CategoryId { get; init; }
|
||||
public int? AuthorId { get; init; }
|
||||
public string? Q { get; init; }
|
||||
public string? Sort { get; init; }
|
||||
public int Page { get; init; } = 1;
|
||||
public int PageSize { get; init; } = 20;
|
||||
}
|
||||
|
||||
public record ProposalSummary(
|
||||
int Id, string Title, int CategoryId, int AuthorId, string Status, DateTime CreatedAt,
|
||||
long VotesFor, long VotesAgainst, long Score, int? MyVote);
|
||||
|
||||
public sealed record ProposalDetail(
|
||||
int Id, string Title, int CategoryId, int AuthorId, string Status, DateTime CreatedAt,
|
||||
long VotesFor, long VotesAgainst, long Score, int? MyVote, string Description, IReadOnlyList<ProposalEventDto> Events)
|
||||
: ProposalSummary(Id, Title, CategoryId, AuthorId, Status, CreatedAt, VotesFor, VotesAgainst, Score, MyVote);
|
||||
|
||||
public sealed record ProposalEventDto(
|
||||
int Id, string EventType, string? FromStatus, string ToStatus, int ActorId, string ActorName, string? Note,
|
||||
DateTime OccurredAt);
|
||||
@@ -0,0 +1,111 @@
|
||||
using Helpdesk.Application.Common;
|
||||
using Helpdesk.Domain;
|
||||
using Helpdesk.Domain.Proposals;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace Helpdesk.Application.Proposals;
|
||||
|
||||
public sealed partial class ProposalService
|
||||
{
|
||||
public async Task<PagedResult<ProposalSummary>> ListAsync(
|
||||
ProposalQuery filters, DateTimeOffset? from, DateTimeOffset? to, CancellationToken ct)
|
||||
{
|
||||
await GetActorRoleAsync(ct);
|
||||
var proposals = db.Proposals.AsNoTracking();
|
||||
if (filters.Status is { } code)
|
||||
{
|
||||
var status = ParseStatus(code);
|
||||
proposals = proposals.Where(p => p.Status == status);
|
||||
}
|
||||
if (filters.CategoryId is int categoryId)
|
||||
proposals = proposals.Where(p => p.CategoryId == categoryId);
|
||||
if (filters.AuthorId is int authorId)
|
||||
proposals = proposals.Where(p => p.AuthorId == authorId);
|
||||
if (from >= to)
|
||||
throw new BadRequestException("Začátek období musí předcházet jeho konci.");
|
||||
if (from?.UtcDateTime is DateTime fromUtc)
|
||||
proposals = proposals.Where(p => p.CreatedAt >= fromUtc);
|
||||
if (to?.UtcDateTime is DateTime toUtc)
|
||||
proposals = proposals.Where(p => p.CreatedAt < toUtc);
|
||||
if (!string.IsNullOrWhiteSpace(filters.Q))
|
||||
{
|
||||
var term = filters.Q.Trim();
|
||||
proposals = proposals.Where(p => p.Title.Contains(term) || p.Description.Contains(term));
|
||||
}
|
||||
|
||||
var rows = WithScores(proposals);
|
||||
var ordered = filters.Sort switch
|
||||
{
|
||||
null or "newest" => rows.OrderByDescending(r => r.Proposal.CreatedAt).ThenByDescending(r => r.Proposal.Id),
|
||||
"score" => rows.OrderByDescending(r => r.Score).ThenByDescending(r => r.Proposal.CreatedAt)
|
||||
.ThenByDescending(r => r.Proposal.Id),
|
||||
_ => throw new BadRequestException("Řazení musí být newest nebo score."),
|
||||
};
|
||||
|
||||
var page = Math.Max(1, filters.Page);
|
||||
var pageSize = Math.Clamp(filters.PageSize, 1, 100);
|
||||
var total = await proposals.CountAsync(ct);
|
||||
var offset = (long)(page - 1) * pageSize;
|
||||
if (offset >= total)
|
||||
return new PagedResult<ProposalSummary>([], total, page, pageSize);
|
||||
|
||||
var pageRows = await ordered.Skip((int)offset).Take(pageSize).ToListAsync(ct);
|
||||
return new PagedResult<ProposalSummary>(pageRows.Select(ToSummary).ToArray(), total, page, pageSize);
|
||||
}
|
||||
|
||||
public async Task<ProposalDetail> GetAsync(int id, CancellationToken ct)
|
||||
{
|
||||
await GetActorRoleAsync(ct);
|
||||
return await LoadDetailAsync(id, ct);
|
||||
}
|
||||
|
||||
private async Task<ProposalDetail> LoadDetailAsync(int id, CancellationToken ct)
|
||||
{
|
||||
var row = await WithScores(db.Proposals.AsNoTracking().Where(p => p.Id == id)).SingleOrDefaultAsync(ct)
|
||||
?? throw new NotFoundException("Návrh neexistuje.");
|
||||
var entries = await (
|
||||
from entry in db.ProposalEvents.AsNoTracking()
|
||||
join actor in db.Users on entry.ActorId equals actor.Id
|
||||
where entry.ProposalId == id
|
||||
orderby entry.OccurredAt, entry.Id
|
||||
select new { Entry = entry, actor.FirstName, actor.LastName }).ToListAsync(ct);
|
||||
var events = entries.Select(e => new ProposalEventDto(
|
||||
e.Entry.Id, e.Entry.EventType.ToCode(), e.Entry.FromStatus?.ToCode(), e.Entry.ToStatus.ToCode(),
|
||||
e.Entry.ActorId, $"{e.FirstName} {e.LastName}", e.Entry.Note, e.Entry.OccurredAt)).ToArray();
|
||||
var summary = ToSummary(row);
|
||||
return new ProposalDetail(summary.Id, summary.Title, summary.CategoryId, summary.AuthorId, summary.Status,
|
||||
summary.CreatedAt, summary.VotesFor, summary.VotesAgainst, summary.Score, summary.MyVote, row.Proposal.Description, events);
|
||||
}
|
||||
|
||||
private IQueryable<ScoredProposal> WithScores(IQueryable<Proposal> proposals)
|
||||
{
|
||||
var actorId = currentUser.Id;
|
||||
return from proposal in proposals
|
||||
join score in db.ProposalScores on proposal.Id equals score.ProposalId
|
||||
select new ScoredProposal
|
||||
{
|
||||
Proposal = proposal,
|
||||
VotesFor = score.VotesFor,
|
||||
VotesAgainst = score.VotesAgainst,
|
||||
Score = score.Score,
|
||||
MyVote = db.ProposalVotes.Where(v => v.ProposalId == proposal.Id && v.UserId == actorId)
|
||||
.Select(v => (sbyte?)v.Value).FirstOrDefault(),
|
||||
};
|
||||
}
|
||||
|
||||
private static ProposalSummary ToSummary(ScoredProposal row)
|
||||
{
|
||||
var proposal = row.Proposal;
|
||||
return new ProposalSummary(proposal.Id, proposal.Title, proposal.CategoryId, proposal.AuthorId,
|
||||
proposal.Status.ToCode(), proposal.CreatedAt, (long)row.VotesFor, (long)row.VotesAgainst, (long)row.Score, row.MyVote);
|
||||
}
|
||||
|
||||
private sealed class ScoredProposal
|
||||
{
|
||||
public required Proposal Proposal { get; init; }
|
||||
public decimal VotesFor { get; init; }
|
||||
public decimal VotesAgainst { get; init; }
|
||||
public decimal Score { get; init; }
|
||||
public sbyte? MyVote { get; init; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,156 @@
|
||||
using System.Text;
|
||||
using Helpdesk.Application.Abstractions;
|
||||
using Helpdesk.Application.Common;
|
||||
using Helpdesk.Application.Notifications;
|
||||
using Helpdesk.Domain;
|
||||
using Helpdesk.Domain.Proposals;
|
||||
using Helpdesk.Domain.Users;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace Helpdesk.Application.Proposals;
|
||||
|
||||
public sealed partial class ProposalService(
|
||||
IAppDbContext db, ICurrentUser currentUser, NotificationWriter notifications, TimeProvider clock)
|
||||
{
|
||||
private const int MaxTextBytes = 65_535;
|
||||
|
||||
public async Task<ProposalDetail> CreateAsync(SaveProposalRequest request, CancellationToken ct)
|
||||
{
|
||||
await GetActorRoleAsync(ct);
|
||||
var (title, description) = ValidateDetails(request);
|
||||
await RequireActiveCategoryAsync(request.CategoryId, ct);
|
||||
var proposal = new Proposal(currentUser.Id, title, description, request.CategoryId);
|
||||
db.Proposals.Add(proposal);
|
||||
AddEvent(proposal, ProposalEventType.Created);
|
||||
await db.SaveChangesAsync(ct);
|
||||
return await LoadDetailAsync(proposal.Id, ct);
|
||||
}
|
||||
|
||||
public async Task<ProposalDetail> EditAsync(int id, SaveProposalRequest request, CancellationToken ct)
|
||||
{
|
||||
var role = await GetActorRoleAsync(ct);
|
||||
var (title, description) = ValidateDetails(request);
|
||||
await using (var transaction = await db.BeginWriteAsync(ct))
|
||||
{
|
||||
var proposal = await LockProposalAsync(id, ct);
|
||||
if (!proposal.CanEditAs(currentUser.Id, role))
|
||||
throw new ForbiddenException("Návrh může upravit jeho autor nebo administrátor.");
|
||||
if (!proposal.IsEditable)
|
||||
throw new ConflictException("Návrh lze upravit jen ve stavu Podán.");
|
||||
|
||||
if (proposal.CategoryId != request.CategoryId)
|
||||
await RequireActiveCategoryAsync(request.CategoryId, ct);
|
||||
|
||||
proposal.Edit(currentUser.Id, role, title, description, request.CategoryId);
|
||||
AddEvent(proposal, ProposalEventType.Updated);
|
||||
await db.SaveChangesAsync(ct);
|
||||
await transaction.CommitAsync(ct);
|
||||
}
|
||||
|
||||
return await LoadDetailAsync(id, ct);
|
||||
}
|
||||
|
||||
public async Task<ProposalDetail> ChangeStatusAsync(int id, ChangeProposalStatusRequest request, CancellationToken ct)
|
||||
{
|
||||
var role = await GetActorRoleAsync(ct);
|
||||
if (!Proposal.CanReview(role))
|
||||
throw new ForbiddenException("Stav návrhu může změnit vedení školy nebo administrátor.");
|
||||
|
||||
var target = ParseStatus(request.Status);
|
||||
var note = string.IsNullOrWhiteSpace(request.Note) ? null : request.Note.Trim();
|
||||
if (target == ProposalStatus.Rejected && note is null)
|
||||
throw new BadRequestException("Zamítnutí vyžaduje vyjádření.");
|
||||
if (note is not null && Encoding.UTF8.GetByteCount(note) > MaxTextBytes)
|
||||
throw new BadRequestException("Vyjádření je příliš dlouhé.");
|
||||
|
||||
await using (var transaction = await db.BeginWriteAsync(ct))
|
||||
{
|
||||
var proposal = await LockProposalAsync(id, ct);
|
||||
var previous = proposal.Status;
|
||||
if (!proposal.CanTransitionTo(target))
|
||||
throw new ConflictException("Přechod do požadovaného stavu není povolen.");
|
||||
|
||||
proposal.ChangeStatus(target, role, note);
|
||||
AddEvent(proposal, ProposalEventType.StatusChanged, previous, note);
|
||||
await notifications.ForProposalStatusAsync(proposal, currentUser.Id, ct);
|
||||
await db.SaveChangesAsync(ct);
|
||||
await transaction.CommitAsync(ct);
|
||||
}
|
||||
|
||||
return await LoadDetailAsync(id, ct);
|
||||
}
|
||||
|
||||
public Task SetVoteAsync(int id, int value, CancellationToken ct)
|
||||
{
|
||||
if (value is not (1 or -1))
|
||||
throw new BadRequestException("Hlas musí mít hodnotu 1 nebo -1.");
|
||||
|
||||
return ChangeVoteAsync(id, (sbyte)value, ct);
|
||||
}
|
||||
|
||||
public Task RemoveVoteAsync(int id, CancellationToken ct) => ChangeVoteAsync(id, null, ct);
|
||||
|
||||
private async Task ChangeVoteAsync(int id, sbyte? value, CancellationToken ct)
|
||||
{
|
||||
await GetActorRoleAsync(ct);
|
||||
var actorId = currentUser.Id;
|
||||
await using var transaction = await db.BeginWriteAsync(ct);
|
||||
var proposal = await LockProposalAsync(id, ct);
|
||||
if (proposal.IsAuthor(actorId))
|
||||
throw new ForbiddenException("Autor nemůže hlasovat o vlastním návrhu.");
|
||||
if (!proposal.IsVotingOpen)
|
||||
throw new ConflictException("Hlasování je uzavřeno.");
|
||||
|
||||
var vote = await db.ProposalVotes.SingleOrDefaultAsync(v => v.ProposalId == id && v.UserId == actorId, ct);
|
||||
if (value is sbyte newValue)
|
||||
{
|
||||
var now = clock.GetUtcNow().UtcDateTime;
|
||||
if (vote is null)
|
||||
db.ProposalVotes.Add(new ProposalVote(proposal, actorId, newValue, now));
|
||||
else
|
||||
vote.SetValue(proposal, newValue, now);
|
||||
}
|
||||
else if (vote is not null)
|
||||
{
|
||||
db.ProposalVotes.Remove(vote);
|
||||
}
|
||||
|
||||
await db.SaveChangesAsync(ct);
|
||||
await transaction.CommitAsync(ct);
|
||||
}
|
||||
|
||||
private async Task<UserRole> GetActorRoleAsync(CancellationToken ct)
|
||||
{
|
||||
var id = currentUser.Id;
|
||||
return await db.Users.Where(u => u.Id == id && u.IsActive).Select(u => (UserRole?)u.Role).SingleOrDefaultAsync(ct)
|
||||
?? throw new UnauthorizedException("Účet není aktivní.");
|
||||
}
|
||||
|
||||
private async Task<Proposal> LockProposalAsync(int id, CancellationToken ct) =>
|
||||
await db.LockProposalAsync(id, ct) ?? throw new NotFoundException("Návrh neexistuje.");
|
||||
|
||||
private async Task RequireActiveCategoryAsync(int id, CancellationToken ct)
|
||||
{
|
||||
if (!await db.ProposalCategories.AnyAsync(c => c.Id == id && c.IsActive, ct))
|
||||
throw new BadRequestException("Vyberte aktivní oblast návrhu.");
|
||||
}
|
||||
|
||||
private static (string Title, string Description) ValidateDetails(SaveProposalRequest request)
|
||||
{
|
||||
var title = request.Title?.Trim();
|
||||
var description = request.Description?.Trim();
|
||||
if (string.IsNullOrEmpty(title) || title.Length > 200)
|
||||
throw new BadRequestException("Název návrhu musí mít 1 až 200 znaků.");
|
||||
if (string.IsNullOrEmpty(description) || Encoding.UTF8.GetByteCount(description) > MaxTextBytes)
|
||||
throw new BadRequestException("Vyplňte popis návrhu v povolené délce.");
|
||||
return (title, description);
|
||||
}
|
||||
|
||||
private void AddEvent(Proposal proposal, ProposalEventType type, ProposalStatus? previous = null, string? note = null) =>
|
||||
db.ProposalEvents.Add(new ProposalEvent(proposal, type, previous, currentUser.Id, note, clock.GetUtcNow().UtcDateTime));
|
||||
|
||||
private static ProposalStatus ParseStatus(string status) =>
|
||||
EnumCode.TryParse<ProposalStatus>(status, out var value)
|
||||
? value
|
||||
: throw new BadRequestException("Neplatný stav návrhu.");
|
||||
}
|
||||
@@ -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<string, int> 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);
|
||||
@@ -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<StatisticsOverview> 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<IssueStatus>()
|
||||
.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<IReadOnlyList<IssueCategoryStatistics>> 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<IReadOnlyList<IssueBuildingStatistics>> 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<IReadOnlyList<IssueAssigneeStatistics>> 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<IReadOnlyList<IssueTrendPoint>> 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<IssueTrendPoint>();
|
||||
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<IReadOnlyList<TopProposal>> 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<Issue> 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<Dictionary<int, int>> CountByMonthAsync(
|
||||
IQueryable<DateTime> 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;
|
||||
}
|
||||
@@ -1,4 +1,6 @@
|
||||
using System.Text;
|
||||
using FluentValidation;
|
||||
using Helpdesk.Application.Auth;
|
||||
using Helpdesk.Domain;
|
||||
using Helpdesk.Domain.Users;
|
||||
|
||||
@@ -45,3 +47,29 @@ public sealed record AdminUserDto(
|
||||
public sealed record ChangeRoleRequest(string Role);
|
||||
|
||||
public sealed record SetActiveRequest(bool IsActive);
|
||||
|
||||
public sealed record AdminUserDetailsDto(int Id, string Email, string FirstName, string LastName, string? Phone,
|
||||
string Role, bool IsActive, bool EmailConfirmed, bool EmailNotificationsEnabled, bool? VerificationEmailSent = null)
|
||||
{
|
||||
public static AdminUserDetailsDto From(User user) => new(user.Id, user.Email, user.FirstName, user.LastName, user.Phone,
|
||||
user.Role.ToCode(), user.IsActive, user.EmailConfirmed, user.EmailNotificationsEnabled);
|
||||
}
|
||||
|
||||
public sealed record SaveAdminUserRequest(string Email, string FirstName, string LastName, string? Phone,
|
||||
string Role, bool IsActive, bool EmailConfirmed, bool EmailNotificationsEnabled, string? Password);
|
||||
|
||||
public sealed class SaveAdminUserRequestValidator : AbstractValidator<SaveAdminUserRequest>
|
||||
{
|
||||
public SaveAdminUserRequestValidator()
|
||||
{
|
||||
RuleFor(x => x.Email).NotEmpty().EmailAddress().MaximumLength(254);
|
||||
RuleFor(x => x.Role).NotEmpty();
|
||||
RuleFor(x => x.Password)
|
||||
.NotEmpty().MinimumLength(PasswordRules.MinLength).MaximumLength(PasswordRules.MaxLength)
|
||||
.Must(password => password is null || Encoding.UTF8.GetByteCount(password) <= 72)
|
||||
.WithMessage("Heslo může mít nejvýše 72 bajtů v UTF-8.")
|
||||
.When(x => x.Password is not null);
|
||||
}
|
||||
}
|
||||
|
||||
public sealed record BulkAdminUsersRequest(int[] UserIds, string Action, string? Role);
|
||||
@@ -13,7 +13,10 @@ namespace Helpdesk.Application.Users;
|
||||
public sealed class UserService(
|
||||
IAppDbContext db,
|
||||
TokenRevocationService revocation,
|
||||
IValidator<UpdateProfileRequest> profileValidator)
|
||||
AuthService auth,
|
||||
IValidator<UpdateProfileRequest> profileValidator,
|
||||
IValidator<SaveAdminUserRequest> adminUserValidator,
|
||||
IPasswordHasher passwordHasher)
|
||||
{
|
||||
public async Task<UserDto> GetMeAsync(ICurrentUser currentUser, CancellationToken ct) =>
|
||||
UserDto.From(await GetAsync(currentUser.Id, ct));
|
||||
@@ -22,9 +25,13 @@ public sealed class UserService(
|
||||
{
|
||||
await profileValidator.ValidateAndThrowAsync(request, ct);
|
||||
|
||||
var user = await GetAsync(currentUser.Id, ct);
|
||||
await using var transaction = await db.BeginWriteAsync(ct);
|
||||
var user = RequireAccount(await db.LockUserAsync(currentUser.Id, ct), currentUser.Id);
|
||||
if (!user.IsActive)
|
||||
throw new UnauthorizedException("Účet není aktivní.");
|
||||
user.UpdateProfile(request.FirstName, request.LastName, request.Phone, request.EmailNotificationsEnabled);
|
||||
await db.SaveChangesAsync(ct);
|
||||
await transaction.CommitAsync(ct);
|
||||
return UserDto.From(user);
|
||||
}
|
||||
|
||||
@@ -33,7 +40,7 @@ public sealed class UserService(
|
||||
page = Math.Max(page, 1);
|
||||
pageSize = Math.Clamp(pageSize, 1, 100);
|
||||
|
||||
var query = db.Users.AsNoTracking();
|
||||
var query = db.Users.AsNoTracking().Where(u => !u.IsDeleted);
|
||||
if (!string.IsNullOrWhiteSpace(q))
|
||||
{
|
||||
var term = q.Trim();
|
||||
@@ -46,9 +53,13 @@ public sealed class UserService(
|
||||
}
|
||||
|
||||
var total = await query.CountAsync(ct);
|
||||
var offset = (long)(page - 1) * pageSize;
|
||||
if (offset >= total)
|
||||
return new PagedResult<AdminUserDto>([], total, page, pageSize);
|
||||
|
||||
var users = await query
|
||||
.OrderBy(u => u.LastName).ThenBy(u => u.FirstName).ThenBy(u => u.Id)
|
||||
.Skip((page - 1) * pageSize).Take(pageSize)
|
||||
.Skip((int)offset).Take(pageSize)
|
||||
.ToListAsync(ct);
|
||||
|
||||
var items = users
|
||||
@@ -58,39 +69,197 @@ public sealed class UserService(
|
||||
}
|
||||
|
||||
/// <summary>Změna role zneplatní tokeny uživatele – po novém přihlášení dostane token s novou rolí.</summary>
|
||||
public async Task ChangeRoleAsync(ICurrentUser admin, int userId, ChangeRoleRequest request, CancellationToken ct)
|
||||
public Task ChangeRoleAsync(ICurrentUser admin, int userId, ChangeRoleRequest request, CancellationToken ct)
|
||||
{
|
||||
var role = ParseRole(request.Role);
|
||||
if (userId == admin.Id)
|
||||
throw new ConflictException("Administrátor nemůže změnit roli sám sobě.");
|
||||
|
||||
var user = await GetAsync(userId, ct);
|
||||
if (user.Role == role)
|
||||
return;
|
||||
|
||||
await revocation.RevokeAllAsync(user.Id, RevokeReason.RoleChanged, ct);
|
||||
user.ChangeRole(role);
|
||||
await db.SaveChangesAsync(ct);
|
||||
return UpdateAccountsAsync(admin, [userId], user => ChangeRole(user, role), ct);
|
||||
}
|
||||
|
||||
public async Task SetActiveAsync(ICurrentUser admin, int userId, SetActiveRequest request, CancellationToken ct)
|
||||
public Task SetActiveAsync(ICurrentUser admin, int userId, SetActiveRequest request, CancellationToken ct) =>
|
||||
userId == admin.Id && request.IsActive
|
||||
? Task.CompletedTask
|
||||
: UpdateAccountsAsync(admin, [userId], user => SetActive(user, request.IsActive), ct);
|
||||
|
||||
public async Task<AdminUserDetailsDto> GetAdminAsync(int id, CancellationToken ct) =>
|
||||
AdminUserDetailsDto.From(await GetAsync(id, ct));
|
||||
|
||||
public async Task<AdminUserDetailsDto> CreateAsync(ICurrentUser admin, SaveAdminUserRequest request, CancellationToken ct)
|
||||
{
|
||||
if (userId == admin.Id && !request.IsActive)
|
||||
throw new ConflictException("Administrátor nemůže deaktivovat sám sebe.");
|
||||
|
||||
var user = await GetAsync(userId, ct);
|
||||
if (user.IsActive == request.IsActive)
|
||||
return;
|
||||
|
||||
if (!request.IsActive)
|
||||
await revocation.RevokeAllAsync(user.Id, RevokeReason.AccountDeactivated, ct);
|
||||
await ValidateAsync(request, ct);
|
||||
if (string.IsNullOrWhiteSpace(request.Password))
|
||||
throw new BadRequestException("Zadejte počáteční heslo.");
|
||||
var role = ParseRole(request.Role);
|
||||
var user = User.Create(request.Email, passwordHasher.Hash(request.Password), request.FirstName, request.LastName, role);
|
||||
ApplyProfile(user, request);
|
||||
user.SetActive(request.IsActive);
|
||||
|
||||
await using (var transaction = await db.BeginWriteAsync(ct))
|
||||
{
|
||||
RequireAdministrator(await db.LockUserAsync(admin.Id, ct));
|
||||
db.Users.Add(user);
|
||||
await db.SaveChangesAsync(ct);
|
||||
await transaction.CommitAsync(ct);
|
||||
}
|
||||
return await AccountSavedAsync(user, ct);
|
||||
}
|
||||
|
||||
public async Task<AdminUserDetailsDto?> UpdateAsync(ICurrentUser admin, int userId, SaveAdminUserRequest request, CancellationToken ct)
|
||||
{
|
||||
await ValidateAsync(request, ct);
|
||||
var role = ParseRole(request.Role);
|
||||
var passwordHash = request.Password is null ? null : passwordHasher.Hash(request.Password);
|
||||
var sendLink = false;
|
||||
var updated = await UpdateAccountsAsync(admin, [userId], user =>
|
||||
{
|
||||
var emailChanged = user.EmailNormalized != User.NormalizeEmail(request.Email);
|
||||
var confirmed = !emailChanged && request.EmailConfirmed;
|
||||
var confirmationChanged = user.EmailConfirmed != confirmed;
|
||||
var roleChanged = ChangeRole(user, role);
|
||||
var activeChanged = SetActive(user, request.IsActive);
|
||||
ApplyProfile(user, request with { EmailConfirmed = confirmed });
|
||||
sendLink = emailChanged && user.IsActive;
|
||||
if (passwordHash is not null)
|
||||
user.ChangePasswordHash(passwordHash);
|
||||
|
||||
if (emailChanged || confirmationChanged)
|
||||
return RevokeReason.LogoutAll;
|
||||
if (passwordHash is not null)
|
||||
return RevokeReason.PasswordChanged;
|
||||
return roleChanged ?? activeChanged;
|
||||
}, ct);
|
||||
return sendLink ? await AccountSavedAsync(updated.Single(), ct) : null;
|
||||
}
|
||||
|
||||
public async Task SendEmailConfirmationAsync(int userId, CancellationToken ct)
|
||||
{
|
||||
var user = await GetAsync(userId, ct);
|
||||
if (!user.IsActive || user.EmailConfirmed)
|
||||
throw new ConflictException("Ověřovací odkaz lze poslat pouze aktivnímu účtu s neověřeným e-mailem.");
|
||||
|
||||
if (!await auth.SendEmailConfirmationAsync(user, ct))
|
||||
throw new ConflictException("Účet se mezitím změnil. Obnovte jeho detail.");
|
||||
}
|
||||
|
||||
public Task DeleteAsync(ICurrentUser admin, int userId, CancellationToken ct) =>
|
||||
UpdateAccountsAsync(admin, [userId], Delete, ct);
|
||||
|
||||
public Task BulkUpdateAsync(ICurrentUser admin, BulkAdminUsersRequest request, CancellationToken ct)
|
||||
{
|
||||
if (request.UserIds is not { Length: >= 1 and <= 100 } || request.UserIds.Any(id => id <= 0))
|
||||
throw new BadRequestException("Vyberte 1 až 100 uživatelů.");
|
||||
|
||||
var role = request.Action == "role" ? ParseRole(request.Role ?? "") : default;
|
||||
return request.Action switch
|
||||
{
|
||||
"activate" => UpdateAccountsAsync(admin, request.UserIds, user => SetActive(user, true), ct),
|
||||
"deactivate" => UpdateAccountsAsync(admin, request.UserIds, user => SetActive(user, false), ct),
|
||||
"role" => UpdateAccountsAsync(admin, request.UserIds, user => ChangeRole(user, role), ct),
|
||||
"delete" => UpdateAccountsAsync(admin, request.UserIds, Delete, ct),
|
||||
_ => throw new BadRequestException("Vyberte platnou hromadnou akci."),
|
||||
};
|
||||
}
|
||||
|
||||
private async Task<List<User>> UpdateAccountsAsync(ICurrentUser admin, int[] ids, Func<User, RevokeReason?> update, CancellationToken ct)
|
||||
{
|
||||
if (ids.Contains(admin.Id))
|
||||
throw new ConflictException("Vlastní účet upravujte v nastavení profilu.");
|
||||
|
||||
await using var transaction = await db.BeginWriteAsync(ct);
|
||||
var users = new List<User>();
|
||||
// Stejné pořadí při překryvu výběrů. Zámek správce brání souběžnému odebrání role.
|
||||
foreach (var id in ids.Append(admin.Id).Distinct().Order())
|
||||
{
|
||||
var user = await db.LockUserAsync(id, ct);
|
||||
if (id == admin.Id)
|
||||
RequireAdministrator(user);
|
||||
else
|
||||
users.Add(RequireAccount(user, id));
|
||||
}
|
||||
|
||||
var changes = new List<(int Id, RevokeReason Reason)>();
|
||||
foreach (var user in users)
|
||||
{
|
||||
if (update(user) is { } reason)
|
||||
changes.Add((user.Id, reason));
|
||||
}
|
||||
|
||||
var revoked = new List<TokenRevocationService.RevokedAccessToken>();
|
||||
foreach (var group in changes.GroupBy(change => change.Reason))
|
||||
revoked.AddRange(await revocation.StageRevokeAllAsync(group.Select(change => change.Id).ToArray(), group.Key, ct));
|
||||
var deletedIds = users.Where(user => user.IsDeleted).Select(user => user.Id).ToArray();
|
||||
if (deletedIds.Length > 0)
|
||||
await db.PushDevices.Where(device => deletedIds.Contains(device.UserId)).ExecuteDeleteAsync(ct);
|
||||
|
||||
await db.SaveChangesAsync(ct);
|
||||
await transaction.CommitAsync(ct);
|
||||
revocation.Publish(revoked);
|
||||
return users;
|
||||
}
|
||||
|
||||
private async Task<AdminUserDetailsDto> AccountSavedAsync(User user, CancellationToken ct)
|
||||
{
|
||||
var result = AdminUserDetailsDto.From(user);
|
||||
if (!user.IsActive || user.EmailConfirmed)
|
||||
return result;
|
||||
|
||||
try
|
||||
{
|
||||
return result with { VerificationEmailSent = await auth.SendEmailConfirmationAsync(user, ct) };
|
||||
}
|
||||
catch (EmailDeliveryException)
|
||||
{
|
||||
// Účet je již uložený a ověřovací e-mail lze poslat znovu.
|
||||
return result with { VerificationEmailSent = false };
|
||||
}
|
||||
}
|
||||
|
||||
private async Task ValidateAsync(SaveAdminUserRequest request, CancellationToken ct)
|
||||
{
|
||||
await adminUserValidator.ValidateAndThrowAsync(request, ct);
|
||||
await profileValidator.ValidateAndThrowAsync(
|
||||
new UpdateProfileRequest(request.FirstName, request.LastName, request.Phone, request.EmailNotificationsEnabled), ct);
|
||||
}
|
||||
|
||||
private static void ApplyProfile(User user, SaveAdminUserRequest request)
|
||||
{
|
||||
user.UpdateProfile(request.FirstName, request.LastName, request.Phone, request.EmailNotificationsEnabled);
|
||||
user.ChangeEmail(request.Email);
|
||||
user.SetEmailConfirmed(request.EmailConfirmed);
|
||||
}
|
||||
|
||||
private static RevokeReason? ChangeRole(User user, UserRole role)
|
||||
{
|
||||
if (user.Role == role)
|
||||
return null;
|
||||
user.ChangeRole(role);
|
||||
return RevokeReason.RoleChanged;
|
||||
}
|
||||
|
||||
private static RevokeReason? SetActive(User user, bool active)
|
||||
{
|
||||
var wasActive = user.IsActive;
|
||||
user.SetActive(active);
|
||||
return wasActive && !active ? RevokeReason.AccountDeactivated : null;
|
||||
}
|
||||
|
||||
private static RevokeReason? Delete(User user)
|
||||
{
|
||||
user.Delete();
|
||||
return RevokeReason.AccountDeactivated;
|
||||
}
|
||||
|
||||
private async Task<User> GetAsync(int id, CancellationToken ct) =>
|
||||
await db.Users.SingleOrDefaultAsync(u => u.Id == id, ct)
|
||||
?? throw new NotFoundException($"Uživatel {id} neexistuje.");
|
||||
RequireAccount(await db.Users.SingleOrDefaultAsync(u => u.Id == id, ct), id);
|
||||
|
||||
private static User RequireAccount(User? user, int id) => user is { IsDeleted: false }
|
||||
? user
|
||||
: throw new NotFoundException($"Uživatel {id} neexistuje.");
|
||||
|
||||
private static void RequireAdministrator(User? user)
|
||||
{
|
||||
if (user is not { Role: UserRole.Admin, IsActive: true, IsDeleted: false })
|
||||
throw new ForbiddenException("K této akci potřebujete aktivní účet administrátora.");
|
||||
}
|
||||
|
||||
private static UserRole ParseRole(string code) =>
|
||||
EnumCode.TryParse<UserRole>(code, out var role)
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
/// <summary>Oblast návrhu na zlepšení (tabulka <c>proposal_category</c>).</summary>
|
||||
@@ -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;
|
||||
}
|
||||
@@ -0,0 +1,140 @@
|
||||
using Helpdesk.Domain.Users;
|
||||
|
||||
namespace Helpdesk.Domain.Issues;
|
||||
|
||||
public enum IssueStatus { Received, Assigned, InProgress, PendingVerification, Resolved, Rejected }
|
||||
public enum IssuePriority { Low, Normal, High }
|
||||
public enum IssueEventType { Created, Updated, Assigned, StatusChanged, Commented }
|
||||
public enum IssueAction { Edit, Assign, StartWork, SubmitForVerification, Confirm, Reopen, Reject, Comment, AddAttachments }
|
||||
public enum IssueActionAvailability { Allowed, Forbidden, InvalidState }
|
||||
|
||||
public sealed class Issue : IHasCreatedAt
|
||||
{
|
||||
private Issue() { }
|
||||
|
||||
public Issue(int reporterId, string title, string description, int categoryId, int? buildingId, string? locationDetail)
|
||||
{
|
||||
ReporterId = reporterId;
|
||||
SetDetails(title, description, categoryId, buildingId, locationDetail);
|
||||
}
|
||||
|
||||
public int Id { get; private set; }
|
||||
public string Title { get; private set; } = null!;
|
||||
public string Description { get; private set; } = null!;
|
||||
public int CategoryId { get; private set; }
|
||||
public int? BuildingId { get; private set; }
|
||||
public string? LocationDetail { get; private set; }
|
||||
public IssueStatus Status { get; private set; } = IssueStatus.Received;
|
||||
public IssuePriority Priority { get; private set; } = IssuePriority.Normal;
|
||||
public int ReporterId { get; private set; }
|
||||
public int? AssigneeId { get; private set; }
|
||||
public int RowVersion { get; private set; }
|
||||
public DateTime CreatedAt { get; set; }
|
||||
|
||||
public static bool CanReadAll(UserRole role) => role == UserRole.FacilityManager || CanAssign(role);
|
||||
|
||||
public static bool CanAssign(UserRole role) => role is UserRole.Management or UserRole.Admin;
|
||||
|
||||
public static bool CanBeAssigned(UserRole role) => role is UserRole.FacilityManager or UserRole.Management or UserRole.Admin;
|
||||
|
||||
public bool CanRead(int userId, UserRole role) => CanReadAll(role) || ReporterId == userId;
|
||||
|
||||
public IssueActionAvailability Availability(IssueAction action, int actorId, UserRole role)
|
||||
{
|
||||
var reporter = ReporterId == actorId;
|
||||
var assignee = AssigneeId == actorId && CanBeAssigned(role);
|
||||
var management = role == UserRole.Management;
|
||||
var admin = role == UserRole.Admin;
|
||||
|
||||
var authorized = action switch
|
||||
{
|
||||
IssueAction.Edit or IssueAction.Confirm or IssueAction.Reopen => admin || reporter,
|
||||
IssueAction.Assign => CanAssign(role),
|
||||
IssueAction.StartWork or IssueAction.SubmitForVerification => admin || assignee,
|
||||
IssueAction.Reject => admin || assignee || (management && AssigneeId is null),
|
||||
IssueAction.Comment or IssueAction.AddAttachments => admin || reporter || assignee,
|
||||
_ => false,
|
||||
};
|
||||
|
||||
if (!authorized)
|
||||
return IssueActionAvailability.Forbidden;
|
||||
|
||||
var permittedState = action switch
|
||||
{
|
||||
IssueAction.Edit => Status == IssueStatus.Received,
|
||||
IssueAction.Assign => Status is IssueStatus.Received or IssueStatus.Assigned or IssueStatus.InProgress,
|
||||
IssueAction.StartWork => Status == IssueStatus.Assigned,
|
||||
IssueAction.SubmitForVerification => Status == IssueStatus.InProgress,
|
||||
IssueAction.Confirm or IssueAction.Reopen => Status == IssueStatus.PendingVerification,
|
||||
IssueAction.Reject => Status == IssueStatus.Received
|
||||
? admin || management
|
||||
: (admin || assignee) && Status is (IssueStatus.Assigned or IssueStatus.InProgress),
|
||||
IssueAction.Comment or IssueAction.AddAttachments => Status is not (IssueStatus.Resolved or IssueStatus.Rejected),
|
||||
_ => false,
|
||||
};
|
||||
return permittedState ? IssueActionAvailability.Allowed : IssueActionAvailability.InvalidState;
|
||||
}
|
||||
|
||||
public void Edit(int actorId, UserRole role, string title, string description, int categoryId,
|
||||
int? buildingId, string? locationDetail)
|
||||
{
|
||||
Require(IssueAction.Edit, actorId, role);
|
||||
SetDetails(title, description, categoryId, buildingId, locationDetail);
|
||||
RowVersion++;
|
||||
}
|
||||
|
||||
public void Assign(int actorId, UserRole role, int assigneeId, UserRole assigneeRole, IssuePriority? priority)
|
||||
{
|
||||
Require(IssueAction.Assign, actorId, role);
|
||||
if (!CanBeAssigned(assigneeRole))
|
||||
throw new ArgumentException("Neplatná role řešitele.", nameof(assigneeRole));
|
||||
if (AssigneeId == assigneeId)
|
||||
throw new ArgumentException("Nový řešitel musí být jiný než stávající.", nameof(assigneeId));
|
||||
|
||||
AssigneeId = assigneeId;
|
||||
Priority = priority ?? Priority;
|
||||
Status = IssueStatus.Assigned;
|
||||
RowVersion++;
|
||||
}
|
||||
|
||||
public void Transition(IssueAction action, int actorId, UserRole role, string? reason)
|
||||
{
|
||||
Require(action, actorId, role);
|
||||
if (action is (IssueAction.Reject or IssueAction.Reopen) && string.IsNullOrWhiteSpace(reason))
|
||||
throw new ArgumentException("Důvod je povinný.", nameof(reason));
|
||||
|
||||
Status = action switch
|
||||
{
|
||||
IssueAction.StartWork or IssueAction.Reopen => IssueStatus.InProgress,
|
||||
IssueAction.SubmitForVerification => IssueStatus.PendingVerification,
|
||||
IssueAction.Confirm => IssueStatus.Resolved,
|
||||
IssueAction.Reject => IssueStatus.Rejected,
|
||||
_ => throw new ArgumentOutOfRangeException(nameof(action)),
|
||||
};
|
||||
RowVersion++;
|
||||
}
|
||||
|
||||
public void RecordParticipation(IssueAction action, int actorId, UserRole role)
|
||||
{
|
||||
if (action is not (IssueAction.Comment or IssueAction.AddAttachments))
|
||||
throw new ArgumentOutOfRangeException(nameof(action));
|
||||
|
||||
Require(action, actorId, role);
|
||||
RowVersion++;
|
||||
}
|
||||
|
||||
private void Require(IssueAction action, int actorId, UserRole role)
|
||||
{
|
||||
if (Availability(action, actorId, role) != IssueActionAvailability.Allowed)
|
||||
throw new InvalidOperationException("Akce není pro tuto závadu povolena.");
|
||||
}
|
||||
|
||||
private void SetDetails(string title, string description, int categoryId, int? buildingId, string? locationDetail)
|
||||
{
|
||||
Title = title.Trim();
|
||||
Description = description.Trim();
|
||||
CategoryId = categoryId;
|
||||
BuildingId = buildingId;
|
||||
LocationDetail = string.IsNullOrWhiteSpace(locationDetail) ? null : locationDetail.Trim();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
namespace Helpdesk.Domain.Issues;
|
||||
|
||||
public sealed class IssueEvent
|
||||
{
|
||||
private IssueEvent() { }
|
||||
|
||||
public IssueEvent(Issue issue, IssueEventType eventType, IssueStatus? fromStatus, int actorId, string? note,
|
||||
DateTime occurredAt)
|
||||
{
|
||||
Issue = issue;
|
||||
EventType = eventType;
|
||||
FromStatus = fromStatus;
|
||||
ToStatus = issue.Status;
|
||||
ActorId = actorId;
|
||||
Note = note;
|
||||
OccurredAt = occurredAt;
|
||||
}
|
||||
|
||||
public int Id { get; private set; }
|
||||
public int IssueId { get; private set; }
|
||||
public Issue Issue { get; private set; } = null!;
|
||||
public IssueEventType EventType { get; private set; }
|
||||
public IssueStatus? FromStatus { get; private set; }
|
||||
public IssueStatus ToStatus { get; private set; }
|
||||
public int ActorId { get; private set; }
|
||||
public string? Note { get; private set; }
|
||||
public DateTime OccurredAt { get; private set; }
|
||||
}
|
||||
|
||||
public sealed class Attachment(
|
||||
Issue issue, string originalFileName, string storedFileName, string contentType, long sizeBytes) : IHasCreatedAt
|
||||
{
|
||||
private Attachment() : this(null!, null!, null!, null!, 0) { }
|
||||
|
||||
public int Id { get; private set; }
|
||||
public int IssueId { get; private set; }
|
||||
public Issue Issue { get; private set; } = issue;
|
||||
public string OriginalFileName { get; private set; } = originalFileName;
|
||||
public string StoredFileName { get; private set; } = storedFileName;
|
||||
public string ContentType { get; private set; } = contentType;
|
||||
public long SizeBytes { get; private set; } = sizeBytes;
|
||||
public DateTime CreatedAt { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
using Helpdesk.Domain.Issues;
|
||||
using Helpdesk.Domain.Proposals;
|
||||
|
||||
namespace Helpdesk.Domain.Notifications;
|
||||
|
||||
public enum NotificationType { IssueCreated, IssueAssigned, IssueStatusChanged, IssueCommentAdded, IssueReopened, ProposalStatusChanged }
|
||||
public enum DeliveryChannel { Email, Push }
|
||||
public enum DeliveryStatus { Pending, Sent, Failed, Skipped }
|
||||
|
||||
public sealed class Notification : IHasCreatedAt
|
||||
{
|
||||
private Notification() { }
|
||||
|
||||
public Notification(Issue issue, int userId, NotificationType type, string title, string message)
|
||||
: this(userId, type, title, message)
|
||||
{
|
||||
Issue = issue;
|
||||
}
|
||||
|
||||
public Notification(Proposal proposal, int userId, string title)
|
||||
: this(userId, NotificationType.ProposalStatusChanged, title, proposal.Title)
|
||||
{
|
||||
ProposalId = proposal.Id;
|
||||
}
|
||||
|
||||
private Notification(int userId, NotificationType type, string title, string message)
|
||||
{
|
||||
UserId = userId;
|
||||
Type = type;
|
||||
Title = title;
|
||||
Message = message;
|
||||
}
|
||||
|
||||
public int Id { get; private set; }
|
||||
public int? IssueId { get; private set; }
|
||||
public int? ProposalId { get; private set; }
|
||||
public Issue? Issue { get; private set; }
|
||||
public int UserId { get; private set; }
|
||||
public NotificationType Type { get; private set; }
|
||||
public string Title { get; private set; } = null!;
|
||||
public string Message { get; private set; } = null!;
|
||||
public DateTime CreatedAt { get; set; }
|
||||
public DateTime? ReadAt { get; private set; }
|
||||
}
|
||||
|
||||
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; }
|
||||
public int NotificationId { get; private set; }
|
||||
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!;
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
using Helpdesk.Domain.Users;
|
||||
|
||||
namespace Helpdesk.Domain.Proposals;
|
||||
|
||||
public enum ProposalStatus { Submitted, UnderReview, Accepted, Rejected, Implemented }
|
||||
public enum ProposalEventType { Created, Updated, StatusChanged }
|
||||
|
||||
public sealed class Proposal : IHasCreatedAt
|
||||
{
|
||||
private Proposal() { }
|
||||
|
||||
public Proposal(int authorId, string title, string description, int categoryId)
|
||||
{
|
||||
AuthorId = authorId;
|
||||
SetDetails(title, description, categoryId);
|
||||
}
|
||||
|
||||
public int Id { get; private set; }
|
||||
public int AuthorId { get; private set; }
|
||||
public string Title { get; private set; } = null!;
|
||||
public string Description { get; private set; } = null!;
|
||||
public int CategoryId { get; private set; }
|
||||
public ProposalStatus Status { get; private set; } = ProposalStatus.Submitted;
|
||||
public DateTime CreatedAt { get; set; }
|
||||
|
||||
public bool IsAuthor(int userId) => AuthorId == userId;
|
||||
public bool IsEditable => Status == ProposalStatus.Submitted;
|
||||
public bool IsVotingOpen => Status is ProposalStatus.Submitted or ProposalStatus.UnderReview;
|
||||
public bool CanEditAs(int userId, UserRole role) => role == UserRole.Admin || IsAuthor(userId);
|
||||
public bool CanVote(int userId) => !IsAuthor(userId) && IsVotingOpen;
|
||||
|
||||
public static bool CanReview(UserRole role) => role is UserRole.Management or UserRole.Admin;
|
||||
|
||||
public bool CanTransitionTo(ProposalStatus target) => Status switch
|
||||
{
|
||||
ProposalStatus.Submitted => target is ProposalStatus.UnderReview or ProposalStatus.Accepted or ProposalStatus.Rejected,
|
||||
ProposalStatus.UnderReview => target is ProposalStatus.Accepted or ProposalStatus.Rejected,
|
||||
ProposalStatus.Accepted => target == ProposalStatus.Implemented,
|
||||
_ => false,
|
||||
};
|
||||
|
||||
public void Edit(int actorId, UserRole role, string title, string description, int categoryId)
|
||||
{
|
||||
if (!CanEditAs(actorId, role) || !IsEditable)
|
||||
throw new InvalidOperationException("Návrh nelze upravit.");
|
||||
|
||||
SetDetails(title, description, categoryId);
|
||||
}
|
||||
|
||||
public void ChangeStatus(ProposalStatus target, UserRole role, string? note)
|
||||
{
|
||||
if (!CanReview(role) || !CanTransitionTo(target))
|
||||
throw new InvalidOperationException("Stav návrhu nelze změnit.");
|
||||
if (target == ProposalStatus.Rejected && string.IsNullOrWhiteSpace(note))
|
||||
throw new ArgumentException("Zamítnutí vyžaduje vyjádření.", nameof(note));
|
||||
|
||||
Status = target;
|
||||
}
|
||||
|
||||
private void SetDetails(string title, string description, int categoryId)
|
||||
{
|
||||
Title = title;
|
||||
Description = description;
|
||||
CategoryId = categoryId;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
namespace Helpdesk.Domain.Proposals;
|
||||
|
||||
public sealed class ProposalEvent
|
||||
{
|
||||
private ProposalEvent() { }
|
||||
|
||||
public ProposalEvent(Proposal proposal, ProposalEventType eventType, ProposalStatus? fromStatus, int actorId,
|
||||
string? note, DateTime occurredAt)
|
||||
{
|
||||
Proposal = proposal;
|
||||
EventType = eventType;
|
||||
FromStatus = fromStatus;
|
||||
ToStatus = proposal.Status;
|
||||
ActorId = actorId;
|
||||
Note = note;
|
||||
OccurredAt = occurredAt;
|
||||
}
|
||||
|
||||
public int Id { get; private set; }
|
||||
public int ProposalId { get; private set; }
|
||||
public Proposal Proposal { get; private set; } = null!;
|
||||
public ProposalEventType EventType { get; private set; }
|
||||
public ProposalStatus? FromStatus { get; private set; }
|
||||
public ProposalStatus ToStatus { get; private set; }
|
||||
public int ActorId { get; private set; }
|
||||
public string? Note { get; private set; }
|
||||
public DateTime OccurredAt { get; private set; }
|
||||
}
|
||||
|
||||
public sealed class ProposalVote
|
||||
{
|
||||
private ProposalVote() { }
|
||||
|
||||
public ProposalVote(Proposal proposal, int userId, sbyte value, DateTime now)
|
||||
{
|
||||
ProposalId = proposal.Id;
|
||||
UserId = userId;
|
||||
SetValue(proposal, value, now);
|
||||
}
|
||||
|
||||
public int ProposalId { get; private set; }
|
||||
public int UserId { get; private set; }
|
||||
public sbyte Value { get; private set; }
|
||||
public DateTime VotedAt { get; private set; }
|
||||
|
||||
public void SetValue(Proposal proposal, sbyte value, DateTime now)
|
||||
{
|
||||
if (proposal.Id != ProposalId || !proposal.CanVote(UserId))
|
||||
throw new InvalidOperationException("O návrhu nelze hlasovat.");
|
||||
if (value is not (1 or -1))
|
||||
throw new ArgumentOutOfRangeException(nameof(value));
|
||||
if (Value == value)
|
||||
return;
|
||||
|
||||
Value = value;
|
||||
VotedAt = now;
|
||||
}
|
||||
}
|
||||
|
||||
public sealed class ProposalScore
|
||||
{
|
||||
public int ProposalId { get; private set; }
|
||||
public decimal VotesFor { get; private set; }
|
||||
public decimal VotesAgainst { get; private set; }
|
||||
public decimal Score { get; private set; }
|
||||
}
|
||||
@@ -21,6 +21,7 @@ public sealed class User : IHasCreatedAt
|
||||
public string? Phone { get; private set; }
|
||||
public UserRole Role { get; private set; }
|
||||
public bool IsActive { get; private set; } = true;
|
||||
public bool IsDeleted { get; private set; }
|
||||
public bool EmailConfirmed { get; private set; }
|
||||
public bool EmailNotificationsEnabled { get; private set; } = true;
|
||||
public int FailedLoginCount { get; private set; }
|
||||
@@ -62,6 +63,14 @@ public sealed class User : IHasCreatedAt
|
||||
|
||||
public void ConfirmEmail() => EmailConfirmed = true;
|
||||
|
||||
public void SetEmailConfirmed(bool confirmed) => EmailConfirmed = confirmed;
|
||||
|
||||
public void ChangeEmail(string email)
|
||||
{
|
||||
Email = email.Trim();
|
||||
EmailNormalized = NormalizeEmail(email);
|
||||
}
|
||||
|
||||
public void ChangePasswordHash(string passwordHash)
|
||||
{
|
||||
PasswordHash = passwordHash;
|
||||
@@ -79,4 +88,14 @@ public sealed class User : IHasCreatedAt
|
||||
public void ChangeRole(UserRole role) => Role = role;
|
||||
|
||||
public void SetActive(bool isActive) => IsActive = isActive;
|
||||
|
||||
public void Delete()
|
||||
{
|
||||
UpdateProfile("Smazaný", "uživatel", null, false);
|
||||
ChangeEmail($"deleted:{Id.ToString(System.Globalization.CultureInfo.InvariantCulture)}");
|
||||
ChangePasswordHash("");
|
||||
SetEmailConfirmed(false);
|
||||
SetActive(false);
|
||||
IsDeleted = true;
|
||||
}
|
||||
}
|
||||
@@ -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<NotificationDispatcher> 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<bool> DeliverNextAsync(CancellationToken ct)
|
||||
{
|
||||
using var scope = scopes.CreateScope();
|
||||
var db = scope.ServiceProvider.GetRequiredService<HelpdeskDbContext>();
|
||||
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);
|
||||
}
|
||||
@@ -1,17 +1,23 @@
|
||||
using Helpdesk.Application.Abstractions;
|
||||
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;
|
||||
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.");
|
||||
@@ -31,11 +37,37 @@ public static class DependencyInjection
|
||||
services.AddSingleton<IPasswordHasher, BCryptPasswordHasher>();
|
||||
services.AddSingleton<ITokenService, JwtTokenService>();
|
||||
services.AddSingleton<IRevokedTokenStore, RevokedTokenStore>();
|
||||
services.AddSingleton<IEmailSender, LoggingEmailSender>();
|
||||
AddEmailSender(services, configuration.GetSection("Smtp"), environment);
|
||||
var firebaseCredentials = configuration["Firebase:ServiceAccountJson"];
|
||||
if (!string.IsNullOrWhiteSpace(firebaseCredentials))
|
||||
services.AddSingleton(_ => FirebasePushSender.Create(firebaseCredentials));
|
||||
services.AddSingleton<IAttachmentStore, FileAttachmentStore>();
|
||||
|
||||
services.AddHostedService<RevokedTokenStoreLoader>();
|
||||
services.AddHostedService<AdminSeeder>();
|
||||
services.AddHostedService<AuthTokenCleanupService>();
|
||||
services.AddHostedService<NotificationDispatcher>();
|
||||
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<IEmailSender, LoggingEmailSender>();
|
||||
return;
|
||||
}
|
||||
|
||||
services.AddOptions<SmtpOptions>()
|
||||
.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<IEmailSender, SmtpEmailSender>();
|
||||
}
|
||||
}
|
||||
@@ -4,8 +4,7 @@ using Microsoft.Extensions.Logging;
|
||||
namespace Helpdesk.Infrastructure.Email;
|
||||
|
||||
/// <summary>
|
||||
/// 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 <c>docker compose logs api</c>). 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.
|
||||
/// </summary>
|
||||
internal sealed partial class LoggingEmailSender(ILogger<LoggingEmailSender> logger) : IEmailSender
|
||||
{
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
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<SmtpOptions> options, ILogger<SmtpEmailSender> 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("SMTP_INVALID_RECIPIENT", retryable: false);
|
||||
}
|
||||
|
||||
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);
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
[LoggerMessage(Level = LogLevel.Warning, Message = "Doručení e-mailu přes SMTP selhalo ({FailureType}).")]
|
||||
private partial void LogDeliveryFailure(string failureType);
|
||||
}
|
||||
@@ -0,0 +1,155 @@
|
||||
using System.Buffers.Binary;
|
||||
using System.IO.Compression;
|
||||
using Helpdesk.Application.Common;
|
||||
using Helpdesk.Application.Issues;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace Helpdesk.Infrastructure.Files;
|
||||
|
||||
internal sealed class FileAttachmentStore(ILogger<FileAttachmentStore> logger) : IAttachmentStore
|
||||
{
|
||||
private readonly string directory = Path.Combine(AppContext.BaseDirectory, "uploads");
|
||||
|
||||
public async Task<StoredAttachment> SaveAsync(AttachmentUpload upload, CancellationToken ct)
|
||||
{
|
||||
if (upload.SizeBytes is <= 0 or > AttachmentLimits.MaxFileBytes)
|
||||
throw new BadRequestException("Příloha musí mít velikost od 1 B do 10 MB.");
|
||||
|
||||
var name = Path.GetFileName(upload.FileName.Replace('\\', '/')).Trim();
|
||||
if (name.Length is 0 or > 255 || name.Any(char.IsControl))
|
||||
throw new BadRequestException("Neplatný název přílohy.");
|
||||
|
||||
var extension = Path.GetExtension(name).ToLowerInvariant();
|
||||
var contentType = extension switch
|
||||
{
|
||||
".jpg" or ".jpeg" => "image/jpeg",
|
||||
".png" => "image/png",
|
||||
".heic" => "image/heic",
|
||||
".pdf" => "application/pdf",
|
||||
".docx" => "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
|
||||
_ => throw new BadRequestException("Tento typ přílohy není povolen."),
|
||||
};
|
||||
|
||||
Directory.CreateDirectory(directory);
|
||||
var key = Guid.NewGuid().ToString("D");
|
||||
var path = FilePath(key);
|
||||
|
||||
var created = false;
|
||||
try
|
||||
{
|
||||
await using var input = upload.OpenRead();
|
||||
await using var output = new FileStream(path, FileMode.CreateNew, FileAccess.ReadWrite, FileShare.None,
|
||||
bufferSize: 64 * 1024, useAsync: true);
|
||||
created = true;
|
||||
|
||||
var buffer = new byte[64 * 1024];
|
||||
long written = 0;
|
||||
int read;
|
||||
while ((read = await input.ReadAsync(buffer, ct)) > 0)
|
||||
{
|
||||
written += read;
|
||||
if (written > upload.SizeBytes)
|
||||
throw new BadRequestException("Velikost přílohy neodpovídá požadavku.");
|
||||
await output.WriteAsync(buffer.AsMemory(0, read), ct);
|
||||
}
|
||||
|
||||
if (written != upload.SizeBytes)
|
||||
throw new BadRequestException("Velikost přílohy neodpovídá požadavku.");
|
||||
|
||||
output.Position = 0;
|
||||
if (!await HasExpectedFormatAsync(output, extension, ct))
|
||||
throw new BadRequestException("Obsah přílohy neodpovídá její příponě.");
|
||||
|
||||
return new StoredAttachment(name, key, contentType, written);
|
||||
}
|
||||
catch
|
||||
{
|
||||
if (created)
|
||||
Delete(key);
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
public Stream OpenRead(string storedFileName)
|
||||
{
|
||||
try
|
||||
{
|
||||
return new FileStream(FilePath(storedFileName), FileMode.Open, FileAccess.Read, FileShare.Read,
|
||||
bufferSize: 64 * 1024, useAsync: true);
|
||||
}
|
||||
catch (IOException exception) when (exception is FileNotFoundException or DirectoryNotFoundException)
|
||||
{
|
||||
logger.LogError(exception, "Soubor přílohy {AttachmentKey} v úložišti chybí.", storedFileName);
|
||||
throw new NotFoundException("Soubor přílohy není dostupný.");
|
||||
}
|
||||
}
|
||||
|
||||
public void Delete(string storedFileName)
|
||||
{
|
||||
try
|
||||
{
|
||||
File.Delete(FilePath(storedFileName));
|
||||
}
|
||||
catch (Exception exception) when (exception is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
logger.LogError(exception, "Soubor přílohy {AttachmentKey} se nepodařilo uklidit.", storedFileName);
|
||||
}
|
||||
}
|
||||
|
||||
private string FilePath(string key) => Guid.TryParseExact(key, "D", out _)
|
||||
? Path.Combine(directory, key)
|
||||
: throw new InvalidOperationException("Neplatný klíč souboru přílohy.");
|
||||
|
||||
private static async Task<bool> HasExpectedFormatAsync(Stream stream, string extension, CancellationToken ct)
|
||||
{
|
||||
var header = new byte[(int)Math.Min(stream.Length, 512)];
|
||||
await stream.ReadExactlyAsync(header, ct);
|
||||
return extension switch
|
||||
{
|
||||
".jpg" or ".jpeg" => header.AsSpan().StartsWith(new byte[] { 0xff, 0xd8, 0xff }),
|
||||
".png" => header.AsSpan().StartsWith(new byte[] { 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a }),
|
||||
".pdf" => header.AsSpan().StartsWith("%PDF-"u8),
|
||||
".heic" => IsHeic(header, stream.Length),
|
||||
".docx" => IsDocx(stream, header),
|
||||
_ => false,
|
||||
};
|
||||
}
|
||||
|
||||
private static bool IsHeic(ReadOnlySpan<byte> header, long length)
|
||||
{
|
||||
if (header.Length < 16 || !header.Slice(4, 4).SequenceEqual("ftyp"u8))
|
||||
return false;
|
||||
|
||||
var boxLength = BinaryPrimitives.ReadUInt32BigEndian(header);
|
||||
if (boxLength < 16 || boxLength > length)
|
||||
return false;
|
||||
|
||||
for (var offset = 8; offset + 4 <= Math.Min(boxLength, header.Length); offset += 4)
|
||||
{
|
||||
if (offset == 12)
|
||||
continue; // minor_version
|
||||
var brand = header.Slice(offset, 4);
|
||||
if (brand.SequenceEqual("heic"u8) || brand.SequenceEqual("heix"u8) ||
|
||||
brand.SequenceEqual("hevc"u8) || brand.SequenceEqual("hevx"u8))
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private static bool IsDocx(Stream stream, ReadOnlySpan<byte> header)
|
||||
{
|
||||
if (!header.StartsWith(new byte[] { 0x50, 0x4b, 0x03, 0x04 }))
|
||||
return false;
|
||||
|
||||
stream.Position = 0;
|
||||
try
|
||||
{
|
||||
using var zip = new ZipArchive(stream, ZipArchiveMode.Read, leaveOpen: true);
|
||||
return zip.GetEntry("[Content_Types].xml") is not null && zip.GetEntry("word/document.xml") is not null;
|
||||
}
|
||||
catch (InvalidDataException)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -10,6 +10,8 @@
|
||||
<PackageReference Include="MySqlConnector" />
|
||||
<PackageReference Include="EFCore.NamingConventions" />
|
||||
<PackageReference Include="BCrypt.Net-Next" />
|
||||
<PackageReference Include="MailKit" />
|
||||
<PackageReference Include="FirebaseAdmin" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" />
|
||||
<PackageReference Include="Microsoft.Extensions.Caching.Memory" />
|
||||
<PackageReference Include="Microsoft.Extensions.Hosting.Abstractions" />
|
||||
|
||||
@@ -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<string> InvalidTokens);
|
||||
|
||||
internal sealed class FirebasePushSender(FirebaseApp app) : IDisposable
|
||||
{
|
||||
public static FirebasePushSender Create(string serviceAccountJson)
|
||||
{
|
||||
ServiceAccountCredential credential;
|
||||
try
|
||||
{
|
||||
credential = CredentialFactory.FromJson<ServiceAccountCredential>(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<PushDeliveryResult> SendAsync(Notification notification, string[] tokens, CancellationToken ct)
|
||||
{
|
||||
var data = new Dictionary<string, string>
|
||||
{
|
||||
["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<string>();
|
||||
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();
|
||||
}
|
||||
@@ -9,7 +9,7 @@ using Microsoft.Extensions.Logging;
|
||||
namespace Helpdesk.Infrastructure.Persistence;
|
||||
|
||||
/// <summary>
|
||||
/// Při startu vytvoří účet administrátora z <c>ADMIN_EMAIL</c> a <c>ADMIN_PASSWORD</c>, pokud ještě neexistuje.
|
||||
/// Při startu vytvoří účet administrátora z <c>ADMIN_EMAIL</c> a <c>ADMIN_PASSWORD</c>, pokud není žádný aktivní administrátor.
|
||||
/// Admin není v migracích, aby hash hesla vznikl stejným algoritmem jako u ostatních uživatelů.
|
||||
/// </summary>
|
||||
internal sealed partial class AdminSeeder(
|
||||
@@ -29,7 +29,8 @@ internal sealed partial class AdminSeeder(
|
||||
var hasher = scope.ServiceProvider.GetRequiredService<IPasswordHasher>();
|
||||
|
||||
var normalized = User.NormalizeEmail(email);
|
||||
if (await db.Users.AnyAsync(u => u.EmailNormalized == normalized, cancellationToken))
|
||||
if (await db.Users.AnyAsync(u => u.EmailNormalized == normalized ||
|
||||
(u.Role == UserRole.Admin && u.IsActive), cancellationToken))
|
||||
return;
|
||||
|
||||
var admin = User.Create(email, hasher.Hash(password), "Administrátor", "Systému", UserRole.Admin);
|
||||
|
||||
@@ -1,10 +1,18 @@
|
||||
using System.Data;
|
||||
using Helpdesk.Application.Abstractions;
|
||||
using Helpdesk.Application.Common;
|
||||
using Helpdesk.Application.Statistics;
|
||||
using Helpdesk.Domain.Auth;
|
||||
using Helpdesk.Domain.Catalogs;
|
||||
using Helpdesk.Domain.Issues;
|
||||
using Helpdesk.Domain.Notifications;
|
||||
using Helpdesk.Domain.Proposals;
|
||||
using Helpdesk.Domain.Users;
|
||||
using Helpdesk.Infrastructure.Security;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Storage;
|
||||
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
|
||||
using MySqlConnector;
|
||||
|
||||
namespace Helpdesk.Infrastructure.Persistence;
|
||||
|
||||
@@ -20,6 +28,53 @@ public sealed class HelpdeskDbContext(DbContextOptions<HelpdeskDbContext> option
|
||||
public DbSet<Building> Buildings => Set<Building>();
|
||||
public DbSet<IssueCategory> IssueCategories => Set<IssueCategory>();
|
||||
public DbSet<ProposalCategory> ProposalCategories => Set<ProposalCategory>();
|
||||
public DbSet<Issue> Issues => Set<Issue>();
|
||||
public DbSet<IssueEvent> IssueEvents => Set<IssueEvent>();
|
||||
public IQueryable<IssueTiming> IssueTimings => Set<IssueTiming>();
|
||||
public DbSet<Attachment> Attachments => Set<Attachment>();
|
||||
public DbSet<Proposal> Proposals => Set<Proposal>();
|
||||
public DbSet<ProposalEvent> ProposalEvents => Set<ProposalEvent>();
|
||||
public DbSet<ProposalVote> ProposalVotes => Set<ProposalVote>();
|
||||
public DbSet<ProposalScore> ProposalScores => Set<ProposalScore>();
|
||||
public DbSet<Notification> Notifications => Set<Notification>();
|
||||
public DbSet<NotificationDelivery> NotificationDeliveries => Set<NotificationDelivery>();
|
||||
public DbSet<PushDevice> PushDevices => Set<PushDevice>();
|
||||
|
||||
public override async Task<int> 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.");
|
||||
}
|
||||
catch (DbUpdateException exception) when (
|
||||
exception.InnerException is MySqlException { ErrorCode: MySqlErrorCode.DuplicateKeyEntry } &&
|
||||
exception.Entries is [var entry] && entry.Entity is User)
|
||||
{
|
||||
throw new ConflictException("Účet s tímto e-mailem už existuje.");
|
||||
}
|
||||
}
|
||||
|
||||
public Task<IDbContextTransaction> BeginWriteAsync(CancellationToken ct) =>
|
||||
Database.BeginTransactionAsync(IsolationLevel.ReadCommitted, ct);
|
||||
|
||||
public async Task<User?> LockUserAsync(int id, CancellationToken ct)
|
||||
{
|
||||
var rows = await Users.FromSql($"SELECT * FROM app_user WHERE id = {id} FOR UPDATE").ToListAsync(ct);
|
||||
return rows.SingleOrDefault();
|
||||
}
|
||||
|
||||
public async Task<Proposal?> LockProposalAsync(int id, CancellationToken ct)
|
||||
{
|
||||
// Všechny zápisy nad návrhem zamykají stejný řádek před čtením stavu a hlasů.
|
||||
var rows = await Proposals.FromSql($"SELECT * FROM proposal WHERE id = {id} FOR UPDATE").ToListAsync(ct);
|
||||
return rows.SingleOrDefault();
|
||||
}
|
||||
|
||||
protected override void OnModelCreating(ModelBuilder modelBuilder)
|
||||
{
|
||||
@@ -28,8 +83,33 @@ public sealed class HelpdeskDbContext(DbContextOptions<HelpdeskDbContext> option
|
||||
modelBuilder.ApplyConfiguration(new BuildingConfiguration());
|
||||
modelBuilder.ApplyConfiguration(new IssueCategoryConfiguration());
|
||||
modelBuilder.ApplyConfiguration(new ProposalCategoryConfiguration());
|
||||
modelBuilder.ApplyConfiguration(new IssueConfiguration());
|
||||
modelBuilder.ApplyConfiguration(new IssueEventConfiguration());
|
||||
modelBuilder.Entity<IssueTiming>().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());
|
||||
modelBuilder.ApplyConfiguration(new ProposalVoteConfiguration());
|
||||
modelBuilder.Entity<ProposalScore>().HasNoKey().ToView("v_proposal_score");
|
||||
modelBuilder.ApplyConfiguration(new NotificationConfiguration());
|
||||
modelBuilder.ApplyConfiguration(new NotificationDeliveryConfiguration());
|
||||
var pushDevice = modelBuilder.Entity<PushDevice>();
|
||||
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".
|
||||
|
||||
@@ -0,0 +1,79 @@
|
||||
using Helpdesk.Domain.Catalogs;
|
||||
using Helpdesk.Domain.Issues;
|
||||
using Helpdesk.Domain.Notifications;
|
||||
using Helpdesk.Domain.Proposals;
|
||||
using Helpdesk.Domain.Users;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Metadata.Builders;
|
||||
|
||||
namespace Helpdesk.Infrastructure.Persistence;
|
||||
|
||||
internal sealed class IssueConfiguration : IEntityTypeConfiguration<Issue>
|
||||
{
|
||||
public void Configure(EntityTypeBuilder<Issue> b)
|
||||
{
|
||||
b.ToTable("issue");
|
||||
b.Property(x => x.Title).HasMaxLength(200);
|
||||
b.Property(x => x.Description).HasColumnType("text");
|
||||
b.Property(x => x.LocationDetail).HasMaxLength(255);
|
||||
b.Property(x => x.Status).HasConversion<EnumCodeConverter<IssueStatus>>().HasMaxLength(30);
|
||||
b.Property(x => x.Priority).HasConversion<EnumCodeConverter<IssuePriority>>().HasMaxLength(10);
|
||||
b.Property(x => x.RowVersion).IsConcurrencyToken();
|
||||
b.HasOne<IssueCategory>().WithMany().HasForeignKey(x => x.CategoryId);
|
||||
b.HasOne<Building>().WithMany().HasForeignKey(x => x.BuildingId);
|
||||
b.HasOne<User>().WithMany().HasForeignKey(x => x.ReporterId);
|
||||
b.HasOne<User>().WithMany().HasForeignKey(x => x.AssigneeId);
|
||||
}
|
||||
}
|
||||
|
||||
internal sealed class IssueEventConfiguration : IEntityTypeConfiguration<IssueEvent>
|
||||
{
|
||||
public void Configure(EntityTypeBuilder<IssueEvent> b)
|
||||
{
|
||||
b.ToTable("issue_event");
|
||||
b.Property(x => x.EventType).HasConversion<EnumCodeConverter<IssueEventType>>().HasMaxLength(20);
|
||||
b.Property(x => x.FromStatus).HasConversion<EnumCodeConverter<IssueStatus>>().HasMaxLength(30);
|
||||
b.Property(x => x.ToStatus).HasConversion<EnumCodeConverter<IssueStatus>>().HasMaxLength(30);
|
||||
b.Property(x => x.Note).HasColumnType("text");
|
||||
b.HasOne(x => x.Issue).WithMany().HasForeignKey(x => x.IssueId);
|
||||
b.HasOne<User>().WithMany().HasForeignKey(x => x.ActorId);
|
||||
}
|
||||
}
|
||||
|
||||
internal sealed class AttachmentConfiguration : IEntityTypeConfiguration<Attachment>
|
||||
{
|
||||
public void Configure(EntityTypeBuilder<Attachment> b)
|
||||
{
|
||||
b.ToTable("attachment");
|
||||
b.Property(x => x.OriginalFileName).HasMaxLength(255);
|
||||
b.Property(x => x.StoredFileName).HasMaxLength(36);
|
||||
b.Property(x => x.ContentType).HasMaxLength(100);
|
||||
b.HasOne(x => x.Issue).WithMany().HasForeignKey(x => x.IssueId);
|
||||
}
|
||||
}
|
||||
|
||||
internal sealed class NotificationConfiguration : IEntityTypeConfiguration<Notification>
|
||||
{
|
||||
public void Configure(EntityTypeBuilder<Notification> b)
|
||||
{
|
||||
b.ToTable("notification");
|
||||
b.Property(x => x.Type).HasConversion<EnumCodeConverter<NotificationType>>().HasMaxLength(40);
|
||||
b.Property(x => x.Title).HasMaxLength(200);
|
||||
b.Property(x => x.Message).HasMaxLength(1000);
|
||||
b.HasOne(x => x.Issue).WithMany().HasForeignKey(x => x.IssueId).IsRequired(false);
|
||||
b.HasOne<Proposal>().WithMany().HasForeignKey(x => x.ProposalId);
|
||||
b.HasOne<User>().WithMany().HasForeignKey(x => x.UserId);
|
||||
}
|
||||
}
|
||||
|
||||
internal sealed class NotificationDeliveryConfiguration : IEntityTypeConfiguration<NotificationDelivery>
|
||||
{
|
||||
public void Configure(EntityTypeBuilder<NotificationDelivery> b)
|
||||
{
|
||||
b.ToTable("notification_delivery");
|
||||
b.Property(x => x.Channel).HasConversion<EnumCodeConverter<DeliveryChannel>>().HasMaxLength(10);
|
||||
b.Property(x => x.Status).HasConversion<EnumCodeConverter<DeliveryStatus>>().HasMaxLength(10);
|
||||
b.Property(x => x.LastError).HasMaxLength(1000);
|
||||
b.HasOne(x => x.Notification).WithMany().HasForeignKey(x => x.NotificationId);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
using Helpdesk.Domain.Catalogs;
|
||||
using Helpdesk.Domain.Proposals;
|
||||
using Helpdesk.Domain.Users;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Metadata.Builders;
|
||||
|
||||
namespace Helpdesk.Infrastructure.Persistence;
|
||||
|
||||
internal sealed class ProposalConfiguration : IEntityTypeConfiguration<Proposal>
|
||||
{
|
||||
public void Configure(EntityTypeBuilder<Proposal> b)
|
||||
{
|
||||
b.ToTable("proposal");
|
||||
b.Property(x => x.Title).HasMaxLength(200);
|
||||
b.Property(x => x.Description).HasColumnType("text");
|
||||
b.Property(x => x.Status).HasConversion<EnumCodeConverter<ProposalStatus>>().HasMaxLength(30);
|
||||
b.HasOne<ProposalCategory>().WithMany().HasForeignKey(x => x.CategoryId);
|
||||
b.HasOne<User>().WithMany().HasForeignKey(x => x.AuthorId);
|
||||
}
|
||||
}
|
||||
|
||||
internal sealed class ProposalEventConfiguration : IEntityTypeConfiguration<ProposalEvent>
|
||||
{
|
||||
public void Configure(EntityTypeBuilder<ProposalEvent> b)
|
||||
{
|
||||
b.ToTable("proposal_event");
|
||||
b.Property(x => x.EventType).HasConversion<EnumCodeConverter<ProposalEventType>>().HasMaxLength(20);
|
||||
b.Property(x => x.FromStatus).HasConversion<EnumCodeConverter<ProposalStatus>>().HasMaxLength(30);
|
||||
b.Property(x => x.ToStatus).HasConversion<EnumCodeConverter<ProposalStatus>>().HasMaxLength(30);
|
||||
b.Property(x => x.Note).HasColumnType("text");
|
||||
b.HasOne(x => x.Proposal).WithMany().HasForeignKey(x => x.ProposalId);
|
||||
b.HasOne<User>().WithMany().HasForeignKey(x => x.ActorId);
|
||||
}
|
||||
}
|
||||
|
||||
internal sealed class ProposalVoteConfiguration : IEntityTypeConfiguration<ProposalVote>
|
||||
{
|
||||
public void Configure(EntityTypeBuilder<ProposalVote> b)
|
||||
{
|
||||
b.ToTable("proposal_vote");
|
||||
b.HasKey(x => new { x.ProposalId, x.UserId });
|
||||
b.Property(x => x.Value).HasColumnType("tinyint");
|
||||
b.HasOne<Proposal>().WithMany().HasForeignKey(x => x.ProposalId);
|
||||
b.HasOne<User>().WithMany().HasForeignKey(x => x.UserId);
|
||||
}
|
||||
}
|
||||
@@ -26,8 +26,9 @@ internal sealed class RevokedTokenStore(TimeProvider clock) : IRevokedTokenStore
|
||||
|
||||
public void Add(string jti, DateTime expiresAt)
|
||||
{
|
||||
if (expiresAt > clock.GetUtcNow().UtcDateTime)
|
||||
_revoked[jti] = expiresAt;
|
||||
var rejectUntil = expiresAt + JwtTokenService.ClockSkew;
|
||||
if (rejectUntil > clock.GetUtcNow().UtcDateTime)
|
||||
_revoked[jti] = rejectUntil;
|
||||
}
|
||||
|
||||
private void PruneOccasionally()
|
||||
@@ -52,10 +53,10 @@ internal sealed class RevokedTokenStoreLoader(IServiceScopeFactory scopes, IRevo
|
||||
{
|
||||
using var scope = scopes.CreateScope();
|
||||
var db = scope.ServiceProvider.GetRequiredService<HelpdeskDbContext>();
|
||||
var now = clock.GetUtcNow().UtcDateTime;
|
||||
var earliestExpiry = clock.GetUtcNow().UtcDateTime - JwtTokenService.ClockSkew;
|
||||
|
||||
var revoked = await db.AuthTokens.AsNoTracking()
|
||||
.Where(t => t.TokenType == TokenType.Access && t.RevokedAt != null && t.ExpiresAt > now)
|
||||
.Where(t => t.TokenType == TokenType.Access && t.RevokedAt != null && t.ExpiresAt > earliestExpiry)
|
||||
.Select(t => new { t.Jti, t.ExpiresAt })
|
||||
.ToListAsync(cancellationToken);
|
||||
|
||||
|
||||
@@ -0,0 +1,153 @@
|
||||
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.Users;
|
||||
using Helpdesk.Infrastructure.Persistence;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using static Helpdesk.IntegrationTests.BackendFixture;
|
||||
|
||||
namespace Helpdesk.IntegrationTests;
|
||||
|
||||
public sealed class AdminAccountLifecycleTests(BackendFixture fixture) : IClassFixture<BackendFixture>
|
||||
{
|
||||
private const string Users = "/api/v1/admin/users";
|
||||
|
||||
[Fact]
|
||||
public async Task AdminCanCreateEditAndAnonymizeAccountsWhileKeepingIssueHistory()
|
||||
{
|
||||
using var anonymous = fixture.CreateClient();
|
||||
var administrator = await LoginAsync(anonymous, AdminEmail);
|
||||
using var admin = fixture.CreateClient(administrator.AccessToken);
|
||||
var request = new SaveAdminUserRequest("[email protected]", "Jan", "Novák", "+420 123 456 789",
|
||||
"STUDENT", true, true, false, Password);
|
||||
await ExpectAsync(anonymous.PostAsJsonAsync(Users, request, Cancellation), HttpStatusCode.Unauthorized);
|
||||
var created = await ReadAsync<AdminUserDetailsDto>(admin.PostAsJsonAsync(Users, request, Cancellation), HttpStatusCode.Created);
|
||||
var path = $"{Users}/{created.Id}";
|
||||
Assert.Equal(created, await ReadAsync<AdminUserDetailsDto>(admin.GetAsync(path, Cancellation)));
|
||||
Assert.Null(created.VerificationEmailSent);
|
||||
await ExpectAsync(admin.PostAsync(path + "/email-confirmation", null, Cancellation), HttpStatusCode.Conflict);
|
||||
await ExpectAsync(admin.PostAsJsonAsync(Users, request with { Email = "[email protected]" }, Cancellation), HttpStatusCode.Conflict);
|
||||
|
||||
var login = await LoginAsync(anonymous, request.Email);
|
||||
using var student = fixture.CreateClient(login.AccessToken);
|
||||
await ExpectAsync(student.DeleteAsync(path, Cancellation), HttpStatusCode.Forbidden);
|
||||
var category = (await ReadAsync<CategoryDto[]>(student.GetAsync("/api/v1/issue-categories", Cancellation)))[0];
|
||||
var issue = await ReadAsync<IssueDetail>(student.PostAsJsonAsync("/api/v1/issues",
|
||||
new CreateIssueRequest("Rozbitý zámek", "Učebnu nelze otevřít.", category.Id, null, null), Cancellation), HttpStatusCode.Created);
|
||||
|
||||
var edit = request with { Email = "[email protected]", FirstName = "Jana", Role = "TEACHER", Password = "New-password-for-test" };
|
||||
var saved = await ReadAsync<AdminUserDetailsDto>(admin.PutAsJsonAsync(path, edit, Cancellation));
|
||||
Assert.False(saved.EmailConfirmed);
|
||||
Assert.True(saved.VerificationEmailSent);
|
||||
await ExpectAsync(student.GetAsync("/api/v1/users/me", Cancellation), HttpStatusCode.Unauthorized);
|
||||
await ExpectAsync(anonymous.PostAsJsonAsync("/api/v1/auth/login", new LoginRequest(edit.Email, Password), Cancellation),
|
||||
HttpStatusCode.Unauthorized);
|
||||
await ExpectAsync(anonymous.PostAsJsonAsync("/api/v1/auth/login", new LoginRequest(edit.Email, edit.Password!), Cancellation),
|
||||
HttpStatusCode.Forbidden);
|
||||
await ConfirmEmailAsync(anonymous, await fixture.TakeConfirmationTokenAsync(edit.Email));
|
||||
var edited = await ReadAsync<AuthResponse>(anonymous.PostAsJsonAsync("/api/v1/auth/login",
|
||||
new LoginRequest(edit.Email, edit.Password!), Cancellation));
|
||||
Assert.Equal((created.Id, edit.Email, edit.FirstName, edit.Role), (edited.User.Id, edited.User.Email, edited.User.FirstName, edited.User.Role));
|
||||
using var teacher = fixture.CreateClient(edited.AccessToken);
|
||||
await ExpectAsync(teacher.PostAsJsonAsync("/api/v1/devices", new { token = "test-device-token" }, Cancellation),
|
||||
HttpStatusCode.NoContent);
|
||||
|
||||
await ExpectAsync(admin.DeleteAsync(path, Cancellation), HttpStatusCode.NoContent);
|
||||
await ExpectAsync(admin.GetAsync(path, Cancellation), HttpStatusCode.NotFound);
|
||||
await ExpectAsync(admin.PutAsJsonAsync(path + "/active", new SetActiveRequest(true), Cancellation), HttpStatusCode.NotFound);
|
||||
await ExpectAsync(teacher.GetAsync("/api/v1/users/me", Cancellation), HttpStatusCode.Unauthorized);
|
||||
await ExpectAsync(anonymous.PostAsJsonAsync("/api/v1/auth/refresh", new RefreshTokenRequest(edited.RefreshToken), Cancellation),
|
||||
HttpStatusCode.Unauthorized);
|
||||
var list = await ReadAsync<PagedResult<AdminUserDto>>(admin.GetAsync(Users, Cancellation));
|
||||
Assert.DoesNotContain(list.Items, user => user.Id == created.Id);
|
||||
var issuePath = $"/api/v1/issues/{issue.Id}";
|
||||
Assert.Equal(created.Id, (await ReadAsync<IssueDetail>(admin.GetAsync(issuePath, Cancellation))).ReporterId);
|
||||
var entry = Assert.Single(await ReadAsync<IssueEventDto[]>(admin.GetAsync(issuePath + "/events", Cancellation)));
|
||||
Assert.Equal((created.Id, "Smazaný uživatel"), (entry.ActorId, entry.ActorName));
|
||||
var replacement = await ReadAsync<AdminUserDetailsDto>(admin.PostAsJsonAsync(Users, request with { Email = edit.Email }, Cancellation),
|
||||
HttpStatusCode.Created);
|
||||
Assert.NotEqual(created.Id, replacement.Id);
|
||||
|
||||
await using var scope = fixture.Services.CreateAsyncScope();
|
||||
var db = scope.ServiceProvider.GetRequiredService<HelpdeskDbContext>();
|
||||
var retained = await db.Users.AsNoTracking().SingleAsync(user => user.Id == created.Id, Cancellation);
|
||||
Assert.True(retained.IsDeleted);
|
||||
Assert.False(retained.IsActive);
|
||||
Assert.Null(retained.Phone);
|
||||
Assert.Empty(retained.PasswordHash);
|
||||
Assert.NotEqual(edit.Email, retained.Email);
|
||||
Assert.False(await db.PushDevices.AnyAsync(device => device.UserId == created.Id, Cancellation));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AdminCreationSendsAnActivationLinkAndFailedDeliveryCanBeRetried()
|
||||
{
|
||||
using var anonymous = fixture.CreateClient();
|
||||
using var admin = fixture.CreateClient((await LoginAsync(anonymous, AdminEmail)).AccessToken);
|
||||
var request = new SaveAdminUserRequest("[email protected]", "Test", "Uživatel", null,
|
||||
"STUDENT", true, false, false, Password);
|
||||
var created = await ReadAsync<AdminUserDetailsDto>(admin.PostAsJsonAsync(Users, request, Cancellation), HttpStatusCode.Created);
|
||||
Assert.True(created.VerificationEmailSent);
|
||||
Assert.False(created.EmailConfirmed);
|
||||
var originalToken = await fixture.TakeConfirmationTokenAsync(request.Email);
|
||||
|
||||
var moved = request with { Email = "[email protected]", Password = null };
|
||||
var updated = await ReadAsync<AdminUserDetailsDto>(admin.PutAsJsonAsync($"{Users}/{created.Id}", moved, Cancellation));
|
||||
Assert.True(updated.VerificationEmailSent);
|
||||
await ConfirmEmailAsync(anonymous, originalToken, HttpStatusCode.BadRequest);
|
||||
await ConfirmEmailAsync(anonymous, await fixture.TakeConfirmationTokenAsync(moved.Email));
|
||||
Assert.Equal(created.Id, (await LoginAsync(anonymous, moved.Email)).User.Id);
|
||||
|
||||
var retry = request with { Email = "[email protected]" };
|
||||
fixture.FailNextEmail(retry.Email, "SMTP_UNAVAILABLE", retryable: true);
|
||||
var saved = await ReadAsync<AdminUserDetailsDto>(admin.PostAsJsonAsync(Users, retry, Cancellation), HttpStatusCode.Created);
|
||||
Assert.False(saved.VerificationEmailSent);
|
||||
Assert.Equal(retry.Email, (await ReadAsync<AdminUserDetailsDto>(admin.GetAsync($"{Users}/{saved.Id}", Cancellation))).Email);
|
||||
await ExpectAsync(admin.PostAsync($"{Users}/{saved.Id}/email-confirmation", null, Cancellation), HttpStatusCode.NoContent);
|
||||
await ConfirmEmailAsync(anonymous, await fixture.TakeConfirmationTokenAsync(retry.Email));
|
||||
Assert.Equal(saved.Id, (await LoginAsync(anonymous, retry.Email)).User.Id);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task BulkActionsUpdateAllSelectedAccountsAndRejectTheEntireInvalidSelection()
|
||||
{
|
||||
using var anonymous = fixture.CreateClient();
|
||||
var administrator = await LoginAsync(anonymous, AdminEmail);
|
||||
using var admin = fixture.CreateClient(administrator.AccessToken);
|
||||
var request = new SaveAdminUserRequest("[email protected]", "První", "Účet", null, "STUDENT", true, true, false, Password);
|
||||
var first = await ReadAsync<AdminUserDetailsDto>(admin.PostAsJsonAsync(Users, request, Cancellation), HttpStatusCode.Created);
|
||||
var second = await ReadAsync<AdminUserDetailsDto>(admin.PostAsJsonAsync(Users, request with { Email = "[email protected]" }, Cancellation),
|
||||
HttpStatusCode.Created);
|
||||
var both = new[] { first.Id, second.Id };
|
||||
|
||||
await ExpectAsync(admin.PostAsJsonAsync(Users + "/bulk",
|
||||
new BulkAdminUsersRequest([first.Id, int.MaxValue], "deactivate", null), Cancellation), HttpStatusCode.NotFound);
|
||||
Assert.True((await ReadAsync<AdminUserDetailsDto>(admin.GetAsync($"{Users}/{first.Id}", Cancellation))).IsActive);
|
||||
await ExpectAsync(admin.PostAsJsonAsync(Users + "/bulk",
|
||||
new BulkAdminUsersRequest([first.Id, administrator.User.Id], "delete", null), Cancellation), HttpStatusCode.Conflict);
|
||||
await ExpectAsync(admin.PostAsJsonAsync(Users + "/bulk",
|
||||
new BulkAdminUsersRequest(both, "role", "TEACHER"), Cancellation), HttpStatusCode.NoContent);
|
||||
foreach (var id in both)
|
||||
Assert.Equal("TEACHER", (await ReadAsync<AdminUserDetailsDto>(admin.GetAsync($"{Users}/{id}", Cancellation))).Role);
|
||||
|
||||
foreach (var (action, active) in new[] { ("deactivate", false), ("activate", true) })
|
||||
{
|
||||
await ExpectAsync(admin.PostAsJsonAsync(Users + "/bulk",
|
||||
new BulkAdminUsersRequest(both, action, null), Cancellation), HttpStatusCode.NoContent);
|
||||
foreach (var id in both)
|
||||
Assert.Equal(active, (await ReadAsync<AdminUserDetailsDto>(admin.GetAsync($"{Users}/{id}", Cancellation))).IsActive);
|
||||
}
|
||||
|
||||
await ExpectAsync(admin.PostAsJsonAsync(Users + "/bulk",
|
||||
new BulkAdminUsersRequest(both, "delete", null), Cancellation), HttpStatusCode.NoContent);
|
||||
foreach (var id in both)
|
||||
await ExpectAsync(admin.GetAsync($"{Users}/{id}", Cancellation), HttpStatusCode.NotFound);
|
||||
}
|
||||
|
||||
private static Task ConfirmEmailAsync(HttpClient client, string token, HttpStatusCode expected = HttpStatusCode.NoContent) =>
|
||||
ExpectAsync(client.PostAsJsonAsync("/api/v1/auth/confirm-email", new EmailTokenRequest(token), Cancellation), expected);
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
using System.Net;
|
||||
using System.Net.Http.Json;
|
||||
using System.Text;
|
||||
using Helpdesk.Application.Auth;
|
||||
using Helpdesk.Application.Catalogs;
|
||||
using Helpdesk.Application.Common;
|
||||
using Helpdesk.Application.Users;
|
||||
using Helpdesk.Infrastructure.Persistence;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using static Helpdesk.IntegrationTests.BackendFixture;
|
||||
|
||||
namespace Helpdesk.IntegrationTests;
|
||||
|
||||
public sealed class AdministrationTests(BackendFixture fixture) : IClassFixture<BackendFixture>
|
||||
{
|
||||
[Theory]
|
||||
[InlineData("/api/v1/issue-categories")]
|
||||
[InlineData("/api/v1/proposal-categories")]
|
||||
public async Task AdministratorsCanManageCategories(string route)
|
||||
{
|
||||
using var anonymous = fixture.CreateClient();
|
||||
using var admin = fixture.CreateClient((await LoginAsync(anonymous, AdminEmail)).AccessToken);
|
||||
var user = await fixture.RegisterAsync(anonymous);
|
||||
using var member = fixture.CreateClient((await LoginAsync(anonymous, user.Email)).AccessToken);
|
||||
var request = new SaveCategoryRequest("Testovací kategorie", "Popis");
|
||||
await ExpectAsync(member.PostAsJsonAsync(route, request, Cancellation), HttpStatusCode.Forbidden);
|
||||
var category = await ReadAsync<CategoryDto>(admin.PostAsJsonAsync(route, request, Cancellation), HttpStatusCode.Created);
|
||||
await ExpectAsync(admin.PostAsJsonAsync(route, request, Cancellation), HttpStatusCode.Conflict);
|
||||
var path = $"{route}/{category.Id}";
|
||||
var edited = await ReadAsync<CategoryDto>(admin.PutAsJsonAsync(path, request with { Name = "Upravená kategorie" }, Cancellation));
|
||||
Assert.Equal("Upravená kategorie", edited.Name);
|
||||
await ExpectAsync(admin.DeleteAsync(path, Cancellation), HttpStatusCode.NoContent);
|
||||
|
||||
var active = await ReadAsync<CategoryDto[]>(member.GetAsync(route + "?includeInactive=true", Cancellation));
|
||||
var all = await ReadAsync<CategoryDto[]>(admin.GetAsync(route + "?includeInactive=true", Cancellation));
|
||||
Assert.DoesNotContain(active, item => item.Id == category.Id);
|
||||
Assert.False(Assert.Single(all, item => item.Id == category.Id).IsActive);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task BuildingCodesAreUniqueAndInactiveBuildingsStayAvailableToTheAdministrator()
|
||||
{
|
||||
using var anonymous = fixture.CreateClient();
|
||||
using var admin = fixture.CreateClient((await LoginAsync(anonymous, AdminEmail)).AccessToken);
|
||||
const string route = "/api/v1/buildings";
|
||||
var request = new SaveBuildingRequest("TEST", "Testovací budova", null);
|
||||
var building = await ReadAsync<BuildingDto>(admin.PostAsJsonAsync(route, request, Cancellation), HttpStatusCode.Created);
|
||||
await ExpectAsync(admin.PostAsJsonAsync(route, request with { Code = " TEST " }, Cancellation), HttpStatusCode.Conflict);
|
||||
var path = $"{route}/{building.Id}";
|
||||
var edited = await ReadAsync<BuildingDto>(admin.PutAsJsonAsync(path, request with { Address = "Náměstí 1" }, Cancellation));
|
||||
Assert.Equal("Náměstí 1", edited.Address);
|
||||
await ExpectAsync(admin.DeleteAsync(path, Cancellation), HttpStatusCode.NoContent);
|
||||
var active = await ReadAsync<BuildingDto[]>(admin.GetAsync(route, Cancellation));
|
||||
var all = await ReadAsync<BuildingDto[]>(admin.GetAsync(route + "?includeInactive=true", Cancellation));
|
||||
Assert.DoesNotContain(active, item => item.Id == building.Id);
|
||||
Assert.False(Assert.Single(all, item => item.Id == building.Id).IsActive);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ProfileDataRoundTripsAndDeactivationRevokesTheSession()
|
||||
{
|
||||
using var anonymous = fixture.CreateClient();
|
||||
using var admin = fixture.CreateClient((await LoginAsync(anonymous, AdminEmail)).AccessToken);
|
||||
var user = await fixture.RegisterAsync(anonymous);
|
||||
using var member = fixture.CreateClient((await LoginAsync(anonymous, user.Email)).AccessToken);
|
||||
const string profile = "/api/v1/users/me";
|
||||
const string phone = "+420 123 456 789";
|
||||
var request = new UpdateProfileRequest("Jana", "Nováková", phone, false);
|
||||
var validation = await ReadAsync<ValidationProblemDetails>(member.PutAsJsonAsync(profile,
|
||||
request with { Phone = "invalid" }, Cancellation), HttpStatusCode.BadRequest);
|
||||
Assert.Contains("phone", validation.Errors.Keys);
|
||||
var updated = await ReadAsync<UserDto>(member.PutAsJsonAsync(profile, request, Cancellation));
|
||||
Assert.Equal(updated, await ReadAsync<UserDto>(member.GetAsync(profile, Cancellation)));
|
||||
Assert.Equal((request.FirstName, request.LastName, phone, false),
|
||||
(updated.FirstName, updated.LastName, updated.Phone, updated.EmailNotificationsEnabled));
|
||||
|
||||
await using var scope = fixture.Services.CreateAsyncScope();
|
||||
var db = scope.ServiceProvider.GetRequiredService<HelpdeskDbContext>();
|
||||
var encrypted = await db.Database.SqlQuery<byte[]>($"SELECT phone_encrypted AS Value FROM app_user WHERE id = {user.Id}")
|
||||
.SingleAsync(Cancellation);
|
||||
Assert.NotEmpty(encrypted);
|
||||
Assert.False(Encoding.UTF8.GetBytes(phone).SequenceEqual(encrypted));
|
||||
|
||||
var search = $"/api/v1/admin/users?q={Uri.EscapeDataString(user.Email)}&role=STUDENT&pageSize=1";
|
||||
await ExpectAsync(member.GetAsync(search, Cancellation), HttpStatusCode.Forbidden);
|
||||
var page = await ReadAsync<PagedResult<AdminUserDto>>(admin.GetAsync(search, Cancellation));
|
||||
Assert.Equal(user.Id, Assert.Single(page.Items).Id);
|
||||
var activation = $"/api/v1/admin/users/{user.Id}/active";
|
||||
await ExpectAsync(admin.PutAsJsonAsync(activation, new SetActiveRequest(false), Cancellation), HttpStatusCode.NoContent);
|
||||
await ExpectAsync(member.GetAsync(profile, Cancellation), HttpStatusCode.Unauthorized);
|
||||
await ExpectAsync(anonymous.PostAsJsonAsync("/api/v1/auth/login", new LoginRequest(user.Email, Password), Cancellation),
|
||||
HttpStatusCode.Forbidden);
|
||||
await ExpectAsync(admin.PutAsJsonAsync(activation, new SetActiveRequest(true), Cancellation), HttpStatusCode.NoContent);
|
||||
Assert.Equal(user.Id, (await LoginAsync(anonymous, user.Email)).User.Id);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
using System.Globalization;
|
||||
using System.IO.Compression;
|
||||
using System.Net;
|
||||
using System.Net.Http.Json;
|
||||
using Helpdesk.Application.Catalogs;
|
||||
using Helpdesk.Application.Issues;
|
||||
using Helpdesk.Infrastructure.Persistence;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using static Helpdesk.IntegrationTests.BackendFixture;
|
||||
|
||||
namespace Helpdesk.IntegrationTests;
|
||||
|
||||
public sealed class AttachmentTests(BackendFixture fixture) : IClassFixture<BackendFixture>
|
||||
{
|
||||
[Fact]
|
||||
public async Task AttachmentsRespectFormatAndAccessAndFailedBatchesAreNotSaved()
|
||||
{
|
||||
using var anonymous = fixture.CreateClient();
|
||||
using var admin = fixture.CreateClient((await LoginAsync(anonymous, AdminEmail)).AccessToken);
|
||||
var authorUser = await fixture.RegisterAsync(anonymous);
|
||||
var otherUser = await fixture.RegisterAsync(anonymous);
|
||||
using var author = fixture.CreateClient((await LoginAsync(anonymous, authorUser.Email)).AccessToken);
|
||||
using var other = fixture.CreateClient((await LoginAsync(anonymous, otherUser.Email)).AccessToken);
|
||||
var categories = await ReadAsync<CategoryDto[]>(author.GetAsync("/api/v1/issue-categories", Cancellation));
|
||||
var png = Convert.FromBase64String("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAusB9Wl6t1sAAAAASUVORK5CYII=");
|
||||
using var createForm = new MultipartFormDataContent();
|
||||
createForm.Add(new StringContent("Rozbitý zámek"), "title");
|
||||
createForm.Add(new StringContent("Dveře nelze odemknout."), "description");
|
||||
createForm.Add(new StringContent(categories[0].Id.ToString(CultureInfo.InvariantCulture)), "categoryId");
|
||||
AddFile(createForm, "zamek.png", png);
|
||||
|
||||
await using var scope = fixture.Services.CreateAsyncScope();
|
||||
var db = scope.ServiceProvider.GetRequiredService<HelpdeskDbContext>();
|
||||
var store = scope.ServiceProvider.GetRequiredService<IAttachmentStore>();
|
||||
try
|
||||
{
|
||||
var issue = await ReadAsync<IssueDetail>(author.PostAsync("/api/v1/issues", createForm, Cancellation), HttpStatusCode.Created);
|
||||
var pngAttachment = Assert.Single(issue.Attachments);
|
||||
var download = $"/api/v1/attachments/{pngAttachment.Id}";
|
||||
using var fetched = await author.GetAsync(download, Cancellation);
|
||||
Assert.Equal(HttpStatusCode.OK, fetched.StatusCode);
|
||||
Assert.Equal("image/png", fetched.Content.Headers.ContentType?.MediaType);
|
||||
Assert.Equal("nosniff", Assert.Single(fetched.Headers.GetValues("X-Content-Type-Options")));
|
||||
Assert.Equal(png, await fetched.Content.ReadAsByteArrayAsync(Cancellation));
|
||||
await ExpectAsync(other.GetAsync(download, Cancellation), HttpStatusCode.Forbidden);
|
||||
|
||||
var path = $"/api/v1/issues/{issue.Id}/attachments";
|
||||
using var mixed = new MultipartFormDataContent();
|
||||
AddFile(mixed, "spravny.pdf", "%PDF-1.7\n%%EOF"u8.ToArray());
|
||||
AddFile(mixed, "podvrzeny.png", "obsah nemá formát PNG"u8.ToArray());
|
||||
await ExpectAsync(author.PostAsync(path, mixed, Cancellation), HttpStatusCode.BadRequest);
|
||||
|
||||
using var wrongField = new MultipartFormDataContent();
|
||||
wrongField.Add(new ByteArrayContent(png), "image", "zamek.png");
|
||||
await ExpectAsync(author.PostAsync(path, wrongField, Cancellation), HttpStatusCode.BadRequest);
|
||||
var afterFailure = await ReadAsync<IssueDetail>(author.GetAsync($"/api/v1/issues/{issue.Id}", Cancellation));
|
||||
Assert.Equal(issue.RowVersion, afterFailure.RowVersion);
|
||||
Assert.Equal(pngAttachment.Id, Assert.Single(afterFailure.Attachments).Id);
|
||||
|
||||
using var files = new MultipartFormDataContent();
|
||||
AddFile(files, "protokol.pdf", "%PDF-1.7\n%%EOF"u8.ToArray());
|
||||
AddFile(files, "fotka.jpg", [0xff, 0xd8, 0xff, 0xd9]);
|
||||
AddFile(files, "fotka.heic", [0, 0, 0, 20, .. "ftypmif1"u8, 0, 0, 0, 0, .. "heic"u8]);
|
||||
AddFile(files, "protokol.docx", Docx());
|
||||
var added = await ReadAsync<AttachmentDto[]>(admin.PostAsync(path, files, Cancellation));
|
||||
Assert.Equal(["application/pdf", "image/jpeg", "image/heic",
|
||||
"application/vnd.openxmlformats-officedocument.wordprocessingml.document"], added.Select(item => item.ContentType));
|
||||
|
||||
var key = await db.Attachments.Where(item => item.Id == pngAttachment.Id).Select(item => item.StoredFileName).SingleAsync(Cancellation);
|
||||
store.Delete(key);
|
||||
await ExpectAsync(author.GetAsync(download, Cancellation), HttpStatusCode.NotFound);
|
||||
}
|
||||
finally
|
||||
{
|
||||
foreach (var key in await db.Attachments.Select(item => item.StoredFileName).ToListAsync(CancellationToken.None))
|
||||
store.Delete(key);
|
||||
}
|
||||
}
|
||||
|
||||
private static void AddFile(MultipartFormDataContent form, string name, byte[] bytes) =>
|
||||
form.Add(new ByteArrayContent(bytes), "files", name);
|
||||
|
||||
private static byte[] Docx()
|
||||
{
|
||||
using var stream = new MemoryStream();
|
||||
using (var zip = new ZipArchive(stream, ZipArchiveMode.Create, leaveOpen: true))
|
||||
{
|
||||
using (var contentTypes = zip.CreateEntry("[Content_Types].xml").Open())
|
||||
contentTypes.Write("<Types/>"u8);
|
||||
using (var document = zip.CreateEntry("word/document.xml").Open())
|
||||
document.Write("<document/>"u8);
|
||||
}
|
||||
return stream.ToArray();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
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<BackendFixture>
|
||||
{
|
||||
[Fact]
|
||||
public async Task ChangingPasswordThroughAnEmailLinkRevokesTheOldSession()
|
||||
{
|
||||
using var anonymous = fixture.CreateClient();
|
||||
var user = await fixture.RegisterAsync(anonymous);
|
||||
using var oldSession = fixture.CreateClient((await LoginAsync(anonymous, user.Email)).AccessToken);
|
||||
await ExpectAsync(anonymous.PostAsJsonAsync("/api/v1/auth/forgot-password",
|
||||
new ForgotPasswordRequest(user.Email), Cancellation), HttpStatusCode.NoContent);
|
||||
|
||||
const string newPassword = "New-integration-password";
|
||||
var reset = new ResetPasswordRequest(await fixture.TakeResetTokenAsync(user.Email), newPassword);
|
||||
await ExpectAsync(anonymous.PostAsJsonAsync("/api/v1/auth/reset-password", reset, Cancellation), HttpStatusCode.NoContent);
|
||||
await ExpectAsync(anonymous.PostAsJsonAsync("/api/v1/auth/reset-password", reset, Cancellation), HttpStatusCode.BadRequest);
|
||||
await ExpectAsync(oldSession.GetAsync("/api/v1/users/me", Cancellation), HttpStatusCode.Unauthorized);
|
||||
await ExpectAsync(anonymous.PostAsJsonAsync("/api/v1/auth/login",
|
||||
new LoginRequest(user.Email, Password), Cancellation), HttpStatusCode.Unauthorized);
|
||||
var session = await ReadAsync<AuthResponse>(anonymous.PostAsJsonAsync("/api/v1/auth/login",
|
||||
new LoginRequest(user.Email, newPassword), Cancellation));
|
||||
Assert.Equal(user.Id, session.User.Id);
|
||||
}
|
||||
|
||||
[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<HelpdeskDbContext>();
|
||||
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<HttpResponseMessage> first;
|
||||
Task<HttpResponseMessage> 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<HelpdeskDbContext>();
|
||||
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<AuthResponse>(first);
|
||||
await ExpectAsync(duplicate, HttpStatusCode.Unauthorized);
|
||||
await using var after = fixture.Services.CreateAsyncScope();
|
||||
var tokens = after.ServiceProvider.GetRequiredService<HelpdeskDbContext>().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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,212 @@
|
||||
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.Common;
|
||||
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 = "[email protected]";
|
||||
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 WebApplicationFactory<Program> CreateApiBehindProxies(string proxyIp, string webIp) =>
|
||||
new ApiFactory(database.GetConnectionString(), email, TokenSaves, proxyIp, webIp);
|
||||
|
||||
internal async Task<UserDto> RegisterAsync(HttpClient client)
|
||||
{
|
||||
var address = $"{Guid.NewGuid():N}@student.example.test";
|
||||
var user = await ReadAsync<UserDto>(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(await TakeConfirmationTokenAsync(address)), Cancellation), HttpStatusCode.NoContent);
|
||||
return user;
|
||||
}
|
||||
|
||||
internal async Task<AuthResponse> RegisterStaffAsync(HttpClient anonymous, HttpClient admin, string role)
|
||||
{
|
||||
var user = await 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);
|
||||
}
|
||||
|
||||
internal Task<string> TakeConfirmationTokenAsync(string address) => email.TakeTokenAsync(address, "/confirm-email");
|
||||
|
||||
internal Task<string> TakeResetTokenAsync(string address) => email.TakeTokenAsync(address, "/reset-password");
|
||||
|
||||
internal void FailNextEmail(string address, string reason, bool retryable) =>
|
||||
email.Failures[address] = new EmailDeliveryException(reason, retryable);
|
||||
|
||||
internal static Task<AuthResponse> LoginAsync(HttpClient client, string address) =>
|
||||
ReadAsync<AuthResponse>(client.PostAsJsonAsync("/api/v1/auth/login",
|
||||
new LoginRequest(address, Password), Cancellation));
|
||||
|
||||
internal static async Task<T> ReadAsync<T>(Task<HttpResponseMessage> request, HttpStatusCode expected = HttpStatusCode.OK)
|
||||
where T : class
|
||||
{
|
||||
using var response = await request;
|
||||
Assert.Equal(expected, response.StatusCode);
|
||||
return Assert.IsType<T>(await response.Content.ReadFromJsonAsync<T>(Cancellation));
|
||||
}
|
||||
|
||||
internal static async Task ExpectAsync(Task<HttpResponseMessage> 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,
|
||||
string proxyIp = "", string webIp = "")
|
||||
: WebApplicationFactory<Program>
|
||||
{
|
||||
private readonly Dictionary<string, string?> 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"] = proxyIp,
|
||||
["ReverseProxy:TrustedWebIp"] = webIp,
|
||||
};
|
||||
|
||||
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<IEmailSender>();
|
||||
services.AddSingleton<IEmailSender>(email);
|
||||
services.AddDbContext<HelpdeskDbContext>((_, options) => options.AddInterceptors(tokenSaves));
|
||||
});
|
||||
}
|
||||
|
||||
private sealed class TestEmailSender : IEmailSender
|
||||
{
|
||||
private readonly ConcurrentDictionary<(string Address, string Path), TaskCompletionSource<string>> tokens = new();
|
||||
internal ConcurrentDictionary<string, EmailDeliveryException> Failures { get; } = new();
|
||||
|
||||
public Task SendAsync(string to, string subject, string body, CancellationToken cancellationToken = default)
|
||||
{
|
||||
if (Failures.TryRemove(to, out var failure))
|
||||
throw failure;
|
||||
|
||||
if (Uri.TryCreate(body[(body.LastIndexOf('\n') + 1)..], UriKind.Absolute, out var link) &&
|
||||
link.AbsolutePath is "/confirm-email" or "/reset-password")
|
||||
{
|
||||
var token = QueryHelpers.ParseQuery(link.Query)["token"].ToString();
|
||||
GetTokenSlot((to, link.AbsolutePath)).TrySetResult(token);
|
||||
}
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
internal async Task<string> TakeTokenAsync(string address, string path)
|
||||
{
|
||||
var key = (address, path);
|
||||
var token = await GetTokenSlot(key).Task.WaitAsync(TimeSpan.FromSeconds(10), Cancellation);
|
||||
tokens.TryRemove(key, out _);
|
||||
return token;
|
||||
}
|
||||
|
||||
private TaskCompletionSource<string> GetTokenSlot((string Address, string Path) key) =>
|
||||
tokens.GetOrAdd(key, _ => new(TaskCreationOptions.RunContinuationsAsynchronously));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
using System.Net;
|
||||
using System.Text.Json;
|
||||
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<BackendFixture>
|
||||
{
|
||||
[Fact]
|
||||
public async Task MigratorAppliesEveryScriptAndEfCanReadTheSchema()
|
||||
{
|
||||
using var client = fixture.CreateClient();
|
||||
await using var scope = fixture.Services.CreateAsyncScope();
|
||||
var db = scope.ServiceProvider.GetRequiredService<HelpdeskDbContext>();
|
||||
var expected = Directory.EnumerateFiles(MigrationsPath, "V*__*.sql")
|
||||
.Select(Path.GetFileName).Order(StringComparer.Ordinal).ToArray();
|
||||
var applied = await db.Database
|
||||
.SqlQueryRaw<string>("SELECT scriptname AS Value FROM schema_version ORDER BY schemaversionid")
|
||||
.ToListAsync(Cancellation);
|
||||
Assert.Equal(expected, applied);
|
||||
var health = await ReadAsync<HealthResponse>(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 OnlyAdministratorsCanReadTheOpenApiDocument()
|
||||
{
|
||||
using var client = fixture.CreateClient();
|
||||
const string path = "/api/v1/admin/openapi/v1.json";
|
||||
await ExpectAsync(client.GetAsync(path, Cancellation), HttpStatusCode.Unauthorized);
|
||||
var student = await fixture.RegisterAsync(client);
|
||||
using var studentClient = fixture.CreateClient((await LoginAsync(client, student.Email)).AccessToken);
|
||||
await ExpectAsync(studentClient.GetAsync(path, Cancellation), HttpStatusCode.Forbidden);
|
||||
using var admin = fixture.CreateClient((await LoginAsync(client, AdminEmail)).AccessToken);
|
||||
await ExpectAsync(admin.GetAsync("/swagger/index.html", Cancellation), HttpStatusCode.NotFound);
|
||||
await ExpectAsync(admin.GetAsync("/swagger/v1/swagger.json", Cancellation), HttpStatusCode.NotFound);
|
||||
using var document = await ReadAsync<JsonDocument>(admin.GetAsync(path, Cancellation));
|
||||
var paths = document.RootElement.GetProperty("paths");
|
||||
var create = paths.GetProperty("/api/v1/issues").GetProperty("post").GetProperty("requestBody").GetProperty("content");
|
||||
Assert.True(create.TryGetProperty("application/json", out _));
|
||||
var createSchema = create.GetProperty("multipart/form-data").GetProperty("schema");
|
||||
Assert.Contains(createSchema.GetProperty("required").EnumerateArray(), field => field.GetString() == "categoryId");
|
||||
var uploadSchema = paths.GetProperty("/api/v1/issues/{id}/attachments").GetProperty("post")
|
||||
.GetProperty("requestBody").GetProperty("content").GetProperty("multipart/form-data").GetProperty("schema");
|
||||
Assert.Equal("files", Assert.Single(uploadSchema.GetProperty("required").EnumerateArray()).GetString());
|
||||
var files = uploadSchema.GetProperty("properties").GetProperty("files");
|
||||
Assert.Equal(5, files.GetProperty("maxItems").GetInt32());
|
||||
Assert.Equal("binary", files.GetProperty("items").GetProperty("format").GetString());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DatabaseRejectsAnAssignedIssueWithoutAnAssignee()
|
||||
{
|
||||
await using var scope = fixture.Services.CreateAsyncScope();
|
||||
var db = scope.ServiceProvider.GetRequiredService<HelpdeskDbContext>();
|
||||
var reporterId = await db.Users.Where(user => user.Email == AdminEmail).Select(user => user.Id).SingleAsync(Cancellation);
|
||||
var categoryId = await db.IssueCategories.MinAsync(category => category.Id, Cancellation);
|
||||
|
||||
var error = await Assert.ThrowsAsync<MySqlException>(() => 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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<IsPackable>false</IsPackable>
|
||||
<OutputType>Exe</OutputType>
|
||||
<UseMicrosoftTestingPlatformRunner>true</UseMicrosoftTestingPlatformRunner>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\..\src\Helpdesk.Api\Helpdesk.Api.csproj" />
|
||||
<ProjectReference Include="..\..\src\Helpdesk.Migrator\Helpdesk.Migrator.csproj" />
|
||||
<None Include="..\..\..\db\migrations\V*__*.sql" Link="migrations\%(Filename)%(Extension)" CopyToOutputDirectory="PreserveNewest" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.AspNetCore.Mvc.Testing" />
|
||||
<PackageReference Include="Microsoft.Testing.Extensions.CodeCoverage" PrivateAssets="all" />
|
||||
<PackageReference Include="MySqlConnector" />
|
||||
<PackageReference Include="Testcontainers.MariaDb" />
|
||||
<PackageReference Include="xunit.v3" />
|
||||
<Using Include="Xunit" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -0,0 +1,161 @@
|
||||
using System.Net;
|
||||
using System.Net.Http.Json;
|
||||
using Helpdesk.Application.Catalogs;
|
||||
using Helpdesk.Application.Common;
|
||||
using Helpdesk.Application.Issues;
|
||||
using Helpdesk.Application.Notifications;
|
||||
using Helpdesk.Application.Statistics;
|
||||
using static Helpdesk.IntegrationTests.BackendFixture;
|
||||
|
||||
namespace Helpdesk.IntegrationTests;
|
||||
|
||||
public sealed class IssueWorkflowTests(BackendFixture fixture) : IClassFixture<BackendFixture>
|
||||
{
|
||||
[Fact]
|
||||
public async Task ReporterAndAssigneesCanResolveAnIssueAndManagementCanReportOnIt()
|
||||
{
|
||||
using var anonymous = fixture.CreateClient();
|
||||
var administrator = await LoginAsync(anonymous, AdminEmail);
|
||||
using var admin = fixture.CreateClient(administrator.AccessToken);
|
||||
var author = await fixture.RegisterAsync(anonymous);
|
||||
using var reporter = fixture.CreateClient((await LoginAsync(anonymous, author.Email)).AccessToken);
|
||||
var management = await fixture.RegisterStaffAsync(anonymous, admin, "MANAGEMENT");
|
||||
var firstAssignee = await fixture.RegisterStaffAsync(anonymous, admin, "FACILITY_MANAGER");
|
||||
var secondAssignee = await fixture.RegisterStaffAsync(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<CategoryDto[]>(reporter.GetAsync("/api/v1/issue-categories", Cancellation));
|
||||
var buildings = await ReadAsync<BuildingDto[]>(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);
|
||||
|
||||
issue = await ReadAsync<IssueDetail>(reporter.PutAsJsonAsync(path,
|
||||
new EditIssueRequest(issue.Title, "Projektor nereaguje ani po restartu.", issue.CategoryId,
|
||||
issue.BuildingId, issue.LocationDetail, issue.RowVersion), Cancellation));
|
||||
Assert.Equal("Projektor nereaguje ani po restartu.", issue.Description);
|
||||
issue = await ReadAsync<IssueDetail>(admin.PutAsJsonAsync(path,
|
||||
new EditIssueRequest(issue.Title, issue.Description, issue.CategoryId,
|
||||
issue.BuildingId, "A102", issue.RowVersion), Cancellation));
|
||||
Assert.Equal(("A102", author.Id), (issue.LocationDetail, issue.ReporterId));
|
||||
var assign = new AssignIssueRequest(firstAssignee.User.Id, null, issue.RowVersion);
|
||||
await ExpectAsync(reporter.PostAsJsonAsync(path + "/assign", assign, Cancellation), HttpStatusCode.Forbidden);
|
||||
issue = await PostIssueAsync(admin, path + "/assign", assign);
|
||||
Assert.Equal(firstAssignee.User.Id, issue.AssigneeId);
|
||||
Assert.Contains("ASSIGN", (await ReadAsync<IssueDetail>(admin.GetAsync(path, Cancellation))).AllowedActions);
|
||||
var adminIssues = await ReadAsync<PagedResult<IssueSummary>>(admin.GetAsync("/api/v1/issues", Cancellation));
|
||||
Assert.Contains(adminIssues.Items, item => item.Id == issue.Id);
|
||||
var assignable = await ReadAsync<AssignableUserDto[]>(admin.GetAsync("/api/v1/users/assignable", Cancellation));
|
||||
Assert.Contains(assignable, user => user.Id == firstAssignee.User.Id);
|
||||
Assert.Contains(assignable, user => user.Id == administrator.User.Id);
|
||||
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(admin, path + "/start", new IssueVersionRequest(issue.RowVersion));
|
||||
Assert.Equal("IN_PROGRESS", issue.Status);
|
||||
reporterNotifications = await InboxAsync(reporter, issue.Id);
|
||||
issue = await PostIssueAsync(admin, 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<IssueEventDto>(admin.PostAsJsonAsync(path + "/comments",
|
||||
new CommentRequest(commentText), Cancellation));
|
||||
Assert.Equal(administrator.User.Id, comment.ActorId);
|
||||
issue = await ReadAsync<IssueDetail>(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(admin, path + "/reopen", new IssueReasonRequest(issue.RowVersion, "Porucha se vrátila."));
|
||||
Assert.Equal("IN_PROGRESS", issue.Status);
|
||||
Assert.Contains(await InboxAsync(firstSolver, issue.Id), notification => notification.Type == "ISSUE_REOPENED");
|
||||
issue = await PostIssueAsync(admin, path + "/submit-for-verification", new VerifyIssueRequest(issue.RowVersion, "Ověřeno."));
|
||||
issue = await PostIssueAsync(admin, path + "/confirm", new IssueVersionRequest(issue.RowVersion));
|
||||
Assert.Equal("RESOLVED", issue.Status);
|
||||
var events = await ReadAsync<IssueEventDto[]>(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);
|
||||
var rejected = await PostIssueAsync(manager, $"/api/v1/issues/{openIssue.Id}/reject",
|
||||
new IssueReasonRequest(openIssue.RowVersion, "Duplicitní hlášení."));
|
||||
Assert.Equal("REJECTED", rejected.Status);
|
||||
|
||||
var officeIssue = await PostIssueAsync(reporter, "/api/v1/issues",
|
||||
request with { Title = "Porucha v kanceláři" }, HttpStatusCode.Created);
|
||||
var officePath = $"/api/v1/issues/{officeIssue.Id}";
|
||||
officeIssue = await PostIssueAsync(manager, officePath + "/assign",
|
||||
new AssignIssueRequest(administrator.User.Id, null, officeIssue.RowVersion));
|
||||
Assert.Equal(administrator.User.Id, officeIssue.AssigneeId);
|
||||
Assert.Equal("ISSUE_ASSIGNED", Assert.Single(await InboxAsync(admin, officeIssue.Id)).Type);
|
||||
var rejectedByAdmin = await PostIssueAsync(admin, officePath + "/reject",
|
||||
new IssueReasonRequest(officeIssue.RowVersion, "Hlášení je duplicitní."));
|
||||
Assert.Equal("REJECTED", rejectedByAdmin.Status);
|
||||
}
|
||||
|
||||
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<PagedResult<IssueSummary>>(manager.GetAsync(query + "&page=1", Cancellation));
|
||||
var second = await ReadAsync<PagedResult<IssueSummary>>(manager.GetAsync(query + "&page=2", Cancellation));
|
||||
var filtered = await ReadAsync<PagedResult<IssueSummary>>(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<StatisticsOverview>(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 byCategory = Assert.Single(await ReadAsync<IssueCategoryStatistics[]>(
|
||||
manager.GetAsync("/api/v1/statistics/issues/by-category" + period, Cancellation)));
|
||||
Assert.Equal((resolved.CategoryId, 2), (byCategory.CategoryId, byCategory.IssueCount));
|
||||
Assert.NotNull(byCategory.AverageHoursToResolution);
|
||||
var byBuilding = Assert.Single(await ReadAsync<IssueBuildingStatistics[]>(
|
||||
manager.GetAsync("/api/v1/statistics/issues/by-building" + period, Cancellation)));
|
||||
Assert.Equal((resolved.BuildingId, 2), (byBuilding.BuildingId, byBuilding.IssueCount));
|
||||
var byAssignee = Assert.Single(await ReadAsync<IssueAssigneeStatistics[]>(
|
||||
manager.GetAsync("/api/v1/statistics/issues/by-assignee" + period, Cancellation)));
|
||||
Assert.Equal((resolved.AssigneeId, 1, 0), ((int?)byAssignee.AssigneeId, byAssignee.ResolvedIssues, byAssignee.OpenIssues));
|
||||
var available = await ReadAsync<AssignableUserDto[]>(manager.GetAsync("/api/v1/users/assignable", Cancellation));
|
||||
Assert.Contains(available, user => user.Id == resolved.AssigneeId && user.OpenIssues == 0);
|
||||
var trend = await ReadAsync<IssueTrendPoint[]>(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<StatisticsOverview>(manager.GetAsync(overview + $"?from={to}", Cancellation));
|
||||
Assert.Equal(0, after.TotalIssues);
|
||||
}
|
||||
|
||||
private static Task<IssueDetail> PostIssueAsync<T>(
|
||||
HttpClient client, string path, T request, HttpStatusCode expected = HttpStatusCode.OK) =>
|
||||
ReadAsync<IssueDetail>(client.PostAsJsonAsync(path, request, Cancellation), expected);
|
||||
|
||||
private static async Task<NotificationDto[]> InboxAsync(HttpClient client, int issueId)
|
||||
{
|
||||
var notifications = await ReadAsync<PagedResult<NotificationDto>>(client.GetAsync("/api/v1/notifications", Cancellation));
|
||||
return notifications.Items.Where(notification => notification.IssueId == issueId).ToArray();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
using System.Net;
|
||||
using System.Net.Http.Json;
|
||||
using Helpdesk.Api.Controllers;
|
||||
using Helpdesk.Application.Catalogs;
|
||||
using Helpdesk.Application.Common;
|
||||
using Helpdesk.Application.Issues;
|
||||
using Helpdesk.Application.Notifications;
|
||||
using Helpdesk.Infrastructure.Persistence;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using static Helpdesk.IntegrationTests.BackendFixture;
|
||||
|
||||
namespace Helpdesk.IntegrationTests;
|
||||
|
||||
public sealed class NotificationTests(BackendFixture fixture) : IClassFixture<BackendFixture>
|
||||
{
|
||||
[Fact]
|
||||
public async Task FailedEmailCanBeRetriedAndOnlyTheRecipientCanMarkNotificationsRead()
|
||||
{
|
||||
using var anonymous = fixture.CreateClient();
|
||||
using var admin = fixture.CreateClient((await LoginAsync(anonymous, AdminEmail)).AccessToken);
|
||||
var user = await fixture.RegisterAsync(anonymous);
|
||||
using var reporter = fixture.CreateClient((await LoginAsync(anonymous, user.Email)).AccessToken);
|
||||
var managerSession = await fixture.RegisterStaffAsync(anonymous, admin, "MANAGEMENT");
|
||||
using var manager = fixture.CreateClient(managerSession.AccessToken);
|
||||
var categories = await ReadAsync<CategoryDto[]>(reporter.GetAsync("/api/v1/issue-categories", Cancellation));
|
||||
var request = new CreateIssueRequest("Porucha v učebně", "Závadu je potřeba prověřit.", categories[0].Id, null, null);
|
||||
const string inbox = "/api/v1/notifications";
|
||||
const string deliveries = "/api/v1/admin/notification-deliveries";
|
||||
|
||||
fixture.FailNextEmail(managerSession.User.Email, "TEST_RECIPIENT_REJECTED", retryable: false);
|
||||
var issue = await ReadAsync<IssueDetail>(reporter.PostAsJsonAsync("/api/v1/issues", request, Cancellation), HttpStatusCode.Created);
|
||||
var notifications = await ReadAsync<PagedResult<NotificationDto>>(manager.GetAsync(inbox + "?unreadOnly=true", Cancellation));
|
||||
var notification = Assert.Single(notifications.Items);
|
||||
Assert.Equal((issue.Id, "ISSUE_CREATED"), (notification.IssueId, notification.Type));
|
||||
await ExpectAsync(reporter.PostAsync($"{inbox}/{notification.Id}/read", null, Cancellation), HttpStatusCode.NotFound);
|
||||
await ExpectAsync(reporter.GetAsync(deliveries, Cancellation), HttpStatusCode.Forbidden);
|
||||
await ExpectAsync(admin.GetAsync(deliveries + "?status=invalid", Cancellation), HttpStatusCode.BadRequest);
|
||||
|
||||
var failed = await WaitForDeliveryAsync(admin, notification.Id, "FAILED");
|
||||
Assert.Equal((1, "TEST_RECIPIENT_REJECTED"), (failed.AttemptCount, failed.LastError));
|
||||
Assert.Null(failed.NextAttemptAt);
|
||||
var retry = $"{deliveries}/{failed.Id}/retry";
|
||||
await ExpectAsync(admin.PostAsync(retry, null, Cancellation), HttpStatusCode.NoContent);
|
||||
var sent = await WaitForDeliveryAsync(admin, notification.Id, "SENT");
|
||||
Assert.Equal(1, sent.AttemptCount);
|
||||
Assert.NotNull(sent.SentAt);
|
||||
Assert.Null(sent.LastError);
|
||||
await ExpectAsync(admin.PostAsync(retry, null, Cancellation), HttpStatusCode.Conflict);
|
||||
await ExpectAsync(admin.PostAsync($"{deliveries}/{int.MaxValue}/retry", null, Cancellation), HttpStatusCode.NotFound);
|
||||
|
||||
var read = $"{inbox}/{notification.Id}/read";
|
||||
await ExpectAsync(manager.PostAsync(read, null, Cancellation), HttpStatusCode.NoContent);
|
||||
await ExpectAsync(manager.PostAsync(read, null, Cancellation), HttpStatusCode.NoContent);
|
||||
Assert.Equal(0, (await ReadAsync<UnreadCountDto>(manager.GetAsync(inbox + "/unread-count", Cancellation))).Count);
|
||||
|
||||
fixture.FailNextEmail(managerSession.User.Email, "TEST_TEMPORARY_FAILURE", retryable: true);
|
||||
var secondIssue = await ReadAsync<IssueDetail>(reporter.PostAsJsonAsync("/api/v1/issues", request, Cancellation), HttpStatusCode.Created);
|
||||
notifications = await ReadAsync<PagedResult<NotificationDto>>(manager.GetAsync(inbox + "?unreadOnly=true", Cancellation));
|
||||
notification = Assert.Single(notifications.Items);
|
||||
Assert.Equal(secondIssue.Id, notification.IssueId);
|
||||
var pending = await WaitForDeliveryAsync(admin, notification.Id, "PENDING", attempts: 1);
|
||||
Assert.Equal("TEST_TEMPORARY_FAILURE", pending.LastError);
|
||||
Assert.True(pending.NextAttemptAt > DateTime.UtcNow);
|
||||
await ExpectAsync(manager.PostAsync(inbox + "/read-all", null, Cancellation), HttpStatusCode.NoContent);
|
||||
Assert.Empty((await ReadAsync<PagedResult<NotificationDto>>(manager.GetAsync(inbox + "?unreadOnly=true", Cancellation))).Items);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeviceRegistrationPreservesCaseAndTransfersOwnership()
|
||||
{
|
||||
using var anonymous = fixture.CreateClient();
|
||||
var firstUser = await fixture.RegisterAsync(anonymous);
|
||||
var secondUser = await fixture.RegisterAsync(anonymous);
|
||||
using var first = fixture.CreateClient((await LoginAsync(anonymous, firstUser.Email)).AccessToken);
|
||||
using var second = fixture.CreateClient((await LoginAsync(anonymous, secondUser.Email)).AccessToken);
|
||||
const string route = "/api/v1/devices";
|
||||
var token = new RegisterDeviceRequest("CaseSensitiveDevice");
|
||||
var otherCase = new RegisterDeviceRequest("casesensitivedevice");
|
||||
await ExpectAsync(first.PostAsJsonAsync(route, new RegisterDeviceRequest("invalid token"), Cancellation), HttpStatusCode.BadRequest);
|
||||
await ExpectAsync(first.PostAsJsonAsync(route, token, Cancellation), HttpStatusCode.NoContent);
|
||||
await ExpectAsync(first.PostAsJsonAsync(route, otherCase, Cancellation), HttpStatusCode.NoContent);
|
||||
await ExpectAsync(second.PostAsJsonAsync(route, token, Cancellation), HttpStatusCode.NoContent);
|
||||
await ExpectAsync(first.DeleteAsync($"{route}/{token.Token}", Cancellation), HttpStatusCode.NoContent);
|
||||
|
||||
await using var scope = fixture.Services.CreateAsyncScope();
|
||||
var db = scope.ServiceProvider.GetRequiredService<HelpdeskDbContext>();
|
||||
var devices = await db.PushDevices.AsNoTracking().ToListAsync(Cancellation);
|
||||
Assert.Equal(secondUser.Id, Assert.Single(devices, item => item.FcmToken == token.Token).UserId);
|
||||
Assert.Equal(firstUser.Id, Assert.Single(devices, item => item.FcmToken == otherCase.Token).UserId);
|
||||
await ExpectAsync(second.DeleteAsync($"{route}/{token.Token}", Cancellation), HttpStatusCode.NoContent);
|
||||
Assert.Equal(otherCase.Token, await db.PushDevices.Select(item => item.FcmToken).SingleAsync(Cancellation));
|
||||
}
|
||||
|
||||
private static async Task<NotificationDeliveryDto> WaitForDeliveryAsync(HttpClient client, int notificationId, string status, int attempts = 1)
|
||||
{
|
||||
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(Cancellation);
|
||||
timeout.CancelAfter(TimeSpan.FromSeconds(15));
|
||||
var path = $"/api/v1/admin/notification-deliveries?status={status}";
|
||||
while (!timeout.IsCancellationRequested)
|
||||
{
|
||||
var page = await ReadAsync<PagedResult<NotificationDeliveryDto>>(client.GetAsync(path, timeout.Token));
|
||||
var delivery = page.Items.SingleOrDefault(item =>
|
||||
item.NotificationId == notificationId && item.Channel == "EMAIL" && item.AttemptCount == attempts);
|
||||
if (delivery is not null)
|
||||
return delivery;
|
||||
await Task.Delay(TimeSpan.FromMilliseconds(100), timeout.Token);
|
||||
}
|
||||
|
||||
throw new TimeoutException($"Notification {notificationId} did not reach {status}.");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
using System.Net;
|
||||
using System.Net.Http.Json;
|
||||
using Helpdesk.Application.Catalogs;
|
||||
using Helpdesk.Application.Common;
|
||||
using Helpdesk.Application.Notifications;
|
||||
using Helpdesk.Application.Proposals;
|
||||
using Helpdesk.Application.Statistics;
|
||||
using static Helpdesk.IntegrationTests.BackendFixture;
|
||||
|
||||
namespace Helpdesk.IntegrationTests;
|
||||
|
||||
public sealed class ProposalWorkflowTests(BackendFixture fixture) : IClassFixture<BackendFixture>
|
||||
{
|
||||
private const string Proposals = "/api/v1/proposals";
|
||||
|
||||
[Fact]
|
||||
public async Task VotesAndDecisionsAreReflectedInTheProposalAndItsHistory()
|
||||
{
|
||||
using var anonymous = fixture.CreateClient();
|
||||
var administrator = await LoginAsync(anonymous, AdminEmail);
|
||||
using var admin = fixture.CreateClient(administrator.AccessToken);
|
||||
var authorUser = await fixture.RegisterAsync(anonymous);
|
||||
using var author = fixture.CreateClient((await LoginAsync(anonymous, authorUser.Email)).AccessToken);
|
||||
var managerSession = await fixture.RegisterStaffAsync(anonymous, admin, "MANAGEMENT");
|
||||
using var manager = fixture.CreateClient(managerSession.AccessToken);
|
||||
var categories = await ReadAsync<CategoryDto[]>(author.GetAsync("/api/v1/proposal-categories", Cancellation));
|
||||
var request = new SaveProposalRequest("Prodloužení studovny", "Rozšířit večerní otevírací dobu.", categories[0].Id);
|
||||
await ExpectAsync(author.PostAsJsonAsync(Proposals, request with { Title = " " }, Cancellation), HttpStatusCode.BadRequest);
|
||||
await ExpectAsync(author.PostAsJsonAsync(Proposals, request with { CategoryId = int.MaxValue }, Cancellation), HttpStatusCode.BadRequest);
|
||||
|
||||
var proposal = await ReadAsync<ProposalDetail>(author.PostAsJsonAsync(Proposals, request, Cancellation), HttpStatusCode.Created);
|
||||
Assert.Equal("SUBMITTED", proposal.Status);
|
||||
var path = $"{Proposals}/{proposal.Id}";
|
||||
var edit = request with { CategoryId = categories[1].Id, Description = "Otevřít do 22 hodin." };
|
||||
await ExpectAsync(manager.PutAsJsonAsync(path, edit, Cancellation), HttpStatusCode.Forbidden);
|
||||
proposal = await ReadAsync<ProposalDetail>(author.PutAsJsonAsync(path, edit, Cancellation));
|
||||
Assert.Equal((edit.CategoryId, edit.Description, "UPDATED"), (proposal.CategoryId, proposal.Description, proposal.Events[^1].EventType));
|
||||
var adminEdit = edit with { Description = "Otevřít do 22 hodin ve všední dny." };
|
||||
proposal = await ReadAsync<ProposalDetail>(admin.PutAsJsonAsync(path, adminEdit, Cancellation));
|
||||
Assert.Equal((adminEdit.Description, authorUser.Id, administrator.User.Id),
|
||||
(proposal.Description, proposal.AuthorId, proposal.Events[^1].ActorId));
|
||||
var other = await ReadAsync<ProposalDetail>(author.PostAsJsonAsync(Proposals, edit with
|
||||
{
|
||||
Title = "Vybavení studovny",
|
||||
}, Cancellation), HttpStatusCode.Created);
|
||||
|
||||
await VerifyVotesAsync(author, manager, path);
|
||||
var from = Uri.EscapeDataString(proposal.CreatedAt.AddMinutes(-1).ToString("O"));
|
||||
var to = Uri.EscapeDataString(other.CreatedAt.AddMinutes(1).ToString("O"));
|
||||
var filter = $"{Proposals}?status=SUBMITTED&categoryId={edit.CategoryId}&authorId={authorUser.Id}&q=studovny&from={from}&to={to}";
|
||||
var first = await ReadAsync<PagedResult<ProposalSummary>>(manager.GetAsync(filter + "&sort=score&pageSize=1", Cancellation));
|
||||
var second = await ReadAsync<PagedResult<ProposalSummary>>(manager.GetAsync(filter + "&sort=score&pageSize=1&page=2", Cancellation));
|
||||
Assert.Equal(2, first.TotalCount);
|
||||
Assert.Equal(proposal.Id, Assert.Single(first.Items).Id);
|
||||
Assert.Equal(other.Id, Assert.Single(second.Items).Id);
|
||||
var newest = await ReadAsync<PagedResult<ProposalSummary>>(manager.GetAsync(filter, Cancellation));
|
||||
Assert.Equal(other.Id, newest.Items[0].Id);
|
||||
var outside = await ReadAsync<PagedResult<ProposalSummary>>(manager.GetAsync($"{Proposals}?from={to}", Cancellation));
|
||||
Assert.Empty(outside.Items);
|
||||
|
||||
await ExpectAsync(author.PostAsJsonAsync(path + "/status", new ChangeProposalStatusRequest("ACCEPTED", null), Cancellation),
|
||||
HttpStatusCode.Forbidden);
|
||||
await ExpectAsync(manager.PostAsJsonAsync(path + "/status", new ChangeProposalStatusRequest("REJECTED", " "), Cancellation),
|
||||
HttpStatusCode.BadRequest);
|
||||
await ExpectAsync(admin.PostAsJsonAsync(path + "/status", new ChangeProposalStatusRequest("IMPLEMENTED", null), Cancellation),
|
||||
HttpStatusCode.Conflict);
|
||||
var review = await ReadAsync<ProposalDetail>(admin.PostAsJsonAsync(path + "/status",
|
||||
new ChangeProposalStatusRequest("UNDER_REVIEW", null), Cancellation));
|
||||
Assert.Equal("UNDER_REVIEW", review.Status);
|
||||
var accepted = await ReadAsync<ProposalDetail>(manager.PostAsJsonAsync(path + "/status",
|
||||
new ChangeProposalStatusRequest("ACCEPTED", " Schváleno. "), Cancellation));
|
||||
Assert.Equal(("ACCEPTED", "Schváleno."), (accepted.Status, accepted.Events[^1].Note));
|
||||
await ExpectAsync(admin.PutAsJsonAsync(path, edit, Cancellation), HttpStatusCode.Conflict);
|
||||
await ExpectAsync(manager.DeleteAsync(path + "/vote", Cancellation), HttpStatusCode.Conflict);
|
||||
|
||||
var inbox = await ReadAsync<PagedResult<NotificationDto>>(author.GetAsync("/api/v1/notifications", Cancellation));
|
||||
Assert.Equal(2, inbox.Items.Count(item => item.ProposalId == proposal.Id && item.Type == "PROPOSAL_STATUS_CHANGED"));
|
||||
var top = Assert.Single(await ReadAsync<TopProposal[]>(
|
||||
admin.GetAsync($"/api/v1/statistics/proposals/top?limit=1&from={from}&to={to}", Cancellation)));
|
||||
Assert.Equal((proposal.Id, 1L), (top.Id, top.Score));
|
||||
}
|
||||
|
||||
private static async Task VerifyVotesAsync(HttpClient author, HttpClient voter, string path)
|
||||
{
|
||||
var vote = path + "/vote";
|
||||
await ExpectAsync(author.PutAsJsonAsync(vote, new VoteRequest(1), Cancellation), HttpStatusCode.Forbidden);
|
||||
await ExpectAsync(voter.PutAsJsonAsync(vote, new VoteRequest(0), Cancellation), HttpStatusCode.BadRequest);
|
||||
|
||||
await ExpectAsync(voter.PutAsJsonAsync(vote, new VoteRequest(1), Cancellation), HttpStatusCode.NoContent);
|
||||
var detail = await ReadAsync<ProposalDetail>(voter.GetAsync(path, Cancellation));
|
||||
Assert.Equal((1L, 0L, 1L, (int?)1), (detail.VotesFor, detail.VotesAgainst, detail.Score, detail.MyVote));
|
||||
await ExpectAsync(voter.PutAsJsonAsync(vote, new VoteRequest(-1), Cancellation), HttpStatusCode.NoContent);
|
||||
detail = await ReadAsync<ProposalDetail>(voter.GetAsync(path, Cancellation));
|
||||
Assert.Equal((0L, 1L, -1L, (int?)-1), (detail.VotesFor, detail.VotesAgainst, detail.Score, detail.MyVote));
|
||||
await ExpectAsync(voter.PutAsJsonAsync(vote, new VoteRequest(-1), Cancellation), HttpStatusCode.NoContent);
|
||||
await ExpectAsync(voter.DeleteAsync(vote, Cancellation), HttpStatusCode.NoContent);
|
||||
detail = await ReadAsync<ProposalDetail>(voter.GetAsync(path, Cancellation));
|
||||
Assert.Equal(0L, detail.Score);
|
||||
Assert.Null(detail.MyVote);
|
||||
await ExpectAsync(voter.PutAsJsonAsync(vote, new VoteRequest(1), Cancellation), HttpStatusCode.NoContent);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
using System.Net;
|
||||
using Microsoft.AspNetCore.TestHost;
|
||||
using static Helpdesk.IntegrationTests.BackendFixture;
|
||||
|
||||
namespace Helpdesk.IntegrationTests;
|
||||
|
||||
public sealed class ProxyRateLimitTests(BackendFixture fixture) : IClassFixture<BackendFixture>
|
||||
{
|
||||
[Fact]
|
||||
public async Task TrustedProxiesShareTheLimitForEachClientAndSeparateDifferentClients()
|
||||
{
|
||||
const string externalProxy = "192.0.2.10";
|
||||
const string web = "192.0.2.11";
|
||||
const string firstClient = "198.51.100.10";
|
||||
const string secondClient = "198.51.100.11";
|
||||
await using var api = fixture.CreateApiBehindProxies(externalProxy, web);
|
||||
|
||||
for (var attempt = 0; attempt < 20; attempt++)
|
||||
Assert.Equal(401, await LoginAsync(api.Server, web, firstClient));
|
||||
|
||||
Assert.Equal(429, await LoginAsync(api.Server, externalProxy, firstClient));
|
||||
Assert.Equal(401, await LoginAsync(api.Server, web, secondClient));
|
||||
Assert.Equal(429, await LoginAsync(api.Server, $"::ffff:{firstClient}", secondClient));
|
||||
}
|
||||
|
||||
private static async Task<int> LoginAsync(TestServer server, string peer, string client)
|
||||
{
|
||||
using var body = new MemoryStream("""{"email":"absent@example.test","password":"test-password"}"""u8.ToArray());
|
||||
var response = await server.SendAsync(context =>
|
||||
{
|
||||
context.Connection.RemoteIpAddress = IPAddress.Parse(peer);
|
||||
context.Request.Method = "POST";
|
||||
context.Request.Path = "/api/v1/auth/login";
|
||||
context.Request.ContentType = "application/json";
|
||||
context.Request.ContentLength = body.Length;
|
||||
context.Request.Body = body;
|
||||
context.Request.Headers["X-Forwarded-For"] = client;
|
||||
}, Cancellation);
|
||||
return response.Response.StatusCode;
|
||||
}
|
||||
}
|
||||
@@ -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<InterceptionResult<int>> SavingChangesAsync(
|
||||
DbContextEventData eventData, InterceptionResult<int> result, CancellationToken cancellationToken = default)
|
||||
{
|
||||
if (Volatile.Read(ref next) is not null &&
|
||||
eventData.Context!.ChangeTracker.Entries<AuthToken>()
|
||||
.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();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<Configuration>
|
||||
<CodeCoverage>
|
||||
<EnableStaticManagedInstrumentation>True</EnableStaticManagedInstrumentation>
|
||||
<EnableDynamicManagedInstrumentation>False</EnableDynamicManagedInstrumentation>
|
||||
<CollectFromChildProcesses>True</CollectFromChildProcesses>
|
||||
<ModulePaths>
|
||||
<Include>
|
||||
<ModulePath>(^|[\\/])Helpdesk\.(Api|Application|Domain|Infrastructure|Migrator)\.dll$</ModulePath>
|
||||
</Include>
|
||||
</ModulePaths>
|
||||
<Sources>
|
||||
<Exclude>
|
||||
<Source>[\\/]obj[\\/]</Source>
|
||||
</Exclude>
|
||||
</Sources>
|
||||
</CodeCoverage>
|
||||
</Configuration>
|
||||
@@ -0,0 +1,147 @@
|
||||
using Helpdesk.Domain.Issues;
|
||||
using Helpdesk.Domain.Users;
|
||||
|
||||
namespace Helpdesk.UnitTests;
|
||||
|
||||
public sealed class IssueTests
|
||||
{
|
||||
private const int Reporter = 1;
|
||||
private const int Manager = 2;
|
||||
private const int Assignee = 3;
|
||||
private const int Replacement = 4;
|
||||
|
||||
[Fact]
|
||||
public void NewIssueStartsReceivedWithNormalPriority()
|
||||
{
|
||||
var issue = At(IssueStatus.Received);
|
||||
Assert.Equal(IssueStatus.Received, issue.Status);
|
||||
Assert.Equal(IssuePriority.Normal, issue.Priority);
|
||||
Assert.Equal(0, issue.RowVersion);
|
||||
Assert.Null(issue.AssigneeId);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(IssueStatus.Received, UserRole.Management)]
|
||||
[InlineData(IssueStatus.Assigned, UserRole.Management)]
|
||||
[InlineData(IssueStatus.InProgress, UserRole.Management)]
|
||||
[InlineData(IssueStatus.Received, UserRole.Admin)]
|
||||
[InlineData(IssueStatus.Assigned, UserRole.Admin)]
|
||||
[InlineData(IssueStatus.InProgress, UserRole.Admin)]
|
||||
public void ManagementAndAdminCanAssignOrReassign(IssueStatus from, UserRole role)
|
||||
{
|
||||
var issue = At(from);
|
||||
var version = issue.RowVersion;
|
||||
Assert.Equal(IssueActionAvailability.Allowed, issue.Availability(IssueAction.Assign, Manager, role));
|
||||
issue.Assign(Manager, role, Replacement, UserRole.Management, IssuePriority.High);
|
||||
Assert.Equal(IssueStatus.Assigned, issue.Status);
|
||||
Assert.Equal(Replacement, issue.AssigneeId);
|
||||
Assert.Equal(IssuePriority.High, issue.Priority);
|
||||
Assert.Equal(version + 1, issue.RowVersion);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(IssueStatus.Assigned, IssueAction.StartWork, Assignee, UserRole.FacilityManager, IssueStatus.InProgress)]
|
||||
[InlineData(IssueStatus.Assigned, IssueAction.StartWork, Replacement, UserRole.Admin, IssueStatus.InProgress)]
|
||||
[InlineData(IssueStatus.InProgress, IssueAction.SubmitForVerification, Assignee, UserRole.FacilityManager, IssueStatus.PendingVerification)]
|
||||
[InlineData(IssueStatus.InProgress, IssueAction.SubmitForVerification, Replacement, UserRole.Admin, IssueStatus.PendingVerification)]
|
||||
[InlineData(IssueStatus.PendingVerification, IssueAction.Confirm, Reporter, UserRole.Admin, IssueStatus.Resolved)]
|
||||
[InlineData(IssueStatus.PendingVerification, IssueAction.Confirm, Replacement, UserRole.Admin, IssueStatus.Resolved)]
|
||||
[InlineData(IssueStatus.PendingVerification, IssueAction.Reopen, Replacement, UserRole.Admin, IssueStatus.InProgress)]
|
||||
[InlineData(IssueStatus.Assigned, IssueAction.Reject, Assignee, UserRole.FacilityManager, IssueStatus.Rejected)]
|
||||
[InlineData(IssueStatus.InProgress, IssueAction.Reject, Assignee, UserRole.FacilityManager, IssueStatus.Rejected)]
|
||||
[InlineData(IssueStatus.Received, IssueAction.Reject, Manager, UserRole.Management, IssueStatus.Rejected)]
|
||||
[InlineData(IssueStatus.Received, IssueAction.Reject, Replacement, UserRole.Admin, IssueStatus.Rejected)]
|
||||
[InlineData(IssueStatus.InProgress, IssueAction.Reject, Replacement, UserRole.Admin, IssueStatus.Rejected)]
|
||||
public void AllowedTransitionsIncrementVersion(
|
||||
IssueStatus from, IssueAction action, int actorId, UserRole role, IssueStatus target)
|
||||
{
|
||||
var issue = At(from);
|
||||
var version = issue.RowVersion;
|
||||
Assert.Equal(IssueActionAvailability.Allowed, issue.Availability(action, actorId, role));
|
||||
issue.Transition(action, actorId, role, "Důvod");
|
||||
Assert.Equal(target, issue.Status);
|
||||
Assert.Equal(version + 1, issue.RowVersion);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(IssueStatus.Assigned, IssueAction.StartWork, Replacement, UserRole.FacilityManager, IssueActionAvailability.Forbidden)]
|
||||
[InlineData(IssueStatus.Assigned, IssueAction.StartWork, Assignee, UserRole.Student, IssueActionAvailability.Forbidden)]
|
||||
[InlineData(IssueStatus.Assigned, IssueAction.Reject, Manager, UserRole.Management, IssueActionAvailability.Forbidden)]
|
||||
[InlineData(IssueStatus.Assigned, IssueAction.SubmitForVerification, Assignee, UserRole.FacilityManager, IssueActionAvailability.InvalidState)]
|
||||
[InlineData(IssueStatus.InProgress, IssueAction.StartWork, Assignee, UserRole.FacilityManager, IssueActionAvailability.InvalidState)]
|
||||
[InlineData(IssueStatus.PendingVerification, IssueAction.Confirm, Assignee, UserRole.FacilityManager, IssueActionAvailability.Forbidden)]
|
||||
[InlineData(IssueStatus.PendingVerification, IssueAction.Reject, Assignee, UserRole.FacilityManager, IssueActionAvailability.InvalidState)]
|
||||
[InlineData(IssueStatus.PendingVerification, IssueAction.Reject, Replacement, UserRole.Admin, IssueActionAvailability.InvalidState)]
|
||||
[InlineData(IssueStatus.Resolved, IssueAction.Reopen, Reporter, UserRole.Admin, IssueActionAvailability.InvalidState)]
|
||||
[InlineData(IssueStatus.Rejected, IssueAction.Reject, Manager, UserRole.Management, IssueActionAvailability.InvalidState)]
|
||||
public void DisallowedTransitionsMatchAvailability(
|
||||
IssueStatus from, IssueAction action, int actorId, UserRole role, IssueActionAvailability expected)
|
||||
{
|
||||
var issue = At(from);
|
||||
var version = issue.RowVersion;
|
||||
Assert.Equal(expected, issue.Availability(action, actorId, role));
|
||||
Assert.Throws<InvalidOperationException>(() => issue.Transition(action, actorId, role, "Důvod"));
|
||||
Assert.Equal(from, issue.Status);
|
||||
Assert.Equal(version, issue.RowVersion);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(IssueStatus.PendingVerification, IssueAction.Reopen, Reporter, UserRole.Admin)]
|
||||
[InlineData(IssueStatus.Received, IssueAction.Reject, Manager, UserRole.Management)]
|
||||
public void ReasonsAreRequired(IssueStatus from, IssueAction action, int actorId, UserRole role)
|
||||
{
|
||||
var issue = At(from);
|
||||
Assert.Throws<ArgumentException>(() => issue.Transition(action, actorId, role, " "));
|
||||
Assert.Equal(from, issue.Status);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ReassigningToSameUserKeepsWorkInProgress()
|
||||
{
|
||||
var issue = At(IssueStatus.InProgress);
|
||||
var version = issue.RowVersion;
|
||||
Assert.Throws<ArgumentException>(() =>
|
||||
issue.Assign(Manager, UserRole.Management, Assignee, UserRole.FacilityManager, IssuePriority.High));
|
||||
Assert.Equal(IssueStatus.InProgress, issue.Status);
|
||||
Assert.Equal(version, issue.RowVersion);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ParticipationFollowsOwnershipAndClosesWithIssue()
|
||||
{
|
||||
var issue = At(IssueStatus.Assigned);
|
||||
Assert.True(issue.CanRead(Reporter, UserRole.Admin));
|
||||
Assert.True(issue.CanRead(Replacement, UserRole.Admin));
|
||||
Assert.False(issue.CanRead(Replacement, UserRole.Student));
|
||||
Assert.True(issue.CanRead(Replacement, UserRole.FacilityManager));
|
||||
Assert.Equal(IssueActionAvailability.Forbidden, issue.Availability(IssueAction.Comment, Manager, UserRole.Management));
|
||||
Assert.Equal(IssueActionAvailability.Allowed, issue.Availability(IssueAction.Comment, Reporter, UserRole.Admin));
|
||||
Assert.Equal(IssueActionAvailability.Allowed, issue.Availability(IssueAction.AddAttachments, Replacement, UserRole.Admin));
|
||||
issue.RecordParticipation(IssueAction.Comment, Reporter, UserRole.Admin);
|
||||
issue.Transition(IssueAction.Reject, Assignee, UserRole.FacilityManager, "Důvod");
|
||||
Assert.Equal(IssueActionAvailability.InvalidState, issue.Availability(IssueAction.AddAttachments, Reporter, UserRole.Admin));
|
||||
}
|
||||
|
||||
private static Issue At(IssueStatus result)
|
||||
{
|
||||
var issue = new Issue(Reporter, "Projektor", "Nefunguje", 1, null, null);
|
||||
if (result == IssueStatus.Received)
|
||||
return issue;
|
||||
if (result == IssueStatus.Rejected)
|
||||
{
|
||||
issue.Transition(IssueAction.Reject, Manager, UserRole.Management, "Důvod");
|
||||
return issue;
|
||||
}
|
||||
|
||||
issue.Assign(Manager, UserRole.Management, Assignee, UserRole.FacilityManager, null);
|
||||
if (result == IssueStatus.Assigned)
|
||||
return issue;
|
||||
issue.Transition(IssueAction.StartWork, Assignee, UserRole.FacilityManager, null);
|
||||
if (result == IssueStatus.InProgress)
|
||||
return issue;
|
||||
issue.Transition(IssueAction.SubmitForVerification, Assignee, UserRole.FacilityManager, null);
|
||||
if (result == IssueStatus.Resolved)
|
||||
issue.Transition(IssueAction.Confirm, Reporter, UserRole.Admin, null);
|
||||
return issue;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
using Helpdesk.Domain.Proposals;
|
||||
using Helpdesk.Domain.Users;
|
||||
|
||||
namespace Helpdesk.UnitTests;
|
||||
|
||||
public sealed class ProposalTests
|
||||
{
|
||||
private const int Author = 1;
|
||||
private const int Voter = 2;
|
||||
|
||||
[Theory]
|
||||
[InlineData(ProposalStatus.Submitted, ProposalStatus.UnderReview, ProposalStatus.Accepted, ProposalStatus.Rejected)]
|
||||
[InlineData(ProposalStatus.UnderReview, ProposalStatus.Accepted, ProposalStatus.Rejected)]
|
||||
[InlineData(ProposalStatus.Accepted, ProposalStatus.Implemented)]
|
||||
[InlineData(ProposalStatus.Rejected)]
|
||||
[InlineData(ProposalStatus.Implemented)]
|
||||
public void EnforcesTransitionTable(ProposalStatus from, params ProposalStatus[] permitted)
|
||||
{
|
||||
foreach (var target in Enum.GetValues<ProposalStatus>())
|
||||
{
|
||||
var proposal = At(from);
|
||||
var allowed = permitted.Contains(target);
|
||||
Assert.Equal(allowed, proposal.CanTransitionTo(target));
|
||||
if (allowed)
|
||||
{
|
||||
proposal.ChangeStatus(target, UserRole.Management, "Vyjádření");
|
||||
Assert.Equal(target, proposal.Status);
|
||||
}
|
||||
else
|
||||
{
|
||||
Assert.Throws<InvalidOperationException>(() => proposal.ChangeStatus(target, UserRole.Management, null));
|
||||
Assert.Equal(from, proposal.Status);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ReviewRequiresManagementOrAdminAndRejectionRequiresNote()
|
||||
{
|
||||
var proposal = At(ProposalStatus.Submitted);
|
||||
Assert.Throws<InvalidOperationException>(() => proposal.ChangeStatus(ProposalStatus.Accepted, UserRole.Student, null));
|
||||
Assert.Throws<ArgumentException>(() => proposal.ChangeStatus(ProposalStatus.Rejected, UserRole.Admin, " "));
|
||||
Assert.Equal(ProposalStatus.Submitted, proposal.Status);
|
||||
proposal.ChangeStatus(ProposalStatus.Accepted, UserRole.Admin, null);
|
||||
Assert.Equal(ProposalStatus.Accepted, proposal.Status);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(ProposalStatus.Submitted, true, true)]
|
||||
[InlineData(ProposalStatus.UnderReview, false, true)]
|
||||
[InlineData(ProposalStatus.Accepted, false, false)]
|
||||
[InlineData(ProposalStatus.Rejected, false, false)]
|
||||
[InlineData(ProposalStatus.Implemented, false, false)]
|
||||
public void AuthorAndAdminEditAndOtherUsersVoteOnlyInEligibleStates(ProposalStatus state, bool mayEdit, bool mayVote)
|
||||
{
|
||||
var proposal = At(state);
|
||||
Assert.Equal(mayEdit, proposal.IsEditable);
|
||||
Assert.False(proposal.CanVote(Author));
|
||||
Assert.Equal(mayVote, proposal.CanVote(Voter));
|
||||
Assert.Throws<InvalidOperationException>(() => proposal.Edit(Voter, UserRole.Student, "Změna", "Popis", 1));
|
||||
if (mayEdit)
|
||||
{
|
||||
proposal.Edit(Author, UserRole.Student, "Změna", "Popis", 1);
|
||||
Assert.Equal("Změna", proposal.Title);
|
||||
proposal.Edit(Voter, UserRole.Admin, "Další změna", "Popis", 1);
|
||||
Assert.Equal("Další změna", proposal.Title);
|
||||
Assert.Equal(Author, proposal.AuthorId);
|
||||
}
|
||||
else
|
||||
{
|
||||
Assert.Throws<InvalidOperationException>(() => proposal.Edit(Author, UserRole.Student, "Změna", "Popis", 1));
|
||||
Assert.Throws<InvalidOperationException>(() => proposal.Edit(Voter, UserRole.Admin, "Změna", "Popis", 1));
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RepeatingVotePreservesTimestampAndClosingPreventsChanges()
|
||||
{
|
||||
var proposal = At(ProposalStatus.Submitted);
|
||||
var now = DateTime.UnixEpoch;
|
||||
Assert.Throws<InvalidOperationException>(() => new ProposalVote(proposal, Author, 1, now));
|
||||
Assert.Throws<ArgumentOutOfRangeException>(() => new ProposalVote(proposal, Voter, 0, now));
|
||||
|
||||
var vote = new ProposalVote(proposal, Voter, 1, now);
|
||||
vote.SetValue(proposal, 1, now.AddMinutes(1));
|
||||
Assert.Equal(now, vote.VotedAt);
|
||||
vote.SetValue(proposal, -1, now.AddMinutes(2));
|
||||
Assert.Equal((sbyte)-1, vote.Value);
|
||||
Assert.Equal(now.AddMinutes(2), vote.VotedAt);
|
||||
proposal.ChangeStatus(ProposalStatus.Accepted, UserRole.Management, null);
|
||||
Assert.Throws<InvalidOperationException>(() => vote.SetValue(proposal, 1, now.AddMinutes(3)));
|
||||
}
|
||||
|
||||
private static Proposal At(ProposalStatus status)
|
||||
{
|
||||
var proposal = new Proposal(Author, "Návrh", "Popis", 1);
|
||||
if (status == ProposalStatus.Implemented)
|
||||
proposal.ChangeStatus(ProposalStatus.Accepted, UserRole.Management, null);
|
||||
if (status != ProposalStatus.Submitted)
|
||||
proposal.ChangeStatus(status, UserRole.Management, "Vyjádření");
|
||||
return proposal;
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
@@ -0,0 +1 @@
|
||||
CREATE INDEX ix_proposal_created_at ON proposal (created_at);
|
||||
@@ -0,0 +1,2 @@
|
||||
ALTER TABLE app_user
|
||||
ADD COLUMN is_deleted BOOLEAN NOT NULL DEFAULT FALSE;
|
||||
+29
-2
@@ -11,8 +11,35 @@ 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
|
||||
# Port webové aplikace na hostiteli (stejná adresa jako API).
|
||||
WEB_HTTP_PORT=8081
|
||||
# Adresa reverse proxy tak, jak ji API a web 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.
|
||||
# Lokálně bez proxy: http://localhost:8081 (odkazy z e-mailů pak vedou na web v Dockeru).
|
||||
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=''
|
||||
|
||||
# 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
|
||||
@@ -0,0 +1,2 @@
|
||||
FROM mariadb:11.4
|
||||
COPY --chmod=0644 01-accounts.sh /docker-entrypoint-initdb.d/01-accounts.sh
|
||||
@@ -1,11 +1,12 @@
|
||||
# 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.
|
||||
# Vývojové spuštění: docker compose -f deploy/docker-compose.yml --env-file deploy/.env up --build
|
||||
# Reverse proxy ukončuje HTTPS a připojuje se k webu a API přes HTTP
|
||||
# (/ včetně /swagger → web, /api/* → api).
|
||||
|
||||
name: helpdesk
|
||||
|
||||
services:
|
||||
db:
|
||||
image: mariadb:11.4
|
||||
build: ./db-init
|
||||
environment:
|
||||
MARIADB_ROOT_PASSWORD: ${DB_ROOT_PASSWORD:?}
|
||||
MARIADB_DATABASE: helpdesk
|
||||
@@ -14,7 +15,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
|
||||
@@ -44,6 +44,16 @@ 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:-}
|
||||
Firebase__ServiceAccountJson: ${FIREBASE_SERVICE_ACCOUNT_JSON:-}
|
||||
ReverseProxy__TrustedIp: ${TRUSTED_REVERSE_PROXY_IP:-}
|
||||
ReverseProxy__TrustedWebIp: ${WEB_API_WEB_IP:-172.30.242.6}
|
||||
ADMIN_EMAIL: ${ADMIN_EMAIL:-}
|
||||
ADMIN_PASSWORD: ${ADMIN_PASSWORD:-}
|
||||
volumes:
|
||||
@@ -51,16 +61,46 @@ 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"
|
||||
networks: [frontend, backend]
|
||||
- "${PROXY_UPSTREAM_BIND_ADDRESS:-127.0.0.1}:${API_HTTP_PORT:-8080}:8080"
|
||||
networks:
|
||||
frontend:
|
||||
backend:
|
||||
web-api:
|
||||
aliases: [api-web]
|
||||
|
||||
web:
|
||||
build:
|
||||
context: ..
|
||||
dockerfile: web/Dockerfile
|
||||
environment:
|
||||
ASPNETCORE_ENVIRONMENT: ${ASPNETCORE_ENVIRONMENT:-Development}
|
||||
Api__BaseUrl: http://api-web:8080/
|
||||
ReverseProxy__TrustedIp: ${TRUSTED_REVERSE_PROXY_IP:-}
|
||||
volumes:
|
||||
# Klíče pro šifrování cookie – bez nich by restart kontejneru odhlásil všechny uživatele.
|
||||
- web-keys:/app/keys
|
||||
depends_on:
|
||||
- api
|
||||
ports:
|
||||
- "${PROXY_UPSTREAM_BIND_ADDRESS:-127.0.0.1}:${WEB_HTTP_PORT:-8081}:8080"
|
||||
networks:
|
||||
frontend:
|
||||
web-api:
|
||||
ipv4_address: ${WEB_API_WEB_IP:-172.30.242.6}
|
||||
|
||||
networks:
|
||||
frontend:
|
||||
backend:
|
||||
internal: true
|
||||
web-api:
|
||||
# Při kolizi s existující sítí lze společně přepsat WEB_API_SUBNET a WEB_API_WEB_IP.
|
||||
internal: true
|
||||
ipam:
|
||||
config:
|
||||
- subnet: ${WEB_API_SUBNET:-172.30.242.0/29}
|
||||
|
||||
volumes:
|
||||
db-data:
|
||||
uploads:
|
||||
web-keys:
|
||||
+123
-109
@@ -72,7 +72,7 @@ Webová i mobilní aplikace jsou **tenké klienty** – nepřistupují do datab
|
||||
| `TEACHER` | Vyučující | Samoregistrace | Stejná oprávnění jako student |
|
||||
| `FACILITY_MANAGER` | Správce budov | Přiděluje administrátor | Řeší přiřazené závady (odpovědná osoba) |
|
||||
| `MANAGEMENT` | Vedení školy | Přiděluje administrátor | Přiřazuje závady řešitelům, hodnotí návrhy, vidí statistiky |
|
||||
| `ADMIN` | Administrátor | Přiděluje administrátor / vytvořen při instalaci | Správa uživatelů a jejich rolí, správa číselníků |
|
||||
| `ADMIN` | Administrátor | Přiděluje administrátor / vytvořen při instalaci | Správa systému, všechny akce nad závadami a návrhy, statistiky |
|
||||
|
||||
- Každý uživatel má **právě jednu roli** (sloupec `app_user.role`). Základní funkce (hlásit závady, podávat návrhy, hlasovat) má každá role, takže kombinace rolí nejsou potřeba – např. vyučující, který je ve vedení, dostane roli `MANAGEMENT`.
|
||||
- Při samoregistraci se role `STUDENT` / `TEACHER` určí automaticky **podle domény e-mailu** (např. `@student.univerzita.cz` → student, `@univerzita.cz` → vyučující). Domény jsou v konfiguraci backendu. Registrace z jiné domény není povolena. Tím se zabrání tomu, aby se student zaregistroval jako vyučující.
|
||||
@@ -86,23 +86,26 @@ Legenda: ✅ povoleno, 🔸 povoleno s podmínkou, — nepovoleno
|
||||
|---|:-:|:-:|:-:|:-:|
|
||||
| Nahlásit závadu, přiložit soubory | ✅ | ✅ | ✅ | ✅ |
|
||||
| Zobrazit vlastní hlášení | ✅ | ✅ | ✅ | ✅ |
|
||||
| Upravit vlastní hlášení | 🔸 jen ve stavu *Přijata* | 🔸 | 🔸 | 🔸 |
|
||||
| Centrální přehled všech závad (filtry) | — | ✅ (jen čtení) | ✅ | — |
|
||||
| Přiřadit / přeřadit závadu řešiteli, nastavit prioritu | — | — | ✅ | — |
|
||||
| Zahájit řešení, předat k ověření | — | 🔸 jen přiřazené jemu | 🔸 jen přiřazené jemu | — |
|
||||
| Zamítnout závadu (s důvodem) | — | 🔸 jen přiřazené jemu | 🔸 přiřazené jemu + ve stavu *Přijata* | — |
|
||||
| Potvrdit vyřešení / znovu otevřít | 🔸 jen hlásič | 🔸 jen hlásič | 🔸 jen hlásič | — |
|
||||
| Komentovat závadu | 🔸 hlásič | 🔸 hlásič nebo řešitel | 🔸 hlásič nebo řešitel; ostatní jen čtení | — |
|
||||
| Upravit hlášení | 🔸 vlastní ve stavu *Přijata* | 🔸 vlastní ve stavu *Přijata* | 🔸 vlastní ve stavu *Přijata* | 🔸 libovolné ve stavu *Přijata* |
|
||||
| Centrální přehled všech závad (filtry) | — | ✅ (jen čtení) | ✅ | ✅ |
|
||||
| Přiřadit / přeřadit závadu řešiteli, nastavit prioritu | — | — | ✅ | ✅ |
|
||||
| Zahájit řešení, předat k ověření | — | 🔸 jen přiřazené jemu | 🔸 jen přiřazené jemu | 🔸 ve stavu příslušného přechodu |
|
||||
| Zamítnout závadu (s důvodem) | — | 🔸 jen přiřazené jemu | 🔸 přiřazené jemu nebo nepřiřazené ve stavu *Přijata* | 🔸 ve stavu příslušného přechodu |
|
||||
| Potvrdit vyřešení / znovu otevřít | 🔸 jen hlásič | 🔸 jen hlásič | 🔸 jen hlásič | 🔸 ve stavu *Čeká na ověření* |
|
||||
| Komentovat závadu / přidat přílohu | 🔸 hlásič | 🔸 hlásič nebo řešitel | 🔸 hlásič nebo řešitel; ostatní jen čtení | 🔸 libovolná otevřená závada |
|
||||
| Podat návrh na zlepšení | ✅ | ✅ | ✅ | ✅ |
|
||||
| Zobrazit všechny návrhy | ✅ | ✅ | ✅ | ✅ |
|
||||
| Hlasovat pro návrh | 🔸 ne pro vlastní | 🔸 | 🔸 | 🔸 |
|
||||
| Hodnotit návrhy (změna stavu, vyjádření) | — | — | ✅ | — |
|
||||
| Statistiky a výkazy | — | — | ✅ | — |
|
||||
| Upravit návrh ve stavu *Podán* | 🔸 autor | 🔸 autor | 🔸 autor | ✅ |
|
||||
| Hodnotit návrhy (změna stavu, vyjádření) | — | — | ✅ | ✅ |
|
||||
| Statistiky a výkazy | — | — | ✅ | ✅ |
|
||||
| Správa uživatelů a rolí | — | — | — | ✅ |
|
||||
| Správa číselníků (budovy, kategorie) | — | — | — | ✅ |
|
||||
|
||||
Pravidla „🔸“ nelze vyjádřit jen rolí – jsou to **pravidla nad konkrétním záznamem** (resource-based authorization) a kontroluje je aplikační vrstva backendu (viz kap. 9.3).
|
||||
|
||||
`ADMIN` může spravovat závady a návrhy ostatních uživatelů. Požadavky na stav záznamu, povinné údaje a `rowVersion` platí pro všechny role. Profil, přihlášení, hlasování, zařízení a osobní notifikace se vztahují k aktuálně přihlášenému účtu.
|
||||
|
||||
---
|
||||
|
||||
## 3. Funkční požadavky
|
||||
@@ -113,7 +116,7 @@ Pravidla „🔸“ nelze vyjádřit jen rolí – jsou to **pravidla nad konkr
|
||||
| FR-01 | Registrace e-mailem a heslem; po registraci ověření e-mailu odkazem. |
|
||||
| FR-02 | Přihlášení e-mailem a heslem, vydání JWT access tokenu a refresh tokenu; odhlášení zablokuje oba tokeny (podle `jti`); „odhlásit ze všech zařízení“. |
|
||||
| FR-03 | Obnova zapomenutého hesla přes e-mail. |
|
||||
| FR-04 | Administrátor vyhledává uživatele, mění jejich roli, deaktivuje účty. |
|
||||
| FR-04 | Administrátor vyhledává, zakládá a upravuje účty, mění role, aktivuje, deaktivuje a maže účty. Role, stav i smazání může změnit u více účtů najednou. |
|
||||
| FR-05 | Uživatel upravuje svůj profil (jméno, telefon, zapnutí e-mailových notifikací). |
|
||||
|
||||
### Hlášení závad
|
||||
@@ -122,7 +125,7 @@ Pravidla „🔸“ nelze vyjádřit jen rolí – jsou to **pravidla nad konkr
|
||||
| FR-10 | Uživatel nahlásí závadu: název, popis, kategorie (typ), budova a upřesnění místa. |
|
||||
| FR-11 | K hlášení lze při vytvoření i později v průběhu komunikace přiložit fotografii nebo jiný soubor (JPG, PNG, HEIC, PDF, DOCX; max. 10 MB/soubor, max. 5 souborů najednou). |
|
||||
| FR-12 | Závada prochází stavy *Přijata → Přiřazena → V řešení → Čeká na ověření → Vyřešena*, případně *Zamítnuta* (kap. 6). Nepovolené přechody server odmítne. |
|
||||
| FR-13 | Vedení přiřazuje závadu odpovědné osobě (správci budov); u každého správce vidí počet jeho otevřených závad. |
|
||||
| FR-13 | Vedení a administrátor přiřazují závadu odpovědné osobě; u každého řešitele vidí počet jeho otevřených závad. |
|
||||
| FR-14 | Řešitel může závadu zamítnout s povinným uvedením důvodu. |
|
||||
| FR-15 | Hlásič potvrdí vyřešení, nebo závadu znovu otevře (s povinným důvodem) → stav *V řešení*. |
|
||||
| FR-16 | Hlásič a řešitel si u závady vyměňují komentáře; protistrana je o novém komentáři informována. |
|
||||
@@ -134,13 +137,13 @@ Pravidla „🔸“ nelze vyjádřit jen rolí – jsou to **pravidla nad konkr
|
||||
| FR-20 | Každý uživatel podá návrh: název, popis, oblast (studium, služby, prostředí, ostatní). |
|
||||
| FR-21 | Uživatel hlasuje pro/proti návrhu jiného uživatele; jeden hlas na návrh, hlas lze změnit či zrušit; autor pro vlastní návrh hlasovat nemůže. |
|
||||
| FR-22 | Seznam návrhů lze řadit podle podpory (skóre) a data a filtrovat podle stavu a oblasti. |
|
||||
| FR-23 | Vedení hodnotí návrhy – mění stav (*V posouzení, Přijat, Zamítnut, Realizován*) a připojuje vyjádření. |
|
||||
| FR-23 | Vedení a administrátor hodnotí návrhy, mění jejich stav (*V posouzení, Přijat, Zamítnut, Realizován*) a připojují vyjádření. |
|
||||
|
||||
### Správa, přehledy, notifikace
|
||||
| ID | Požadavek |
|
||||
|---|---|
|
||||
| FR-30 | Centrální přehled závad a návrhů s filtrováním podle typu (kategorie), stavu, lokality (budovy), řešitele a data; stránkování a řazení. |
|
||||
| FR-31 | Statistiky pro vedení: počet závad podle stavu / kategorie / budovy, průměrná doba do přiřazení a do uzavření, vytížení řešitelů, nejpodporovanější návrhy, vše za zvolené období. |
|
||||
| FR-31 | Statistiky pro vedení a administrátory zahrnují počty závad podle stavu, kategorie či budovy, průměrnou dobu do přiřazení a uzavření, vytížení řešitelů a nejpodporovanější návrhy za zvolené období. |
|
||||
| FR-32 | Notifikace v aplikaci (seznam, počet nepřečtených), e-mailem a push notifikací v mobilní aplikaci (kap. 8). |
|
||||
| FR-33 | Nedoručené e-maily a push notifikace se automaticky opakují; trvale nedoručené vidí administrátor a může je odeslat znovu. |
|
||||
|
||||
@@ -153,7 +156,7 @@ Pravidla „🔸“ nelze vyjádřit jen rolí – jsou to **pravidla nad konkr
|
||||
| NFR-01 | Bezpečnost | Komunikace výhradně přes HTTPS; hesla hashovaná; JWT s krátkou platností; citlivé údaje šifrované (kap. 10). |
|
||||
| NFR-02 | Konzistence | Pravidla životního cyklu a oprávnění jsou pouze na serveru; klienti je jen zobrazují. |
|
||||
| NFR-03 | Souběžnost | Změny stavu závady chráněny optimistickým zamykáním (`row_version`) – dvě souběžné změny nevedou k nekonzistentnímu stavu. |
|
||||
| NFR-04 | Dokumentace API | Swagger UI (OpenAPI) dostupné na `/swagger`, včetně autorizace tokenem. |
|
||||
| NFR-04 | Dokumentace API | Swagger UI na `/swagger` pro administrátory přihlášené na webu. Volání API ze Swaggeru se autorizují access tokenem. |
|
||||
| NFR-05 | Výkon | Seznamy stránkované (výchozí 20 záznamů), indexy pro všechny filtry v přehledu. |
|
||||
| NFR-06 | Použitelnost | Responzivní web (desktop i mobil), mobilní aplikace Android 8.0+ (API 26). Rozhraní v češtině. |
|
||||
| NFR-07 | Nasaditelnost | Celý systém spustitelný příkazem `docker compose up`. |
|
||||
@@ -198,7 +201,7 @@ flowchart LR
|
||||
S --- UC1 & UC2 & UC3 & UC4 & UC10 & UC11
|
||||
F --- UC3 & UC6 & UC7 & UC20
|
||||
M --- UC5 & UC7 & UC12 & UC20 & UC21
|
||||
A --- UC22 & UC23
|
||||
A --- UC5 & UC6 & UC7 & UC12 & UC20 & UC21 & UC22 & UC23
|
||||
```
|
||||
|
||||
*Správce budov, vedení i administrátor mají navíc všechny případy užití studenta (hlášení závad, návrhy, hlasování).*
|
||||
@@ -229,16 +232,16 @@ stateDiagram-v2
|
||||
state "Zamítnuta" as REJECTED
|
||||
|
||||
[*] --> RECEIVED : hlásič vytvoří
|
||||
RECEIVED --> ASSIGNED : vedení přiřadí řešitele
|
||||
ASSIGNED --> ASSIGNED : vedení přeřadí
|
||||
ASSIGNED --> IN_PROGRESS : řešitel zahájí
|
||||
IN_PROGRESS --> ASSIGNED : vedení přeřadí
|
||||
IN_PROGRESS --> PENDING_VERIFICATION : řešitel předá k ověření
|
||||
PENDING_VERIFICATION --> RESOLVED : hlásič potvrdí
|
||||
PENDING_VERIFICATION --> IN_PROGRESS : hlásič znovu otevře
|
||||
RECEIVED --> REJECTED : vedení zamítne
|
||||
ASSIGNED --> REJECTED : řešitel zamítne
|
||||
IN_PROGRESS --> REJECTED : řešitel zamítne
|
||||
RECEIVED --> ASSIGNED : vedení nebo admin přiřadí řešitele
|
||||
ASSIGNED --> ASSIGNED : vedení nebo admin přeřadí
|
||||
ASSIGNED --> IN_PROGRESS : řešitel nebo admin zahájí
|
||||
IN_PROGRESS --> ASSIGNED : vedení nebo admin přeřadí
|
||||
IN_PROGRESS --> PENDING_VERIFICATION : řešitel nebo admin předá k ověření
|
||||
PENDING_VERIFICATION --> RESOLVED : hlásič nebo admin potvrdí
|
||||
PENDING_VERIFICATION --> IN_PROGRESS : hlásič nebo admin znovu otevře
|
||||
RECEIVED --> REJECTED : vedení nebo admin zamítne
|
||||
ASSIGNED --> REJECTED : řešitel nebo admin zamítne
|
||||
IN_PROGRESS --> REJECTED : řešitel nebo admin zamítne
|
||||
RESOLVED --> [*]
|
||||
REJECTED --> [*]
|
||||
```
|
||||
@@ -248,14 +251,14 @@ stateDiagram-v2
|
||||
| # | Z → Do | Kdo smí | Povinné údaje | Vedlejší efekty | Notifikace |
|
||||
|---|---|---|---|---|---|
|
||||
| T1 | — → **Přijata** | každý přihlášený (stává se hlásičem) | název, popis, kategorie | událost `CREATED` | vedení: `ISSUE_CREATED` |
|
||||
| T2 | Přijata → **Přiřazena** | vedení | řešitel (role správce budov / vedení) | `assignee_id`, událost `ASSIGNED` | řešitel: `ISSUE_ASSIGNED`; hlásič: změna stavu |
|
||||
| T3 | Přiřazena / V řešení → **Přiřazena** (přeřazení) | vedení | nový řešitel | změna `assignee_id`, událost `ASSIGNED` | nový řešitel: `ISSUE_ASSIGNED` |
|
||||
| T4 | Přiřazena → **V řešení** | přiřazený řešitel | — | událost `STATUS_CHANGED` | hlásič |
|
||||
| T5 | V řešení → **Čeká na ověření** | přiřazený řešitel | volitelná poznámka | událost `STATUS_CHANGED` | hlásič |
|
||||
| T6 | Čeká na ověření → **Vyřešena** | hlásič | — | událost `STATUS_CHANGED` (= čas uzavření) | řešitel |
|
||||
| T7 | Čeká na ověření → **V řešení** | hlásič | důvod znovuotevření | událost s důvodem v `note` | řešitel: `ISSUE_REOPENED` |
|
||||
| T8 | Přiřazena / V řešení → **Zamítnuta** | přiřazený řešitel | důvod zamítnutí | událost s důvodem v `note` (= čas uzavření) | hlásič |
|
||||
| T9 | Přijata → **Zamítnuta** | vedení | důvod zamítnutí | událost s důvodem v `note` (= čas uzavření) | hlásič |
|
||||
| T2 | Přijata → **Přiřazena** | vedení / admin | řešitel (správce budov / vedení / admin) | `assignee_id`, událost `ASSIGNED` | řešitel: `ISSUE_ASSIGNED`; hlásič: změna stavu |
|
||||
| T3 | Přiřazena / V řešení → **Přiřazena** (přeřazení) | vedení / admin | nový řešitel | změna `assignee_id`, událost `ASSIGNED` | `ISSUE_ASSIGNED` novému řešiteli, `ISSUE_STATUS_CHANGED` hlásiči při změně stavu, pokud hlásič není novým řešitelem |
|
||||
| T4 | Přiřazena → **V řešení** | přiřazený řešitel / admin | — | událost `STATUS_CHANGED` | hlásič |
|
||||
| T5 | V řešení → **Čeká na ověření** | přiřazený řešitel / admin | volitelná poznámka | událost `STATUS_CHANGED` | hlásič |
|
||||
| T6 | Čeká na ověření → **Vyřešena** | hlásič / admin | — | událost `STATUS_CHANGED` (= čas uzavření) | řešitel |
|
||||
| T7 | Čeká na ověření → **V řešení** | hlásič / admin | důvod znovuotevření | událost s důvodem v `note` | řešitel: `ISSUE_REOPENED` |
|
||||
| T8 | Přiřazena / V řešení → **Zamítnuta** | přiřazený řešitel / admin | důvod zamítnutí | událost s důvodem v `note` (= čas uzavření) | hlásič |
|
||||
| T9 | Přijata → **Zamítnuta** | vedení / admin | důvod zamítnutí | událost s důvodem v `note` (= čas uzavření) | hlásič |
|
||||
|
||||
**Obecná pravidla**
|
||||
|
||||
@@ -300,19 +303,19 @@ stateDiagram-v2
|
||||
state "Realizován" as IMPLEMENTED
|
||||
|
||||
[*] --> SUBMITTED : uživatel podá
|
||||
SUBMITTED --> UNDER_REVIEW : vedení
|
||||
SUBMITTED --> ACCEPTED : vedení
|
||||
SUBMITTED --> REJECTED : vedení (s vyjádřením)
|
||||
UNDER_REVIEW --> ACCEPTED : vedení
|
||||
UNDER_REVIEW --> REJECTED : vedení (s vyjádřením)
|
||||
ACCEPTED --> IMPLEMENTED : vedení
|
||||
SUBMITTED --> UNDER_REVIEW : vedení nebo admin
|
||||
SUBMITTED --> ACCEPTED : vedení nebo admin
|
||||
SUBMITTED --> REJECTED : vedení nebo admin (s vyjádřením)
|
||||
UNDER_REVIEW --> ACCEPTED : vedení nebo admin
|
||||
UNDER_REVIEW --> REJECTED : vedení nebo admin (s vyjádřením)
|
||||
ACCEPTED --> IMPLEMENTED : vedení nebo admin
|
||||
REJECTED --> [*]
|
||||
IMPLEMENTED --> [*]
|
||||
```
|
||||
|
||||
- Stavy mění pouze **vedení školy**; zamítnutí vyžaduje vyjádření, u ostatních je volitelné. Vyjádření se ukládá do `note` příslušné události.
|
||||
- Autor může návrh upravit, dokud je ve stavu *Podán* (událost `UPDATED`).
|
||||
- Každá změna se zapisuje do `proposal_event`, autor dostane notifikaci.
|
||||
- Stavy může měnit vedení školy nebo administrátor. Zamítnutí vyžaduje vyjádření, u ostatních přechodů je volitelné. Vyjádření se ukládá do `note` příslušné události.
|
||||
- Autor nebo administrátor může návrh upravit, dokud je ve stavu *Podán* (událost `UPDATED`).
|
||||
- Každá změna se zapisuje do `proposal_event`. Při změně stavu dostane autor notifikaci, pokud stav nezměnil sám.
|
||||
|
||||
### 7.2 Pravidla hlasování
|
||||
|
||||
@@ -320,8 +323,8 @@ stateDiagram-v2
|
||||
|---|---|
|
||||
| Každý uživatel má jeden hlas (na návrh) | Primární klíč `proposal_vote (proposal_id, user_id)` – druhý hlas fyzicky nelze uložit |
|
||||
| Hlas pro / proti | `value` = `+1` / `-1` (CHECK omezení) |
|
||||
| Hlas lze změnit | `PUT /api/proposals/{id}/vote` s novou hodnotou → UPDATE (upsert) |
|
||||
| Hlas lze zrušit | `DELETE /api/proposals/{id}/vote` → DELETE |
|
||||
| Hlas lze změnit | `PUT /api/v1/proposals/{id}/vote` s novou hodnotou → UPDATE (upsert) |
|
||||
| Hlas lze zrušit | `DELETE /api/v1/proposals/{id}/vote` → DELETE |
|
||||
| Autor nehlasuje pro vlastní návrh | Kontrola v aplikační vrstvě → 403 |
|
||||
| Hlasovat lze jen o otevřených návrzích | Stav *Podán* nebo *V posouzení*; po rozhodnutí vedení je hlasování uzavřeno (409) |
|
||||
| Pořadí podle podpory | Pohled `v_proposal_score` (počet pro, proti, skóre = součet) |
|
||||
@@ -354,7 +357,7 @@ sequenceDiagram
|
||||
participant SMTP as SMTP server
|
||||
participant FCM as Firebase Cloud Messaging
|
||||
|
||||
C->>API: POST /api/issues/42/assign
|
||||
C->>API: POST /api/v1/issues/42/assign
|
||||
API->>DB: BEGIN; UPDATE issue; INSERT issue_event;<br/>INSERT notification (×N);<br/>INSERT notification_delivery (EMAIL, PUSH); COMMIT
|
||||
API-->>C: 200 OK
|
||||
loop každých pár sekund
|
||||
@@ -371,9 +374,9 @@ sequenceDiagram
|
||||
end
|
||||
```
|
||||
|
||||
- **V aplikaci:** tabulka `notification`. Notifikace v aplikaci je doručena vždy, protože vzniká v DB ve stejné transakci jako událost. Klient zobrazuje seznam a počet nepřečtených (`GET /api/notifications/unread-count`, web jej obnovuje periodicky).
|
||||
- **V aplikaci:** tabulka `notification`. Notifikace v aplikaci je doručena vždy, protože vzniká v DB ve stejné transakci jako událost. Klient zobrazuje seznam a počet nepřečtených (`GET /api/v1/notifications/unread-count`, web jej obnovuje periodicky).
|
||||
- **E-mail:** SMTP (knihovna MailKit); ve vývoji zachytává e-maily kontejner Mailpit.
|
||||
- **Push:** mobilní aplikace po přihlášení zaregistruje FCM token (`POST /api/devices`); backend odesílá přes Firebase Admin SDK.
|
||||
- **Push:** mobilní aplikace po přihlášení zaregistruje FCM token (`POST /api/v1/devices`); backend odesílá přes Firebase Admin SDK.
|
||||
- Pro každou notifikaci se vytvoří řádek `notification_delivery` pro každý externí kanál. Stav kanálu se tak sleduje samostatně: e-mail může selhat, i když push prošel.
|
||||
|
||||
### 8.3 Řešení nedoručení
|
||||
@@ -388,7 +391,7 @@ sequenceDiagram
|
||||
| Výpadek backendu během odesílání | řádek zůstal `PENDING` | po restartu jej dispatcher zpracuje znovu (doručení *alespoň jednou*; výjimečně může e-mail přijít dvakrát) | — |
|
||||
| Push dorazil, ale telefon byl offline / notifikaci uživatel zavřel | nelze zjistit | mobilní aplikace při spuštění a návratu do popředí načte nepřečtené notifikace z API | — |
|
||||
|
||||
- **Administrátor** má přehled nedoručených notifikací (`GET /api/admin/notification-deliveries?status=FAILED`) s důvodem chyby a může doručení ručně zopakovat (`POST …/{id}/retry` – vrátí stav na `PENDING`).
|
||||
- **Administrátor** má přehled nedoručených notifikací (`GET /api/v1/admin/notification-deliveries?status=FAILED`) s důvodem chyby a může doručení ručně zopakovat (`POST …/{id}/retry` – vrátí stav na `PENDING`).
|
||||
- `FOR UPDATE SKIP LOCKED` (MariaDB 10.6+) zajistí, že jeden záznam nezpracují dvě instance dispatcheru současně.
|
||||
- Úspěšná uživatelská operace nikdy neselže kvůli nedostupnému SMTP nebo FCM. Odeslání probíhá asynchronně z fronty v DB (outbox pattern).
|
||||
|
||||
@@ -407,8 +410,8 @@ flowchart TB
|
||||
|
||||
subgraph Docker["Docker Compose"]
|
||||
PROXY[Reverzní proxy nginx<br/>HTTPS / TLS]
|
||||
WEB[Webová aplikace<br/>ASP.NET Core MVC]
|
||||
API[Backend REST API<br/>ASP.NET Core Web API<br/>+ Swagger]
|
||||
WEB[Webová aplikace<br/>ASP.NET Core MVC<br/>+ Swagger UI]
|
||||
API[Backend REST API<br/>ASP.NET Core Web API<br/>+ OpenAPI]
|
||||
DB[(MariaDB 11)]
|
||||
FILES[[Volume: přílohy]]
|
||||
end
|
||||
@@ -419,7 +422,7 @@ flowchart TB
|
||||
BROWSER -- HTTPS --> PROXY
|
||||
MOB -- "HTTPS, JWT" --> PROXY
|
||||
PROXY --> WEB
|
||||
PROXY -- /api, /swagger --> API
|
||||
PROXY -- "/api/*" --> API
|
||||
WEB -- "REST, JWT" --> API
|
||||
API --> DB
|
||||
API --> FILES
|
||||
@@ -444,8 +447,8 @@ Fyzické nasazení (sítě, porty, úložiště, tajné klíče) popisuje kapito
|
||||
|
||||
### 9.3 Autorizace
|
||||
|
||||
1. **Podle role** – atribut `[Authorize(Roles = "MANAGEMENT")]` / politiky (např. `CanAssignIssues`, `CanEvaluateProposals`, `IsAdmin`). Role je v JWT jako claim `role`.
|
||||
2. **Nad konkrétním záznamem** – v aplikační vrstvě (`IssueAuthorizationService`): „je aktuální uživatel hlásičem / přiřazeným řešitelem této závady?“, „je autorem návrhu?“. Porušení → 403.
|
||||
1. **Podle role** – atributy jako `[Authorize(Roles = Roles.ManagementOrAdmin)]` a autorizační politiky. Role je v JWT jako claim `role`.
|
||||
2. **Nad konkrétním záznamem** – aplikační a doménová vrstva ověřují oprávnění k akci. U závad a úprav návrhů může administrátor jednat i u cizích záznamů. Porušení → 403.
|
||||
3. **Podle stavu** – stavový automat v doméně. Porušení → 409.
|
||||
|
||||
Detail závady vrací pole `allowedActions` (např. `["START_WORK", "REJECT", "COMMENT"]`), podle kterého klienti zobrazují ovládací prvky – logika tak není duplikována v klientech.
|
||||
@@ -508,10 +511,11 @@ Větvení: `main` (stabilní), `develop`, feature větve `feature/<nazev>`, merg
|
||||
| Oblast | Řešení |
|
||||
|---|---|
|
||||
| Hesla | Hash BCrypt (knihovna BCrypt.Net-Next, work factor 12; sůl je součástí hashe). Min. délka hesla 8 znaků. |
|
||||
| Přihlášení | Ochrana proti hádání hesla: po 5 neúspěšných pokusech zámek účtu na 15 minut (`failed_login_count`, `lockout_until`), rate limiting na `/api/auth/*`. |
|
||||
| Přihlášení | Ochrana proti hádání hesla: po 5 neúspěšných pokusech zámek účtu na 15 minut (`failed_login_count`, `lockout_until`), rate limiting na `/api/v1/auth/*`. |
|
||||
| Tokeny | Všechny tokeny jsou podepsané JWT podle RFC 7519 s unikátním `jti` a typem v hlavičce. V databázi není žádný token ani jeho hash (kap. 10.1). |
|
||||
| Šifrování citlivých údajů | Telefonní číslo uživatele šifrováno AES-256-GCM (EF Core value converter), klíč mimo DB – v proměnné prostředí / Docker secret. Přenos výhradně HTTPS (TLS 1.2+), HSTS. |
|
||||
| Přílohy | Kontrola typu (přípona + signatura souboru) a velikosti, ukládání pod náhodným GUID mimo webový kořen, stahování jen přes API s kontrolou oprávnění k závadě. |
|
||||
| Zápisy závad | Vytvoření závady, přidání komentáře a nahrání příloh mají společný limit 10 požadavků za minutu na účet a instanci API. Překročení vrací 429. |
|
||||
| Vstupy | Validace DTO (FluentValidation), parametrizované dotazy (EF Core), HTML výstup kódován Razorem (XSS), anti-forgery tokeny ve webových formulářích (CSRF). |
|
||||
| Tajemství | JWT klíč, DB heslo, šifrovací klíč, SMTP a Firebase přístupy pouze v proměnných prostředí / `.env` mimo Git. |
|
||||
|
||||
@@ -537,9 +541,9 @@ Všechny tokeny jsou JWT podle [RFC 7519](https://www.rfc-editor.org/rfc/rfc7519
|
||||
| Token | Hlavička `typ` | `auth_token.token_type` | Platnost | Claimy | `aud` | Kde se ověřuje |
|
||||
|---|---|---|---|---|---|---|
|
||||
| Access token | `at+jwt` | `ACCESS` | 15 min | `iss`, `sub`, `aud`, `iat`, `exp`, `jti`, `role` | `helpdesk-api` | každý požadavek na API |
|
||||
| Refresh token | `refresh+jwt` | `REFRESH` | 14 dní | `iss`, `sub`, `aud`, `iat`, `exp`, `jti` | `helpdesk-auth` | jen `/auth/refresh` a `/auth/logout` |
|
||||
| Ověření e-mailu | `email-confirm+jwt` | `EMAIL_CONFIRM` | 24 h | `iss`, `sub`, `aud`, `iat`, `exp`, `jti` | `helpdesk-auth` | `/auth/confirm-email` – jednorázový |
|
||||
| Reset hesla | `password-reset+jwt` | `PASSWORD_RESET` | 1 h | `iss`, `sub`, `aud`, `iat`, `exp`, `jti` | `helpdesk-auth` | `/auth/reset-password` – jednorázový |
|
||||
| Refresh token | `refresh+jwt` | `REFRESH` | 14 dní | `iss`, `sub`, `aud`, `iat`, `exp`, `jti` | `helpdesk-auth` | jen `/api/v1/auth/refresh` a `/api/v1/auth/logout` |
|
||||
| Ověření e-mailu | `email-confirm+jwt` | `EMAIL_CONFIRM` | 24 h | `iss`, `sub`, `aud`, `iat`, `exp`, `jti` | `helpdesk-auth` | `/api/v1/auth/confirm-email` – jednorázový |
|
||||
| Reset hesla | `password-reset+jwt` | `PASSWORD_RESET` | 1 h | `iss`, `sub`, `aud`, `iat`, `exp`, `jti` | `helpdesk-auth` | `/api/v1/auth/reset-password` – jednorázový |
|
||||
|
||||
Příklad access tokenu (dekódovaná hlavička a tělo):
|
||||
|
||||
@@ -569,7 +573,7 @@ Příklad access tokenu (dekódovaná hlavička a tělo):
|
||||
| `jti` | náhodný GUID v4 (nepatrná pravděpodobnost kolize) | 4.1.7 | registrovaný | `jti` (primární klíč) |
|
||||
| `role` | role uživatele (`app_user.role`) | 4.3 | soukromý | — |
|
||||
|
||||
- Do tokenů se **nedávají osobní údaje** (e-mail, jméno, telefon). JWT je jen podepsaný, ne šifrovaný, takže jeho obsah přečte každý, kdo token získá (RFC 7519, kap. 12). Údaje o uživateli vrací `GET /users/me`.
|
||||
- Do tokenů se **nedávají osobní údaje** (e-mail, jméno, telefon). JWT je jen podepsaný, ne šifrovaný, takže jeho obsah přečte každý, kdo token získá (RFC 7519, kap. 12). Údaje o uživateli vrací `GET /api/v1/users/me`.
|
||||
- Tokeny se přenášejí jen přes HTTPS (RFC 7519, kap. 12).
|
||||
- Claim `nbf` (4.1.5) se nepoužívá, protože tokeny platí hned od vydání.
|
||||
|
||||
@@ -577,10 +581,10 @@ Příklad access tokenu (dekódovaná hlavička a tělo):
|
||||
|
||||
| Akce | Změna v `auth_token` | `revoke_reason` |
|
||||
|---|---|---|
|
||||
| Přihlášení (`/auth/login`) | INSERT access + refresh tokenu | — |
|
||||
| Obnova tokenů (`/auth/refresh`) | použitý refresh token zneplatněn, INSERT nového páru | `USED` |
|
||||
| Odhlášení (`/auth/logout`) | zneplatněn access + refresh token tohoto zařízení, ostatní zařízení fungují dál | `LOGOUT` |
|
||||
| Odhlásit ze všech zařízení (`/auth/logout-all`) | zneplatněny všechny platné tokeny uživatele | `LOGOUT_ALL` |
|
||||
| Přihlášení (`/api/v1/auth/login`) | INSERT access + refresh tokenu | — |
|
||||
| Obnova tokenů (`/api/v1/auth/refresh`) | použitý refresh token zneplatněn, INSERT nového páru | `USED` |
|
||||
| Odhlášení (`/api/v1/auth/logout`) | zneplatněn access + refresh token tohoto zařízení, ostatní zařízení fungují dál | `LOGOUT` |
|
||||
| Odhlásit ze všech zařízení (`/api/v1/auth/logout-all`) | zneplatněny všechny platné tokeny uživatele | `LOGOUT_ALL` |
|
||||
| Změna nebo reset hesla | zneplatněny všechny platné tokeny uživatele | `PASSWORD_CHANGED` |
|
||||
| Změna role administrátorem | zneplatněny všechny tokeny; uživatel se přihlásí znovu a dostane token s novou rolí | `ROLE_CHANGED` |
|
||||
| Deaktivace účtu administrátorem | zneplatněny všechny platné tokeny uživatele | `ACCOUNT_DEACTIVATED` |
|
||||
@@ -595,7 +599,7 @@ Příklad access tokenu (dekódovaná hlavička a tělo):
|
||||
Každý token, který přijde na server, projde těmito kontrolami. Pokud kterákoli selže, server vrátí 401 („If any of the listed steps fail, then the JWT MUST be rejected“).
|
||||
|
||||
1. Formát JWS a správný podpis. Přijímá se **jen algoritmus HS256**, tokeny s `alg: none` nebo jiným algoritmem se odmítnou.
|
||||
2. `typ` v hlavičce odpovídá endpointu (např. `/api/issues` přijme jen `at+jwt`).
|
||||
2. `typ` v hlavičce odpovídá endpointu (např. `/api/v1/issues` přijme jen `at+jwt`).
|
||||
3. `iss` je naše API a `aud` odpovídá druhu tokenu.
|
||||
4. Token není prošlý (`exp`). Povolená odchylka hodin (`ClockSkew`) je **30 s**. Výchozí hodnota v .NET je 5 minut, takže se musí nastavit ručně.
|
||||
5. Token s tímto `jti` není v `auth_token` zneplatněný (`revoked_at IS NULL`).
|
||||
@@ -614,7 +618,7 @@ SET revoked_at = UTC_TIMESTAMP(6), revoke_reason = 'USED'
|
||||
WHERE jti = ? AND token_type = 'REFRESH' AND revoked_at IS NULL;
|
||||
```
|
||||
|
||||
- **Změněn 1 řádek** → token se používá poprvé, server vydá nový pár tokenů.
|
||||
- **Změněn 1 řádek** → token se používá poprvé, server uloží nový pár tokenů ve stejné databázové transakci.
|
||||
- **Změněno 0 řádků** → token už byl použitý nebo zneplatněný. U refresh tokenu to znamená, že ho zneužil někdo jiný. Server zneplatní všechny tokeny uživatele (`REUSE_DETECTED`) a vrátí 401.
|
||||
|
||||
Ze dvou současných požadavků se stejným tokenem vždy uspěje jen jeden. Klienti (mobil i web) proto musí obnovu tokenů provádět vždy jen jednou současně. Jinak by souběžné obnovy vyhodnotil server jako krádež.
|
||||
@@ -626,13 +630,13 @@ sequenceDiagram
|
||||
participant S as Server
|
||||
|
||||
Note over U,A: Oba mají refresh token R1 (jti = r1)
|
||||
A->>S: POST /auth/refresh (R1)
|
||||
A->>S: POST /api/v1/auth/refresh (R1)
|
||||
S->>S: UPDATE r1 → USED (1 řádek)
|
||||
S-->>A: nový pár tokenů (a2, r2)
|
||||
U->>S: POST /auth/refresh (R1)
|
||||
U->>S: POST /api/v1/auth/refresh (R1)
|
||||
S->>S: UPDATE r1 → 0 řádků = token už byl použit<br/>všechny tokeny uživatele → REUSE_DETECTED
|
||||
S-->>U: 401 → přihlásí se znovu
|
||||
A->>S: GET /api/issues (access token a2)
|
||||
A->>S: GET /api/v1/issues (access token a2)
|
||||
S-->>A: 401 – a2 je zneplatněný
|
||||
```
|
||||
|
||||
@@ -642,7 +646,11 @@ sequenceDiagram
|
||||
|
||||
## 11. Návrh REST API
|
||||
|
||||
Všechny endpointy mají prefix `/api`, formát JSON, chyby ve formátu **ProblemDetails** (RFC 9457). Seznamy jsou stránkované: `?page=1&pageSize=20`, odpověď `{ items: [...], totalCount, page, pageSize }`. Dokumentace: Swagger UI na `/swagger`.
|
||||
Aplikační API má základní cestu **`/api/v1`**. Připojte tento prefix před cesty v tabulkách. Výsledkem je například `POST /api/v1/auth/register` nebo `GET /api/v1/statistics/overview?from=&to=`. Výchozí formát je JSON. Chyby mají formát **ProblemDetails** (RFC 9457). Stránkování používá `?page=1&pageSize=20` a vrací `{ items: [...], totalCount, page, pageSize }`.
|
||||
|
||||
Číslo v URL je hlavní verze API. Zpětně kompatibilní rozšíření patří do stávající verze. Při nekompatibilní změně vznikne nová cesta (např. `/api/v2`) a samostatný OpenAPI dokument. Během přechodu klientů poběží obě verze souběžně. Před ukončením podpory starší verze se oznámí termín a zdokumentuje přechod.
|
||||
|
||||
Swagger UI je na webu na `/swagger`. UI i jeho OpenAPI dokument na `/swagger/v1/swagger.json` vyžadují administrátorskou relaci. Web načítá dokument z `GET /api/v1/admin/openapi/v1.json` s access tokenem administrátora. Provozní kontrola API je na `GET /health`.
|
||||
|
||||
### Autentizace a účet
|
||||
| Metoda | Endpoint | Role | Popis |
|
||||
@@ -660,23 +668,24 @@ Všechny endpointy mají prefix `/api`, formát JSON, chyby ve formátu **Proble
|
||||
### Hlášení závad
|
||||
| Metoda | Endpoint | Role | Popis |
|
||||
|---|---|---|---|
|
||||
| GET | `/issues` | přihlášený | Seznam; filtry `status`, `categoryId`, `buildingId`, `assigneeId`, `reporterId`, `from`, `to`, `q`, `mine`; řazení `sort`. Student/vyučující dostane jen vlastní. |
|
||||
| POST | `/issues` | přihlášený | Vytvoření hlášení (T1) |
|
||||
| GET | `/issues/{id}` | účastník / správce / vedení | Detail vč. `allowedActions` a `rowVersion` |
|
||||
| PUT | `/issues/{id}` | hlásič | Úprava ve stavu Přijata |
|
||||
| POST | `/issues/{id}/assign` | vedení | `{ assigneeId, priority?, rowVersion }` (T2, T3) |
|
||||
| POST | `/issues/{id}/start` | řešitel | T4 |
|
||||
| POST | `/issues/{id}/submit-for-verification` | řešitel | `{ note? }` (T5) |
|
||||
| POST | `/issues/{id}/confirm` | hlásič | T6 |
|
||||
| POST | `/issues/{id}/reopen` | hlásič | `{ reason }` (T7) |
|
||||
| POST | `/issues/{id}/reject` | řešitel / vedení | `{ reason }` (T8, T9) |
|
||||
| GET | `/issues` | přihlášený | Seznam; filtry `status`, `categoryId`, `buildingId`, `assigneeId`, `reporterId`, `from`, `to`, `q`, `mine`; řazení `sort=newest\|oldest`. Student a vyučující vidí jen vlastní. |
|
||||
| POST | `/issues` | přihlášený | Vytvoření hlášení (T1), JSON do 1 MiB nebo multipart s poli hlášení a soubory v poli `files` |
|
||||
| GET | `/issues/{id}` | účastník / správce / vedení / admin | Detail vč. `allowedActions` a `rowVersion` |
|
||||
| PUT | `/issues/{id}` | hlásič / admin | Úprava ve stavu Přijata s `rowVersion` |
|
||||
| POST | `/issues/{id}/assign` | vedení / admin | `{ assigneeId, priority?, rowVersion }` (T2, T3) |
|
||||
| POST | `/issues/{id}/start` | řešitel / admin | `{ rowVersion }` (T4) |
|
||||
| POST | `/issues/{id}/submit-for-verification` | řešitel / admin | `{ rowVersion, note? }` (T5) |
|
||||
| POST | `/issues/{id}/confirm` | hlásič / admin | `{ rowVersion }` (T6) |
|
||||
| POST | `/issues/{id}/reopen` | hlásič / admin | `{ rowVersion, reason }` (T7) |
|
||||
| POST | `/issues/{id}/reject` | řešitel / vedení / admin | `{ rowVersion, reason }` (T8, T9) |
|
||||
| GET | `/issues/{id}/events` | jako detail | Časová osa – všechny události včetně komentářů (`issue_event`) |
|
||||
| POST | `/issues/{id}/comments` | hlásič, řešitel | `{ text }` – zapíše událost `COMMENTED` |
|
||||
| POST | `/issues/{id}/attachments` | hlásič, řešitel | `multipart/form-data` |
|
||||
| POST | `/issues/{id}/comments` | hlásič / řešitel / admin | `{ text }` – zapíše událost `COMMENTED` |
|
||||
| POST | `/issues/{id}/attachments` | hlásič / řešitel / admin | `multipart/form-data`, 1–5 souborů v poli `files` |
|
||||
| GET | `/attachments/{id}` | jako detail závady | Stažení souboru |
|
||||
| GET | `/users/assignable` | vedení | Možní řešitelé s počtem otevřených závad |
|
||||
| GET | `/users/assignable` | vedení / admin | Možní řešitelé s počtem otevřených závad |
|
||||
|
||||
Přechody stavů jsou záměrně **samostatné akční endpointy** místo obecného `PATCH status` – každý má vlastní vstupní data, oprávnění a je jednoznačně zdokumentovaný ve Swaggeru.
|
||||
Po přidání komentáře nebo příloh klient znovu načte detail, aby získal aktuální `rowVersion`.
|
||||
|
||||
### Návrhy na zlepšení
|
||||
| Metoda | Endpoint | Role | Popis |
|
||||
@@ -684,10 +693,10 @@ Přechody stavů jsou záměrně **samostatné akční endpointy** místo obecn
|
||||
| GET | `/proposals` | přihlášený | Filtry `status`, `categoryId`, `authorId`, `q`; `sort=score\|newest`; obsahuje skóre a můj hlas |
|
||||
| POST | `/proposals` | přihlášený | Podání návrhu |
|
||||
| GET | `/proposals/{id}` | přihlášený | Detail vč. událostí a vyjádření vedení |
|
||||
| PUT | `/proposals/{id}` | autor | Úprava ve stavu Podán |
|
||||
| PUT | `/proposals/{id}` | autor / admin | Úprava ve stavu Podán |
|
||||
| PUT | `/proposals/{id}/vote` | přihlášený (ne autor) | `{ value: 1 \| -1 }` – vytvoření nebo změna hlasu |
|
||||
| DELETE | `/proposals/{id}/vote` | přihlášený | Zrušení hlasu |
|
||||
| POST | `/proposals/{id}/status` | vedení | `{ status, note? }` |
|
||||
| POST | `/proposals/{id}/status` | vedení / admin | `{ status, note? }` |
|
||||
|
||||
### Notifikace a zařízení
|
||||
| Metoda | Endpoint | Role | Popis |
|
||||
@@ -702,12 +711,12 @@ Přechody stavů jsou záměrně **samostatné akční endpointy** místo obecn
|
||||
### Statistiky
|
||||
| Metoda | Endpoint | Role | Popis |
|
||||
|---|---|---|---|
|
||||
| GET | `/statistics/overview?from=&to=` | vedení | Souhrnné KPI: počty podle stavu, průměrná doba do přiřazení a do uzavření |
|
||||
| GET | `/statistics/issues/by-category` | vedení | Počty a průměrná doba řešení podle kategorie |
|
||||
| GET | `/statistics/issues/by-building` | vedení | Podle budovy |
|
||||
| GET | `/statistics/issues/by-assignee` | vedení | Vytížení řešitelů (otevřené / uzavřené) |
|
||||
| GET | `/statistics/issues/trend?granularity=month` | vedení | Nové vs. uzavřené závady v čase |
|
||||
| GET | `/statistics/proposals/top?limit=10` | vedení | Nejpodporovanější návrhy |
|
||||
| GET | `/statistics/overview?from=&to=` | vedení / admin | Souhrnné KPI: počty podle stavu, průměrná doba do přiřazení a do uzavření |
|
||||
| GET | `/statistics/issues/by-category` | vedení / admin | Počty a průměrná doba řešení podle kategorie |
|
||||
| GET | `/statistics/issues/by-building` | vedení / admin | Podle budovy |
|
||||
| GET | `/statistics/issues/by-assignee` | vedení / admin | Vytížení řešitelů (otevřené / uzavřené) |
|
||||
| GET | `/statistics/issues/trend?granularity=month` | vedení / admin | Nové vs. uzavřené závady v čase |
|
||||
| GET | `/statistics/proposals/top?limit=10` | vedení / admin | Nejpodporovanější návrhy |
|
||||
|
||||
### Číselníky a administrace
|
||||
| Metoda | Endpoint | Role | Popis |
|
||||
@@ -715,6 +724,11 @@ Přechody stavů jsou záměrně **samostatné akční endpointy** místo obecn
|
||||
| GET | `/buildings`, `/issue-categories`, `/proposal-categories` | přihlášený | Číselníky pro formuláře |
|
||||
| POST / PUT / DELETE | totéž | admin | Správa (DELETE = deaktivace `is_active`) |
|
||||
| GET | `/admin/users?q=&role=` | admin | Vyhledání uživatelů |
|
||||
| POST | `/admin/users` | admin | Založení účtu s počátečním heslem a ručním nebo e-mailovým ověřením |
|
||||
| GET / PUT | `/admin/users/{id}` | admin | Detail a úprava účtu, nové heslo je volitelné. Změna adresy aktivního účtu spustí nové ověření. |
|
||||
| POST | `/admin/users/{id}/email-confirmation` | admin | Opětovné odeslání odkazu aktivnímu účtu s neověřeným e-mailem |
|
||||
| DELETE | `/admin/users/{id}` | admin | Znepřístupnění účtu a anonymizace profilu |
|
||||
| POST | `/admin/users/bulk` | admin | Změna role, aktivace, deaktivace nebo smazání vybraných účtů v jedné transakci |
|
||||
| PUT | `/admin/users/{id}/role` | admin | `{ role: "FACILITY_MANAGER" }` |
|
||||
| PUT | `/admin/users/{id}/active` | admin | Aktivace / deaktivace účtu |
|
||||
| GET | `/admin/notification-deliveries?status=FAILED` | admin | Nedoručené notifikace s důvodem chyby |
|
||||
@@ -970,9 +984,9 @@ V první verzi byla tabulka uživatelů „chobotnice“: vedlo na ni 17 cizích
|
||||
- **Normalizace (3NF)**: číselníky jsou v samostatných tabulkách. Časy životního cyklu se neukládají redundantně, ale odvozují se z událostí.
|
||||
- **Stavy jako text + CHECK** místo nativního `ENUM`: hodnoty jsou v DB čitelné, rozšíření je snadné a v EF Core se mapují na C# `enum` přes `HasConversion<string>()`.
|
||||
- **Integritní omezení v DB** jako druhá linie obrany za aplikační logikou. Zamítnutí i znovuotevření musí mít důvod. Závada ve stavu *Přiřazena / V řešení / Čeká na ověření* musí mít řešitele. Událost `CREATED` musí začínat výchozím stavem, komentář (`COMMENTED`) musí mít text a nesmí měnit stav. Hlas je jen `+1`/`-1`, příloha má max. 10 MB a odeslané doručení musí mít `sent_at`. Notifikace typu `ISSUE_*` musí odkazovat na závadu, typu `PROPOSAL_*` na návrh.
|
||||
- **Pravidla vyžadující více tabulek** (autor nehlasuje pro svůj návrh, řešitel musí mít roli správce budov / vedení) hlídá aplikační vrstva. V DB by vyžadovala triggery a logika by se rozdělila na dvě místa.
|
||||
- **Pravidla vyžadující více tabulek** (autor nehlasuje pro svůj návrh, řešitel musí mít roli správce budov, vedení nebo administrátora) hlídá aplikační vrstva. V DB by vyžadovala triggery a logika by se rozdělila na dvě místa.
|
||||
- **Optimistické zamykání**: `issue.row_version` (EF Core concurrency token).
|
||||
- **Mazání**: uživatelé, závady, návrhy a číselníky se nemažou. Uživatelé a číselníky se deaktivují (`is_active`). `ON DELETE CASCADE` je jen u čistě závislých dat.
|
||||
- **Mazání účtů**: smazaný účet se deaktivuje, jeho profil se anonymizuje a účet se skryje ze správy uživatelů (`is_deleted`). Původní e-mail je volný pro nový účet. Vazby závad, návrhů, hlasů a událostí zůstanou v databázi. Číselníky se deaktivují (`is_active`), závady a návrhy zůstávají v historii.
|
||||
- **Časy v UTC**, `DATETIME(6)`; převod do místního času dělá klient.
|
||||
- **Kódování** `utf8mb4`, engine InnoDB (transakce, cizí klíče).
|
||||
- **Indexy** pokrývají filtry centrálního přehledu, frontu nedoručených notifikací (`status, next_attempt_at`), zneplatnění všech tokenů uživatele (`user_id, revoked_at`) a úklid prošlých tokenů (`expires_at`).
|
||||
@@ -1029,13 +1043,13 @@ ORDER BY n.created_at DESC;
|
||||
| Nástěnka (moje otevřená hlášení, poslední notifikace, top návrhy) | ✅ | ✅ | všichni |
|
||||
| Nové hlášení závady (formulář + přílohy / fotoaparát) | ✅ | ✅ | všichni |
|
||||
| Moje hlášení (seznam se stavem) | ✅ | ✅ | všichni |
|
||||
| Detail závady (stav, časová osa, akce podle `allowedActions`, komentáře, přílohy) | ✅ | ✅ | účastníci, správce, vedení |
|
||||
| Detail závady (stav, časová osa, akce podle `allowedActions`, komentáře, přílohy) | ✅ | ✅ | účastníci, správce, vedení, admin |
|
||||
| Přiřazené závady (pracovní fronta řešitele) | ✅ | ✅ | správce budov |
|
||||
| Centrální přehled závad (tabulka, filtry, hromadný přehled) | ✅ | — | správce budov, vedení |
|
||||
| Centrální přehled závad (tabulka, filtry, hromadný přehled) | ✅ | — | správce budov, vedení, admin |
|
||||
| Návrhy – seznam (řazení podle skóre, hlasování přímo v seznamu) | ✅ | ✅ | všichni |
|
||||
| Detail návrhu / nový návrh | ✅ | ✅ | všichni |
|
||||
| Hodnocení návrhů (fronta podaných návrhů) | ✅ | — | vedení |
|
||||
| Statistiky (KPI dlaždice, grafy, filtr období) | ✅ | — | vedení |
|
||||
| Hodnocení návrhů (fronta podaných návrhů) | ✅ | — | vedení, admin |
|
||||
| Statistiky (KPI dlaždice, grafy, filtr období) | ✅ | — | vedení, admin |
|
||||
| Notifikace | ✅ | ✅ | všichni |
|
||||
| Profil a nastavení notifikací | ✅ | ✅ | všichni |
|
||||
| Správa uživatelů a rolí | ✅ | — | admin |
|
||||
@@ -1121,9 +1135,9 @@ flowchart LR
|
||||
end
|
||||
|
||||
BROWSER -- "HTTPS 443" --> PROXY
|
||||
MOBILE -- "HTTPS 443 /api" --> PROXY
|
||||
MOBILE -- "HTTPS 443 /api/v1/*" --> PROXY
|
||||
PROXY -- "HTTP 8080 /" --> WEB
|
||||
PROXY -- "HTTP 8080 /api, /swagger" --> API
|
||||
PROXY -- "HTTP 8080 /api/*" --> API
|
||||
WEB -- "HTTP 8080 REST + JWT" --> API
|
||||
API -- "TCP 3306" --> DB
|
||||
MIG -- "TCP 3306" --> DB
|
||||
@@ -1143,7 +1157,7 @@ flowchart LR
|
||||
- `backend` – api, migrator, db. Je označená jako `internal: true`, takže kontejnery v ní nemají přístup do internetu a nejsou dostupné zvenku.
|
||||
- **Databáze je dostupná jen pro `api` a `migrator`.** Webový kontejner ani proxy k ní nemají síťovou cestu. Web pracuje s daty výhradně přes REST API.
|
||||
- **`api` je jediná služba v obou sítích.** Odchozí spojení k SMTP a FCM vede přes síť `frontend`.
|
||||
- **Mobilní aplikace** komunikuje se stejnou adresou jako web (`https://<doména>/api/...`). Push notifikace k ní doručuje FCM, ne náš server.
|
||||
- **Mobilní aplikace** komunikuje se stejnou adresou jako web (`https://<doména>/api/v1/...`). Push notifikace k ní doručuje FCM, ne náš server.
|
||||
|
||||
### 15.2 Síťová komunikace
|
||||
|
||||
@@ -1151,9 +1165,9 @@ flowchart LR
|
||||
|---|---|---|---|---|
|
||||
| prohlížeč | proxy | HTTPS 443 (HTTP 80 → přesměrování) | internet | webová aplikace |
|
||||
| mobil | proxy | HTTPS 443 | internet | REST API |
|
||||
| proxy | web | HTTP 8080 | frontend | stránky (`/`) |
|
||||
| proxy | api | HTTP 8080 | frontend | `/api/*`, `/swagger` |
|
||||
| web | api | HTTP 8080 (`http://api:8080`) | frontend | volání API s JWT přihlášeného uživatele |
|
||||
| proxy | web | HTTP 8080 | frontend | stránky (`/`), administrátorské Swagger UI (`/swagger`) |
|
||||
| proxy | api | HTTP 8080 | frontend | `/api/*` |
|
||||
| web | api | HTTP 8080 (`http://api:8080/api/v1/`) | frontend | volání API s JWT přihlášeného uživatele |
|
||||
| api | db | TCP 3306 | backend | data – DB účet `helpdesk_app` |
|
||||
| migrator | db | TCP 3306 | backend | migrace – DB účet `helpdesk_migrator` |
|
||||
| api | SMTP server | SMTP 587 (STARTTLS) | internet, odchozí | e-mailové notifikace |
|
||||
@@ -1164,9 +1178,9 @@ flowchart LR
|
||||
|
||||
| Služba | Image | Sítě | Porty | Úložiště | Poznámka |
|
||||
|---|---|---|---|---|---|
|
||||
| `proxy` | `nginx` | frontend | **80, 443 publikované** | certifikáty | TLS (vývoj: `mkcert`, produkce: Let's Encrypt), HSTS, limit velikosti požadavku 50 MB (5 příloh × 10 MB) |
|
||||
| `web` | vlastní (`dotnet/aspnet`) | frontend | interně 8080 | `web-keys` | klíče ASP.NET Core Data Protection pro šifrované cookie (bez persistence by restart odhlásil všechny uživatele) |
|
||||
| `api` | vlastní (`dotnet/aspnet`) | frontend, backend | interně 8080 | `uploads` | Swagger na `/swagger`, `GET /health`, vytvoření admin účtu z env |
|
||||
| `proxy` | `nginx` | frontend | **80, 443 publikované** | certifikáty | TLS (vývoj: `mkcert`, produkce: Let's Encrypt), HSTS, limit velikosti požadavku 51 MiB (5 příloh × 10 MiB a režie multipart) |
|
||||
| `web` | vlastní (`dotnet/aspnet`) | frontend | interně 8080 | `web-keys` | administrátorské Swagger UI na `/swagger`, klíče Data Protection pro šifrované cookie |
|
||||
| `api` | vlastní (`dotnet/aspnet`) | frontend, backend | interně 8080 | `uploads` | OpenAPI pro administrátory, `GET /health`, vytvoření admin účtu z env |
|
||||
| `migrator` | vlastní (`dotnet/runtime`) | backend | — | — | aplikuje nové migrace z `db/migrations` a skončí |
|
||||
| `db` | `mariadb:11.4` | backend | interně 3306 | `db-data` | při prvním startu vytvoří DB účty skriptem z `deploy/db-init/` |
|
||||
| `mailpit` | `axllent/mailpit` | frontend | 8025 (jen vývoj) | — | zachytává e-maily, v produkci se nespouští |
|
||||
@@ -1234,10 +1248,10 @@ Možná rozšíření (mimo rozsah zadání): automatické potvrzení vyřešen
|
||||
| Fáze | Týden | Náplň |
|
||||
|---|---|---|
|
||||
| **1. Návrh** | 1–2 | Tento dokument, databázové schéma, založení Git repozitáře a struktury projektů; zapracování připomínek z obhajoby (v1.1) |
|
||||
| **2. Implementace** | 3 | Backend: `Helpdesk.Migrator` (DbUp), entity a EF Core mapování, autentizace (registrace, login, JWT s `jti`, refresh, blokování tokenů), role, Swagger |
|
||||
| **2. Implementace** | 3 | Backend: `Helpdesk.Migrator` (DbUp), entity a EF Core mapování, autentizace (registrace, login, JWT s `jti`, refresh, blokování tokenů), role, REST API `/api/v1`, Swagger |
|
||||
| | 4 | Backend: závady – stavový automat, události, přílohy, komentáře; unit testy automatu |
|
||||
| | 5 | Backend: návrhy a hlasování, notifikace (in-app, e-mail, push, opakování nedoručených), statistiky |
|
||||
| | 6 | Webová aplikace: všechny obrazovky včetně statistik a administrace |
|
||||
| | 7 | Mobilní aplikace: přihlášení, hlášení s fotkou, detail a komentáře, návrhy, push notifikace |
|
||||
| **3. Testování a nasazení** | 8 | Integrační testy, ladění, Docker Compose + HTTPS |
|
||||
| | 6 | Webová aplikace: všechny obrazovky včetně statistik a administrace, napojení na API v1 |
|
||||
| | 7 | Mobilní aplikace nad API v1: přihlášení, hlášení s fotkou, detail a komentáře, návrhy, push notifikace |
|
||||
| **3. Testování a nasazení** | 8 | Integrační testy, ladění, Docker Compose + HTTPS, ověření verzovaných URL přes proxy |
|
||||
| | 9 | Uživatelská příručka, technická dokumentace, finální nasazení a předvedení |
|
||||
@@ -0,0 +1,11 @@
|
||||
<Project>
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<Nullable>enable</Nullable>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<LangVersion>latest</LangVersion>
|
||||
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
|
||||
<!-- Web zobrazuje data a čísla česky (cs-CZ), proto plná podpora kultur. -->
|
||||
<InvariantGlobalization>false</InvariantGlobalization>
|
||||
</PropertyGroup>
|
||||
</Project>
|
||||
@@ -0,0 +1,13 @@
|
||||
<Project>
|
||||
<PropertyGroup>
|
||||
<ManagePackageVersionsCentrally>true</ManagePackageVersionsCentrally>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<PackageVersion Include="Swashbuckle.AspNetCore.SwaggerUI" Version="10.3.1" />
|
||||
<!-- Testy -->
|
||||
<PackageVersion Include="Microsoft.AspNetCore.Mvc.Testing" Version="10.0.14" />
|
||||
<PackageVersion Include="Microsoft.NET.Test.Sdk" Version="18.11.0" />
|
||||
<PackageVersion Include="xunit.v3" Version="4.0.2" />
|
||||
<PackageVersion Include="xunit.runner.visualstudio" Version="4.0.1" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
@@ -0,0 +1,22 @@
|
||||
# Vícefázový build webové aplikace. Kontext sestavení = kořen repozitáře.
|
||||
# docker build -f web/Dockerfile .
|
||||
|
||||
FROM mcr.microsoft.com/dotnet/sdk:10.0 AS build
|
||||
WORKDIR /src
|
||||
# Nejdřív jen projektové soubory – restore se cachuje, dokud se nezmění závislosti.
|
||||
COPY web/Directory.Build.props web/Directory.Packages.props ./
|
||||
COPY web/Helpdesk.Web/Helpdesk.Web.csproj Helpdesk.Web/
|
||||
RUN dotnet restore Helpdesk.Web/Helpdesk.Web.csproj
|
||||
COPY web/Helpdesk.Web/ Helpdesk.Web/
|
||||
RUN dotnet publish Helpdesk.Web/Helpdesk.Web.csproj -c Release -o /out --no-restore
|
||||
|
||||
FROM mcr.microsoft.com/dotnet/aspnet:10.0
|
||||
WORKDIR /app
|
||||
COPY --from=build /out .
|
||||
# Klíče Data Protection (šifrování autentizační cookie) – v Compose je tu volume web-keys.
|
||||
RUN mkdir -p /app/keys && chown "$APP_UID" /app/keys
|
||||
USER $APP_UID
|
||||
ENV ASPNETCORE_HTTP_PORTS=8080 \
|
||||
DataProtection__KeysPath=/app/keys
|
||||
EXPOSE 8080
|
||||
ENTRYPOINT ["dotnet", "Helpdesk.Web.dll"]
|
||||
@@ -0,0 +1,294 @@
|
||||
using System.Net;
|
||||
using System.Text;
|
||||
using System.Text.RegularExpressions;
|
||||
using Helpdesk.Web.Api;
|
||||
using Helpdesk.Web.Auth;
|
||||
using Microsoft.AspNetCore.Mvc.Testing;
|
||||
using Microsoft.AspNetCore.TestHost;
|
||||
using Microsoft.AspNetCore.WebUtilities;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using static Helpdesk.Web.Tests.WebTestSession;
|
||||
|
||||
namespace Helpdesk.Web.Tests;
|
||||
|
||||
public sealed class AdminUsersTests
|
||||
{
|
||||
private const string UsersPath = "/admin/users";
|
||||
|
||||
[Theory]
|
||||
[InlineData(null, "/login")]
|
||||
[InlineData(UserRoles.Student, "/error/403")]
|
||||
[InlineData(UserRoles.Management, "/error/403")]
|
||||
public async Task OnlyAnAdministratorCanListOrChangeUsers(string? role, string redirect)
|
||||
{
|
||||
var backend = new AdminUsersBackend();
|
||||
await using var application = CreateApplication(backend);
|
||||
using var client = CreateClient(application);
|
||||
if (role is not null)
|
||||
SignIn(application.Services, client, role);
|
||||
var ct = TestContext.Current.CancellationToken;
|
||||
|
||||
foreach (var path in new[] { UsersPath, UsersPath + "/new", UsersPath + "/7/edit" })
|
||||
{
|
||||
using var page = await client.GetAsync(path, ct);
|
||||
Assert.Equal(HttpStatusCode.Redirect, page.StatusCode);
|
||||
Assert.Equal(redirect, page.Headers.Location?.AbsolutePath);
|
||||
}
|
||||
foreach (var action in new[] { "7/role", "7/active", "new", "7/edit", "7/delete", "7/email-confirmation", "bulk" })
|
||||
{
|
||||
using var update = await client.PostAsync($"{UsersPath}/{action}", null, ct);
|
||||
Assert.Equal(HttpStatusCode.Redirect, update.StatusCode);
|
||||
Assert.Equal(redirect, update.Headers.Location?.AbsolutePath);
|
||||
}
|
||||
Assert.Empty(backend.Requests);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AdministratorCanSearchAndChangeRoleAndActivation()
|
||||
{
|
||||
var backend = new AdminUsersBackend();
|
||||
await using var application = CreateApplication(backend);
|
||||
using var client = CreateClient(application);
|
||||
SignIn(application.Services, client, UserRoles.Admin);
|
||||
var ct = TestContext.Current.CancellationToken;
|
||||
const string query = "?q=Nov%C3%A1k&role=STUDENT&page=2";
|
||||
|
||||
using var list = await client.GetAsync(UsersPath + query, ct);
|
||||
Assert.Equal(HttpStatusCode.OK, list.StatusCode);
|
||||
Assert.True(list.Headers.CacheControl?.NoStore == true);
|
||||
var html = WebUtility.HtmlDecode(await list.Content.ReadAsStringAsync(ct));
|
||||
Assert.Contains("Správa uživatelů", html);
|
||||
Assert.Contains("Strana 2 z 3", html);
|
||||
Assert.Contains("[email protected]", html);
|
||||
Assert.Contains("E-mail neověřený", html);
|
||||
Assert.Contains("Váš účet", html);
|
||||
Assert.DoesNotContain($"{UsersPath}/1/role", html);
|
||||
Assert.DoesNotContain($"{UsersPath}/1/active", html);
|
||||
Assert.Contains($"{UsersPath}/7/role{query}", html);
|
||||
Assert.Contains($"{UsersPath}/7/active{query}", html);
|
||||
var token = AntiforgeryToken(html);
|
||||
|
||||
var search = Assert.Single(backend.Requests);
|
||||
Assert.Equal(HttpMethod.Get, search.Method);
|
||||
var filters = QueryHelpers.ParseQuery(search.Uri.Query);
|
||||
Assert.Equal("Novák", filters["q"].ToString());
|
||||
Assert.Equal("STUDENT", filters["role"].ToString());
|
||||
Assert.Equal("2", filters["page"].ToString());
|
||||
|
||||
var updates = new[]
|
||||
{
|
||||
(Endpoint: "role", Field: "newRole", Value: UserRoles.Teacher, Body: """{"role":"TEACHER"}"""),
|
||||
(Endpoint: "active", Field: "isActive", Value: "false", Body: """{"isActive":false}"""),
|
||||
(Endpoint: "active", Field: "isActive", Value: "true", Body: """{"isActive":true}"""),
|
||||
};
|
||||
foreach (var update in updates)
|
||||
{
|
||||
using var form = new FormUrlEncodedContent(new Dictionary<string, string>
|
||||
{
|
||||
["__RequestVerificationToken"] = token,
|
||||
[update.Field] = update.Value,
|
||||
});
|
||||
using var response = await client.PostAsync($"{UsersPath}/7/{update.Endpoint}{query}", form, ct);
|
||||
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
|
||||
Assert.Equal(UsersPath + query, response.Headers.Location?.OriginalString);
|
||||
var request = backend.Requests[^1];
|
||||
Assert.Equal(HttpMethod.Put, request.Method);
|
||||
Assert.Equal($"/api/v1{UsersPath}/7/{update.Endpoint}", request.Uri.AbsolutePath);
|
||||
Assert.Equal(update.Body, request.Body);
|
||||
}
|
||||
Assert.Equal(4, backend.Requests.Count);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("role")]
|
||||
[InlineData("active")]
|
||||
public async Task AdministratorUpdatesRequireAntiforgeryToken(string action)
|
||||
{
|
||||
var backend = new AdminUsersBackend();
|
||||
await using var application = CreateApplication(backend);
|
||||
using var client = CreateClient(application);
|
||||
SignIn(application.Services, client, UserRoles.Admin);
|
||||
using var response = await client.PostAsync($"{UsersPath}/7/{action}", null, TestContext.Current.CancellationToken);
|
||||
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
|
||||
Assert.Empty(backend.Requests);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AdminCanSubmitAccountFormsAndConfirmedBulkDeletion()
|
||||
{
|
||||
var backend = new AdminUsersBackend();
|
||||
await using var application = CreateApplication(backend);
|
||||
using var client = CreateClient(application);
|
||||
SignIn(application.Services, client, UserRoles.Admin);
|
||||
var ct = TestContext.Current.CancellationToken;
|
||||
|
||||
using var createPage = await client.GetAsync(UsersPath + "/new", ct);
|
||||
Assert.Equal(HttpStatusCode.OK, createPage.StatusCode);
|
||||
var page = WebUtility.HtmlDecode(await createPage.Content.ReadAsStringAsync(ct));
|
||||
Assert.Contains("Počáteční heslo", page);
|
||||
Assert.Contains("Ověřit e-mail ručně", page);
|
||||
Assert.Matches("""<input\b(?=[^>]*id="verification-email")(?=[^>]*checked="checked")[^>]*>""", page);
|
||||
Assert.True(page.IndexOf("Správa uživatelů", StringComparison.Ordinal) < page.IndexOf("Swagger API", StringComparison.Ordinal));
|
||||
var fields = new Dictionary<string, string>
|
||||
{
|
||||
["__RequestVerificationToken"] = AntiforgeryToken(page),
|
||||
["FirstName"] = "Jan",
|
||||
["LastName"] = "Test",
|
||||
["Email"] = "[email protected]",
|
||||
["Role"] = UserRoles.Student,
|
||||
["Password"] = "Initial-password",
|
||||
["IsActive"] = "true",
|
||||
["EmailConfirmed"] = "true",
|
||||
};
|
||||
using var createForm = new FormUrlEncodedContent(fields);
|
||||
using var created = await client.PostAsync(UsersPath + "/new", createForm, ct);
|
||||
Assert.Equal(HttpStatusCode.Redirect, created.StatusCode);
|
||||
var createdRequest = Assert.Single(backend.Requests);
|
||||
Assert.Equal(HttpMethod.Post, createdRequest.Method);
|
||||
Assert.Equal("/api/v1/admin/users", createdRequest.Uri.AbsolutePath);
|
||||
Assert.Contains("\"email\":\"[email protected]\"", createdRequest.Body);
|
||||
Assert.Contains("\"emailConfirmed\":true", createdRequest.Body);
|
||||
|
||||
using var editPage = await client.GetAsync(UsersPath + "/7/edit", ct);
|
||||
Assert.Equal(HttpStatusCode.OK, editPage.StatusCode);
|
||||
Assert.Contains("[email protected]", await editPage.Content.ReadAsStringAsync(ct));
|
||||
fields.Remove("Password");
|
||||
using var editForm = new FormUrlEncodedContent(fields);
|
||||
using var edited = await client.PostAsync(UsersPath + "/7/edit", editForm, ct);
|
||||
Assert.Equal(HttpStatusCode.Redirect, edited.StatusCode);
|
||||
Assert.Equal(HttpMethod.Put, backend.Requests[^1].Method);
|
||||
Assert.Contains("\"password\":null", backend.Requests[^1].Body);
|
||||
|
||||
var bulk = new List<KeyValuePair<string, string>>
|
||||
{
|
||||
new("__RequestVerificationToken", fields["__RequestVerificationToken"]),
|
||||
new("action", "delete"),
|
||||
new("userIds", "7"),
|
||||
new("userIds", "8"),
|
||||
};
|
||||
var count = backend.Requests.Count;
|
||||
using var unconfirmedForm = new FormUrlEncodedContent(bulk);
|
||||
using var unconfirmed = await client.PostAsync(UsersPath + "/bulk", unconfirmedForm, ct);
|
||||
Assert.Equal(HttpStatusCode.Redirect, unconfirmed.StatusCode);
|
||||
Assert.Equal(count, backend.Requests.Count);
|
||||
|
||||
bulk.Add(new("confirmDelete", "true"));
|
||||
using var confirmedForm = new FormUrlEncodedContent(bulk);
|
||||
using var confirmed = await client.PostAsync(UsersPath + "/bulk", confirmedForm, ct);
|
||||
Assert.Equal(HttpStatusCode.Redirect, confirmed.StatusCode);
|
||||
Assert.Equal("/api/v1/admin/users/bulk", backend.Requests[^1].Uri.AbsolutePath);
|
||||
Assert.Contains("\"userIds\":[7,8]", backend.Requests[^1].Body);
|
||||
Assert.Contains("\"action\":\"delete\"", backend.Requests[^1].Body);
|
||||
|
||||
using var singleForm = new FormUrlEncodedContent(new Dictionary<string, string>
|
||||
{
|
||||
["__RequestVerificationToken"] = fields["__RequestVerificationToken"],
|
||||
["confirmDelete"] = "true",
|
||||
});
|
||||
using var deleted = await client.PostAsync(UsersPath + "/7/delete", singleForm, ct);
|
||||
Assert.Equal(HttpStatusCode.Redirect, deleted.StatusCode);
|
||||
Assert.Equal(HttpMethod.Delete, backend.Requests[^1].Method);
|
||||
Assert.Equal("/api/v1/admin/users/7", backend.Requests[^1].Uri.AbsolutePath);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AdminCanResendVerificationAfterCreationSavedAnAccountButDeliveryFailed()
|
||||
{
|
||||
var backend = new AdminUsersBackend(failVerification: true);
|
||||
await using var application = CreateApplication(backend);
|
||||
using var client = CreateClient(application);
|
||||
SignIn(application.Services, client, UserRoles.Admin);
|
||||
var ct = TestContext.Current.CancellationToken;
|
||||
|
||||
using var createPage = await client.GetAsync(UsersPath + "/new", ct);
|
||||
var page = WebUtility.HtmlDecode(await createPage.Content.ReadAsStringAsync(ct));
|
||||
using var createForm = new FormUrlEncodedContent(new Dictionary<string, string>
|
||||
{
|
||||
["__RequestVerificationToken"] = AntiforgeryToken(page),
|
||||
["FirstName"] = "Jan",
|
||||
["LastName"] = "Novák",
|
||||
["Email"] = "[email protected]",
|
||||
["Role"] = UserRoles.Student,
|
||||
["Password"] = "Initial-password",
|
||||
["IsActive"] = "true",
|
||||
["EmailConfirmed"] = "false",
|
||||
});
|
||||
using var created = await client.PostAsync(UsersPath + "/new", createForm, ct);
|
||||
Assert.Equal(HttpStatusCode.Redirect, created.StatusCode);
|
||||
Assert.StartsWith(UsersPath + "/7/edit", created.Headers.Location?.OriginalString);
|
||||
|
||||
using var editPage = await client.GetAsync(created.Headers.Location, ct);
|
||||
var edit = WebUtility.HtmlDecode(await editPage.Content.ReadAsStringAsync(ct));
|
||||
Assert.Contains("Účet byl založen.", edit);
|
||||
Assert.Contains("Ověřovací e-mail se nepodařilo odeslat.", edit);
|
||||
Assert.Contains("Poslat ověřovací e-mail", edit);
|
||||
|
||||
using var resendForm = new FormUrlEncodedContent(new Dictionary<string, string>
|
||||
{
|
||||
["__RequestVerificationToken"] = AntiforgeryToken(edit),
|
||||
});
|
||||
using var resent = await client.PostAsync(UsersPath + "/7/email-confirmation", resendForm, ct);
|
||||
Assert.Equal(HttpStatusCode.Redirect, resent.StatusCode);
|
||||
Assert.Equal((HttpMethod.Post, "/api/v1/admin/users/7/email-confirmation"),
|
||||
(backend.Requests[^1].Method, backend.Requests[^1].Uri.AbsolutePath));
|
||||
}
|
||||
|
||||
private static string AntiforgeryToken(string html)
|
||||
{
|
||||
var token = Regex.Match(html, "name=\"__RequestVerificationToken\"[^>]*value=\"([^\"]+)\"").Groups[1].Value;
|
||||
Assert.NotEmpty(token);
|
||||
return token;
|
||||
}
|
||||
|
||||
private static WebApplicationFactory<Program> CreateApplication(AdminUsersBackend backend) =>
|
||||
new WebApplicationFactory<Program>().WithWebHostBuilder(builder =>
|
||||
builder.ConfigureTestServices(services => services.AddHttpClient(nameof(HelpdeskApiClient))
|
||||
.ConfigurePrimaryHttpMessageHandler(() => backend)));
|
||||
|
||||
private static HttpClient CreateClient(WebApplicationFactory<Program> application) =>
|
||||
application.CreateClient(new WebApplicationFactoryClientOptions
|
||||
{
|
||||
AllowAutoRedirect = false,
|
||||
BaseAddress = new Uri("https://localhost"),
|
||||
});
|
||||
|
||||
private sealed class AdminUsersBackend(bool failVerification = false) : HttpMessageHandler
|
||||
{
|
||||
public List<(HttpMethod Method, Uri Uri, string? Body)> Requests { get; } = [];
|
||||
|
||||
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken ct)
|
||||
{
|
||||
Assert.Equal("test-access", request.Headers.Authorization?.Parameter);
|
||||
var uri = Assert.IsType<Uri>(request.RequestUri);
|
||||
Requests.Add((request.Method, uri, request.Content is null ? null : await request.Content.ReadAsStringAsync(ct)));
|
||||
if (request.Method == HttpMethod.Post && uri.AbsolutePath == "/api/v1/admin/users" && failVerification)
|
||||
return new HttpResponseMessage(HttpStatusCode.Created)
|
||||
{
|
||||
Content = new StringContent("""
|
||||
{"id":7,"email":"[email protected]","firstName":"Jan","lastName":"Novák","role":"STUDENT","isActive":true,"emailConfirmed":false,"emailNotificationsEnabled":true,"verificationEmailSent":false}
|
||||
""", Encoding.UTF8, "application/json"),
|
||||
};
|
||||
if (request.Method != HttpMethod.Get)
|
||||
return new HttpResponseMessage(HttpStatusCode.NoContent);
|
||||
|
||||
if (uri.AbsolutePath == "/api/v1/admin/users/7")
|
||||
return new HttpResponseMessage(HttpStatusCode.OK)
|
||||
{
|
||||
Content = new StringContent("""
|
||||
{"id":7,"email":"[email protected]","firstName":"Jan","lastName":"Novák","role":"STUDENT","isActive":true,"emailConfirmed":false,"emailNotificationsEnabled":true}
|
||||
""", Encoding.UTF8, "application/json"),
|
||||
};
|
||||
|
||||
Assert.Equal("/api/v1" + UsersPath, uri.AbsolutePath);
|
||||
return new HttpResponseMessage(HttpStatusCode.OK)
|
||||
{
|
||||
Content = new StringContent("""
|
||||
{"items":[
|
||||
{"id":1,"email":"[email protected]","firstName":"Test","lastName":"Admin","role":"ADMIN","isActive":true,"emailConfirmed":true,"createdAt":"2026-10-03T08:00:00Z"},
|
||||
{"id":7,"email":"[email protected]","firstName":"Jan","lastName":"Novák","role":"STUDENT","isActive":false,"emailConfirmed":false,"createdAt":"2026-10-05T08:00:00Z"}
|
||||
],"totalCount":45,"page":2,"pageSize":20}
|
||||
""", Encoding.UTF8, "application/json"),
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,142 @@
|
||||
using System.Net;
|
||||
using System.Security.Claims;
|
||||
using System.Text;
|
||||
using Helpdesk.Web.Api;
|
||||
using Helpdesk.Web.Auth;
|
||||
using Helpdesk.Web.Infrastructure;
|
||||
using Helpdesk.Web.Models;
|
||||
using Microsoft.AspNetCore.Authentication;
|
||||
using Microsoft.AspNetCore.Mvc.ModelBinding;
|
||||
|
||||
namespace Helpdesk.Web.Tests;
|
||||
|
||||
public class AuthCookieTests
|
||||
{
|
||||
private static readonly TokenSet Tokens = new(
|
||||
"access", new DateTimeOffset(2026, 12, 1, 10, 15, 0, TimeSpan.Zero),
|
||||
"refresh", new DateTimeOffset(2026, 12, 15, 10, 0, 0, TimeSpan.Zero));
|
||||
|
||||
[Fact]
|
||||
public void Tokeny_ulozene_v_cookie_se_prectou_zpet()
|
||||
{
|
||||
var properties = new AuthenticationProperties();
|
||||
AuthCookie.StoreTokens(properties, Tokens);
|
||||
|
||||
Assert.Equal(Tokens, AuthCookie.ReadTokens(properties));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Trvale_prihlaseni_plati_stejne_dlouho_jako_refresh_token()
|
||||
{
|
||||
var properties = new AuthenticationProperties { IsPersistent = true };
|
||||
AuthCookie.StoreTokens(properties, Tokens);
|
||||
|
||||
Assert.Equal(Tokens.RefreshTokenExpiresAt, properties.ExpiresUtc);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Cookie_bez_tokenu_neni_platna() => Assert.Null(AuthCookie.ReadTokens(new AuthenticationProperties()));
|
||||
|
||||
[Fact]
|
||||
public void Identita_nese_roli_pro_IsInRole()
|
||||
{
|
||||
var principal = AuthCookie.CreatePrincipal(new UserDto(7, "[email protected]", "Eva", "Malá", null, UserRoles.Management, true));
|
||||
|
||||
Assert.True(principal.IsInRole(UserRoles.Management));
|
||||
Assert.Equal("Eva Malá", principal.Identity!.Name);
|
||||
Assert.Equal("7", principal.FindFirst(ClaimTypes.NameIdentifier)!.Value);
|
||||
}
|
||||
}
|
||||
|
||||
public class ApiExceptionTests
|
||||
{
|
||||
private static HttpResponseMessage Problem(HttpStatusCode status, string json) => new(status)
|
||||
{
|
||||
Content = new StringContent(json, Encoding.UTF8, "application/problem+json"),
|
||||
};
|
||||
|
||||
[Fact]
|
||||
public async Task Validacni_chyby_z_ProblemDetails_se_nactou_podle_poli()
|
||||
{
|
||||
using var response = Problem(HttpStatusCode.BadRequest,
|
||||
"""{"title":"Neplatná vstupní data.","status":400,"errors":{"password":["Heslo je příliš krátké."]}}""");
|
||||
|
||||
var error = await ApiException.FromResponseAsync(response, CancellationToken.None);
|
||||
|
||||
Assert.Equal(HttpStatusCode.BadRequest, error.StatusCode);
|
||||
Assert.Equal("Neplatná vstupní data.", error.UserMessage);
|
||||
Assert.Equal(["Heslo je příliš krátké."], error.Errors["Password"]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Odpoved_bez_tela_ma_srozumitelnou_zpravu()
|
||||
{
|
||||
using var response = new HttpResponseMessage(HttpStatusCode.TooManyRequests);
|
||||
|
||||
var error = await ApiException.FromResponseAsync(response, CancellationToken.None);
|
||||
|
||||
Assert.Equal("Příliš mnoho pokusů. Zkuste to prosím za minutu.", error.UserMessage);
|
||||
Assert.Empty(error.Errors);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Poskozeny_JSON_nezpusobi_vyjimku()
|
||||
{
|
||||
using var response = Problem(HttpStatusCode.InternalServerError, "{nejde o json");
|
||||
|
||||
var error = await ApiException.FromResponseAsync(response, CancellationToken.None);
|
||||
|
||||
Assert.Equal(HttpStatusCode.InternalServerError, error.StatusCode);
|
||||
Assert.Null(error.Title);
|
||||
}
|
||||
}
|
||||
|
||||
public class ModelStateExtensionsTests
|
||||
{
|
||||
[Fact]
|
||||
public void Chyba_pole_z_API_patri_k_vlastnosti_formulare()
|
||||
{
|
||||
var modelState = new ModelStateDictionary();
|
||||
var error = new ApiException(HttpStatusCode.BadRequest, "Neplatná vstupní data.",
|
||||
new Dictionary<string, string[]> { ["newPassword"] = ["Heslo musí mít alespoň 8 znaků."] });
|
||||
|
||||
modelState.AddApiErrors(error, typeof(ResetPasswordViewModel));
|
||||
|
||||
Assert.Equal("Heslo musí mít alespoň 8 znaků.", modelState[nameof(ResetPasswordViewModel.NewPassword)]!.Errors.Single().ErrorMessage);
|
||||
Assert.False(modelState.ContainsKey(string.Empty));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Chyba_bez_pole_jde_do_souhrnu()
|
||||
{
|
||||
var modelState = new ModelStateDictionary();
|
||||
var error = new ApiException(HttpStatusCode.Conflict, "Účet s tímto e-mailem už existuje.", new Dictionary<string, string[]>());
|
||||
|
||||
modelState.AddApiErrors(error, typeof(RegisterViewModel));
|
||||
|
||||
Assert.Equal("Účet s tímto e-mailem už existuje.", modelState[string.Empty]!.Errors.Single().ErrorMessage);
|
||||
}
|
||||
}
|
||||
|
||||
public class NavigationTests
|
||||
{
|
||||
private static ClaimsPrincipal UserWithRole(string role) =>
|
||||
new(new ClaimsIdentity([new Claim(ClaimTypes.Role, role)], "test"));
|
||||
|
||||
[Fact]
|
||||
public void Neprihlaseny_uzivatel_menu_nevidi() =>
|
||||
Assert.Empty(Navigation.For(new ClaimsPrincipal(new ClaimsIdentity())));
|
||||
|
||||
[Fact]
|
||||
public void Polozka_s_roli_je_videt_jen_te_roli()
|
||||
{
|
||||
var item = new NavItem("Statistiky", "Statistics", "Index", UserRoles.Management);
|
||||
|
||||
Assert.True(item.IsVisibleTo(UserWithRole(UserRoles.Management)));
|
||||
Assert.False(item.IsVisibleTo(UserWithRole(UserRoles.Student)));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Polozka_bez_roli_je_videt_vsem_prihlasenym() =>
|
||||
Assert.True(new NavItem("Nástěnka", "Home", "Index").IsVisibleTo(UserWithRole(UserRoles.Student)));
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
using System.Net;
|
||||
using Helpdesk.Web.Api;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
|
||||
namespace Helpdesk.Web.Tests;
|
||||
|
||||
public sealed class ForwardedClientIpHandlerTests
|
||||
{
|
||||
[Fact]
|
||||
public async Task UsesTheCurrentConnectionAddressInsteadOfTheIncomingHeader()
|
||||
{
|
||||
const string header = "X-Forwarded-For";
|
||||
var context = new DefaultHttpContext();
|
||||
context.Connection.RemoteIpAddress = IPAddress.Parse("198.51.100.10");
|
||||
context.Request.Headers[header] = "203.0.113.11";
|
||||
var accessor = new HttpContextAccessor { HttpContext = context };
|
||||
using var client = new HttpMessageInvoker(new ForwardedClientIpHandler(accessor) { InnerHandler = new Responder() });
|
||||
using var request = new HttpRequestMessage(HttpMethod.Post, "http://api-web:8080/api/v1/auth/login");
|
||||
using var response = await client.SendAsync(request, TestContext.Current.CancellationToken);
|
||||
Assert.Equal("198.51.100.10", Assert.Single(request.Headers.GetValues(header)));
|
||||
|
||||
accessor.HttpContext = null;
|
||||
using var next = new HttpRequestMessage(HttpMethod.Post, request.RequestUri);
|
||||
using var nextResponse = await client.SendAsync(next, TestContext.Current.CancellationToken);
|
||||
Assert.False(next.Headers.Contains(header));
|
||||
}
|
||||
|
||||
private sealed class Responder : HttpMessageHandler
|
||||
{
|
||||
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) =>
|
||||
Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<IsPackable>false</IsPackable>
|
||||
<OutputType>Exe</OutputType>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<FrameworkReference Include="Microsoft.AspNetCore.App" />
|
||||
<ProjectReference Include="..\Helpdesk.Web\Helpdesk.Web.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.AspNetCore.Mvc.Testing" />
|
||||
<PackageReference Include="Microsoft.NET.Test.Sdk" />
|
||||
<PackageReference Include="xunit.v3" />
|
||||
<PackageReference Include="xunit.runner.visualstudio" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Using Include="Xunit" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -0,0 +1,174 @@
|
||||
using System.Net;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Text;
|
||||
using System.Text.Json.Nodes;
|
||||
using Helpdesk.Web.Api;
|
||||
using Helpdesk.Web.Models;
|
||||
|
||||
namespace Helpdesk.Web.Tests;
|
||||
|
||||
public class IssueDetailViewModelTests
|
||||
{
|
||||
private static readonly DateTimeOffset T = DateTimeOffset.UnixEpoch;
|
||||
|
||||
private static IssueEventDto Event(string type, string? from, string to, string actor, string? note = null) =>
|
||||
new(1, type, from, to, 1, actor, note, T);
|
||||
|
||||
private static IssueDetailViewModel Model(int? assigneeId, params IssueEventDto[] events) => new()
|
||||
{
|
||||
Issue = new IssueDetail(42, "Projektor", "Bliká.", 2, null, null, "IN_PROGRESS", "HIGH", 5, assigneeId, T, 3,
|
||||
[IssueActions.SubmitForVerification, IssueActions.Reject, IssueActions.Comment], []),
|
||||
Events = events,
|
||||
CategoryName = "Technické vybavení",
|
||||
};
|
||||
|
||||
[Fact]
|
||||
public void Jmena_hlasice_a_resitele_vezme_z_casove_osy()
|
||||
{
|
||||
var model = Model(7,
|
||||
Event("CREATED", null, "RECEIVED", "Jan Novák"),
|
||||
Event("ASSIGNED", "RECEIVED", "ASSIGNED", "Vedení Školy", "Petr Svoboda"),
|
||||
Event("ASSIGNED", "ASSIGNED", "ASSIGNED", "Vedení Školy", "Eva Malá"));
|
||||
|
||||
Assert.Equal("Jan Novák", model.ReporterName);
|
||||
Assert.Equal("Eva Malá", model.AssigneeName); // po přeřazení platí poslední přiřazení
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Nepriprazena_zavada_nema_resitele() => Assert.Null(Model(null, Event("CREATED", null, "RECEIVED", "Jan")).AssigneeName);
|
||||
|
||||
[Fact]
|
||||
public void Akce_zmeny_stavu_jsou_jen_povolene_a_v_poradi_zivotniho_cyklu() =>
|
||||
Assert.Equal([IssueActions.SubmitForVerification, IssueActions.Reject], Model(7).Transitions);
|
||||
|
||||
[Theory]
|
||||
[InlineData("CREATED", null, "RECEIVED", null, "nahlásil/a závadu", null)]
|
||||
[InlineData("ASSIGNED", "RECEIVED", "ASSIGNED", "Petr Svoboda", "přiřadil/a závadu řešiteli Petr Svoboda", null)]
|
||||
[InlineData("ASSIGNED", "IN_PROGRESS", "ASSIGNED", "Eva Malá", "přeřadil/a závadu na Eva Malá", null)]
|
||||
[InlineData("STATUS_CHANGED", "ASSIGNED", "IN_PROGRESS", null, "zahájil/a řešení", null)]
|
||||
[InlineData("STATUS_CHANGED", "PENDING_VERIFICATION", "IN_PROGRESS", "Pořád bliká", "znovu otevřel/a závadu", "Důvod")]
|
||||
[InlineData("STATUS_CHANGED", "IN_PROGRESS", "PENDING_VERIFICATION", "Vyměněna lampa", "předal/a závadu k ověření", "Poznámka")]
|
||||
[InlineData("STATUS_CHANGED", "IN_PROGRESS", "REJECTED", "Duplicitní hlášení", "zamítl/a závadu", "Důvod")]
|
||||
[InlineData("COMMENTED", null, "IN_PROGRESS", "Funguje HDMI?", "napsal/a komentář", null)]
|
||||
public void Udalost_casove_osy_ma_srozumitelny_popis(string type, string? from, string to, string? note, string text, string? noteLabel)
|
||||
{
|
||||
var entry = TimelineEntry.From(Event(type, from, to, "Někdo", note));
|
||||
|
||||
Assert.Equal(text, entry.Text);
|
||||
Assert.Equal(noteLabel, entry.NoteLabel);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Komentar_nema_stitek_stavu()
|
||||
{
|
||||
var entry = TimelineEntry.From(Event("COMMENTED", null, "IN_PROGRESS", "Jan", "Funguje HDMI?"));
|
||||
|
||||
Assert.True(entry.IsComment);
|
||||
Assert.Null(entry.Status);
|
||||
Assert.Equal("Funguje HDMI?", entry.Note);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(900, "900 B")]
|
||||
[InlineData(300_000, "293 kB")]
|
||||
[InlineData(2_500_000, "2,4 MB")]
|
||||
public void Velikost_prilohy_je_citelna(long bytes, string expected) =>
|
||||
Assert.Equal(expected, IssueDetailViewModel.FileSize(bytes).Replace('.', ','));
|
||||
}
|
||||
|
||||
public class IssueActionsApiTests
|
||||
{
|
||||
[Theory]
|
||||
[InlineData(IssueActions.StartWork, null, "/api/v1/issues/42/start", """{"rowVersion":3}""")]
|
||||
[InlineData(IssueActions.SubmitForVerification, "Hotovo", "/api/v1/issues/42/submit-for-verification", """{"rowVersion":3,"note":"Hotovo"}""")]
|
||||
[InlineData(IssueActions.Confirm, null, "/api/v1/issues/42/confirm", """{"rowVersion":3}""")]
|
||||
[InlineData(IssueActions.Reopen, "Bliká dál", "/api/v1/issues/42/reopen", """{"rowVersion":3,"reason":"Bliká dál"}""")]
|
||||
[InlineData(IssueActions.Reject, "Duplicita", "/api/v1/issues/42/reject", """{"rowVersion":3,"reason":"Duplicita"}""")]
|
||||
public async Task Zmena_stavu_jde_na_akcni_endpoint_s_rowVersion(string action, string? text, string path, string body)
|
||||
{
|
||||
var handler = new RecordingHandler(DetailJson);
|
||||
await Client(handler).TransitionIssueAsync(42, action, 3, text, CancellationToken.None);
|
||||
|
||||
Assert.Equal(HttpMethod.Post, handler.Method);
|
||||
Assert.Equal(path, handler.Path);
|
||||
Assert.True(JsonNode.DeepEquals(JsonNode.Parse(body), JsonNode.Parse(handler.Body!)), handler.Body);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Neznama_akce_se_do_API_neposle() =>
|
||||
await Assert.ThrowsAsync<ArgumentException>(() =>
|
||||
Client(new RecordingHandler(DetailJson)).TransitionIssueAsync(42, "DELETE", 3, null, CancellationToken.None));
|
||||
|
||||
[Fact]
|
||||
public async Task Prirazeni_posle_resitele_prioritu_a_verzi()
|
||||
{
|
||||
var handler = new RecordingHandler(DetailJson);
|
||||
await Client(handler).AssignIssueAsync(42, new AssignIssueRequest(7, "HIGH", 3), CancellationToken.None);
|
||||
|
||||
Assert.Equal("/api/v1/issues/42/assign", handler.Path);
|
||||
Assert.Equal("""{"assigneeId":7,"priority":"HIGH","rowVersion":3}""", handler.Body);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Detail_nacte_akce_i_prilohy()
|
||||
{
|
||||
var issue = await Client(new RecordingHandler(DetailJson)).GetIssueAsync(42, CancellationToken.None);
|
||||
|
||||
Assert.True(issue.Can(IssueActions.Comment));
|
||||
Assert.False(issue.Can(IssueActions.Assign));
|
||||
Assert.Equal("foto.jpg", Assert.Single(issue.Attachments).FileName);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Priloha_si_zachova_cesky_nazev_souboru()
|
||||
{
|
||||
var handler = new RecordingHandler("", response =>
|
||||
{
|
||||
response.Content = new ByteArrayContent([0xFF, 0xD8, 0xFF]);
|
||||
response.Content.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg");
|
||||
response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") { FileNameStar = "učebna B-205.jpg" };
|
||||
});
|
||||
|
||||
using var file = await Client(handler).DownloadAttachmentAsync(9, CancellationToken.None);
|
||||
|
||||
Assert.Equal("/api/v1/attachments/9", handler.Path);
|
||||
Assert.Equal("učebna B-205.jpg", file.FileName);
|
||||
Assert.Equal("image/jpeg", file.ContentType);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Chyby_poli_z_API_se_spoji_do_jedne_zpravy()
|
||||
{
|
||||
var ex = new ApiException(HttpStatusCode.BadRequest, "One or more validation errors occurred.",
|
||||
new Dictionary<string, string[]> { ["reason"] = ["Důvod je povinný."], ["rowVersion"] = ["Chybí verze."] });
|
||||
|
||||
Assert.Equal("Důvod je povinný. Chybí verze.", ex.AllMessages);
|
||||
}
|
||||
|
||||
private const string DetailJson = """
|
||||
{"id":42,"title":"Projektor","description":"Bliká.","categoryId":2,"buildingId":null,"locationDetail":null,
|
||||
"status":"IN_PROGRESS","priority":"NORMAL","reporterId":5,"assigneeId":7,"createdAt":"2026-10-03T08:00:00Z",
|
||||
"rowVersion":4,"allowedActions":["COMMENT","ADD_ATTACHMENTS"],
|
||||
"attachments":[{"id":9,"fileName":"foto.jpg","contentType":"image/jpeg","sizeBytes":3,"createdAt":"2026-10-03T08:00:00Z"}]}
|
||||
""";
|
||||
|
||||
private static HelpdeskApiClient Client(HttpMessageHandler handler) =>
|
||||
new(new HttpClient(handler) { BaseAddress = new ApiOptions { BaseUrl = "http://api/" }.VersionedBaseAddress() });
|
||||
|
||||
private sealed class RecordingHandler(string json, Action<HttpResponseMessage>? customize = null) : HttpMessageHandler
|
||||
{
|
||||
public HttpMethod? Method { get; private set; }
|
||||
public string? Path { get; private set; }
|
||||
public string? Body { get; private set; }
|
||||
|
||||
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken ct)
|
||||
{
|
||||
Method = request.Method;
|
||||
Path = request.RequestUri!.AbsolutePath;
|
||||
Body = request.Content is null ? null : await request.Content.ReadAsStringAsync(ct);
|
||||
var response = new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(json, Encoding.UTF8, "application/json") };
|
||||
customize?.Invoke(response);
|
||||
return response;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
using System.Net;
|
||||
using System.Text;
|
||||
using Helpdesk.Web.Api;
|
||||
using Helpdesk.Web.Models;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
|
||||
namespace Helpdesk.Web.Tests;
|
||||
|
||||
public class AttachmentRulesTests
|
||||
{
|
||||
private static IFormFile File(string name, long length) =>
|
||||
new FormFile(new MemoryStream(new byte[Math.Min(length, 16)]), 0, length, "Files", name);
|
||||
|
||||
[Fact]
|
||||
public void Povolene_soubory_projdou() =>
|
||||
Assert.Empty(AttachmentRules.Validate([File("projektor.JPG", 2_000_000), File("protokol.pdf", 300_000)]));
|
||||
|
||||
[Fact]
|
||||
public void Vic_nez_pet_souboru_neprojde() =>
|
||||
Assert.Contains(AttachmentRules.Validate(Enumerable.Range(1, 6).Select(i => File($"foto{i}.png", 1000)).ToList()),
|
||||
e => e.Contains("nejvýše 5"));
|
||||
|
||||
[Theory]
|
||||
[InlineData("virus.exe", "povolený typ")]
|
||||
[InlineData("velka.jpg", "10 MB")]
|
||||
[InlineData("prazdny.png", "prázdný")]
|
||||
public void Nepovoleny_soubor_ma_srozumitelnou_chybu(string name, string expected)
|
||||
{
|
||||
var length = name switch { "velka.jpg" => AttachmentRules.MaxFileBytes + 1, "prazdny.png" => 0, _ => 100 };
|
||||
Assert.Contains(AttachmentRules.Validate([File(name, length)]), e => e.Contains(expected));
|
||||
}
|
||||
}
|
||||
|
||||
public class IssueListViewModelTests
|
||||
{
|
||||
private static readonly IssueListViewModel Model = new()
|
||||
{
|
||||
Issues = new PagedResult<IssueSummary>([], 0, 1, 20),
|
||||
CategoryNames = new Dictionary<int, string> { [2] = "Technické vybavení" },
|
||||
BuildingNames = new Dictionary<int, string> { [2] = "Budova B" },
|
||||
};
|
||||
|
||||
private static IssueSummary Issue(int? buildingId, string? detail) =>
|
||||
new(1, "Projektor", 2, buildingId, detail, "RECEIVED", "NORMAL", 1, null, DateTimeOffset.UnixEpoch);
|
||||
|
||||
[Theory]
|
||||
[InlineData(2, "učebna B-205", "Budova B – učebna B-205")]
|
||||
[InlineData(2, null, "Budova B")]
|
||||
[InlineData(null, "venku u vchodu", "venku u vchodu")]
|
||||
[InlineData(null, null, null)]
|
||||
public void Misto_spoji_budovu_a_upresneni(int? buildingId, string? detail, string? expected) =>
|
||||
Assert.Equal(expected, Model.Location(Issue(buildingId, detail)));
|
||||
|
||||
[Fact]
|
||||
public void Neznama_kategorie_neshodi_stranku() => Assert.Equal("Neznámá kategorie", Model.CategoryName(99));
|
||||
}
|
||||
|
||||
public class CreateIssueRequestTests
|
||||
{
|
||||
[Fact]
|
||||
public async Task Hlaseni_s_prilohou_jde_do_API_jako_multipart()
|
||||
{
|
||||
var handler = new RecordingHandler();
|
||||
var api = new HelpdeskApiClient(new HttpClient(handler) { BaseAddress = new ApiOptions { BaseUrl = "http://api/" }.VersionedBaseAddress() });
|
||||
|
||||
var issue = await api.CreateIssueAsync(
|
||||
new CreateIssueRequest("Projektor", "Bliká.", 2, BuildingId: null, LocationDetail: "B-205"),
|
||||
[new UploadFile("foto.jpg", "image/jpeg", () => new MemoryStream([0xFF, 0xD8, 0xFF]))],
|
||||
CancellationToken.None);
|
||||
|
||||
Assert.Equal(7, issue.Id);
|
||||
Assert.Equal("/api/v1/issues", handler.Path);
|
||||
Assert.StartsWith("multipart/form-data", handler.ContentType);
|
||||
Assert.Contains("name=title", handler.Body);
|
||||
Assert.Contains("name=categoryId", handler.Body);
|
||||
Assert.Contains("name=files; filename=foto.jpg", handler.Body);
|
||||
Assert.DoesNotContain("name=buildingId", handler.Body); // nepovinná pole bez hodnoty se neposílají
|
||||
}
|
||||
|
||||
private sealed class RecordingHandler : HttpMessageHandler
|
||||
{
|
||||
public string? Path { get; private set; }
|
||||
public string? ContentType { get; private set; }
|
||||
public string Body { get; private set; } = "";
|
||||
|
||||
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken ct)
|
||||
{
|
||||
Path = request.RequestUri!.AbsolutePath;
|
||||
ContentType = request.Content!.Headers.ContentType!.ToString();
|
||||
Body = await request.Content.ReadAsStringAsync(ct);
|
||||
return new HttpResponseMessage(HttpStatusCode.Created)
|
||||
{
|
||||
Content = new StringContent("""{"id":7,"title":"Projektor","status":"RECEIVED","rowVersion":0,"allowedActions":["EDIT"]}""",
|
||||
Encoding.UTF8, "application/json"),
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
using Helpdesk.Web.Infrastructure;
|
||||
|
||||
namespace Helpdesk.Web.Tests;
|
||||
|
||||
public class StatusLabelsTests
|
||||
{
|
||||
[Theory]
|
||||
[InlineData("RECEIVED", "Přijata")]
|
||||
[InlineData("IN_PROGRESS", "V řešení")]
|
||||
[InlineData("PENDING_VERIFICATION", "Čeká na ověření")]
|
||||
[InlineData("in_progress", "V řešení")]
|
||||
public void Stav_zavady_ma_cesky_nazev(string status, string label) => Assert.Equal(label, StatusLabels.For(status));
|
||||
|
||||
[Fact]
|
||||
public void Zamitnuti_se_sklonuje_podle_zavady_a_navrhu()
|
||||
{
|
||||
Assert.Equal("Zamítnuta", StatusLabels.For("REJECTED"));
|
||||
Assert.Equal("Zamítnut", StatusLabels.For("REJECTED", isProposal: true));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Neznamy_kod_se_zobrazi_tak_jak_prisel() => Assert.Equal("ARCHIVED", StatusLabels.For("ARCHIVED"));
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
using System.Net;
|
||||
using System.Text;
|
||||
using Helpdesk.Web.Api;
|
||||
using Helpdesk.Web.Auth;
|
||||
using Microsoft.AspNetCore.Mvc.Testing;
|
||||
using Microsoft.AspNetCore.TestHost;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using static Helpdesk.Web.Tests.WebTestSession;
|
||||
|
||||
namespace Helpdesk.Web.Tests;
|
||||
|
||||
public sealed class SwaggerAccessTests
|
||||
{
|
||||
[Fact]
|
||||
public async Task SwaggerAndItsAssetsRequireAnAdministratorSession()
|
||||
{
|
||||
await using var application = new WebApplicationFactory<Program>().WithWebHostBuilder(builder =>
|
||||
builder.ConfigureTestServices(services => services.AddHttpClient(nameof(HelpdeskApiClient))
|
||||
.ConfigurePrimaryHttpMessageHandler(() => new OpenApiBackend())));
|
||||
using var client = application.CreateClient(new WebApplicationFactoryClientOptions
|
||||
{
|
||||
AllowAutoRedirect = false,
|
||||
BaseAddress = new Uri("https://localhost"),
|
||||
});
|
||||
var ct = TestContext.Current.CancellationToken;
|
||||
string[] paths = ["/swagger", "/swagger/index.html", "/swagger/index.js", "/swagger/swagger-ui.css", "/swagger/v1/swagger.json"];
|
||||
foreach (var path in paths)
|
||||
{
|
||||
using var response = await client.GetAsync(path, ct);
|
||||
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
|
||||
Assert.Equal("/login", response.Headers.Location?.AbsolutePath);
|
||||
}
|
||||
|
||||
SignIn(application.Services, client, UserRoles.Student);
|
||||
foreach (var path in paths)
|
||||
{
|
||||
using var response = await client.GetAsync(path, ct);
|
||||
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
|
||||
Assert.Equal("/error/403", response.Headers.Location?.AbsolutePath);
|
||||
}
|
||||
|
||||
SignIn(application.Services, client, UserRoles.Admin);
|
||||
using var entry = await client.GetAsync("/swagger", ct);
|
||||
Assert.Equal(HttpStatusCode.MovedPermanently, entry.StatusCode);
|
||||
using var index = await client.GetAsync("/swagger/index.html", ct);
|
||||
Assert.Equal(HttpStatusCode.OK, index.StatusCode);
|
||||
Assert.Contains("Helpdesk API", await index.Content.ReadAsStringAsync(ct));
|
||||
Assert.True(index.Headers.CacheControl?.NoStore == true);
|
||||
using var script = await client.GetAsync("/swagger/index.js", ct);
|
||||
Assert.Equal(HttpStatusCode.OK, script.StatusCode);
|
||||
Assert.Contains("v1/swagger.json", await script.Content.ReadAsStringAsync(ct));
|
||||
using var css = await client.GetAsync("/swagger/swagger-ui.css", ct);
|
||||
Assert.Equal(HttpStatusCode.OK, css.StatusCode);
|
||||
using var document = await client.GetAsync("/swagger/v1/swagger.json", ct);
|
||||
Assert.Equal(HttpStatusCode.OK, document.StatusCode);
|
||||
Assert.Contains("\"openapi\"", await document.Content.ReadAsStringAsync(ct));
|
||||
Assert.True(document.Headers.CacheControl?.NoStore == true);
|
||||
}
|
||||
|
||||
private sealed class OpenApiBackend : HttpMessageHandler
|
||||
{
|
||||
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
|
||||
{
|
||||
Assert.Equal("/api/v1/admin/openapi/v1.json", request.RequestUri?.AbsolutePath);
|
||||
Assert.Equal("Bearer", request.Headers.Authorization?.Scheme);
|
||||
Assert.Equal("test-access", request.Headers.Authorization?.Parameter);
|
||||
return Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK)
|
||||
{
|
||||
Content = new StringContent("""{"openapi":"3.0.4"}""", Encoding.UTF8, "application/json"),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
using Helpdesk.Web.Api;
|
||||
using Helpdesk.Web.Auth;
|
||||
|
||||
namespace Helpdesk.Web.Tests;
|
||||
|
||||
public class TokenRefresherTests
|
||||
{
|
||||
private static readonly DateTimeOffset Now = new(2026, 12, 1, 10, 0, 0, TimeSpan.Zero);
|
||||
private readonly FakeClock _clock = new(Now);
|
||||
|
||||
private static TokenSet NewTokens(string suffix) =>
|
||||
new($"access-{suffix}", Now.AddMinutes(15), $"refresh-{suffix}", Now.AddDays(14));
|
||||
|
||||
[Fact]
|
||||
public async Task Soubezne_obnovy_stejneho_tokenu_volaji_API_jen_jednou()
|
||||
{
|
||||
var refresher = new TokenRefresher(_clock);
|
||||
var calls = 0;
|
||||
var gate = new TaskCompletionSource<TokenSet?>();
|
||||
|
||||
Task<TokenSet?> Refresh(string _)
|
||||
{
|
||||
Interlocked.Increment(ref calls);
|
||||
return gate.Task;
|
||||
}
|
||||
|
||||
var pending = Enumerable.Range(0, 5).Select(_ => refresher.RefreshAsync("refresh-old", Refresh)).ToArray();
|
||||
gate.SetResult(NewTokens("new"));
|
||||
var results = await Task.WhenAll(pending);
|
||||
|
||||
Assert.Equal(1, calls);
|
||||
Assert.All(results, r => Assert.Equal("access-new", r!.AccessToken));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Pozdni_pozadavek_se_starou_cookie_dostane_stejny_vysledek()
|
||||
{
|
||||
var refresher = new TokenRefresher(_clock);
|
||||
var calls = 0;
|
||||
Task<TokenSet?> Refresh(string _) { calls++; return Task.FromResult<TokenSet?>(NewTokens($"{calls}")); }
|
||||
|
||||
var first = await refresher.RefreshAsync("refresh-old", Refresh);
|
||||
_clock.Advance(TimeSpan.FromSeconds(20));
|
||||
var late = await refresher.RefreshAsync("refresh-old", Refresh);
|
||||
|
||||
Assert.Equal(1, calls);
|
||||
Assert.Equal(first, late);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Vysledek_se_po_uplynuti_doby_zapomene()
|
||||
{
|
||||
var refresher = new TokenRefresher(_clock);
|
||||
var calls = 0;
|
||||
Task<TokenSet?> Refresh(string _) { calls++; return Task.FromResult<TokenSet?>(null); }
|
||||
|
||||
await refresher.RefreshAsync("refresh-old", Refresh);
|
||||
_clock.Advance(TokenRefresher.ResultLifetime + TimeSpan.FromSeconds(1));
|
||||
await refresher.RefreshAsync("refresh-old", Refresh);
|
||||
|
||||
Assert.Equal(2, calls);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Ruzne_tokeny_se_obnovuji_nezavisle()
|
||||
{
|
||||
var refresher = new TokenRefresher(_clock);
|
||||
var calls = 0;
|
||||
Task<TokenSet?> Refresh(string token) { calls++; return Task.FromResult<TokenSet?>(NewTokens(token)); }
|
||||
|
||||
var a = await refresher.RefreshAsync("refresh-a", Refresh);
|
||||
var b = await refresher.RefreshAsync("refresh-b", Refresh);
|
||||
|
||||
Assert.Equal(2, calls);
|
||||
Assert.NotEqual(a, b);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Docasna_chyba_se_nepamatuje()
|
||||
{
|
||||
var refresher = new TokenRefresher(_clock);
|
||||
var calls = 0;
|
||||
Task<TokenSet?> Refresh(string _) =>
|
||||
++calls == 1 ? throw new HttpRequestException("API nedostupné") : Task.FromResult<TokenSet?>(NewTokens("new"));
|
||||
|
||||
await Assert.ThrowsAsync<HttpRequestException>(() => refresher.RefreshAsync("refresh-old", Refresh));
|
||||
var retry = await refresher.RefreshAsync("refresh-old", Refresh);
|
||||
|
||||
Assert.Equal(2, calls);
|
||||
Assert.Equal("access-new", retry!.AccessToken);
|
||||
}
|
||||
}
|
||||
|
||||
internal sealed class FakeClock(DateTimeOffset now) : TimeProvider
|
||||
{
|
||||
private DateTimeOffset _now = now;
|
||||
|
||||
public override DateTimeOffset GetUtcNow() => _now;
|
||||
|
||||
public void Advance(TimeSpan by) => _now += by;
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
using Helpdesk.Web.Api;
|
||||
using Helpdesk.Web.Infrastructure;
|
||||
|
||||
namespace Helpdesk.Web.Tests;
|
||||
|
||||
public class ApiVersioningTests
|
||||
{
|
||||
[Theory]
|
||||
[InlineData("http://api:8080/")]
|
||||
[InlineData("http://api:8080")]
|
||||
public void Zaklad_adresy_obsahuje_verzi_API(string baseUrl) =>
|
||||
Assert.Equal("http://api:8080/api/v1/", new ApiOptions { BaseUrl = baseUrl }.VersionedBaseAddress().ToString());
|
||||
|
||||
[Fact]
|
||||
public void Relativni_cesta_se_slozi_pod_verzi()
|
||||
{
|
||||
var baseAddress = new ApiOptions { BaseUrl = "http://api:8080/" }.VersionedBaseAddress();
|
||||
|
||||
Assert.Equal("/api/v1/auth/login", new Uri(baseAddress, "auth/login").AbsolutePath);
|
||||
}
|
||||
}
|
||||
|
||||
public class AppVersionTests
|
||||
{
|
||||
[Theory]
|
||||
[InlineData("0.2.0+6e742b4029cca8896173c0d64783b7fb7540f214", "0.2.0 (6e742b4)")]
|
||||
[InlineData("0.2.0", "0.2.0")]
|
||||
[InlineData(null, "neznámá")]
|
||||
public void Verze_se_zobrazi_s_kratkym_hashem_commitu(string? informational, string expected) =>
|
||||
Assert.Equal(expected, AppVersion.Format(informational));
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
using Helpdesk.Web.Api;
|
||||
using Helpdesk.Web.Auth;
|
||||
using Microsoft.AspNetCore.Authentication;
|
||||
using Microsoft.AspNetCore.Authentication.Cookies;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Options;
|
||||
|
||||
namespace Helpdesk.Web.Tests;
|
||||
|
||||
internal static class WebTestSession
|
||||
{
|
||||
public static void SignIn(IServiceProvider services, HttpClient client, string role)
|
||||
{
|
||||
var scheme = CookieAuthenticationDefaults.AuthenticationScheme;
|
||||
var options = services.GetRequiredService<IOptionsMonitor<CookieAuthenticationOptions>>().Get(scheme);
|
||||
var now = DateTimeOffset.UtcNow;
|
||||
var properties = new AuthenticationProperties { IssuedUtc = now, ExpiresUtc = now.AddHours(1) };
|
||||
AuthCookie.StoreTokens(properties, new TokenSet("test-access", now.AddMinutes(15), "test-refresh", now.AddDays(1)));
|
||||
var user = new UserDto(1, "[email protected]", "Test", "User", null, role, true);
|
||||
var ticket = new AuthenticationTicket(AuthCookie.CreatePrincipal(user), properties, scheme);
|
||||
|
||||
client.DefaultRequestHeaders.Remove("Cookie");
|
||||
client.DefaultRequestHeaders.Add("Cookie", $"{AuthCookie.Name}={options.TicketDataFormat.Protect(ticket)}");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
|
||||
Microsoft Visual Studio Solution File, Format Version 12.00
|
||||
# Visual Studio Version 17
|
||||
VisualStudioVersion = 17.0.31903.59
|
||||
MinimumVisualStudioVersion = 10.0.40219.1
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Helpdesk.Web", "Helpdesk.Web\Helpdesk.Web.csproj", "{25D75863-E1EF-4B3E-B5FE-CE8F7E21F2F6}"
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Helpdesk.Web.Tests", "Helpdesk.Web.Tests\Helpdesk.Web.Tests.csproj", "{A1D048EA-6B9C-4920-A3F2-5DB3B92404CA}"
|
||||
EndProject
|
||||
Global
|
||||
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
||||
Debug|Any CPU = Debug|Any CPU
|
||||
Debug|x64 = Debug|x64
|
||||
Debug|x86 = Debug|x86
|
||||
Release|Any CPU = Release|Any CPU
|
||||
Release|x64 = Release|x64
|
||||
Release|x86 = Release|x86
|
||||
EndGlobalSection
|
||||
GlobalSection(ProjectConfigurationPlatforms) = postSolution
|
||||
{25D75863-E1EF-4B3E-B5FE-CE8F7E21F2F6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{25D75863-E1EF-4B3E-B5FE-CE8F7E21F2F6}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{25D75863-E1EF-4B3E-B5FE-CE8F7E21F2F6}.Debug|x64.ActiveCfg = Debug|Any CPU
|
||||
{25D75863-E1EF-4B3E-B5FE-CE8F7E21F2F6}.Debug|x64.Build.0 = Debug|Any CPU
|
||||
{25D75863-E1EF-4B3E-B5FE-CE8F7E21F2F6}.Debug|x86.ActiveCfg = Debug|Any CPU
|
||||
{25D75863-E1EF-4B3E-B5FE-CE8F7E21F2F6}.Debug|x86.Build.0 = Debug|Any CPU
|
||||
{25D75863-E1EF-4B3E-B5FE-CE8F7E21F2F6}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{25D75863-E1EF-4B3E-B5FE-CE8F7E21F2F6}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{25D75863-E1EF-4B3E-B5FE-CE8F7E21F2F6}.Release|x64.ActiveCfg = Release|Any CPU
|
||||
{25D75863-E1EF-4B3E-B5FE-CE8F7E21F2F6}.Release|x64.Build.0 = Release|Any CPU
|
||||
{25D75863-E1EF-4B3E-B5FE-CE8F7E21F2F6}.Release|x86.ActiveCfg = Release|Any CPU
|
||||
{25D75863-E1EF-4B3E-B5FE-CE8F7E21F2F6}.Release|x86.Build.0 = Release|Any CPU
|
||||
{A1D048EA-6B9C-4920-A3F2-5DB3B92404CA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{A1D048EA-6B9C-4920-A3F2-5DB3B92404CA}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{A1D048EA-6B9C-4920-A3F2-5DB3B92404CA}.Debug|x64.ActiveCfg = Debug|Any CPU
|
||||
{A1D048EA-6B9C-4920-A3F2-5DB3B92404CA}.Debug|x64.Build.0 = Debug|Any CPU
|
||||
{A1D048EA-6B9C-4920-A3F2-5DB3B92404CA}.Debug|x86.ActiveCfg = Debug|Any CPU
|
||||
{A1D048EA-6B9C-4920-A3F2-5DB3B92404CA}.Debug|x86.Build.0 = Debug|Any CPU
|
||||
{A1D048EA-6B9C-4920-A3F2-5DB3B92404CA}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{A1D048EA-6B9C-4920-A3F2-5DB3B92404CA}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{A1D048EA-6B9C-4920-A3F2-5DB3B92404CA}.Release|x64.ActiveCfg = Release|Any CPU
|
||||
{A1D048EA-6B9C-4920-A3F2-5DB3B92404CA}.Release|x64.Build.0 = Release|Any CPU
|
||||
{A1D048EA-6B9C-4920-A3F2-5DB3B92404CA}.Release|x86.ActiveCfg = Release|Any CPU
|
||||
{A1D048EA-6B9C-4920-A3F2-5DB3B92404CA}.Release|x86.Build.0 = Release|Any CPU
|
||||
EndGlobalSection
|
||||
GlobalSection(SolutionProperties) = preSolution
|
||||
HideSolutionNode = FALSE
|
||||
EndGlobalSection
|
||||
EndGlobal
|
||||
@@ -0,0 +1,76 @@
|
||||
using System.Net;
|
||||
using System.Net.Http.Json;
|
||||
using System.Text.Json;
|
||||
|
||||
namespace Helpdesk.Web.Api;
|
||||
|
||||
/// <summary>
|
||||
/// Neúspěšná odpověď API ve formátu ProblemDetails (RFC 9457). Nese stav, titulek
|
||||
/// a u validačních chyb seznam chyb podle polí (klíče jsou názvy vlastností v camelCase).
|
||||
/// </summary>
|
||||
public sealed class ApiException(HttpStatusCode statusCode, string? title, IReadOnlyDictionary<string, string[]> errors)
|
||||
: Exception(title ?? $"API vrátilo stav {(int)statusCode}.")
|
||||
{
|
||||
public HttpStatusCode StatusCode { get; } = statusCode;
|
||||
public string? Title { get; } = title;
|
||||
public IReadOnlyDictionary<string, string[]> Errors { get; } = errors;
|
||||
|
||||
/// <summary>Text pro uživatele. API píše titulky chyb česky, kromě odpovědí bez těla (např. 429).</summary>
|
||||
public string UserMessage => StatusCode switch
|
||||
{
|
||||
HttpStatusCode.TooManyRequests => "Příliš mnoho pokusů. Zkuste to prosím za minutu.",
|
||||
_ when !string.IsNullOrWhiteSpace(Title) => Title,
|
||||
HttpStatusCode.Forbidden => "K této akci nemáte oprávnění.",
|
||||
HttpStatusCode.NotFound => "Záznam nebyl nalezen.",
|
||||
_ => "Požadavek se nepodařilo zpracovat. Zkuste to prosím znovu.",
|
||||
};
|
||||
|
||||
/// <summary>Chyby polí, pokud je API poslalo, jinak <see cref="UserMessage"/> – pro zprávu mimo formulář.</summary>
|
||||
public string AllMessages => Errors.Count == 0
|
||||
? UserMessage
|
||||
: string.Join(" ", Errors.Values.SelectMany(messages => messages).Distinct());
|
||||
|
||||
public static async Task<ApiException> FromResponseAsync(HttpResponseMessage response, CancellationToken ct)
|
||||
{
|
||||
string? title = null;
|
||||
Dictionary<string, string[]> errors = new(StringComparer.OrdinalIgnoreCase);
|
||||
|
||||
if (response.Content.Headers.ContentType?.MediaType is { } mediaType && mediaType.Contains("json", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
try
|
||||
{
|
||||
var problem = await response.Content.ReadFromJsonAsync<ProblemBody>(ct);
|
||||
title = problem?.Title;
|
||||
if (problem?.Errors is { } fieldErrors)
|
||||
{
|
||||
foreach (var (field, messages) in fieldErrors)
|
||||
errors[field] = messages;
|
||||
}
|
||||
}
|
||||
catch (JsonException)
|
||||
{
|
||||
// Tělo není ProblemDetails – zůstane jen stavový kód.
|
||||
}
|
||||
}
|
||||
|
||||
return new ApiException(response.StatusCode, title, errors);
|
||||
}
|
||||
|
||||
private sealed record ProblemBody(string? Title, Dictionary<string, string[]>? Errors);
|
||||
}
|
||||
|
||||
internal static class ApiResponse
|
||||
{
|
||||
public static async Task EnsureSuccessAsync(HttpResponseMessage response, CancellationToken ct)
|
||||
{
|
||||
if (!response.IsSuccessStatusCode)
|
||||
throw await ApiException.FromResponseAsync(response, ct);
|
||||
}
|
||||
|
||||
public static async Task<T> ReadAsync<T>(HttpResponseMessage response, CancellationToken ct)
|
||||
{
|
||||
await EnsureSuccessAsync(response, ct);
|
||||
return await response.Content.ReadFromJsonAsync<T>(ct)
|
||||
?? throw new InvalidOperationException($"API vrátilo prázdnou odpověď místo {typeof(T).Name}.");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,183 @@
|
||||
namespace Helpdesk.Web.Api;
|
||||
|
||||
// Kontrakt REST API /api/v1 tak, jak ho web používá. Web je tenký klient a na projekty
|
||||
// backendu nemá referenci – DTO jsou zde zrcadlem dokumentace ve Swaggeru.
|
||||
|
||||
public sealed record UserDto(
|
||||
int Id,
|
||||
string Email,
|
||||
string FirstName,
|
||||
string LastName,
|
||||
string? Phone,
|
||||
string Role,
|
||||
bool EmailNotificationsEnabled)
|
||||
{
|
||||
public string FullName => $"{FirstName} {LastName}";
|
||||
}
|
||||
|
||||
public sealed record AuthResponse(
|
||||
string AccessToken,
|
||||
DateTimeOffset AccessTokenExpiresAt,
|
||||
string RefreshToken,
|
||||
DateTimeOffset RefreshTokenExpiresAt,
|
||||
UserDto User)
|
||||
{
|
||||
public TokenSet Tokens => new(AccessToken, AccessTokenExpiresAt, RefreshToken, RefreshTokenExpiresAt);
|
||||
}
|
||||
|
||||
/// <summary>Pár tokenů uložený v autentizační cookie webu.</summary>
|
||||
public sealed record TokenSet(
|
||||
string AccessToken,
|
||||
DateTimeOffset AccessTokenExpiresAt,
|
||||
string RefreshToken,
|
||||
DateTimeOffset RefreshTokenExpiresAt);
|
||||
|
||||
public sealed record LoginRequest(string Email, string Password);
|
||||
|
||||
public sealed record RegisterRequest(string Email, string Password, string FirstName, string LastName);
|
||||
|
||||
public sealed record RefreshTokenRequest(string RefreshToken);
|
||||
|
||||
public sealed record EmailTokenRequest(string Token);
|
||||
|
||||
public sealed record ForgotPasswordRequest(string Email);
|
||||
|
||||
public sealed record ResetPasswordRequest(string Token, string NewPassword);
|
||||
|
||||
public sealed record UpdateProfileRequest(string FirstName, string LastName, string? Phone, bool EmailNotificationsEnabled);
|
||||
|
||||
public sealed record AdminUserDto(
|
||||
int Id, string Email, string FirstName, string LastName, string Role, bool IsActive, bool EmailConfirmed, DateTimeOffset CreatedAt)
|
||||
{
|
||||
public string FullName => $"{FirstName} {LastName}";
|
||||
}
|
||||
|
||||
public sealed record AdminUserDetailsDto(int Id, string Email, string FirstName, string LastName, string? Phone,
|
||||
string Role, bool IsActive, bool EmailConfirmed, bool EmailNotificationsEnabled, bool? VerificationEmailSent = null);
|
||||
|
||||
public sealed record SaveAdminUserRequest(string Email, string FirstName, string LastName, string? Phone,
|
||||
string Role, bool IsActive, bool EmailConfirmed, bool EmailNotificationsEnabled, string? Password);
|
||||
|
||||
/// <summary>Stránkovaný seznam z API: <c>{ items, totalCount, page, pageSize }</c>.</summary>
|
||||
public sealed record PagedResult<T>(IReadOnlyList<T> Items, int TotalCount, int Page, int PageSize)
|
||||
{
|
||||
public int PageCount => PageSize <= 0 ? 0 : (int)Math.Ceiling(TotalCount / (double)PageSize);
|
||||
}
|
||||
|
||||
public sealed record CategoryDto(int Id, string Name, string? Description, bool IsActive);
|
||||
|
||||
public sealed record BuildingDto(int Id, string Code, string Name, string? Address, bool IsActive);
|
||||
|
||||
/// <summary>Závada v seznamu. Kategorie a budova jsou jen ID – názvy doplňuje web z číselníků.</summary>
|
||||
public sealed record IssueSummary(
|
||||
int Id, string Title, int CategoryId, int? BuildingId, string? LocationDetail, string Status,
|
||||
string Priority, int ReporterId, int? AssigneeId, DateTimeOffset CreatedAt);
|
||||
|
||||
/// <summary>Nové hlášení. Přílohy jdou ve stejném požadavku (multipart, pole <c>files</c>).</summary>
|
||||
public sealed record CreateIssueRequest(string Title, string Description, int CategoryId, int? BuildingId, string? LocationDetail);
|
||||
|
||||
/// <summary>Soubor přeposílaný z formuláře webu do API.</summary>
|
||||
public sealed record UploadFile(string FileName, string ContentType, Func<Stream> OpenRead);
|
||||
|
||||
/// <summary>
|
||||
/// Detail závady. <c>AllowedActions</c> říká, co smí aktuální uživatel udělat (kódy z <see cref="IssueActions"/>),
|
||||
/// <c>RowVersion</c> se posílá zpět s každou úpravou a změnou stavu (optimistické zamykání, jinak 409).
|
||||
/// </summary>
|
||||
public sealed record IssueDetail(
|
||||
int Id, string Title, string Description, int CategoryId, int? BuildingId, string? LocationDetail, string Status,
|
||||
string Priority, int ReporterId, int? AssigneeId, DateTimeOffset CreatedAt, int RowVersion,
|
||||
IReadOnlyList<string> AllowedActions, IReadOnlyList<AttachmentDto> Attachments)
|
||||
{
|
||||
public bool Can(string action) => AllowedActions?.Contains(action) == true;
|
||||
}
|
||||
|
||||
public sealed record AttachmentDto(int Id, string FileName, string ContentType, long SizeBytes, DateTimeOffset CreatedAt);
|
||||
|
||||
/// <summary>Událost na časové ose závady – vytvoření, přiřazení, změna stavu i komentář (FR-17).</summary>
|
||||
public sealed record IssueEventDto(
|
||||
int Id, string EventType, string? FromStatus, string ToStatus, int ActorId, string ActorName, string? Note,
|
||||
DateTimeOffset OccurredAt);
|
||||
|
||||
/// <summary>Možný řešitel (jen pro vedení) s počtem jeho otevřených závad (FR-13).</summary>
|
||||
public sealed record AssignableUserDto(int Id, string FirstName, string LastName, string Role, int OpenIssues)
|
||||
{
|
||||
public string FullName => $"{FirstName} {LastName}";
|
||||
}
|
||||
|
||||
public sealed record EditIssueRequest(
|
||||
string Title, string Description, int CategoryId, int? BuildingId, string? LocationDetail, int RowVersion);
|
||||
|
||||
public sealed record AssignIssueRequest(int AssigneeId, string? Priority, int RowVersion);
|
||||
|
||||
public sealed record CommentRequest(string Text);
|
||||
|
||||
/// <summary>Stažená příloha. Proud čte přímo odpověď API a uvolní se spolu s ní.</summary>
|
||||
public sealed class ApiFile(Stream content, string contentType, string fileName, IDisposable response) : IDisposable
|
||||
{
|
||||
public Stream Content { get; } = content;
|
||||
public string ContentType { get; } = contentType;
|
||||
public string FileName { get; } = fileName;
|
||||
|
||||
public void Dispose() => response.Dispose();
|
||||
}
|
||||
|
||||
/// <summary>Kódy akcí z <c>allowedActions</c> v detailu závady.</summary>
|
||||
public static class IssueActions
|
||||
{
|
||||
public const string Edit = "EDIT";
|
||||
public const string Assign = "ASSIGN";
|
||||
public const string StartWork = "START_WORK";
|
||||
public const string SubmitForVerification = "SUBMIT_FOR_VERIFICATION";
|
||||
public const string Confirm = "CONFIRM";
|
||||
public const string Reopen = "REOPEN";
|
||||
public const string Reject = "REJECT";
|
||||
public const string Comment = "COMMENT";
|
||||
public const string AddAttachments = "ADD_ATTACHMENTS";
|
||||
|
||||
/// <summary>Změny stavu v pořadí, v jakém je web nabízí (T4 – T9).</summary>
|
||||
public static readonly IReadOnlyList<string> Transitions = [StartWork, SubmitForVerification, Confirm, Reopen, Reject];
|
||||
|
||||
/// <summary>Akční endpoint <c>POST /issues/{id}/…</c> pro změnu stavu.</summary>
|
||||
public static string? TransitionPath(string? action) => action switch
|
||||
{
|
||||
StartWork => "start",
|
||||
SubmitForVerification => "submit-for-verification",
|
||||
Confirm => "confirm",
|
||||
Reopen => "reopen",
|
||||
Reject => "reject",
|
||||
_ => null,
|
||||
};
|
||||
|
||||
/// <summary>Zamítnutí a znovuotevření vyžadují důvod (T7 – T9).</summary>
|
||||
public static bool RequiresReason(string action) => action is Reopen or Reject;
|
||||
|
||||
/// <summary>Předání k ověření má nepovinnou poznámku (T5).</summary>
|
||||
public static bool AcceptsText(string action) => action is SubmitForVerification || RequiresReason(action);
|
||||
|
||||
/// <summary>Texty tlačítek – stejné jako v mobilní aplikaci.</summary>
|
||||
public static string Label(string action) => action switch
|
||||
{
|
||||
StartWork => "Zahájit řešení",
|
||||
SubmitForVerification => "Předat k ověření",
|
||||
Confirm => "Potvrdit vyřešení",
|
||||
Reopen => "Znovu otevřít závadu",
|
||||
Reject => "Zamítnout závadu",
|
||||
_ => action,
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>Priorita závady; názvy jako v mobilní aplikaci.</summary>
|
||||
public static class IssuePriorities
|
||||
{
|
||||
public static readonly IReadOnlyList<string> All = ["LOW", "NORMAL", "HIGH"];
|
||||
|
||||
public static string Label(string? priority) => priority switch
|
||||
{
|
||||
"LOW" => "Nízká",
|
||||
"HIGH" => "Vysoká",
|
||||
_ => "Běžná",
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>Filtry <c>GET /api/v1/issues</c>; prázdné hodnoty se do dotazu neposílají.</summary>
|
||||
public sealed record IssueListQuery(string? Status = null, bool Mine = false, string Sort = "newest", int Page = 1, int PageSize = 20);
|
||||
Loaded 100 of 164 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user