Compare commits
9
Commits
79772e10ce
...
mobile-app
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
46f3b21a0b | ||
|
|
b402d9f92c | ||
|
|
bbbbca95fa | ||
|
|
c4fe447d9d | ||
|
|
a1bf12ba72 | ||
|
|
599237dd2c | ||
|
|
c96eb155ae | ||
|
|
28fc49ea39 | ||
|
|
b1e0638979 |
No files matched your search
@@ -9,7 +9,7 @@ Univerzitní helpdesk a portál návrhů na zlepšení – semestrální práce
|
|||||||
| Složka / soubor | Obsah |
|
| 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) |
|
| [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) |
|
| [backend/](backend/) | ASP.NET Core Web API, DbUp migrator, unit testy (.NET 10) |
|
||||||
| [mobile/](mobile/) | Android klient v Kotlinu a Jetpack Compose (Android 8+), připojení k API a ukázkový režim |
|
| [mobile/](mobile/) | Android klient v Kotlinu a Jetpack Compose (Android 8+), připojení k API a ukázkový režim |
|
||||||
| [deploy/](deploy/) | Docker Compose, inicializace DB účtů, šablona `.env` |
|
| [deploy/](deploy/) | Docker Compose, inicializace DB účtů, šablona `.env` |
|
||||||
@@ -24,7 +24,7 @@ Potřeba je jen Docker Desktop.
|
|||||||
cp deploy/.env.example deploy/.env
|
cp deploy/.env.example deploy/.env
|
||||||
```
|
```
|
||||||
|
|
||||||
Výchozí port API je `8080`. Pokud jej používá jiná aplikace, změňte u služby `api` v `deploy/docker-compose.yml` mapování na `8081:8080`. Port je v aktuální konfiguraci zadaný přímo.
|
Výchozí port API je `8080`. Pokud jej používá jiná aplikace, nastavte v `deploy/.env` hodnotu `API_HTTP_PORT=8081`.
|
||||||
|
|
||||||
2. Spusťte databázi, migrace a API:
|
2. Spusťte databázi, migrace a API:
|
||||||
|
|
||||||
@@ -34,9 +34,17 @@ Potřeba je jen Docker Desktop.
|
|||||||
|
|
||||||
3. Swagger UI: <http://localhost:8080/swagger> · stav a verze schématu: <http://localhost:8080/health>
|
3. Swagger UI: <http://localhost:8080/swagger> · stav a verze schématu: <http://localhost:8080/health>
|
||||||
|
|
||||||
Při mapování `8081:8080` použijte <http://localhost:8081/swagger> a <http://localhost:8081/health>.
|
Při nastavení `API_HTTP_PORT=8081` použijte <http://localhost:8081/swagger> a <http://localhost:8081/health>.
|
||||||
|
|
||||||
Při prvním startu se vytvoří účet administrátora z `ADMIN_EMAIL` / `ADMIN_PASSWORD`. V prostředí `Development` je odesílání e-mailů zatím jen do logu – odkaz pro ověření e-mailu po registraci najdete v `docker compose -f deploy/docker-compose.yml logs api`. Mimo vývoj se obsah e-mailů neloguje a poštovní transport ještě není zapojený.
|
Při prvním startu se vytvoří účet administrátora, pokud vyplníte `ADMIN_EMAIL` a `ADMIN_PASSWORD`. V režimu `Development` s prázdnými hodnotami `SMTP_MAILBOX` a `SMTP_PASSWORD` najdete ověřovací odkazy a odkazy pro obnovu hesla v logu služby `api`.
|
||||||
|
|
||||||
|
Pro nasazení nastavte v `deploy/.env` režim `Production`, veřejnou HTTPS adresu webu v `PUBLIC_BASE_URL` a skutečné univerzitní domény v `STUDENT_EMAIL_DOMAIN` a `TEACHER_EMAIL_DOMAIN`. Pro Email Profi vyplňte `SMTP_MAILBOX` celou adresou schránky a nastavte `SMTP_PASSWORD`. API odesílá přes `smtp.seznam.cz:465` s TLS.
|
||||||
|
|
||||||
|
Reverse proxy ukončuje HTTPS a předává požadavky přes HTTP na adresu `PROXY_UPSTREAM_BIND_ADDRESS` a port `API_HTTP_PORT`. Výchozí hodnoty `127.0.0.1` a `8080` odpovídají proxy běžící přímo na stejném hostiteli.
|
||||||
|
|
||||||
|
Pro zpracování `X-Forwarded-For` a `X-Forwarded-Proto` nastavte `TRUSTED_REVERSE_PROXY_IP` na IP bezprostředního protějšku, kterou vidí API. Tato IP se může při průchodu Docker sítí lišit od adresy, na kterou je API vázáno.
|
||||||
|
|
||||||
|
S nakonfigurovaným SMTP odesílá backend i e-mailové notifikace z databázové fronty. Pro mobilní push nastavte `FIREBASE_SERVICE_ACCOUNT_JSON` na jednořádkový JSON klíče servisního účtu Firebase.
|
||||||
|
|
||||||
### Vývoj bez Dockeru
|
### Vývoj bez Dockeru
|
||||||
|
|
||||||
@@ -50,7 +58,7 @@ dotnet run --project backend/tests/Helpdesk.UnitTests/Helpdesk.UnitTests.csproj
|
|||||||
|
|
||||||
Otevřete složku `mobile` v Android Studiu, nechte dokončit synchronizaci Gradle a spusťte aplikaci na Androidu 8.0 nebo novějším. Na úvodní obrazovce lze zvolit **Prohlédnout ukázku** bez běžícího serveru. Vlastní backend se nastavuje přes **Nastavení serveru**; výchozí adresa pro emulátor je `http://10.0.2.2:8080/`.
|
Otevřete složku `mobile` v Android Studiu, nechte dokončit synchronizaci Gradle a spusťte aplikaci na Androidu 8.0 nebo novějším. Na úvodní obrazovce lze zvolit **Prohlédnout ukázku** bez běžícího serveru. Vlastní backend se nastavuje přes **Nastavení serveru**; výchozí adresa pro emulátor je `http://10.0.2.2:8080/`.
|
||||||
|
|
||||||
Pokud jste port API změnili na `8081:8080`, zadejte v aplikaci `http://10.0.2.2:8081/`. Mobil je napojený na implementované API závad, návrhů a oznámení včetně příloh, hlasování a pracovního postupu řešitele; ukázkový režim je samostatná volba.
|
Pokud jste nastavili `API_HTTP_PORT=8081`, zadejte v aplikaci `http://10.0.2.2:8081/`. Pro skutečný telefon ve stejné Wi-Fi nastavte také `PROXY_UPSTREAM_BIND_ADDRESS=0.0.0.0` a v aplikaci použijte LAN adresu počítače; výchozí vazba `127.0.0.1` je určená místní proxy a emulátoru. Mobil je napojený na implementované API závad, návrhů a oznámení včetně příloh, hlasování a pracovního postupu řešitele; ukázkový režim je samostatná volba.
|
||||||
|
|
||||||
Podrobný postup sestavení, rozsah funkcí a stav napojení na API: [mobile/README.md](mobile/README.md).
|
Podrobný postup sestavení, rozsah funkcí a stav napojení na API: [mobile/README.md](mobile/README.md).
|
||||||
|
|
||||||
|
|||||||
@@ -17,6 +17,8 @@
|
|||||||
<PackageVersion Include="Microsoft.Extensions.Options.ConfigurationExtensions" 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" Version="10.3.1" />
|
||||||
<PackageVersion Include="BCrypt.Net-Next" Version="4.2.0" />
|
<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" Version="12.2.0" />
|
||||||
<PackageVersion Include="FluentValidation.DependencyInjectionExtensions" Version="12.2.0" />
|
<PackageVersion Include="FluentValidation.DependencyInjectionExtensions" Version="12.2.0" />
|
||||||
<!-- testy -->
|
<!-- testy -->
|
||||||
|
|||||||
@@ -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>
|
/// <summary>Správa uživatelů a rolí (jen administrátor).</summary>
|
||||||
[ApiController]
|
[ApiController]
|
||||||
[Authorize(Roles = Roles.Admin)]
|
[Authorize(Roles = Roles.Admin)]
|
||||||
[Route("api/admin/users")]
|
[Route(ApiRoutes.V1 + "/admin/users")]
|
||||||
[Produces("application/json")]
|
[Produces("application/json")]
|
||||||
public sealed class AdminUsersController(UserService users, ICurrentUser currentUser) : ControllerBase
|
public sealed class AdminUsersController(UserService users, ICurrentUser currentUser) : ControllerBase
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
using Helpdesk.Api.Infrastructure;
|
||||||
using Helpdesk.Application.Issues;
|
using Helpdesk.Application.Issues;
|
||||||
using Microsoft.AspNetCore.Authorization;
|
using Microsoft.AspNetCore.Authorization;
|
||||||
using Microsoft.AspNetCore.Mvc;
|
using Microsoft.AspNetCore.Mvc;
|
||||||
@@ -7,7 +8,7 @@ namespace Helpdesk.Api.Controllers;
|
|||||||
[ApiController]
|
[ApiController]
|
||||||
[Authorize]
|
[Authorize]
|
||||||
[ResponseCache(NoStore = true, Location = ResponseCacheLocation.None)]
|
[ResponseCache(NoStore = true, Location = ResponseCacheLocation.None)]
|
||||||
[Route("api/attachments")]
|
[Route(ApiRoutes.V1 + "/attachments")]
|
||||||
public sealed class AttachmentsController(IssueService issues) : ControllerBase
|
public sealed class AttachmentsController(IssueService issues) : ControllerBase
|
||||||
{
|
{
|
||||||
[HttpGet("{id:int}")]
|
[HttpGet("{id:int}")]
|
||||||
|
|||||||
@@ -10,7 +10,7 @@ namespace Helpdesk.Api.Controllers;
|
|||||||
|
|
||||||
/// <summary>Registrace, přihlášení a správa tokenů.</summary>
|
/// <summary>Registrace, přihlášení a správa tokenů.</summary>
|
||||||
[ApiController]
|
[ApiController]
|
||||||
[Route("api/auth")]
|
[Route(ApiRoutes.V1 + "/auth")]
|
||||||
[EnableRateLimiting(RateLimitPolicies.Auth)]
|
[EnableRateLimiting(RateLimitPolicies.Auth)]
|
||||||
[Produces("application/json")]
|
[Produces("application/json")]
|
||||||
public sealed class AuthController(AuthService auth) : ControllerBase
|
public sealed class AuthController(AuthService auth) : ControllerBase
|
||||||
@@ -21,10 +21,11 @@ public sealed class AuthController(AuthService auth) : ControllerBase
|
|||||||
[ProducesResponseType<UserDto>(StatusCodes.Status201Created)]
|
[ProducesResponseType<UserDto>(StatusCodes.Status201Created)]
|
||||||
[ProducesResponseType<ValidationProblemDetails>(StatusCodes.Status400BadRequest)]
|
[ProducesResponseType<ValidationProblemDetails>(StatusCodes.Status400BadRequest)]
|
||||||
[ProducesResponseType<ProblemDetails>(StatusCodes.Status409Conflict)]
|
[ProducesResponseType<ProblemDetails>(StatusCodes.Status409Conflict)]
|
||||||
|
[ProducesResponseType<ProblemDetails>(StatusCodes.Status503ServiceUnavailable)]
|
||||||
public async Task<ActionResult<UserDto>> Register(RegisterRequest request, CancellationToken ct)
|
public async Task<ActionResult<UserDto>> Register(RegisterRequest request, CancellationToken ct)
|
||||||
{
|
{
|
||||||
var user = await auth.RegisterAsync(request, 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>
|
/// <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>
|
/// <summary>Odešle e-mail s odkazem pro nastavení nového hesla. Odpověď je stejná, ať účet existuje, nebo ne.</summary>
|
||||||
[HttpPost("forgot-password")]
|
[HttpPost("forgot-password")]
|
||||||
[ProducesResponseType(StatusCodes.Status204NoContent)]
|
[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();
|
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>
|
/// <summary>Číselníky pro formuláře (budovy, kategorie závad a návrhů) a jejich správa.</summary>
|
||||||
[ApiController]
|
[ApiController]
|
||||||
[Authorize]
|
[Authorize]
|
||||||
[Route("api")]
|
[Route(ApiRoutes.V1)]
|
||||||
[Produces("application/json")]
|
[Produces("application/json")]
|
||||||
public sealed class CatalogsController(CatalogService catalogs) : ControllerBase
|
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) =>
|
public Task<IReadOnlyList<BuildingDto>> GetBuildings([FromQuery] bool includeInactive = false, CancellationToken ct = default) =>
|
||||||
catalogs.GetBuildingsAsync(includeInactive && User.IsInRole(Roles.Admin), ct);
|
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)]
|
[Authorize(Roles = Roles.Admin)]
|
||||||
[HttpPost("buildings")]
|
[HttpPost("buildings")]
|
||||||
[ProducesResponseType<BuildingDto>(StatusCodes.Status201Created)]
|
[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)
|
public async Task<ActionResult<BuildingDto>> CreateBuilding(SaveBuildingRequest request, CancellationToken ct)
|
||||||
{
|
{
|
||||||
var building = await catalogs.CreateBuildingAsync(request, 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)]
|
[Authorize(Roles = Roles.Admin)]
|
||||||
@@ -51,4 +45,76 @@ public sealed class CatalogsController(CatalogService catalogs) : ControllerBase
|
|||||||
await catalogs.DeactivateBuildingAsync(id, ct);
|
await catalogs.DeactivateBuildingAsync(id, ct);
|
||||||
return NoContent();
|
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();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -16,7 +16,7 @@ namespace Helpdesk.Api.Controllers;
|
|||||||
[ApiController]
|
[ApiController]
|
||||||
[Authorize]
|
[Authorize]
|
||||||
[ResponseCache(NoStore = true, Location = ResponseCacheLocation.None)]
|
[ResponseCache(NoStore = true, Location = ResponseCacheLocation.None)]
|
||||||
[Route("api/issues")]
|
[Route(ApiRoutes.V1 + "/issues")]
|
||||||
[ProducesResponseType<ProblemDetails>(StatusCodes.Status400BadRequest)]
|
[ProducesResponseType<ProblemDetails>(StatusCodes.Status400BadRequest)]
|
||||||
[ProducesResponseType<ProblemDetails>(StatusCodes.Status401Unauthorized)]
|
[ProducesResponseType<ProblemDetails>(StatusCodes.Status401Unauthorized)]
|
||||||
[ProducesResponseType<ProblemDetails>(StatusCodes.Status403Forbidden)]
|
[ProducesResponseType<ProblemDetails>(StatusCodes.Status403Forbidden)]
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
using Helpdesk.Application.Common;
|
using Helpdesk.Application.Common;
|
||||||
|
using Helpdesk.Api.Infrastructure;
|
||||||
using Helpdesk.Application.Notifications;
|
using Helpdesk.Application.Notifications;
|
||||||
using Microsoft.AspNetCore.Authorization;
|
using Microsoft.AspNetCore.Authorization;
|
||||||
using Microsoft.AspNetCore.Mvc;
|
using Microsoft.AspNetCore.Mvc;
|
||||||
@@ -7,7 +8,7 @@ namespace Helpdesk.Api.Controllers;
|
|||||||
|
|
||||||
[ApiController]
|
[ApiController]
|
||||||
[Authorize]
|
[Authorize]
|
||||||
[Route("api/notifications")]
|
[Route(ApiRoutes.V1 + "/notifications")]
|
||||||
[ResponseCache(NoStore = true, Location = ResponseCacheLocation.None)]
|
[ResponseCache(NoStore = true, Location = ResponseCacheLocation.None)]
|
||||||
[ProducesResponseType<ProblemDetails>(StatusCodes.Status401Unauthorized)]
|
[ProducesResponseType<ProblemDetails>(StatusCodes.Status401Unauthorized)]
|
||||||
public sealed class NotificationsController(NotificationService notifications) : ControllerBase
|
public sealed class NotificationsController(NotificationService notifications) : ControllerBase
|
||||||
|
|||||||
@@ -9,7 +9,7 @@ namespace Helpdesk.Api.Controllers;
|
|||||||
[ApiController]
|
[ApiController]
|
||||||
[Authorize]
|
[Authorize]
|
||||||
[ResponseCache(NoStore = true, Location = ResponseCacheLocation.None)]
|
[ResponseCache(NoStore = true, Location = ResponseCacheLocation.None)]
|
||||||
[Route("api/proposals")]
|
[Route(ApiRoutes.V1 + "/proposals")]
|
||||||
[ProducesResponseType<ProblemDetails>(StatusCodes.Status400BadRequest)]
|
[ProducesResponseType<ProblemDetails>(StatusCodes.Status400BadRequest)]
|
||||||
[ProducesResponseType<ProblemDetails>(StatusCodes.Status401Unauthorized)]
|
[ProducesResponseType<ProblemDetails>(StatusCodes.Status401Unauthorized)]
|
||||||
[ProducesResponseType<ProblemDetails>(StatusCodes.Status403Forbidden)]
|
[ProducesResponseType<ProblemDetails>(StatusCodes.Status403Forbidden)]
|
||||||
@@ -17,9 +17,15 @@ namespace Helpdesk.Api.Controllers;
|
|||||||
[ProducesResponseType<ProblemDetails>(StatusCodes.Status409Conflict)]
|
[ProducesResponseType<ProblemDetails>(StatusCodes.Status409Conflict)]
|
||||||
public sealed class ProposalsController(ProposalService proposals) : ControllerBase
|
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]
|
[HttpGet]
|
||||||
public Task<PagedResult<ProposalSummary>> List([FromQuery] ProposalQuery query, CancellationToken ct) =>
|
public Task<PagedResult<ProposalSummary>> List([FromQuery] ProposalQuery query,
|
||||||
proposals.ListAsync(query, ct);
|
[FromQuery] DateTimeOffset? from, [FromQuery] DateTimeOffset? to, CancellationToken ct) =>
|
||||||
|
proposals.ListAsync(query, from, to, ct);
|
||||||
|
|
||||||
[HttpGet("{id:int}")]
|
[HttpGet("{id:int}")]
|
||||||
public Task<ProposalDetail> Get(int id, CancellationToken ct) => proposals.GetAsync(id, ct);
|
public Task<ProposalDetail> Get(int id, CancellationToken ct) => proposals.GetAsync(id, 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. Období v UTC zahrnuje začátek a vylučuje konec.</summary>
|
||||||
|
[ApiController]
|
||||||
|
[Authorize(Roles = Roles.Management)]
|
||||||
|
[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);
|
||||||
|
}
|
||||||
@@ -10,7 +10,7 @@ namespace Helpdesk.Api.Controllers;
|
|||||||
/// <summary>Profil přihlášeného uživatele.</summary>
|
/// <summary>Profil přihlášeného uživatele.</summary>
|
||||||
[ApiController]
|
[ApiController]
|
||||||
[Authorize]
|
[Authorize]
|
||||||
[Route("api/users")]
|
[Route(ApiRoutes.V1 + "/users")]
|
||||||
[Produces("application/json")]
|
[Produces("application/json")]
|
||||||
public sealed class UsersController(UserService users, ICurrentUser currentUser, IssueService issues) : ControllerBase
|
public sealed class UsersController(UserService users, ICurrentUser currentUser, IssueService issues) : ControllerBase
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -0,0 +1,6 @@
|
|||||||
|
namespace Helpdesk.Api.Infrastructure;
|
||||||
|
|
||||||
|
internal static class ApiRoutes
|
||||||
|
{
|
||||||
|
public const string V1 = "api/v1";
|
||||||
|
}
|
||||||
@@ -19,7 +19,7 @@ public static class SwaggerSetup
|
|||||||
{
|
{
|
||||||
Title = "Univerzitní helpdesk – API",
|
Title = "Univerzitní helpdesk – API",
|
||||||
Version = "v1",
|
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
|
options.AddSecurityDefinition(SchemeId, new OpenApiSecurityScheme
|
||||||
|
|||||||
@@ -1,14 +1,23 @@
|
|||||||
|
using System.Net;
|
||||||
using System.Threading.RateLimiting;
|
using System.Threading.RateLimiting;
|
||||||
using Helpdesk.Api.Infrastructure;
|
using Helpdesk.Api.Infrastructure;
|
||||||
using Helpdesk.Application;
|
using Helpdesk.Application;
|
||||||
using Helpdesk.Application.Abstractions;
|
using Helpdesk.Application.Abstractions;
|
||||||
|
using Helpdesk.Application.Auth;
|
||||||
using Helpdesk.Infrastructure;
|
using Helpdesk.Infrastructure;
|
||||||
|
using Microsoft.AspNetCore.HttpOverrides;
|
||||||
using Microsoft.IdentityModel.JsonWebTokens;
|
using Microsoft.IdentityModel.JsonWebTokens;
|
||||||
|
|
||||||
var builder = WebApplication.CreateBuilder(args);
|
var builder = WebApplication.CreateBuilder(args);
|
||||||
|
|
||||||
builder.Services.AddApplication(builder.Configuration);
|
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.AddHttpContextAccessor();
|
||||||
builder.Services.AddScoped<ICurrentUser, HttpCurrentUser>();
|
builder.Services.AddScoped<ICurrentUser, HttpCurrentUser>();
|
||||||
@@ -21,6 +30,21 @@ builder.Services.AddProblemDetails();
|
|||||||
builder.Services.AddExceptionHandler<AppExceptionHandler>();
|
builder.Services.AddExceptionHandler<AppExceptionHandler>();
|
||||||
builder.Services.AddHelpdeskSwagger();
|
builder.Services.AddHelpdeskSwagger();
|
||||||
|
|
||||||
|
var trustedProxy = builder.Configuration["ReverseProxy:TrustedIp"];
|
||||||
|
if (!string.IsNullOrWhiteSpace(trustedProxy))
|
||||||
|
{
|
||||||
|
if (!IPAddress.TryParse(trustedProxy, out var proxyAddress))
|
||||||
|
throw new InvalidOperationException("Nastavte platnou IP adresu důvěryhodné reverse proxy.");
|
||||||
|
|
||||||
|
builder.Services.Configure<ForwardedHeadersOptions>(options =>
|
||||||
|
{
|
||||||
|
options.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto;
|
||||||
|
options.KnownIPNetworks.Clear();
|
||||||
|
options.KnownProxies.Clear();
|
||||||
|
options.KnownProxies.Add(proxyAddress);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
// Ochrana přihlášení a zápisů závad proti zahlcení (kap. 10).
|
// Ochrana přihlášení a zápisů závad proti zahlcení (kap. 10).
|
||||||
builder.Services.AddRateLimiter(options =>
|
builder.Services.AddRateLimiter(options =>
|
||||||
{
|
{
|
||||||
@@ -40,6 +64,9 @@ builder.Services.AddRateLimiter(options =>
|
|||||||
|
|
||||||
var app = builder.Build();
|
var app = builder.Build();
|
||||||
|
|
||||||
|
if (!string.IsNullOrWhiteSpace(trustedProxy))
|
||||||
|
app.UseForwardedHeaders();
|
||||||
|
|
||||||
app.UseExceptionHandler();
|
app.UseExceptionHandler();
|
||||||
app.UseStatusCodePages();
|
app.UseStatusCodePages();
|
||||||
|
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
using Helpdesk.Application.Statistics;
|
||||||
using Helpdesk.Domain.Auth;
|
using Helpdesk.Domain.Auth;
|
||||||
using Helpdesk.Domain.Catalogs;
|
using Helpdesk.Domain.Catalogs;
|
||||||
using Helpdesk.Domain.Issues;
|
using Helpdesk.Domain.Issues;
|
||||||
@@ -18,6 +19,7 @@ public interface IAppDbContext
|
|||||||
DbSet<ProposalCategory> ProposalCategories { get; }
|
DbSet<ProposalCategory> ProposalCategories { get; }
|
||||||
DbSet<Issue> Issues { get; }
|
DbSet<Issue> Issues { get; }
|
||||||
DbSet<IssueEvent> IssueEvents { get; }
|
DbSet<IssueEvent> IssueEvents { get; }
|
||||||
|
IQueryable<IssueTiming> IssueTimings { get; }
|
||||||
DbSet<Attachment> Attachments { get; }
|
DbSet<Attachment> Attachments { get; }
|
||||||
DbSet<Proposal> Proposals { get; }
|
DbSet<Proposal> Proposals { get; }
|
||||||
DbSet<ProposalEvent> ProposalEvents { get; }
|
DbSet<ProposalEvent> ProposalEvents { get; }
|
||||||
@@ -30,6 +32,7 @@ public interface IAppDbContext
|
|||||||
Task<int> SaveChangesAsync(CancellationToken cancellationToken = default);
|
Task<int> SaveChangesAsync(CancellationToken cancellationToken = default);
|
||||||
Task<IDbContextTransaction> BeginProposalWriteAsync(CancellationToken ct);
|
Task<IDbContextTransaction> BeginProposalWriteAsync(CancellationToken ct);
|
||||||
Task<Proposal?> LockProposalAsync(int id, CancellationToken ct);
|
Task<Proposal?> LockProposalAsync(int id, CancellationToken ct);
|
||||||
|
Task RegisterPushDeviceAsync(int userId, string token, CancellationToken ct);
|
||||||
}
|
}
|
||||||
|
|
||||||
public interface IPasswordHasher
|
public interface IPasswordHasher
|
||||||
|
|||||||
@@ -32,12 +32,17 @@ public sealed class AuthService(
|
|||||||
?? throw new BadRequestException("Registrace je možná jen s univerzitním e-mailem.");
|
?? throw new BadRequestException("Registrace je možná jen s univerzitním e-mailem.");
|
||||||
|
|
||||||
var normalized = User.NormalizeEmail(request.Email);
|
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.");
|
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 SendEmailTokenAsync(user, TokenType.EmailConfirm, ct);
|
||||||
return UserDto.From(user);
|
return UserDto.From(user);
|
||||||
@@ -123,8 +128,17 @@ public sealed class AuthService(
|
|||||||
{
|
{
|
||||||
var normalized = User.NormalizeEmail(request.Email ?? "");
|
var normalized = User.NormalizeEmail(request.Email ?? "");
|
||||||
var user = await db.Users.SingleOrDefaultAsync(u => u.EmailNormalized == normalized && u.IsActive, ct);
|
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);
|
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)
|
public async Task ResetPasswordAsync(ResetPasswordRequest request, CancellationToken ct)
|
||||||
|
|||||||
@@ -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 SaveBuildingRequest(string Code, string Name, string? Address);
|
||||||
|
|
||||||
|
public sealed record SaveCategoryRequest(string Name, string? Description);
|
||||||
|
|
||||||
public sealed class SaveBuildingRequestValidator : AbstractValidator<SaveBuildingRequest>
|
public sealed class SaveBuildingRequestValidator : AbstractValidator<SaveBuildingRequest>
|
||||||
{
|
{
|
||||||
public SaveBuildingRequestValidator()
|
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>
|
/// <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) =>
|
public async Task<IReadOnlyList<BuildingDto>> GetBuildingsAsync(bool includeInactive, CancellationToken ct) =>
|
||||||
await db.Buildings.AsNoTracking()
|
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))
|
.Select(b => new BuildingDto(b.Id, b.Code, b.Name, b.Address, b.IsActive))
|
||||||
.ToListAsync(ct);
|
.ToListAsync(ct);
|
||||||
|
|
||||||
public async Task<IReadOnlyList<CategoryDto>> GetIssueCategoriesAsync(CancellationToken ct) =>
|
public async Task<IReadOnlyList<CategoryDto>> GetIssueCategoriesAsync(bool includeInactive, CancellationToken ct) =>
|
||||||
await db.IssueCategories.AsNoTracking()
|
await db.IssueCategories.AsNoTracking()
|
||||||
.Where(c => c.IsActive)
|
.Where(c => includeInactive || c.IsActive)
|
||||||
.OrderBy(c => c.Id)
|
.OrderBy(c => c.Id)
|
||||||
.Select(c => new CategoryDto(c.Id, c.Name, c.Description, c.IsActive))
|
.Select(c => new CategoryDto(c.Id, c.Name, c.Description, c.IsActive))
|
||||||
.ToListAsync(ct);
|
.ToListAsync(ct);
|
||||||
|
|
||||||
public async Task<IReadOnlyList<CategoryDto>> GetProposalCategoriesAsync(CancellationToken ct) =>
|
public async Task<IReadOnlyList<CategoryDto>> GetProposalCategoriesAsync(bool includeInactive, CancellationToken ct) =>
|
||||||
await db.ProposalCategories.AsNoTracking()
|
await db.ProposalCategories.AsNoTracking()
|
||||||
.Where(c => c.IsActive)
|
.Where(c => includeInactive || c.IsActive)
|
||||||
.OrderBy(c => c.Id)
|
.OrderBy(c => c.Id)
|
||||||
.Select(c => new CategoryDto(c.Id, c.Name, c.Description, c.IsActive))
|
.Select(c => new CategoryDto(c.Id, c.Name, c.Description, c.IsActive))
|
||||||
.ToListAsync(ct);
|
.ToListAsync(ct);
|
||||||
@@ -75,10 +87,68 @@ public sealed class CatalogService(IAppDbContext db, IValidator<SaveBuildingRequ
|
|||||||
await db.SaveChangesAsync(ct);
|
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) =>
|
private async Task<Building> GetBuildingAsync(int id, CancellationToken ct) =>
|
||||||
await db.Buildings.SingleOrDefaultAsync(b => b.Id == id, ct)
|
await db.Buildings.SingleOrDefaultAsync(b => b.Id == id, ct)
|
||||||
?? throw new NotFoundException($"Budova {id} neexistuje.");
|
?? 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)
|
private async Task EnsureUniqueCodeAsync(string code, int? exceptId, CancellationToken ct)
|
||||||
{
|
{
|
||||||
var trimmed = code.Trim();
|
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 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 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);
|
public sealed record PagedResult<T>(IReadOnlyList<T> Items, int TotalCount, int Page, int PageSize);
|
||||||
@@ -4,6 +4,7 @@ using Helpdesk.Application.Catalogs;
|
|||||||
using Helpdesk.Application.Issues;
|
using Helpdesk.Application.Issues;
|
||||||
using Helpdesk.Application.Notifications;
|
using Helpdesk.Application.Notifications;
|
||||||
using Helpdesk.Application.Proposals;
|
using Helpdesk.Application.Proposals;
|
||||||
|
using Helpdesk.Application.Statistics;
|
||||||
using Helpdesk.Application.Users;
|
using Helpdesk.Application.Users;
|
||||||
using Microsoft.Extensions.Configuration;
|
using Microsoft.Extensions.Configuration;
|
||||||
using Microsoft.Extensions.DependencyInjection;
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
@@ -23,8 +24,11 @@ public static class DependencyInjection
|
|||||||
services.AddScoped<CatalogService>();
|
services.AddScoped<CatalogService>();
|
||||||
services.AddScoped<IssueService>();
|
services.AddScoped<IssueService>();
|
||||||
services.AddScoped<NotificationService>();
|
services.AddScoped<NotificationService>();
|
||||||
|
services.AddScoped<NotificationDeliveryService>();
|
||||||
services.AddScoped<NotificationWriter>();
|
services.AddScoped<NotificationWriter>();
|
||||||
|
services.AddScoped<PushDeviceService>();
|
||||||
services.AddScoped<ProposalService>();
|
services.AddScoped<ProposalService>();
|
||||||
|
services.AddScoped<StatisticsService>();
|
||||||
return services;
|
return services;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -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,27 @@
|
|||||||
|
using Helpdesk.Application.Abstractions;
|
||||||
|
using Helpdesk.Application.Common;
|
||||||
|
using Microsoft.EntityFrameworkCore;
|
||||||
|
|
||||||
|
namespace Helpdesk.Application.Notifications;
|
||||||
|
|
||||||
|
public sealed class PushDeviceService(IAppDbContext db, ICurrentUser currentUser)
|
||||||
|
{
|
||||||
|
public Task RegisterAsync(string token, CancellationToken ct)
|
||||||
|
{
|
||||||
|
ValidateToken(token);
|
||||||
|
return db.RegisterPushDeviceAsync(currentUser.Id, token, ct);
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task UnregisterAsync(string token, CancellationToken ct)
|
||||||
|
{
|
||||||
|
ValidateToken(token);
|
||||||
|
var userId = currentUser.Id;
|
||||||
|
await db.PushDevices.Where(d => d.UserId == userId && d.FcmToken == token).ExecuteDeleteAsync(ct);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void ValidateToken(string? token)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrEmpty(token) || token.Length > 512 || token.Any(c => char.IsWhiteSpace(c) || char.IsControl(c)))
|
||||||
|
throw new BadRequestException("Neplatný registrační token zařízení.");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -7,7 +7,8 @@ namespace Helpdesk.Application.Proposals;
|
|||||||
|
|
||||||
public sealed partial class ProposalService
|
public sealed partial class ProposalService
|
||||||
{
|
{
|
||||||
public async Task<PagedResult<ProposalSummary>> ListAsync(ProposalQuery filters, CancellationToken ct)
|
public async Task<PagedResult<ProposalSummary>> ListAsync(
|
||||||
|
ProposalQuery filters, DateTimeOffset? from, DateTimeOffset? to, CancellationToken ct)
|
||||||
{
|
{
|
||||||
await GetActorRoleAsync(ct);
|
await GetActorRoleAsync(ct);
|
||||||
var proposals = db.Proposals.AsNoTracking();
|
var proposals = db.Proposals.AsNoTracking();
|
||||||
@@ -20,6 +21,12 @@ public sealed partial class ProposalService
|
|||||||
proposals = proposals.Where(p => p.CategoryId == categoryId);
|
proposals = proposals.Where(p => p.CategoryId == categoryId);
|
||||||
if (filters.AuthorId is int authorId)
|
if (filters.AuthorId is int authorId)
|
||||||
proposals = proposals.Where(p => p.AuthorId == 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))
|
if (!string.IsNullOrWhiteSpace(filters.Q))
|
||||||
{
|
{
|
||||||
var term = filters.Q.Trim();
|
var term = filters.Q.Trim();
|
||||||
|
|||||||
@@ -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;
|
||||||
|
}
|
||||||
@@ -31,10 +31,20 @@ public sealed class IssueCategory
|
|||||||
{
|
{
|
||||||
private IssueCategory() { } // EF Core
|
private IssueCategory() { } // EF Core
|
||||||
|
|
||||||
|
public IssueCategory(string name, string? description) => Update(name, description);
|
||||||
|
|
||||||
public int Id { get; private set; }
|
public int Id { get; private set; }
|
||||||
public string Name { get; private set; } = null!;
|
public string Name { get; private set; } = null!;
|
||||||
public string? Description { get; private set; }
|
public string? Description { get; private set; }
|
||||||
public bool IsActive { get; private set; } = true;
|
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>
|
/// <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
|
private ProposalCategory() { } // EF Core
|
||||||
|
|
||||||
|
public ProposalCategory(string name, string? description) => Update(name, description);
|
||||||
|
|
||||||
public int Id { get; private set; }
|
public int Id { get; private set; }
|
||||||
public string Name { get; private set; } = null!;
|
public string Name { get; private set; } = null!;
|
||||||
public string? Description { get; private set; }
|
public string? Description { get; private set; }
|
||||||
public bool IsActive { get; private set; } = true;
|
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;
|
||||||
}
|
}
|
||||||
@@ -5,7 +5,7 @@ namespace Helpdesk.Domain.Notifications;
|
|||||||
|
|
||||||
public enum NotificationType { IssueCreated, IssueAssigned, IssueStatusChanged, IssueCommentAdded, IssueReopened, ProposalStatusChanged }
|
public enum NotificationType { IssueCreated, IssueAssigned, IssueStatusChanged, IssueCommentAdded, IssueReopened, ProposalStatusChanged }
|
||||||
public enum DeliveryChannel { Email, Push }
|
public enum DeliveryChannel { Email, Push }
|
||||||
public enum DeliveryStatus { Pending, Skipped }
|
public enum DeliveryStatus { Pending, Sent, Failed, Skipped }
|
||||||
|
|
||||||
public sealed class Notification : IHasCreatedAt
|
public sealed class Notification : IHasCreatedAt
|
||||||
{
|
{
|
||||||
@@ -46,6 +46,9 @@ public sealed class Notification : IHasCreatedAt
|
|||||||
public sealed class NotificationDelivery(
|
public sealed class NotificationDelivery(
|
||||||
Notification notification, DeliveryChannel channel, bool enabled, DateTime now)
|
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) { }
|
private NotificationDelivery() : this(null!, default, false, default) { }
|
||||||
|
|
||||||
public int Id { get; private set; }
|
public int Id { get; private set; }
|
||||||
@@ -53,11 +56,45 @@ public sealed class NotificationDelivery(
|
|||||||
public Notification Notification { get; private set; } = notification;
|
public Notification Notification { get; private set; } = notification;
|
||||||
public DeliveryChannel Channel { get; private set; } = channel;
|
public DeliveryChannel Channel { get; private set; } = channel;
|
||||||
public DeliveryStatus Status { get; private set; } = enabled ? DeliveryStatus.Pending : DeliveryStatus.Skipped;
|
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 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 sealed class PushDevice
|
||||||
{
|
{
|
||||||
public int Id { get; private set; }
|
public int Id { get; private set; }
|
||||||
public int UserId { get; private set; }
|
public int UserId { get; private set; }
|
||||||
|
public string FcmToken { get; private set; } = null!;
|
||||||
}
|
}
|
||||||
@@ -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);
|
||||||
|
}
|
||||||
@@ -3,17 +3,21 @@ using Helpdesk.Application.Issues;
|
|||||||
using Helpdesk.Infrastructure.Background;
|
using Helpdesk.Infrastructure.Background;
|
||||||
using Helpdesk.Infrastructure.Email;
|
using Helpdesk.Infrastructure.Email;
|
||||||
using Helpdesk.Infrastructure.Files;
|
using Helpdesk.Infrastructure.Files;
|
||||||
|
using Helpdesk.Infrastructure.Notifications;
|
||||||
using Helpdesk.Infrastructure.Persistence;
|
using Helpdesk.Infrastructure.Persistence;
|
||||||
using Helpdesk.Infrastructure.Security;
|
using Helpdesk.Infrastructure.Security;
|
||||||
using Microsoft.EntityFrameworkCore;
|
using Microsoft.EntityFrameworkCore;
|
||||||
using Microsoft.Extensions.Configuration;
|
using Microsoft.Extensions.Configuration;
|
||||||
using Microsoft.Extensions.DependencyInjection;
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
|
using Microsoft.Extensions.Hosting;
|
||||||
|
using MimeKit;
|
||||||
|
|
||||||
namespace Helpdesk.Infrastructure;
|
namespace Helpdesk.Infrastructure;
|
||||||
|
|
||||||
public static class DependencyInjection
|
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")
|
var connectionString = configuration.GetConnectionString("Helpdesk")
|
||||||
?? throw new InvalidOperationException("Chybí připojovací řetězec ConnectionStrings:Helpdesk.");
|
?? throw new InvalidOperationException("Chybí připojovací řetězec ConnectionStrings:Helpdesk.");
|
||||||
@@ -33,12 +37,37 @@ public static class DependencyInjection
|
|||||||
services.AddSingleton<IPasswordHasher, BCryptPasswordHasher>();
|
services.AddSingleton<IPasswordHasher, BCryptPasswordHasher>();
|
||||||
services.AddSingleton<ITokenService, JwtTokenService>();
|
services.AddSingleton<ITokenService, JwtTokenService>();
|
||||||
services.AddSingleton<IRevokedTokenStore, RevokedTokenStore>();
|
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.AddSingleton<IAttachmentStore, FileAttachmentStore>();
|
||||||
|
|
||||||
services.AddHostedService<RevokedTokenStoreLoader>();
|
services.AddHostedService<RevokedTokenStoreLoader>();
|
||||||
services.AddHostedService<AdminSeeder>();
|
services.AddHostedService<AdminSeeder>();
|
||||||
services.AddHostedService<AuthTokenCleanupService>();
|
services.AddHostedService<AuthTokenCleanupService>();
|
||||||
|
services.AddHostedService<NotificationDispatcher>();
|
||||||
return services;
|
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>();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -1,27 +1,19 @@
|
|||||||
using Helpdesk.Application.Abstractions;
|
using Helpdesk.Application.Abstractions;
|
||||||
using Microsoft.Extensions.Hosting;
|
|
||||||
using Microsoft.Extensions.Logging;
|
using Microsoft.Extensions.Logging;
|
||||||
|
|
||||||
namespace Helpdesk.Infrastructure.Email;
|
namespace Helpdesk.Infrastructure.Email;
|
||||||
|
|
||||||
/// <summary>
|
/// <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ývojová náhrada odesílání e-mailů, pokud schránka SMTP není nakonfigurována.
|
||||||
/// v <c>docker compose logs api</c>). Odesílání přes SMTP (MailKit + Mailpit) přijde s notifikacemi.
|
|
||||||
/// </summary>
|
/// </summary>
|
||||||
internal sealed partial class LoggingEmailSender(ILogger<LoggingEmailSender> logger, IHostEnvironment environment) : IEmailSender
|
internal sealed partial class LoggingEmailSender(ILogger<LoggingEmailSender> logger) : IEmailSender
|
||||||
{
|
{
|
||||||
public Task SendAsync(string to, string subject, string body, CancellationToken cancellationToken = default)
|
public Task SendAsync(string to, string subject, string body, CancellationToken cancellationToken = default)
|
||||||
{
|
{
|
||||||
if (environment.IsDevelopment())
|
LogEmail(to, subject, body);
|
||||||
LogEmail(to, subject, body);
|
|
||||||
else
|
|
||||||
LogMissingTransport();
|
|
||||||
return Task.CompletedTask;
|
return Task.CompletedTask;
|
||||||
}
|
}
|
||||||
|
|
||||||
[LoggerMessage(Level = LogLevel.Information, Message = "E-mail pro {To} – {Subject}:\n{Body}")]
|
[LoggerMessage(Level = LogLevel.Information, Message = "E-mail pro {To} – {Subject}:\n{Body}")]
|
||||||
private partial void LogEmail(string to, string subject, string body);
|
private partial void LogEmail(string to, string subject, string body);
|
||||||
|
|
||||||
[LoggerMessage(Level = LogLevel.Warning, Message = "E-mail nebyl odeslán. Pro toto prostředí není nakonfigurován poštovní transport.")]
|
|
||||||
private partial void LogMissingTransport();
|
|
||||||
}
|
}
|
||||||
@@ -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);
|
||||||
|
}
|
||||||
@@ -10,6 +10,8 @@
|
|||||||
<PackageReference Include="MySqlConnector" />
|
<PackageReference Include="MySqlConnector" />
|
||||||
<PackageReference Include="EFCore.NamingConventions" />
|
<PackageReference Include="EFCore.NamingConventions" />
|
||||||
<PackageReference Include="BCrypt.Net-Next" />
|
<PackageReference Include="BCrypt.Net-Next" />
|
||||||
|
<PackageReference Include="MailKit" />
|
||||||
|
<PackageReference Include="FirebaseAdmin" />
|
||||||
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" />
|
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" />
|
||||||
<PackageReference Include="Microsoft.Extensions.Caching.Memory" />
|
<PackageReference Include="Microsoft.Extensions.Caching.Memory" />
|
||||||
<PackageReference Include="Microsoft.Extensions.Hosting.Abstractions" />
|
<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();
|
||||||
|
}
|
||||||
@@ -1,5 +1,7 @@
|
|||||||
using System.Data;
|
using System.Data;
|
||||||
using Helpdesk.Application.Abstractions;
|
using Helpdesk.Application.Abstractions;
|
||||||
|
using Helpdesk.Application.Common;
|
||||||
|
using Helpdesk.Application.Statistics;
|
||||||
using Helpdesk.Domain.Auth;
|
using Helpdesk.Domain.Auth;
|
||||||
using Helpdesk.Domain.Catalogs;
|
using Helpdesk.Domain.Catalogs;
|
||||||
using Helpdesk.Domain.Issues;
|
using Helpdesk.Domain.Issues;
|
||||||
@@ -10,6 +12,7 @@ using Helpdesk.Infrastructure.Security;
|
|||||||
using Microsoft.EntityFrameworkCore;
|
using Microsoft.EntityFrameworkCore;
|
||||||
using Microsoft.EntityFrameworkCore.Storage;
|
using Microsoft.EntityFrameworkCore.Storage;
|
||||||
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
|
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
|
||||||
|
using MySqlConnector;
|
||||||
|
|
||||||
namespace Helpdesk.Infrastructure.Persistence;
|
namespace Helpdesk.Infrastructure.Persistence;
|
||||||
|
|
||||||
@@ -27,6 +30,7 @@ public sealed class HelpdeskDbContext(DbContextOptions<HelpdeskDbContext> option
|
|||||||
public DbSet<ProposalCategory> ProposalCategories => Set<ProposalCategory>();
|
public DbSet<ProposalCategory> ProposalCategories => Set<ProposalCategory>();
|
||||||
public DbSet<Issue> Issues => Set<Issue>();
|
public DbSet<Issue> Issues => Set<Issue>();
|
||||||
public DbSet<IssueEvent> IssueEvents => Set<IssueEvent>();
|
public DbSet<IssueEvent> IssueEvents => Set<IssueEvent>();
|
||||||
|
public IQueryable<IssueTiming> IssueTimings => Set<IssueTiming>();
|
||||||
public DbSet<Attachment> Attachments => Set<Attachment>();
|
public DbSet<Attachment> Attachments => Set<Attachment>();
|
||||||
public DbSet<Proposal> Proposals => Set<Proposal>();
|
public DbSet<Proposal> Proposals => Set<Proposal>();
|
||||||
public DbSet<ProposalEvent> ProposalEvents => Set<ProposalEvent>();
|
public DbSet<ProposalEvent> ProposalEvents => Set<ProposalEvent>();
|
||||||
@@ -36,6 +40,20 @@ public sealed class HelpdeskDbContext(DbContextOptions<HelpdeskDbContext> option
|
|||||||
public DbSet<NotificationDelivery> NotificationDeliveries => Set<NotificationDelivery>();
|
public DbSet<NotificationDelivery> NotificationDeliveries => Set<NotificationDelivery>();
|
||||||
public DbSet<PushDevice> PushDevices => Set<PushDevice>();
|
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.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
public Task<IDbContextTransaction> BeginProposalWriteAsync(CancellationToken ct) =>
|
public Task<IDbContextTransaction> BeginProposalWriteAsync(CancellationToken ct) =>
|
||||||
Database.BeginTransactionAsync(IsolationLevel.ReadCommitted, ct);
|
Database.BeginTransactionAsync(IsolationLevel.ReadCommitted, ct);
|
||||||
|
|
||||||
@@ -55,6 +73,12 @@ public sealed class HelpdeskDbContext(DbContextOptions<HelpdeskDbContext> option
|
|||||||
modelBuilder.ApplyConfiguration(new ProposalCategoryConfiguration());
|
modelBuilder.ApplyConfiguration(new ProposalCategoryConfiguration());
|
||||||
modelBuilder.ApplyConfiguration(new IssueConfiguration());
|
modelBuilder.ApplyConfiguration(new IssueConfiguration());
|
||||||
modelBuilder.ApplyConfiguration(new IssueEventConfiguration());
|
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 AttachmentConfiguration());
|
||||||
modelBuilder.ApplyConfiguration(new ProposalConfiguration());
|
modelBuilder.ApplyConfiguration(new ProposalConfiguration());
|
||||||
modelBuilder.ApplyConfiguration(new ProposalEventConfiguration());
|
modelBuilder.ApplyConfiguration(new ProposalEventConfiguration());
|
||||||
@@ -62,9 +86,18 @@ public sealed class HelpdeskDbContext(DbContextOptions<HelpdeskDbContext> option
|
|||||||
modelBuilder.Entity<ProposalScore>().HasNoKey().ToView("v_proposal_score");
|
modelBuilder.Entity<ProposalScore>().HasNoKey().ToView("v_proposal_score");
|
||||||
modelBuilder.ApplyConfiguration(new NotificationConfiguration());
|
modelBuilder.ApplyConfiguration(new NotificationConfiguration());
|
||||||
modelBuilder.ApplyConfiguration(new NotificationDeliveryConfiguration());
|
modelBuilder.ApplyConfiguration(new NotificationDeliveryConfiguration());
|
||||||
modelBuilder.Entity<PushDevice>().ToTable("push_device");
|
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)
|
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".
|
// Všechny časy jsou v DB v UTC; při čtení jim nastavíme Kind = Utc, aby se v JSON serializovaly se "Z".
|
||||||
|
|||||||
@@ -73,6 +73,7 @@ internal sealed class NotificationDeliveryConfiguration : IEntityTypeConfigurati
|
|||||||
b.ToTable("notification_delivery");
|
b.ToTable("notification_delivery");
|
||||||
b.Property(x => x.Channel).HasConversion<EnumCodeConverter<DeliveryChannel>>().HasMaxLength(10);
|
b.Property(x => x.Channel).HasConversion<EnumCodeConverter<DeliveryChannel>>().HasMaxLength(10);
|
||||||
b.Property(x => x.Status).HasConversion<EnumCodeConverter<DeliveryStatus>>().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);
|
b.HasOne(x => x.Notification).WithMany().HasForeignKey(x => x.NotificationId);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -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);
|
||||||
+26
-2
@@ -11,10 +11,34 @@ APP_DB_PASSWORD=change-me-app
|
|||||||
JWT_SIGNING_KEY=change-me-to-a-random-string-of-at-least-32-bytes
|
JWT_SIGNING_KEY=change-me-to-a-random-string-of-at-least-32-bytes
|
||||||
ENCRYPTION_KEY=AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=
|
ENCRYPTION_KEY=AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=
|
||||||
|
|
||||||
# Účet administrátora – vytvoří se při prvním startu API, pokud neexistuje.
|
# Volitelný účet administrátora vytvořený při prvním startu API.
|
||||||
ADMIN_EMAIL=admin@univerzita.cz
|
ADMIN_EMAIL=admin@domain.local
|
||||||
ADMIN_PASSWORD=change-me-admin
|
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
|
||||||
|
# Adresa reverse proxy tak, jak ji API vidí jako bezprostředního klienta.
|
||||||
|
TRUSTED_REVERSE_PROXY_IP=
|
||||||
|
|
||||||
|
# Veřejná HTTPS adresa webu pro odkazy v e-mailech a povolené univerzitní domény.
|
||||||
|
PUBLIC_BASE_URL= #https://helpdesk.domain.local
|
||||||
|
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
|
ASPNETCORE_ENVIRONMENT=Development
|
||||||
|
|
||||||
API_PORT=8080
|
API_PORT=8080
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
FROM mariadb:11.4
|
||||||
|
COPY --chmod=0644 01-accounts.sh /docker-entrypoint-initdb.d/01-accounts.sh
|
||||||
@@ -1,11 +1,11 @@
|
|||||||
# Vývojové spuštění backendu: docker compose -f deploy/docker-compose.yml --env-file deploy/.env up --build
|
# Vývojové spuštění backendu: docker compose -f deploy/docker-compose.yml --env-file deploy/.env up --build
|
||||||
# Topologie odpovídá kap. 15 návrhu; proxy (nginx + HTTPS), web a mailpit přibudou v dalších fázích.
|
# Reverse proxy ukončuje HTTPS a připojuje se k API přes HTTP.
|
||||||
|
|
||||||
name: helpdesk
|
name: helpdesk
|
||||||
|
|
||||||
services:
|
services:
|
||||||
db:
|
db:
|
||||||
image: mariadb:11.4
|
build: ./db-init
|
||||||
environment:
|
environment:
|
||||||
MARIADB_ROOT_PASSWORD: ${DB_ROOT_PASSWORD:?}
|
MARIADB_ROOT_PASSWORD: ${DB_ROOT_PASSWORD:?}
|
||||||
MARIADB_DATABASE: helpdesk
|
MARIADB_DATABASE: helpdesk
|
||||||
@@ -14,7 +14,6 @@ services:
|
|||||||
APP_DB_PASSWORD: ${APP_DB_PASSWORD:?}
|
APP_DB_PASSWORD: ${APP_DB_PASSWORD:?}
|
||||||
volumes:
|
volumes:
|
||||||
- db-data:/var/lib/mysql
|
- db-data:/var/lib/mysql
|
||||||
- ./db-init:/docker-entrypoint-initdb.d:ro
|
|
||||||
healthcheck:
|
healthcheck:
|
||||||
test: ["CMD", "healthcheck.sh", "--connect", "--innodb_initialized"]
|
test: ["CMD", "healthcheck.sh", "--connect", "--innodb_initialized"]
|
||||||
interval: 5s
|
interval: 5s
|
||||||
@@ -44,6 +43,15 @@ services:
|
|||||||
ConnectionStrings__Helpdesk: "Server=db;Database=helpdesk;User=helpdesk_app;Password=${APP_DB_PASSWORD}"
|
ConnectionStrings__Helpdesk: "Server=db;Database=helpdesk;User=helpdesk_app;Password=${APP_DB_PASSWORD}"
|
||||||
Jwt__SigningKey: ${JWT_SIGNING_KEY:?}
|
Jwt__SigningKey: ${JWT_SIGNING_KEY:?}
|
||||||
Encryption__Key: ${ENCRYPTION_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:-}
|
||||||
ADMIN_EMAIL: ${ADMIN_EMAIL:-}
|
ADMIN_EMAIL: ${ADMIN_EMAIL:-}
|
||||||
ADMIN_PASSWORD: ${ADMIN_PASSWORD:-}
|
ADMIN_PASSWORD: ${ADMIN_PASSWORD:-}
|
||||||
volumes:
|
volumes:
|
||||||
@@ -51,9 +59,8 @@ services:
|
|||||||
depends_on:
|
depends_on:
|
||||||
migrator:
|
migrator:
|
||||||
condition: service_completed_successfully
|
condition: service_completed_successfully
|
||||||
# Dočasně publikováno přímo; po přidání nginx proxy bude API dostupné jen přes ni.
|
|
||||||
ports:
|
ports:
|
||||||
- "8080:8080"
|
- "${PROXY_UPSTREAM_BIND_ADDRESS:-127.0.0.1}:${API_HTTP_PORT:-8080}:8080"
|
||||||
networks: [frontend, backend]
|
networks: [frontend, backend]
|
||||||
|
|
||||||
networks:
|
networks:
|
||||||
|
|||||||
+33
-29
@@ -320,8 +320,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 |
|
| 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 pro / proti | `value` = `+1` / `-1` (CHECK omezení) |
|
||||||
| Hlas lze změnit | `PUT /api/proposals/{id}/vote` s novou hodnotou → UPDATE (upsert) |
|
| Hlas lze změnit | `PUT /api/v1/proposals/{id}/vote` s novou hodnotou → UPDATE (upsert) |
|
||||||
| Hlas lze zrušit | `DELETE /api/proposals/{id}/vote` → DELETE |
|
| Hlas lze zrušit | `DELETE /api/v1/proposals/{id}/vote` → DELETE |
|
||||||
| Autor nehlasuje pro vlastní návrh | Kontrola v aplikační vrstvě → 403 |
|
| 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) |
|
| 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) |
|
| Pořadí podle podpory | Pohled `v_proposal_score` (počet pro, proti, skóre = součet) |
|
||||||
@@ -354,7 +354,7 @@ sequenceDiagram
|
|||||||
participant SMTP as SMTP server
|
participant SMTP as SMTP server
|
||||||
participant FCM as Firebase Cloud Messaging
|
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->>DB: BEGIN; UPDATE issue; INSERT issue_event;<br/>INSERT notification (×N);<br/>INSERT notification_delivery (EMAIL, PUSH); COMMIT
|
||||||
API-->>C: 200 OK
|
API-->>C: 200 OK
|
||||||
loop každých pár sekund
|
loop každých pár sekund
|
||||||
@@ -371,9 +371,9 @@ sequenceDiagram
|
|||||||
end
|
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.
|
- **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.
|
- 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í
|
### 8.3 Řešení nedoručení
|
||||||
@@ -388,7 +388,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) | — |
|
| 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 | — |
|
| 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ě.
|
- `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).
|
- Ú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).
|
||||||
|
|
||||||
@@ -419,7 +419,7 @@ flowchart TB
|
|||||||
BROWSER -- HTTPS --> PROXY
|
BROWSER -- HTTPS --> PROXY
|
||||||
MOB -- "HTTPS, JWT" --> PROXY
|
MOB -- "HTTPS, JWT" --> PROXY
|
||||||
PROXY --> WEB
|
PROXY --> WEB
|
||||||
PROXY -- /api, /swagger --> API
|
PROXY -- "/api/*, /swagger" --> API
|
||||||
WEB -- "REST, JWT" --> API
|
WEB -- "REST, JWT" --> API
|
||||||
API --> DB
|
API --> DB
|
||||||
API --> FILES
|
API --> FILES
|
||||||
@@ -508,7 +508,7 @@ Větvení: `main` (stabilní), `develop`, feature větve `feature/<nazev>`, merg
|
|||||||
| Oblast | Řešení |
|
| 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ů. |
|
| 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). |
|
| 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. |
|
| Š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ě. |
|
| 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ě. |
|
||||||
@@ -538,9 +538,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 |
|
| 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 |
|
| 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` |
|
| 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` | `/auth/confirm-email` – jednorázový |
|
| 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` | `/auth/reset-password` – 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):
|
Příklad access tokenu (dekódovaná hlavička a tělo):
|
||||||
|
|
||||||
@@ -570,7 +570,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íč) |
|
| `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ý | — |
|
| `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).
|
- 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í.
|
- Claim `nbf` (4.1.5) se nepoužívá, protože tokeny platí hned od vydání.
|
||||||
|
|
||||||
@@ -578,10 +578,10 @@ Příklad access tokenu (dekódovaná hlavička a tělo):
|
|||||||
|
|
||||||
| Akce | Změna v `auth_token` | `revoke_reason` |
|
| Akce | Změna v `auth_token` | `revoke_reason` |
|
||||||
|---|---|---|
|
|---|---|---|
|
||||||
| Přihlášení (`/auth/login`) | INSERT access + refresh tokenu | — |
|
| Přihlášení (`/api/v1/auth/login`) | INSERT access + refresh tokenu | — |
|
||||||
| Obnova tokenů (`/auth/refresh`) | použitý refresh token zneplatněn, INSERT nového páru | `USED` |
|
| Obnova tokenů (`/api/v1/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áš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í (`/auth/logout-all`) | zneplatněny všechny platné tokeny uživatele | `LOGOUT_ALL` |
|
| 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 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` |
|
| 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` |
|
| Deaktivace účtu administrátorem | zneplatněny všechny platné tokeny uživatele | `ACCOUNT_DEACTIVATED` |
|
||||||
@@ -596,7 +596,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“).
|
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.
|
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.
|
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ě.
|
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`).
|
5. Token s tímto `jti` není v `auth_token` zneplatněný (`revoked_at IS NULL`).
|
||||||
@@ -627,13 +627,13 @@ sequenceDiagram
|
|||||||
participant S as Server
|
participant S as Server
|
||||||
|
|
||||||
Note over U,A: Oba mají refresh token R1 (jti = r1)
|
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->>S: UPDATE r1 → USED (1 řádek)
|
||||||
S-->>A: nový pár tokenů (a2, r2)
|
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->>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
|
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ý
|
S-->>A: 401 – a2 je zneplatněný
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -643,7 +643,11 @@ sequenceDiagram
|
|||||||
|
|
||||||
## 11. Návrh REST API
|
## 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 `/swagger` a OpenAPI dokument pro v1 na `/swagger/v1/swagger.json`. Provozní kontrola API je na `GET /health`.
|
||||||
|
|
||||||
### Autentizace a účet
|
### Autentizace a účet
|
||||||
| Metoda | Endpoint | Role | Popis |
|
| Metoda | Endpoint | Role | Popis |
|
||||||
@@ -1123,9 +1127,9 @@ flowchart LR
|
|||||||
end
|
end
|
||||||
|
|
||||||
BROWSER -- "HTTPS 443" --> PROXY
|
BROWSER -- "HTTPS 443" --> PROXY
|
||||||
MOBILE -- "HTTPS 443 /api" --> PROXY
|
MOBILE -- "HTTPS 443 /api/v1/*" --> PROXY
|
||||||
PROXY -- "HTTP 8080 /" --> WEB
|
PROXY -- "HTTP 8080 /" --> WEB
|
||||||
PROXY -- "HTTP 8080 /api, /swagger" --> API
|
PROXY -- "HTTP 8080 /api/*, /swagger" --> API
|
||||||
WEB -- "HTTP 8080 REST + JWT" --> API
|
WEB -- "HTTP 8080 REST + JWT" --> API
|
||||||
API -- "TCP 3306" --> DB
|
API -- "TCP 3306" --> DB
|
||||||
MIG -- "TCP 3306" --> DB
|
MIG -- "TCP 3306" --> DB
|
||||||
@@ -1145,7 +1149,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.
|
- `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.
|
- **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`.
|
- **`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
|
### 15.2 Síťová komunikace
|
||||||
|
|
||||||
@@ -1155,7 +1159,7 @@ flowchart LR
|
|||||||
| mobil | proxy | HTTPS 443 | internet | REST API |
|
| mobil | proxy | HTTPS 443 | internet | REST API |
|
||||||
| proxy | web | HTTP 8080 | frontend | stránky (`/`) |
|
| proxy | web | HTTP 8080 | frontend | stránky (`/`) |
|
||||||
| proxy | api | HTTP 8080 | frontend | `/api/*`, `/swagger` |
|
| 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 |
|
| 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` |
|
| api | db | TCP 3306 | backend | data – DB účet `helpdesk_app` |
|
||||||
| migrator | db | TCP 3306 | backend | migrace – DB účet `helpdesk_migrator` |
|
| migrator | db | TCP 3306 | backend | migrace – DB účet `helpdesk_migrator` |
|
||||||
| api | SMTP server | SMTP 587 (STARTTLS) | internet, odchozí | e-mailové notifikace |
|
| api | SMTP server | SMTP 587 (STARTTLS) | internet, odchozí | e-mailové notifikace |
|
||||||
@@ -1236,10 +1240,10 @@ Možná rozšíření (mimo rozsah zadání): automatické potvrzení vyřešen
|
|||||||
| Fáze | Týden | Náplň |
|
| 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) |
|
| **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 |
|
| | 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 |
|
| | 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 |
|
| | 6 | Webová aplikace: všechny obrazovky včetně statistik a administrace, napojení na API v1 |
|
||||||
| | 7 | Mobilní aplikace: přihlášení, hlášení s fotkou, detail a komentáře, návrhy, push notifikace |
|
| | 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 |
|
| **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í |
|
| | 9 | Uživatelská příručka, technická dokumentace, finální nasazení a předvedení |
|
||||||
+12
-6
@@ -33,15 +33,19 @@ Samotná změna AGP na 8.0.2 není vhodná: API 35 oficiálně vyžaduje minimá
|
|||||||
| Prostředí | Příklad |
|
| Prostředí | Příklad |
|
||||||
|---|---|
|
|---|---|
|
||||||
| Android emulátor, backend na stejném počítači | `http://10.0.2.2:8080/` |
|
| Android emulátor, backend na stejném počítači | `http://10.0.2.2:8080/` |
|
||||||
| Android emulátor při mapování portu `8081:8080` | `http://10.0.2.2:8081/` |
|
| Android emulátor při nastavení `API_HTTP_PORT=8081` | `http://10.0.2.2:8081/` |
|
||||||
| Telefon na stejné Wi-Fi jako počítač | `http://192.168.1.100:8080/` (skutečná LAN adresa počítače, dostupný port 8080) |
|
| Telefon na stejné Wi-Fi jako počítač | `http://192.168.1.100:8080/` (skutečná LAN adresa počítače, dostupný port 8080) |
|
||||||
| Nasazený server | `https://helpdesk.example.cz/` |
|
| Nasazený server | `https://helpdesk.example.cz/` |
|
||||||
|
|
||||||
Docker ve výchozím stavu zpřístupňuje API na portu `8080`. Je-li obsazený, změňte u služby `api` v `deploy/docker-compose.yml` mapování na `8081:8080` a spusťte backend znovu. Swagger pak otevřete na <http://localhost:8081/swagger>; v mobilní aplikaci změňte port adresy serveru na `8081` (také při připojení telefonu přes Wi-Fi). Aktuální Compose má port zadaný přímo; samotná proměnná `API_PORT` jej nemění.
|
Docker ve výchozím stavu zpřístupňuje API na `127.0.0.1:8080`. Je-li port obsazený, nastavte v `deploy/.env` hodnotu `API_HTTP_PORT=8081` a spusťte backend znovu podle hlavního README. Swagger pak otevřete na <http://localhost:8081/swagger>; v mobilní aplikaci změňte port adresy serveru na `8081`.
|
||||||
|
|
||||||
|
Pro skutečný telefon ve stejné Wi-Fi nastavte také `PROXY_UPSTREAM_BIND_ADDRESS=0.0.0.0` a v aplikaci použijte LAN adresu počítače s nastaveným portem. Výchozí vazba `127.0.0.1` zpřístupňuje API místnímu počítači a Android emulátoru přes `10.0.2.2`; pro nasazení s reverse proxy na stejném hostiteli ji ponechte. Telefon musí mít přístup k danému portu přes firewall počítače.
|
||||||
|
|
||||||
Přijímá se kořen serveru i URL končící `/api/`. Při změně serveru se místní relace smaže. HTTP je povoleno pouze v debug variantě, release vyžaduje HTTPS a standardně ověřený certifikát. Vypínání kontroly TLS není implementované.
|
Přijímá se kořen serveru i URL končící `/api/`. Při změně serveru se místní relace smaže. HTTP je povoleno pouze v debug variantě, release vyžaduje HTTPS a standardně ověřený certifikát. Vypínání kontroly TLS není implementované.
|
||||||
|
|
||||||
Výchozí backend umožňuje registraci domén `student.univerzita.cz` a `univerzita.cz`. Domény lze změnit na serveru. Po registraci ověřte e-mail; v prostředí `Development` současný backend zapisuje odkaz do logu místo skutečného odeslání. Mimo vývoj se obsah e-mailů neloguje a je nutné doplnit poštovní transport. V aplikaci lze vložit celý ověřovací/resetovací odkaz nebo samotný token. Automatické Android App Links zatím nejsou nastavené.
|
Výchozí backend umožňuje registraci domén `student.univerzita.cz` a `univerzita.cz`. Při spuštění přes Compose se nastavují na serveru proměnnými `STUDENT_EMAIL_DOMAIN` a `TEACHER_EMAIL_DOMAIN` v `deploy/.env`; povolení domény kontroluje server. Po registraci ověřte e-mail. Pokud jsou v prostředí `Development` současně prázdné `SMTP_MAILBOX` a `SMTP_PASSWORD`, najdete ověřovací odkaz v logu služby `api`. S nakonfigurovanou SMTP schránkou backend odesílá skutečné e-maily i ve vývojovém režimu; prostředí `Production` vyžaduje platnou SMTP konfiguraci. Výchozí transport používá `smtp.seznam.cz:465` s TLS.
|
||||||
|
|
||||||
|
Odkazy v e-mailech vycházejí ze serverové hodnoty `PUBLIC_BASE_URL`. V aplikaci lze vložit celý ověřovací/resetovací odkaz nebo samotný token; automatické Android App Links zatím nejsou nastavené. Pokud při registraci selže odeslání e-mailu a server vrátí chybu 503, účet už může být vytvořený. Opakovaná registrace se stejným e-mailem a heslem znovu odešle ověřovací zprávu pro dosud neověřený aktivní účet.
|
||||||
|
|
||||||
**Prohlédnout ukázku** je samostatný režim, výrazně označený na každé obrazovce. Obsahuje ukázková hlášení a návrhy a umožňuje vytváření, úpravy přijatých hlášení, komentáře, přílohy, hlasování a čtení oznámení. Data jsou pouze v paměti, zaniknou po ukončení ukázky nebo procesu. Ukázka se nikdy nezapne automaticky při chybě serveru. Hraje roli studenta; pracovní fronta správce je dostupná v připojeném režimu podle role z API.
|
**Prohlédnout ukázku** je samostatný režim, výrazně označený na každé obrazovce. Obsahuje ukázková hlášení a návrhy a umožňuje vytváření, úpravy přijatých hlášení, komentáře, přílohy, hlasování a čtení oznámení. Data jsou pouze v paměti, zaniknou po ukončení ukázky nebo procesu. Ukázka se nikdy nezapne automaticky při chybě serveru. Hraje roli studenta; pracovní fronta správce je dostupná v připojeném režimu podle role z API.
|
||||||
|
|
||||||
@@ -51,21 +55,23 @@ Výchozí backend umožňuje registraci domén `student.univerzita.cz` a `univer
|
|||||||
|---|---|---|
|
|---|---|---|
|
||||||
| Přihlášení, registrace, ověření e-mailu, obnova hesla | Hotovo | Implementován |
|
| Přihlášení, registrace, ověření e-mailu, obnova hesla | Hotovo | Implementován |
|
||||||
| Obnova relace, odhlášení / všechna zařízení | Hotovo | Implementován |
|
| Obnova relace, odhlášení / všechna zařízení | Hotovo | Implementován |
|
||||||
| Profil, telefon, e-mailové notifikace | Hotovo | Implementován |
|
| Profil, telefon, e-mailové notifikace | Hotovo | Implementován včetně SMTP a doručovací fronty |
|
||||||
| Budovy a kategorie formulářů | Hotovo | Implementován |
|
| Budovy a kategorie formulářů | Hotovo | Implementován včetně správy a deaktivace kategorií |
|
||||||
|
| Správa kategorií a statistiky vedení | Mimo rozsah mobilních obrazovek | Implementovány příslušné administrační a statistické endpointy |
|
||||||
| Nástěnka, seznam a detail vlastních závad, filtry, stránkování | Napojeno na skutečné API | Implementován |
|
| Nástěnka, seznam a detail vlastních závad, filtry, stránkování | Napojeno na skutečné API | Implementován |
|
||||||
| Nová závada, úprava přijaté závady, fotografie a soubory | Napojeno na skutečné API | Implementován |
|
| Nová závada, úprava přijaté závady, fotografie a soubory | Napojeno na skutečné API | Implementován |
|
||||||
| Komentáře, časová osa, stažení příloh | Napojeno na skutečné API | Implementován |
|
| Komentáře, časová osa, stažení příloh | Napojeno na skutečné API | Implementován |
|
||||||
| Pracovní fronta řešitele a serverem povolené změny stavu | Napojeno podle `allowedActions` a `rowVersion` | Implementován |
|
| Pracovní fronta řešitele a serverem povolené změny stavu | Napojeno podle `allowedActions` a `rowVersion` | Implementován |
|
||||||
| Seznam, detail, nový návrh, hlas pro/proti/zrušení | Napojeno včetně uzavřeného hlasování | Implementován |
|
| Seznam, detail, nový návrh, hlas pro/proti/zrušení | Napojeno včetně uzavřeného hlasování | Implementován |
|
||||||
| Seznam oznámení, počet nepřečtených, přečtení a otevření záznamu | Napojeno na skutečné API | Implementován |
|
| Seznam oznámení, počet nepřečtených, přečtení a otevření záznamu | Napojeno na skutečné API | Implementován |
|
||||||
| Push notifikace (Firebase Cloud Messaging) | Nezapojeno | Chybí `/devices` a doručování |
|
| Push notifikace (Firebase Cloud Messaging) | Nezapojeno | Registrace `/devices` a doručovací fronta implementovány; vyžaduje `FIREBASE_SERVICE_ACCOUNT_JSON` |
|
||||||
|
|
||||||
Funkce fungují proti backendu z větve `main`; ukázka zůstává samostatnou volbou. Chyba serveru aplikaci nepřepne na ukázková data. Chyba 404 označuje nenalezený záznam, 409 obnoví konfliktující detail. Administrační a analytické obrazovky, přiřazování závad a hodnocení návrhů patří podle návrhu webové části.
|
Funkce fungují proti backendu z větve `main`; ukázka zůstává samostatnou volbou. Chyba serveru aplikaci nepřepne na ukázková data. Chyba 404 označuje nenalezený záznam, 409 obnoví konfliktující detail. Administrační a analytické obrazovky, přiřazování závad a hodnocení návrhů patří podle návrhu webové části.
|
||||||
|
|
||||||
Přesné síťové kontrakty jsou oddělené v `data/WireDtos.kt` a vycházejí z `backend/src/Helpdesk.Application/Issues/IssueDtos.cs`, `Proposals/ProposalDtos.cs` a `Notifications/NotificationService.cs`. `data/Models.kt` obsahuje modely pro obrazovky, ne předpokládaný formát serverových odpovědí:
|
Přesné síťové kontrakty jsou oddělené v `data/WireDtos.kt` a vycházejí z `backend/src/Helpdesk.Application/Issues/IssueDtos.cs`, `Proposals/ProposalDtos.cs` a `Notifications/NotificationService.cs`. `data/Models.kt` obsahuje modely pro obrazovky, ne předpokládaný formát serverových odpovědí:
|
||||||
|
|
||||||
- JSON v camelCase; seznamy `{ items, totalCount, page, pageSize }`, stránka po 20 položkách.
|
- JSON v camelCase; seznamy `{ items, totalCount, page, pageSize }`, stránka po 20 položkách.
|
||||||
|
- Nové závady a návrhy nabízejí jen aktivní kategorie a budovy. Při úpravě starší závady lze ponechat původní deaktivovanou kategorii nebo budovu; formulář ji označí jako „již není v nabídce“ a zachová její ID i při obnovení číselníků. Obnovení číselníků nemaže rozepsaný název ani popis.
|
||||||
- Seznamy závad a návrhů vracejí souhrny bez popisu a názvů osob. Klient kvůli nim nestahuje každý detail; názvy budov/kategorií doplňuje ze sdílené cache číselníků. Jméno přihlášeného uživatele zná z profilu; další skutečná jména získá z autorů událostí v detailu, jinak zobrazí identifikátor uživatele.
|
- Seznamy závad a návrhů vracejí souhrny bez popisu a názvů osob. Klient kvůli nim nestahuje každý detail; názvy budov/kategorií doplňuje ze sdílené cache číselníků. Jméno přihlášeného uživatele zná z profilu; další skutečná jména získá z autorů událostí v detailu, jinak zobrazí identifikátor uživatele.
|
||||||
- Detail závady obsahuje `locationDetail`, `priority`, `assigneeId`, `rowVersion` (nové hlášení začíná na nule), `allowedActions` a přílohy `{ id, fileName, contentType, sizeBytes, createdAt }`. Události se čtou přes `GET /issues/{id}/events`: `{ id, eventType, fromStatus, toStatus, actorId, actorName, note, occurredAt }`.
|
- Detail závady obsahuje `locationDetail`, `priority`, `assigneeId`, `rowVersion` (nové hlášení začíná na nule), `allowedActions` a přílohy `{ id, fileName, contentType, sizeBytes, createdAt }`. Události se čtou přes `GET /issues/{id}/events`: `{ id, eventType, fromStatus, toStatus, actorId, actorName, note, occurredAt }`.
|
||||||
- `allowedActions` používá skutečné kódy `EDIT`, `START_WORK`, `SUBMIT_FOR_VERIFICATION`, `CONFIRM`, `REOPEN`, `REJECT`, `COMMENT`, `ADD_ATTACHMENTS`. Mobil zobrazuje pouze serverem povolené akce; `ASSIGN` je určený webovému rozhraní vedení.
|
- `allowedActions` používá skutečné kódy `EDIT`, `START_WORK`, `SUBMIT_FOR_VERIFICATION`, `CONFIRM`, `REOPEN`, `REJECT`, `COMMENT`, `ADD_ATTACHMENTS`. Mobil zobrazuje pouze serverem povolené akce; `ASSIGN` je určený webovému rozhraní vedení.
|
||||||
|
|||||||
@@ -0,0 +1,77 @@
|
|||||||
|
package cz.ntbug.mobile
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
|
import androidx.compose.ui.semantics.SemanticsProperties
|
||||||
|
import androidx.compose.ui.test.*
|
||||||
|
import androidx.compose.ui.test.junit4.createAndroidComposeRule
|
||||||
|
import androidx.compose.ui.test.junit4.createComposeRule
|
||||||
|
import androidx.lifecycle.viewmodel.compose.viewModel
|
||||||
|
import androidx.test.ext.junit.runners.AndroidJUnit4
|
||||||
|
import androidx.test.platform.app.InstrumentationRegistry
|
||||||
|
import cz.ntbug.mobile.ui.AccountScreen
|
||||||
|
import cz.ntbug.mobile.ui.AppState
|
||||||
|
import cz.ntbug.mobile.ui.AppViewModel
|
||||||
|
import cz.ntbug.mobile.ui.AuthOutcome
|
||||||
|
import cz.ntbug.mobile.ui.NTBugTheme
|
||||||
|
import org.junit.Assert.assertEquals
|
||||||
|
import org.junit.Rule
|
||||||
|
import org.junit.Test
|
||||||
|
import org.junit.rules.ExternalResource
|
||||||
|
import org.junit.rules.RuleChain
|
||||||
|
import org.junit.runner.RunWith
|
||||||
|
|
||||||
|
/** Auth navigation stays usable without SMTP and never submits credentials automatically. */
|
||||||
|
@RunWith(AndroidJUnit4::class)
|
||||||
|
class AuthFlowUiTest {
|
||||||
|
private val compose = createAndroidComposeRule<MainActivity>()
|
||||||
|
private val cleanSession = object : ExternalResource() {
|
||||||
|
override fun before() {
|
||||||
|
val context = InstrumentationRegistry.getInstrumentation().targetContext
|
||||||
|
check(context.getSharedPreferences("ntbug_session", Context.MODE_PRIVATE).edit().clear().commit())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@get:Rule val rules: RuleChain = RuleChain.outerRule(cleanSession).around(compose)
|
||||||
|
|
||||||
|
@Test fun verificationScreenOffersExplicitRegistrationRetry() {
|
||||||
|
awaitLogin()
|
||||||
|
compose.onNodeWithText("Ověřit e-mail").performScrollTo().performClick()
|
||||||
|
compose.onNodeWithText("Poslat ověřovací e-mail znovu").performScrollTo().performClick()
|
||||||
|
compose.onNodeWithText("Vytvořit účet").performScrollTo().assertIsDisplayed()
|
||||||
|
compose.onNodeWithText("Pokud už máte neověřený účet", substring = true).assertIsDisplayed()
|
||||||
|
compose.onNodeWithText("Jméno").assertExists()
|
||||||
|
compose.onNodeWithText("Heslo znovu").assertExists()
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test fun leavingRegistrationClearsPasswordBeforeReturningToLogin() {
|
||||||
|
awaitLogin()
|
||||||
|
compose.onNodeWithText("Ještě nemám účet").performScrollTo().performClick()
|
||||||
|
val password = compose.onNode(hasSetTextAction() and hasText("Heslo"))
|
||||||
|
password.performScrollTo().performTextInput("LocalTestPassword123")
|
||||||
|
compose.onNodeWithText("Zpět na přihlášení").performScrollTo().performClick()
|
||||||
|
val loginPassword = compose.onNode(hasSetTextAction() and hasText("Heslo"))
|
||||||
|
assertEquals("", loginPassword.fetchSemanticsNode().config[SemanticsProperties.EditableText].text)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun awaitLogin() {
|
||||||
|
compose.waitUntil(15_000) { compose.onAllNodesWithText("Prohlédnout ukázku").fetchSemanticsNodes().isNotEmpty() }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@RunWith(AndroidJUnit4::class)
|
||||||
|
class RestoredAuthOutcomeUiTest {
|
||||||
|
@get:Rule val compose = createComposeRule()
|
||||||
|
|
||||||
|
@Test fun registrationFinishedBeforeScreenCreationStillOpensVerificationAndKeepsItsMessage() {
|
||||||
|
compose.setContent {
|
||||||
|
val vm: AppViewModel = viewModel()
|
||||||
|
NTBugTheme {
|
||||||
|
AccountScreen(AppState(booting = false, authOutcome = AuthOutcome.REGISTERED,
|
||||||
|
authMessage = "Registrace je hotová. Ověřte e-mail."), vm)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
compose.onNodeWithText("Vložte ověřovací odkaz nebo token z registračního e-mailu.").assertIsDisplayed()
|
||||||
|
compose.onNodeWithText("Registrace je hotová. Ověřte e-mail.").performScrollTo().assertIsDisplayed()
|
||||||
|
compose.onNodeWithText("Poslat ověřovací e-mail znovu").performScrollTo().assertIsDisplayed()
|
||||||
|
compose.onNodeWithText("Heslo znovu").assertDoesNotExist()
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,76 @@
|
|||||||
|
package cz.ntbug.mobile
|
||||||
|
|
||||||
|
import androidx.compose.runtime.SideEffect
|
||||||
|
import androidx.compose.runtime.mutableStateOf
|
||||||
|
import androidx.compose.ui.platform.LocalFocusManager
|
||||||
|
import androidx.compose.ui.platform.LocalSoftwareKeyboardController
|
||||||
|
import androidx.compose.ui.semantics.SemanticsProperties
|
||||||
|
import androidx.compose.ui.test.*
|
||||||
|
import androidx.compose.ui.test.junit4.createComposeRule
|
||||||
|
import androidx.compose.ui.text.AnnotatedString
|
||||||
|
import androidx.test.ext.junit.runners.AndroidJUnit4
|
||||||
|
import cz.ntbug.mobile.data.*
|
||||||
|
import cz.ntbug.mobile.ui.NTBugTheme
|
||||||
|
import cz.ntbug.mobile.ui.features.EditIssueScreen
|
||||||
|
import cz.ntbug.mobile.ui.features.NewProposalScreen
|
||||||
|
import org.junit.Assert.*
|
||||||
|
import org.junit.Rule
|
||||||
|
import org.junit.Test
|
||||||
|
import org.junit.runner.RunWith
|
||||||
|
|
||||||
|
@RunWith(AndroidJUnit4::class)
|
||||||
|
class CatalogFormTest {
|
||||||
|
@get:Rule val compose = createComposeRule()
|
||||||
|
|
||||||
|
@Test fun catalogRefreshKeepsEditedTitleAndOriginalInactiveReferences() {
|
||||||
|
val original = Issue(7, "Původní název", "Popis závady", "RECEIVED", 9, "Původní kategorie",
|
||||||
|
buildingId = 20, buildingName = "Původní budova", reporterId = 1, reporterName = "Jana", createdAt = "2026-11-19T10:00:00Z")
|
||||||
|
val catalogs = mutableStateOf(Catalogs(listOf(Building(20, "", "Původní budova")), listOf(Category(9, "Původní kategorie")), emptyList()))
|
||||||
|
var submitted: NewIssue? = null
|
||||||
|
var clearFocus: () -> Unit = {}
|
||||||
|
compose.setContent {
|
||||||
|
val focus = LocalFocusManager.current
|
||||||
|
val keyboard = LocalSoftwareKeyboardController.current
|
||||||
|
SideEffect { clearFocus = { keyboard?.hide(); focus.clearFocus() } }
|
||||||
|
NTBugTheme { EditIssueScreen(original, catalogs.value, busy = false) { submitted = it } }
|
||||||
|
}
|
||||||
|
val title = compose.onNode(hasSetTextAction() and hasText("Název závady *"))
|
||||||
|
title.performScrollTo().performTextReplacement("Rozepsaná změna názvu")
|
||||||
|
compose.runOnIdle { clearFocus(); catalogs.value = Catalogs(emptyList(), emptyList(), emptyList()) }
|
||||||
|
title.assert(SemanticsMatcher.expectValue(SemanticsProperties.EditableText, AnnotatedString("Rozepsaná změna názvu")))
|
||||||
|
compose.onNodeWithText("Původní kategorie (již není v nabídce)").performScrollTo().assertIsDisplayed()
|
||||||
|
compose.onNodeWithText("Původní budova (již není v nabídce)").performScrollTo().assertIsDisplayed()
|
||||||
|
compose.onNodeWithText("Uložit změny").performScrollTo().assertIsEnabled().performClick()
|
||||||
|
compose.runOnIdle {
|
||||||
|
val sent = requireNotNull(submitted)
|
||||||
|
assertEquals("Rozepsaná změna názvu", sent.title)
|
||||||
|
assertEquals(9, sent.categoryId)
|
||||||
|
assertEquals(20, sent.buildingId)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test fun deactivatedProposalCategoryIsRemovedWithoutLosingTheDraft() {
|
||||||
|
val catalogs = mutableStateOf(Catalogs(emptyList(), emptyList(), listOf(Category(2, "Studovna"))))
|
||||||
|
var submitted: NewProposal? = null
|
||||||
|
var clearFocus: () -> Unit = {}
|
||||||
|
compose.setContent {
|
||||||
|
val focus = LocalFocusManager.current
|
||||||
|
val keyboard = LocalSoftwareKeyboardController.current
|
||||||
|
SideEffect { clearFocus = { keyboard?.hide(); focus.clearFocus() } }
|
||||||
|
NTBugTheme { NewProposalScreen(catalogs.value, busy = false) { submitted = it } }
|
||||||
|
}
|
||||||
|
compose.onNodeWithText("Oblast *").performScrollTo().performClick()
|
||||||
|
compose.onNodeWithText("Studovna").performClick()
|
||||||
|
val title = compose.onNode(hasSetTextAction() and hasText("Název návrhu *"))
|
||||||
|
title.performScrollTo().performTextReplacement("Další zásuvky")
|
||||||
|
compose.onNode(hasSetTextAction() and hasText("Popis a přínos *")).performScrollTo().performTextReplacement("Více míst pro studium.")
|
||||||
|
compose.runOnIdle {
|
||||||
|
clearFocus()
|
||||||
|
catalogs.value = catalogs.value.copy(proposalCategories = listOf(Category(2, "Studovna", isActive = false)))
|
||||||
|
}
|
||||||
|
title.performScrollTo().assert(SemanticsMatcher.expectValue(SemanticsProperties.EditableText, AnnotatedString("Další zásuvky")))
|
||||||
|
compose.onNodeWithText("Vybraná oblast už není v nabídce. Vyberte jinou.").performScrollTo().assertIsDisplayed()
|
||||||
|
compose.onNodeWithText("Odeslat návrh").performScrollTo().assertIsNotEnabled()
|
||||||
|
compose.runOnIdle { assertNull(submitted) }
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -52,7 +52,7 @@ class DemoRepository : HelpdeskRepository {
|
|||||||
user = user.copy(firstName = update.firstName.trim(), lastName = update.lastName.trim(), phone = update.phone?.trim()?.takeIf(String::isNotBlank), emailNotificationsEnabled = update.emailNotificationsEnabled)
|
user = user.copy(firstName = update.firstName.trim(), lastName = update.lastName.trim(), phone = update.phone?.trim()?.takeIf(String::isNotBlank), emailNotificationsEnabled = update.emailNotificationsEnabled)
|
||||||
return user
|
return user
|
||||||
}
|
}
|
||||||
override suspend fun catalogs(): Catalogs = catalog
|
override suspend fun catalogs(refresh: Boolean): Catalogs = catalog
|
||||||
override suspend fun issues(page: Int, query: String, status: String?, assigned: Boolean): Page<Issue> = paginate(
|
override suspend fun issues(page: Int, query: String, status: String?, assigned: Boolean): Page<Issue> = paginate(
|
||||||
issueItems.filter { (status == null || it.status == status) && (it.title.contains(query, true) || it.description.contains(query, true)) && !assigned }, page,
|
issueItems.filter { (status == null || it.status == status) && (it.title.contains(query, true) || it.description.contains(query, true)) && !assigned }, page,
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -88,7 +88,7 @@ interface HelpdeskRepository {
|
|||||||
suspend fun restoreUser(): User?
|
suspend fun restoreUser(): User?
|
||||||
suspend fun logout(allDevices: Boolean = false)
|
suspend fun logout(allDevices: Boolean = false)
|
||||||
suspend fun updateProfile(update: ProfileUpdate): User
|
suspend fun updateProfile(update: ProfileUpdate): User
|
||||||
suspend fun catalogs(): Catalogs
|
suspend fun catalogs(refresh: Boolean = false): Catalogs
|
||||||
suspend fun issues(page: Int = 1, query: String = "", status: String? = null, assigned: Boolean = false): Page<Issue>
|
suspend fun issues(page: Int = 1, query: String = "", status: String? = null, assigned: Boolean = false): Page<Issue>
|
||||||
suspend fun issue(id: Int): Issue
|
suspend fun issue(id: Int): Issue
|
||||||
suspend fun createIssue(issue: NewIssue): Issue
|
suspend fun createIssue(issue: NewIssue): Issue
|
||||||
|
|||||||
@@ -120,8 +120,10 @@ class RemoteRepository(baseUrl: String, private val store: SessionPersistence) :
|
|||||||
return user
|
return user
|
||||||
}
|
}
|
||||||
|
|
||||||
override suspend fun catalogs(): Catalogs = catalogLock.withLock {
|
override suspend fun catalogs(refresh: Boolean): Catalogs = catalogLock.withLock {
|
||||||
catalogCache ?: Catalogs(
|
// Administrators can rename/deactivate catalog entries while this session is open.
|
||||||
|
// Publish a replacement only when all three requests have completed successfully.
|
||||||
|
catalogCache?.takeUnless { refresh } ?: Catalogs(
|
||||||
authorized { api.buildings(it) }, authorized { api.issueCategories(it) }, authorized { api.proposalCategories(it) },
|
authorized { api.buildings(it) }, authorized { api.issueCategories(it) }, authorized { api.proposalCategories(it) },
|
||||||
).also { catalogCache = it }
|
).also { catalogCache = it }
|
||||||
}
|
}
|
||||||
@@ -286,6 +288,7 @@ class RemoteRepository(baseUrl: String, private val store: SessionPersistence) :
|
|||||||
409 -> "Záznam se mezitím změnil. Obnovte jej a zkuste akci znovu."
|
409 -> "Záznam se mezitím změnil. Obnovte jej a zkuste akci znovu."
|
||||||
413 -> "Přílohy jsou příliš velké. Limit je 10 MB na soubor."
|
413 -> "Přílohy jsou příliš velké. Limit je 10 MB na soubor."
|
||||||
429 -> "Příliš mnoho požadavků. Zkuste to za chvíli."
|
429 -> "Příliš mnoho požadavků. Zkuste to za chvíli."
|
||||||
|
503 -> "Služba je dočasně nedostupná. Zkuste požadavek později."
|
||||||
else -> "Server je dočasně nedostupný (${error.code()}). Zkuste to později."
|
else -> "Server je dočasně nedostupný (${error.code()}). Zkuste to později."
|
||||||
}
|
}
|
||||||
val body = runCatching { error.response()?.errorBody()?.string() }.getOrNull()
|
val body = runCatching { error.response()?.errorBody()?.string() }.getOrNull()
|
||||||
|
|||||||
@@ -42,8 +42,14 @@ fun AccountScreen(s: AppState, vm: AppViewModel) {
|
|||||||
var token by remember { mutableStateOf("") }
|
var token by remember { mutableStateOf("") }
|
||||||
var validation by remember { mutableStateOf<String?>(null) }
|
var validation by remember { mutableStateOf<String?>(null) }
|
||||||
var serverDialog by remember { mutableStateOf(false) }
|
var serverDialog by remember { mutableStateOf(false) }
|
||||||
fun change(value: AuthMode) {
|
fun complete(value: AuthMode) {
|
||||||
mode = value; password = ""; repeat = ""; token = ""; validation = null; vm.clearFeedback()
|
mode = value; password = ""; repeat = ""; token = ""; validation = null
|
||||||
|
}
|
||||||
|
fun change(value: AuthMode) { complete(value); vm.clearFeedback() }
|
||||||
|
LaunchedEffect(s.authOutcome) {
|
||||||
|
val outcome = s.authOutcome ?: return@LaunchedEffect
|
||||||
|
complete(if (outcome == AuthOutcome.REGISTERED) AuthMode.CONFIRM else AuthMode.LOGIN)
|
||||||
|
vm.consumeAuthOutcome(outcome)
|
||||||
}
|
}
|
||||||
|
|
||||||
Column(
|
Column(
|
||||||
@@ -63,8 +69,8 @@ fun AccountScreen(s: AppState, vm: AppViewModel) {
|
|||||||
Text(mode.title, style = MaterialTheme.typography.headlineLarge, fontWeight = FontWeight.Bold)
|
Text(mode.title, style = MaterialTheme.typography.headlineLarge, fontWeight = FontWeight.Bold)
|
||||||
Text(when (mode) {
|
Text(when (mode) {
|
||||||
AuthMode.LOGIN -> "Lepší univerzita začíná u vás. Nahlaste závadu, sledujte řešení a podpořte dobré nápady."
|
AuthMode.LOGIN -> "Lepší univerzita začíná u vás. Nahlaste závadu, sledujte řešení a podpořte dobré nápady."
|
||||||
AuthMode.REGISTER -> "Použijte univerzitní e-mail. Studentský nebo vyučující účet se určí automaticky."
|
AuthMode.REGISTER -> "Použijte univerzitní e-mail. Studentský nebo vyučující účet se určí automaticky. Pokud už máte neověřený účet, stejné registrační údaje znovu odešlou ověřovací e-mail."
|
||||||
AuthMode.FORGOT -> "Na univerzitní e-mail vám pošleme odkaz pro nastavení nového hesla."
|
AuthMode.FORGOT -> "Požádejte o odkaz pro nastavení nového hesla. Pokud vám zpráva nepřijde, zkontrolujte také složku Spam."
|
||||||
AuthMode.CONFIRM -> "Vložte ověřovací odkaz nebo token z registračního e-mailu."
|
AuthMode.CONFIRM -> "Vložte ověřovací odkaz nebo token z registračního e-mailu."
|
||||||
AuthMode.RESET -> "Vložte odkaz z e-mailu a zvolte nové heslo o délce 8 až 64 znaků."
|
AuthMode.RESET -> "Vložte odkaz z e-mailu a zvolte nové heslo o délce 8 až 64 znaků."
|
||||||
}, color = MaterialTheme.colorScheme.onSurfaceVariant)
|
}, color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||||
@@ -121,7 +127,12 @@ fun AccountScreen(s: AppState, vm: AppViewModel) {
|
|||||||
TextButton(onClick = { change(AuthMode.CONFIRM) }, enabled = !s.busy) { Text("Ověřit e-mail") }
|
TextButton(onClick = { change(AuthMode.CONFIRM) }, enabled = !s.busy) { Text("Ověřit e-mail") }
|
||||||
TextButton(onClick = { change(AuthMode.RESET) }, enabled = !s.busy) { Text("Mám odkaz na reset") }
|
TextButton(onClick = { change(AuthMode.RESET) }, enabled = !s.busy) { Text("Mám odkaz na reset") }
|
||||||
}
|
}
|
||||||
} else TextButton(onClick = { change(AuthMode.LOGIN) }, enabled = !s.busy) { Text("Zpět na přihlášení") }
|
} else {
|
||||||
|
if (mode == AuthMode.CONFIRM) TextButton(onClick = { change(AuthMode.REGISTER) }, enabled = !s.busy, modifier = Modifier.fillMaxWidth()) {
|
||||||
|
Text("Poslat ověřovací e-mail znovu")
|
||||||
|
}
|
||||||
|
TextButton(onClick = { change(AuthMode.LOGIN) }, enabled = !s.busy) { Text("Zpět na přihlášení") }
|
||||||
|
}
|
||||||
TextButton(onClick = { serverDialog = true }, enabled = !s.busy, modifier = Modifier.align(Alignment.CenterHorizontally)) {
|
TextButton(onClick = { serverDialog = true }, enabled = !s.busy, modifier = Modifier.align(Alignment.CenterHorizontally)) {
|
||||||
Icon(Icons.Outlined.Dns, null, modifier = Modifier.size(18.dp)); Spacer(Modifier.width(8.dp)); Text("Nastavení serveru")
|
Icon(Icons.Outlined.Dns, null, modifier = Modifier.size(18.dp)); Spacer(Modifier.width(8.dp)); Text("Nastavení serveru")
|
||||||
}
|
}
|
||||||
@@ -199,7 +210,7 @@ private fun ServerDialog(current: String, onDismiss: () -> Unit, onSave: (String
|
|||||||
var value by remember { mutableStateOf(current) }
|
var value by remember { mutableStateOf(current) }
|
||||||
AlertDialog(onDismissRequest = onDismiss, title = { Text("Server NTBug") },
|
AlertDialog(onDismissRequest = onDismiss, title = { Text("Server NTBug") },
|
||||||
text = { Column(verticalArrangement = Arrangement.spacedBy(12.dp)) {
|
text = { Column(verticalArrangement = Arrangement.spacedBy(12.dp)) {
|
||||||
Text("Pro emulátor použijte http://10.0.2.2:8080/. Na telefonu zadejte adresu počítače ve stejné Wi-Fi síti. Mimo místní vývoj použijte HTTPS.")
|
Text("Pro emulátor použijte http://10.0.2.2:8080/. Na telefonu zadejte adresu počítače ve stejné Wi-Fi síti. Server musí povolovat připojení z místní sítě. Mimo místní vývoj použijte HTTPS.")
|
||||||
AccountField(value, { value = it }, "Adresa serveru", KeyboardType.Uri)
|
AccountField(value, { value = it }, "Adresa serveru", KeyboardType.Uri)
|
||||||
} }, confirmButton = { TextButton(onClick = { onSave(value) }) { Text("Uložit") } }, dismissButton = { TextButton(onClick = onDismiss) { Text("Zrušit") } })
|
} }, confirmButton = { TextButton(onClick = { onSave(value) }) { Text("Uložit") } }, dismissButton = { TextButton(onClick = onDismiss) { Text("Zrušit") } })
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -15,6 +15,8 @@ import kotlinx.coroutines.flow.update
|
|||||||
import kotlinx.coroutines.launch
|
import kotlinx.coroutines.launch
|
||||||
import kotlinx.coroutines.withContext
|
import kotlinx.coroutines.withContext
|
||||||
|
|
||||||
|
enum class AuthOutcome { REGISTERED, EMAIL_CONFIRMED, PASSWORD_RESET }
|
||||||
|
|
||||||
data class AppState(
|
data class AppState(
|
||||||
val booting: Boolean = true,
|
val booting: Boolean = true,
|
||||||
val user: User? = null,
|
val user: User? = null,
|
||||||
@@ -25,6 +27,7 @@ data class AppState(
|
|||||||
val error: String? = null,
|
val error: String? = null,
|
||||||
val message: String? = null,
|
val message: String? = null,
|
||||||
val authMessage: String? = null,
|
val authMessage: String? = null,
|
||||||
|
val authOutcome: AuthOutcome? = null,
|
||||||
val catalogs: Catalogs = Catalogs(emptyList(), emptyList(), emptyList()),
|
val catalogs: Catalogs = Catalogs(emptyList(), emptyList(), emptyList()),
|
||||||
val issues: List<Issue> = emptyList(),
|
val issues: List<Issue> = emptyList(),
|
||||||
val proposals: List<Proposal> = emptyList(),
|
val proposals: List<Proposal> = emptyList(),
|
||||||
@@ -100,26 +103,36 @@ class AppViewModel(application: Application) : AndroidViewModel(application) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fun register(email: String, password: String, firstName: String, lastName: String) = operation {
|
fun register(email: String, password: String, firstName: String, lastName: String) = operation {
|
||||||
repository.register(email.trim(), password, firstName.trim(), lastName.trim())
|
try {
|
||||||
state.update { it.copy(authMessage = "Registrace je hotová. Ověřte e-mail odkazem ze zprávy a pak se přihlaste.") }
|
repository.register(email.trim(), password, firstName.trim(), lastName.trim())
|
||||||
|
} catch (error: ApiException) {
|
||||||
|
// Main saves an unconfirmed account before sending its verification email.
|
||||||
|
// A manual retry with the same credentials resends the email instead of duplicating it.
|
||||||
|
if (error.status == 503) throw ApiException(503, "${error.message}\nZkuste registraci znovu se stejným e-mailem a heslem.")
|
||||||
|
throw error
|
||||||
|
}
|
||||||
|
state.update { it.copy(authMessage = "Registrace je hotová. Ověřte e-mail odkazem ze zprávy a pak se přihlaste.", authOutcome = AuthOutcome.REGISTERED) }
|
||||||
}
|
}
|
||||||
|
|
||||||
fun forgotPassword(email: String) = operation {
|
fun forgotPassword(email: String) = operation {
|
||||||
repository.forgotPassword(email.trim())
|
repository.forgotPassword(email.trim())
|
||||||
state.update { it.copy(authMessage = "Pokud účet existuje, obdržíte e-mail s odkazem pro obnovu hesla.") }
|
state.update { it.copy(authMessage = "Požadavek byl přijat. Pokud účet existuje a e-mail se podaří doručit, obdržíte odkaz pro obnovu hesla.") }
|
||||||
}
|
}
|
||||||
|
|
||||||
fun confirmEmail(token: String) = operation {
|
fun confirmEmail(token: String) = operation {
|
||||||
repository.confirmEmail(extractToken(token))
|
repository.confirmEmail(extractEmailActionToken(token, EmailAction.CONFIRM))
|
||||||
state.update { it.copy(authMessage = "E-mail je ověřený. Nyní se můžete přihlásit.") }
|
state.update { it.copy(authMessage = "E-mail je ověřený. Nyní se můžete přihlásit.", authOutcome = AuthOutcome.EMAIL_CONFIRMED) }
|
||||||
}
|
}
|
||||||
|
|
||||||
fun resetPassword(token: String, password: String) = operation {
|
fun resetPassword(token: String, password: String) = operation {
|
||||||
repository.resetPassword(extractToken(token), password)
|
repository.resetPassword(extractEmailActionToken(token, EmailAction.RESET), password)
|
||||||
state.update { it.copy(authMessage = "Heslo bylo změněno. Přihlaste se novým heslem.") }
|
state.update { it.copy(authMessage = "Heslo bylo změněno. Přihlaste se novým heslem.", authOutcome = AuthOutcome.PASSWORD_RESET) }
|
||||||
}
|
}
|
||||||
|
|
||||||
fun clearFeedback() { state.update { it.copy(error = null, message = null, authMessage = null) } }
|
fun consumeAuthOutcome(outcome: AuthOutcome) {
|
||||||
|
state.update { if (it.authOutcome == outcome) it.copy(authOutcome = null) else it }
|
||||||
|
}
|
||||||
|
fun clearFeedback() { state.update { it.copy(error = null, message = null, authMessage = null, authOutcome = null) } }
|
||||||
fun dismissMessage() { state.update { it.copy(message = null) } }
|
fun dismissMessage() { state.update { it.copy(message = null) } }
|
||||||
|
|
||||||
fun logout(allDevices: Boolean) {
|
fun logout(allDevices: Boolean) {
|
||||||
@@ -145,7 +158,7 @@ class AppViewModel(application: Application) : AndroidViewModel(application) {
|
|||||||
state.update { it.copy(user = user, message = "Profil byl uložen.") }
|
state.update { it.copy(user = user, message = "Profil byl uložen.") }
|
||||||
}
|
}
|
||||||
|
|
||||||
fun load(route: String) {
|
fun load(route: String, refreshCatalogs: Boolean = false) {
|
||||||
currentRoute = route
|
currentRoute = route
|
||||||
loadJob?.cancel()
|
loadJob?.cancel()
|
||||||
val sequence = ++loadSequence
|
val sequence = ++loadSequence
|
||||||
@@ -153,6 +166,15 @@ class AppViewModel(application: Application) : AndroidViewModel(application) {
|
|||||||
val stamp = generation
|
val stamp = generation
|
||||||
state.update { it.copy(loading = true, error = null) }
|
state.update { it.copy(loading = true, error = null) }
|
||||||
try {
|
try {
|
||||||
|
val form = route == "new-issue" || route == "new-proposal" || route.startsWith("edit-issue/")
|
||||||
|
val usesCatalogs = form || route in listOf("home", "issues", "proposals") || route.startsWith("issue/") || route.startsWith("proposal/")
|
||||||
|
if (form || refreshCatalogs && usesCatalogs) {
|
||||||
|
// Categories can be renamed/deactivated by administrators during a session.
|
||||||
|
// Reload before forms and explicit refresh, then share the snapshot with mappers.
|
||||||
|
if (form) state.update { it.copy(catalogs = Catalogs(emptyList(), emptyList(), emptyList())) }
|
||||||
|
val latest = repository.catalogs(refresh = true)
|
||||||
|
state.update { it.copy(catalogs = latest) }
|
||||||
|
}
|
||||||
when {
|
when {
|
||||||
route == "home" -> loadHome()
|
route == "home" -> loadHome()
|
||||||
route == "issues" -> loadIssues(false)
|
route == "issues" -> loadIssues(false)
|
||||||
@@ -187,7 +209,7 @@ class AppViewModel(application: Application) : AndroidViewModel(application) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fun retry() = load(currentRoute)
|
fun retry() = load(currentRoute, refreshCatalogs = true)
|
||||||
|
|
||||||
private suspend fun loadHome() = coroutineScope {
|
private suspend fun loadHome() = coroutineScope {
|
||||||
// Keep usable sections visible when another request temporarily fails.
|
// Keep usable sections visible when another request temporarily fails.
|
||||||
@@ -373,7 +395,7 @@ class AppViewModel(application: Application) : AndroidViewModel(application) {
|
|||||||
state.update { it.copy(loading = false) }
|
state.update { it.copy(loading = false) }
|
||||||
}
|
}
|
||||||
viewModelScope.launch {
|
viewModelScope.launch {
|
||||||
state.update { it.copy(busy = true, error = null, message = null, authMessage = null) }
|
state.update { it.copy(busy = true, error = null, message = null, authMessage = null, authOutcome = null) }
|
||||||
try { block() }
|
try { block() }
|
||||||
catch (e: Exception) { if (e is CancellationException) throw e; failure(e) }
|
catch (e: Exception) { if (e is CancellationException) throw e; failure(e) }
|
||||||
finally { state.update { it.copy(busy = false) } }
|
finally { state.update { it.copy(busy = false) } }
|
||||||
@@ -381,13 +403,6 @@ class AppViewModel(application: Application) : AndroidViewModel(application) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun extractToken(value: String): String {
|
|
||||||
val trimmed = value.trim()
|
|
||||||
return if (trimmed.startsWith("https://") || trimmed.startsWith("http://")) {
|
|
||||||
android.net.Uri.parse(trimmed).getQueryParameter("token") ?: throw IllegalArgumentException("Odkaz neobsahuje ověřovací token.")
|
|
||||||
} else trimmed
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun <T> Result<T>.getOrThrowCancellation(): Result<T> {
|
private fun <T> Result<T>.getOrThrowCancellation(): Result<T> {
|
||||||
(exceptionOrNull() as? CancellationException)?.let { throw it }
|
(exceptionOrNull() as? CancellationException)?.let { throw it }
|
||||||
return this
|
return this
|
||||||
|
|||||||
@@ -0,0 +1,42 @@
|
|||||||
|
package cz.ntbug.mobile.ui
|
||||||
|
|
||||||
|
import java.net.URI
|
||||||
|
import java.net.URLDecoder
|
||||||
|
|
||||||
|
enum class EmailAction(val path: String) {
|
||||||
|
CONFIRM("confirm-email"),
|
||||||
|
RESET("reset-password"),
|
||||||
|
}
|
||||||
|
|
||||||
|
/** WebBaseUrl may differ from the API origin; validate purpose and ambiguity, not its host. */
|
||||||
|
fun extractEmailActionToken(value: String, action: EmailAction): String {
|
||||||
|
val trimmed = value.trim()
|
||||||
|
require(trimmed.isNotEmpty()) { "Vložte token nebo odkaz z e-mailu." }
|
||||||
|
val uri = try { URI(trimmed) } catch (_: Exception) {
|
||||||
|
throw IllegalArgumentException("Vložte platný token nebo úplný odkaz z e-mailu.")
|
||||||
|
}
|
||||||
|
if (uri.scheme == null) {
|
||||||
|
require(trimmed.none(Char::isWhitespace)) { "Token nesmí obsahovat mezery ani konce řádků." }
|
||||||
|
return trimmed
|
||||||
|
}
|
||||||
|
require(uri.scheme.lowercase() in setOf("http", "https") && !uri.host.isNullOrBlank() &&
|
||||||
|
uri.rawUserInfo == null && uri.rawFragment == null) {
|
||||||
|
"Vložte úplný odkaz HTTP nebo HTTPS z e-mailu."
|
||||||
|
}
|
||||||
|
require(uri.path.trimEnd('/').substringAfterLast('/') == action.path) {
|
||||||
|
if (action == EmailAction.CONFIRM) "Tento odkaz není určený k ověření e-mailu."
|
||||||
|
else "Tento odkaz není určený k obnově hesla."
|
||||||
|
}
|
||||||
|
val tokens = try {
|
||||||
|
uri.rawQuery.orEmpty().split('&').map { entry ->
|
||||||
|
val parts = entry.split('=', limit = 2)
|
||||||
|
URLDecoder.decode(parts[0], "UTF-8") to URLDecoder.decode(parts.getOrElse(1) { "" }, "UTF-8")
|
||||||
|
}.filter { it.first == "token" }.map { it.second }
|
||||||
|
} catch (_: Exception) {
|
||||||
|
throw IllegalArgumentException("Odkaz obsahuje neplatně zapsaný token.")
|
||||||
|
}
|
||||||
|
require(tokens.size == 1 && tokens.single().isNotBlank() && tokens.single().none(Char::isWhitespace)) {
|
||||||
|
"Odkaz musí obsahovat právě jeden neprázdný token."
|
||||||
|
}
|
||||||
|
return tokens.single()
|
||||||
|
}
|
||||||
@@ -107,11 +107,11 @@ private fun SignedInApp(s: AppState, vm: AppViewModel) {
|
|||||||
composable("issues") { IssuesScreen(s.issues, s.issueQuery, s.issueStatus, s.assigned, user.role in listOf("FACILITY_MANAGER", "MANAGEMENT"),
|
composable("issues") { IssuesScreen(s.issues, s.issueQuery, s.issueStatus, s.assigned, user.role in listOf("FACILITY_MANAGER", "MANAGEMENT"),
|
||||||
{ vm.issueFilters(query = it) }, { vm.issueFilters(status = it) }, { vm.issueFilters(assigned = it) }, { open("issue/$it") }, { open("new-issue") }, { vm.more("issues") }, s.moreIssues) }
|
{ vm.issueFilters(query = it) }, { vm.issueFilters(status = it) }, { vm.issueFilters(assigned = it) }, { open("issue/$it") }, { open("new-issue") }, { vm.more("issues") }, s.moreIssues) }
|
||||||
composable("new-issue") { NewIssueScreen(s.catalogs, s.busy || s.loading) { request, files -> vm.createIssue(request, files) { created -> nav.navigate("issue/$created") { popUpTo("new-issue") { inclusive = true } } } } }
|
composable("new-issue") { NewIssueScreen(s.catalogs, s.busy || s.loading) { request, files -> vm.createIssue(request, files) { created -> nav.navigate("issue/$created") { popUpTo("new-issue") { inclusive = true } } } } }
|
||||||
composable("issue/{id}") { s.issue?.let { issue -> IssueDetailScreen(issue, s.busy, { text, onSaved -> vm.comment(issue.id, text, onSaved) }, { action, reason -> vm.issueAction(issue.id, action, reason) }, { files, onSaved -> vm.attachments(issue.id, files, onSaved) }, { open("edit-issue/${issue.id}") }, { vm.openAttachment(it.id) }) } }
|
composable("issue/{id}") { s.issue?.let { issue -> IssueDetailScreen(issue, s.busy || s.loading, { text, onSaved -> vm.comment(issue.id, text, onSaved) }, { action, reason -> vm.issueAction(issue.id, action, reason) }, { files, onSaved -> vm.attachments(issue.id, files, onSaved) }, { open("edit-issue/${issue.id}") }, { vm.openAttachment(it.id) }) } }
|
||||||
composable("edit-issue/{id}") { s.issue?.let { issue -> EditIssueScreen(issue, s.catalogs, s.busy || s.loading) { request -> vm.updateIssue(issue.id, request) { nav.popBackStack() } } } }
|
composable("edit-issue/{id}") { s.issue?.let { issue -> EditIssueScreen(issue, s.catalogs, s.busy || s.loading) { request -> vm.updateIssue(issue.id, request) { nav.popBackStack() } } } }
|
||||||
composable("proposals") { ProposalsScreen(s.proposals, user.id, s.proposalQuery, s.proposalSort, { vm.proposalFilters(query = it) }, { vm.proposalFilters(sort = it) }, { open("proposal/$it") }, vm::vote, { open("new-proposal") }, { vm.more("proposals") }, s.moreProposals) }
|
composable("proposals") { ProposalsScreen(s.proposals, user.id, s.proposalQuery, s.proposalSort, { vm.proposalFilters(query = it) }, { vm.proposalFilters(sort = it) }, { open("proposal/$it") }, vm::vote, { open("new-proposal") }, { vm.more("proposals") }, s.moreProposals) }
|
||||||
composable("new-proposal") { NewProposalScreen(s.catalogs, s.busy || s.loading) { request -> vm.createProposal(request) { created -> nav.navigate("proposal/$created") { popUpTo("new-proposal") { inclusive = true } } } } }
|
composable("new-proposal") { NewProposalScreen(s.catalogs, s.busy || s.loading) { request -> vm.createProposal(request) { created -> nav.navigate("proposal/$created") { popUpTo("new-proposal") { inclusive = true } } } } }
|
||||||
composable("proposal/{id}") { s.proposal?.let { proposal -> ProposalDetailScreen(proposal, user.id, s.busy) { vm.vote(proposal.id, it) } } }
|
composable("proposal/{id}") { s.proposal?.let { proposal -> ProposalDetailScreen(proposal, user.id, s.busy || s.loading) { vm.vote(proposal.id, it) } } }
|
||||||
composable("notices") { NoticesScreen(s.notices, { notice -> vm.readNotice(notice) { when { notice.issueId != null -> nav.navigate("issue/${notice.issueId}"); notice.proposalId != null -> nav.navigate("proposal/${notice.proposalId}") } } }, vm::readAll, { vm.more("notices") }, s.moreNotices, unreadCount = s.unreadCount) }
|
composable("notices") { NoticesScreen(s.notices, { notice -> vm.readNotice(notice) { when { notice.issueId != null -> nav.navigate("issue/${notice.issueId}"); notice.proposalId != null -> nav.navigate("proposal/${notice.proposalId}") } } }, vm::readAll, { vm.more("notices") }, s.moreNotices, unreadCount = s.unreadCount) }
|
||||||
composable("profile") { ProfileScreen(user, s, vm) }
|
composable("profile") { ProfileScreen(user, s, vm) }
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,34 @@
|
|||||||
|
package cz.ntbug.mobile.ui.features
|
||||||
|
|
||||||
|
import cz.ntbug.mobile.data.Building
|
||||||
|
import cz.ntbug.mobile.data.Catalogs
|
||||||
|
import cz.ntbug.mobile.data.Category
|
||||||
|
import cz.ntbug.mobile.data.Issue
|
||||||
|
|
||||||
|
/** The server permits keeping an issue's original category even after deactivation. */
|
||||||
|
internal fun issueCategoryOptions(catalogs: Catalogs, initial: Issue?): List<Category> {
|
||||||
|
val active = catalogs.issueCategories.filter { it.isActive }
|
||||||
|
if (initial == null || active.any { it.id == initial.categoryId }) return active
|
||||||
|
val original = catalogs.issueCategories.firstOrNull { it.id == initial.categoryId }
|
||||||
|
?: Category(initial.categoryId, initial.categoryName.ifBlank { "Kategorie #${initial.categoryId}" }, isActive = false)
|
||||||
|
return active + original.copy(isActive = false)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Missing historical buildings stay selectable only on the issue they already belong to. */
|
||||||
|
internal fun issueBuildingOptions(catalogs: Catalogs, initial: Issue?): List<Building> {
|
||||||
|
val active = listOf(Building(-1, "", "Bez vazby na budovu")) + catalogs.buildings.filter { it.isActive }
|
||||||
|
val originalId = initial?.buildingId ?: return active
|
||||||
|
if (active.any { it.id == originalId }) return active
|
||||||
|
val original = catalogs.buildings.firstOrNull { it.id == originalId }
|
||||||
|
?: Building(originalId, "", initial.buildingName?.takeIf(String::isNotBlank) ?: "Budova #$originalId", isActive = false)
|
||||||
|
return active + original.copy(isActive = false)
|
||||||
|
}
|
||||||
|
|
||||||
|
internal fun proposalCategoryOptions(catalogs: Catalogs): List<Category> = catalogs.proposalCategories.filter { it.isActive }
|
||||||
|
|
||||||
|
internal fun categoryOptionLabel(category: Category): String = category.name + if (category.isActive) "" else " (již není v nabídce)"
|
||||||
|
|
||||||
|
internal fun buildingOptionLabel(building: Building): String {
|
||||||
|
val name = if (building.code.isBlank()) building.name else "${building.code} · ${building.name}"
|
||||||
|
return name + if (building.isActive) "" else " (již není v nabídce)"
|
||||||
|
}
|
||||||
@@ -42,10 +42,12 @@ private fun IssueForm(catalogs: Catalogs, busy: Boolean, initial: Issue?, onSubm
|
|||||||
val draft: DraftAttachmentsViewModel = viewModel()
|
val draft: DraftAttachmentsViewModel = viewModel()
|
||||||
val files = draft.files
|
val files = draft.files
|
||||||
var readingFiles by remember { mutableStateOf(false) }
|
var readingFiles by remember { mutableStateOf(false) }
|
||||||
val category = catalogs.issueCategories.find { it.id == categoryId }
|
val categories = issueCategoryOptions(catalogs, initial)
|
||||||
val buildings = listOf(Building(-1, "", "Bez vazby na budovu", null, true)) + catalogs.buildings.filter { it.isActive }
|
val category = categories.find { it.id == categoryId }
|
||||||
|
val buildings = issueBuildingOptions(catalogs, initial)
|
||||||
val building = buildings.find { it.id == buildingId }
|
val building = buildings.find { it.id == buildingId }
|
||||||
val valid = title.isNotBlank() && description.isNotBlank() && category != null
|
val valid = title.isNotBlank() && description.isNotBlank() &&
|
||||||
|
category?.let { it.isActive || it.id == initial?.categoryId } == true && building != null
|
||||||
LazyColumn(contentPadding = screenPadding, verticalArrangement = Arrangement.spacedBy(18.dp), modifier = Modifier.fillMaxSize().imePadding()) {
|
LazyColumn(contentPadding = screenPadding, verticalArrangement = Arrangement.spacedBy(18.dp), modifier = Modifier.fillMaxSize().imePadding()) {
|
||||||
item {
|
item {
|
||||||
Text(if (initial == null) "Co je potřeba opravit?" else "Upravit hlášení", style = MaterialTheme.typography.headlineMedium, fontWeight = FontWeight.Bold)
|
Text(if (initial == null) "Co je potřeba opravit?" else "Upravit hlášení", style = MaterialTheme.typography.headlineMedium, fontWeight = FontWeight.Bold)
|
||||||
@@ -53,8 +55,10 @@ private fun IssueForm(catalogs: Catalogs, busy: Boolean, initial: Issue?, onSubm
|
|||||||
Text(if (initial == null) "Stačí pár údajů. O průběhu řešení vás budeme informovat." else "Upřesněte údaje, aby se závada vyřešila rychleji.", color = MaterialTheme.colorScheme.onSurfaceVariant)
|
Text(if (initial == null) "Stačí pár údajů. O průběhu řešení vás budeme informovat." else "Upřesněte údaje, aby se závada vyřešila rychleji.", color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||||
}
|
}
|
||||||
item { OutlinedTextField(value = title, onValueChange = { title = it.take(200) }, modifier = Modifier.fillMaxWidth(), label = { Text("Název závady *") }, placeholder = { Text("Např. Nefunkční projektor") }, singleLine = true, isError = showErrors && title.isBlank(), keyboardOptions = KeyboardOptions(capitalization = KeyboardCapitalization.Sentences), supportingText = { Text("${title.length}/200") }) }
|
item { OutlinedTextField(value = title, onValueChange = { title = it.take(200) }, modifier = Modifier.fillMaxWidth(), label = { Text("Název závady *") }, placeholder = { Text("Např. Nefunkční projektor") }, singleLine = true, isError = showErrors && title.isBlank(), keyboardOptions = KeyboardOptions(capitalization = KeyboardCapitalization.Sentences), supportingText = { Text("${title.length}/200") }) }
|
||||||
item { SelectionField(label = "Kategorie *", selected = category, items = catalogs.issueCategories, itemLabel = { it.name }, onSelect = { categoryId = it.id }, modifier = Modifier.fillMaxWidth()) }
|
item { SelectionField(label = "Kategorie *", selected = category, items = categories, itemLabel = ::categoryOptionLabel, onSelect = { categoryId = it.id }, modifier = Modifier.fillMaxWidth()) }
|
||||||
item { SelectionField(label = "Budova", selected = building, items = buildings, itemLabel = { if (it.code.isBlank()) it.name else "${it.code} · ${it.name}" }, onSelect = { buildingId = it.id }, modifier = Modifier.fillMaxWidth()) }
|
if (!busy && categoryId > 0 && category == null) item { Text("Vybraná kategorie už není v nabídce. Vyberte jinou.", color = MaterialTheme.colorScheme.error) }
|
||||||
|
item { SelectionField(label = "Budova", selected = building, items = buildings, itemLabel = ::buildingOptionLabel, onSelect = { buildingId = it.id }, modifier = Modifier.fillMaxWidth()) }
|
||||||
|
if (!busy && buildingId > 0 && building == null) item { Text("Vybraná budova už není v nabídce. Vyberte jinou nebo možnost Bez vazby na budovu.", color = MaterialTheme.colorScheme.error) }
|
||||||
item { OutlinedTextField(value = location, onValueChange = { location = it.take(255) }, modifier = Modifier.fillMaxWidth(), label = { Text("Upřesnění místa") }, placeholder = { Text("Učebna, patro nebo jiné místo") }, singleLine = true, keyboardOptions = KeyboardOptions(capitalization = KeyboardCapitalization.Sentences)) }
|
item { OutlinedTextField(value = location, onValueChange = { location = it.take(255) }, modifier = Modifier.fillMaxWidth(), label = { Text("Upřesnění místa") }, placeholder = { Text("Učebna, patro nebo jiné místo") }, singleLine = true, keyboardOptions = KeyboardOptions(capitalization = KeyboardCapitalization.Sentences)) }
|
||||||
item { OutlinedTextField(value = description, onValueChange = { description = it.take(10_000) }, modifier = Modifier.fillMaxWidth(), label = { Text("Co se stalo? *") }, placeholder = { Text("Popište problém a okolnosti, které nám pomohou.") }, minLines = 4, maxLines = 10, isError = showErrors && description.isBlank(), keyboardOptions = KeyboardOptions(capitalization = KeyboardCapitalization.Sentences)) }
|
item { OutlinedTextField(value = description, onValueChange = { description = it.take(10_000) }, modifier = Modifier.fillMaxWidth(), label = { Text("Co se stalo? *") }, placeholder = { Text("Popište problém a okolnosti, které nám pomohou.") }, minLines = 4, maxLines = 10, isError = showErrors && description.isBlank(), keyboardOptions = KeyboardOptions(capitalization = KeyboardCapitalization.Sentences)) }
|
||||||
if (initial == null) item {
|
if (initial == null) item {
|
||||||
@@ -64,10 +68,10 @@ private fun IssueForm(catalogs: Catalogs, busy: Boolean, initial: Issue?, onSubm
|
|||||||
if (draft.busy) LinearProgressIndicator(Modifier.fillMaxWidth())
|
if (draft.busy) LinearProgressIndicator(Modifier.fillMaxWidth())
|
||||||
draft.error?.let { Text(it, color = MaterialTheme.colorScheme.error, style = MaterialTheme.typography.bodySmall) }
|
draft.error?.let { Text(it, color = MaterialTheme.colorScheme.error, style = MaterialTheme.typography.bodySmall) }
|
||||||
}
|
}
|
||||||
if (catalogs.issueCategories.isEmpty()) item { Text("Kategorie se nepodařilo načíst. Vraťte se zpět a obnovte data.", color = MaterialTheme.colorScheme.error) }
|
if (categories.isEmpty()) item { Text("Není dostupná žádná aktivní kategorie závad. Zkuste obnovit data nebo kontaktujte správce.", color = MaterialTheme.colorScheme.error) }
|
||||||
if (showErrors && !valid) item { Text("Vyplňte název, popis a vyberte kategorii závady.", color = MaterialTheme.colorScheme.error, style = MaterialTheme.typography.bodySmall) }
|
if (showErrors && !valid) item { Text("Vyplňte název, popis a vyberte kategorii i budovu, případně možnost Bez vazby na budovu.", color = MaterialTheme.colorScheme.error, style = MaterialTheme.typography.bodySmall) }
|
||||||
item {
|
item {
|
||||||
Button(onClick = { showErrors = true; if (valid) onSubmit(NewIssue(title.trim(), description.trim(), categoryId, buildingId.takeIf { it >= 0 }, location.trim()), files) }, enabled = !busy && !readingFiles && !draft.busy && catalogs.issueCategories.isNotEmpty(), modifier = Modifier.fillMaxWidth().heightIn(min = 52.dp)) {
|
Button(onClick = { showErrors = true; if (valid) onSubmit(NewIssue(title.trim(), description.trim(), categoryId, buildingId.takeIf { it >= 0 }, location.trim()), files) }, enabled = !busy && !readingFiles && !draft.busy && categories.isNotEmpty(), modifier = Modifier.fillMaxWidth().heightIn(min = 52.dp)) {
|
||||||
if (busy) CircularProgressIndicator(Modifier.size(20.dp), strokeWidth = 2.dp) else Icon(Icons.AutoMirrored.Rounded.Send, null)
|
if (busy) CircularProgressIndicator(Modifier.size(20.dp), strokeWidth = 2.dp) else Icon(Icons.AutoMirrored.Rounded.Send, null)
|
||||||
Spacer(Modifier.width(8.dp)); Text(if (busy) "Ukládání…" else if (initial == null) "Odeslat hlášení" else "Uložit změny")
|
Spacer(Modifier.width(8.dp)); Text(if (busy) "Ukládání…" else if (initial == null) "Odeslat hlášení" else "Uložit změny")
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -127,25 +127,27 @@ fun NewProposalScreen(catalogs: Catalogs, busy: Boolean, onSubmit: (NewProposal)
|
|||||||
var description by rememberSaveable { mutableStateOf("") }
|
var description by rememberSaveable { mutableStateOf("") }
|
||||||
var categoryId by rememberSaveable { mutableIntStateOf(-1) }
|
var categoryId by rememberSaveable { mutableIntStateOf(-1) }
|
||||||
var showErrors by rememberSaveable { mutableStateOf(false) }
|
var showErrors by rememberSaveable { mutableStateOf(false) }
|
||||||
val category = catalogs.proposalCategories.find { it.id == categoryId }
|
val categories = proposalCategoryOptions(catalogs)
|
||||||
val valid = title.isNotBlank() && description.isNotBlank() && category != null
|
val category = categories.find { it.id == categoryId }
|
||||||
|
val valid = title.isNotBlank() && description.isNotBlank() && category?.isActive == true
|
||||||
LazyColumn(contentPadding = screenPadding, verticalArrangement = Arrangement.spacedBy(18.dp), modifier = Modifier.fillMaxSize().imePadding()) {
|
LazyColumn(contentPadding = screenPadding, verticalArrangement = Arrangement.spacedBy(18.dp), modifier = Modifier.fillMaxSize().imePadding()) {
|
||||||
item {
|
item {
|
||||||
Text("Máte nápad?", style = MaterialTheme.typography.headlineMedium, fontWeight = FontWeight.Bold)
|
Text("Máte nápad?", style = MaterialTheme.typography.headlineMedium, fontWeight = FontWeight.Bold)
|
||||||
Spacer(Modifier.height(8.dp))
|
Spacer(Modifier.height(8.dp))
|
||||||
Text("Popište, co byste chtěli změnit a komu to pomůže. Ostatní mohou návrh podpořit.", color = MaterialTheme.colorScheme.onSurfaceVariant)
|
Text("Popište, co byste chtěli změnit a komu to pomůže. Ostatní mohou návrh podpořit.", color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||||
}
|
}
|
||||||
item { SelectionField(label = "Oblast *", selected = category, items = catalogs.proposalCategories, itemLabel = { it.name }, onSelect = { categoryId = it.id }, modifier = Modifier.fillMaxWidth()) }
|
item { SelectionField(label = "Oblast *", selected = category, items = categories, itemLabel = ::categoryOptionLabel, onSelect = { categoryId = it.id }, modifier = Modifier.fillMaxWidth()) }
|
||||||
|
if (!busy && categoryId > 0 && category == null) item { Text("Vybraná oblast už není v nabídce. Vyberte jinou.", color = MaterialTheme.colorScheme.error) }
|
||||||
item {
|
item {
|
||||||
OutlinedTextField(value = title, onValueChange = { title = it.take(200) }, modifier = Modifier.fillMaxWidth(), label = { Text("Název návrhu *") }, placeholder = { Text("Např. Více zásuvek ve studovně") }, isError = showErrors && title.isBlank(), singleLine = true, keyboardOptions = KeyboardOptions(capitalization = KeyboardCapitalization.Sentences), supportingText = { Text("${title.length}/200") })
|
OutlinedTextField(value = title, onValueChange = { title = it.take(200) }, modifier = Modifier.fillMaxWidth(), label = { Text("Název návrhu *") }, placeholder = { Text("Např. Více zásuvek ve studovně") }, isError = showErrors && title.isBlank(), singleLine = true, keyboardOptions = KeyboardOptions(capitalization = KeyboardCapitalization.Sentences), supportingText = { Text("${title.length}/200") })
|
||||||
}
|
}
|
||||||
item {
|
item {
|
||||||
OutlinedTextField(value = description, onValueChange = { description = it.take(10_000) }, modifier = Modifier.fillMaxWidth(), label = { Text("Popis a přínos *") }, placeholder = { Text("Co by se mělo změnit a proč?") }, minLines = 5, maxLines = 12, keyboardOptions = KeyboardOptions(capitalization = KeyboardCapitalization.Sentences), isError = showErrors && description.isBlank())
|
OutlinedTextField(value = description, onValueChange = { description = it.take(10_000) }, modifier = Modifier.fillMaxWidth(), label = { Text("Popis a přínos *") }, placeholder = { Text("Co by se mělo změnit a proč?") }, minLines = 5, maxLines = 12, keyboardOptions = KeyboardOptions(capitalization = KeyboardCapitalization.Sentences), isError = showErrors && description.isBlank())
|
||||||
}
|
}
|
||||||
if (catalogs.proposalCategories.isEmpty()) item { Text("Oblasti se nepodařilo načíst. Vraťte se zpět a obnovte data.", color = MaterialTheme.colorScheme.error) }
|
if (categories.isEmpty()) item { Text("Není dostupná žádná aktivní oblast návrhů. Zkuste obnovit data nebo kontaktujte správce.", color = MaterialTheme.colorScheme.error) }
|
||||||
if (showErrors && !valid) item { Text("Vyplňte název, popis a vyberte oblast návrhu.", color = MaterialTheme.colorScheme.error, style = MaterialTheme.typography.bodySmall) }
|
if (showErrors && !valid) item { Text("Vyplňte název, popis a vyberte oblast návrhu.", color = MaterialTheme.colorScheme.error, style = MaterialTheme.typography.bodySmall) }
|
||||||
item {
|
item {
|
||||||
Button(onClick = { showErrors = true; if (valid) onSubmit(NewProposal(title.trim(), description.trim(), categoryId)) }, enabled = !busy && catalogs.proposalCategories.isNotEmpty(), modifier = Modifier.fillMaxWidth().heightIn(min = 52.dp)) {
|
Button(onClick = { showErrors = true; if (valid) onSubmit(NewProposal(title.trim(), description.trim(), categoryId)) }, enabled = !busy && categories.isNotEmpty(), modifier = Modifier.fillMaxWidth().heightIn(min = 52.dp)) {
|
||||||
if (busy) CircularProgressIndicator(Modifier.size(20.dp), strokeWidth = 2.dp) else Icon(Icons.Rounded.Lightbulb, null)
|
if (busy) CircularProgressIndicator(Modifier.size(20.dp), strokeWidth = 2.dp) else Icon(Icons.Rounded.Lightbulb, null)
|
||||||
Spacer(Modifier.width(8.dp)); Text(if (busy) "Odesílání…" else "Odeslat návrh")
|
Spacer(Modifier.width(8.dp)); Text(if (busy) "Odesílání…" else "Odeslat návrh")
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,91 @@
|
|||||||
|
package cz.ntbug.mobile.data
|
||||||
|
|
||||||
|
import kotlinx.coroutines.runBlocking
|
||||||
|
import okhttp3.mockwebserver.Dispatcher
|
||||||
|
import okhttp3.mockwebserver.MockResponse
|
||||||
|
import okhttp3.mockwebserver.MockWebServer
|
||||||
|
import okhttp3.mockwebserver.RecordedRequest
|
||||||
|
import org.junit.After
|
||||||
|
import org.junit.Assert.*
|
||||||
|
import org.junit.Before
|
||||||
|
import org.junit.Test
|
||||||
|
import java.util.concurrent.atomic.AtomicBoolean
|
||||||
|
import java.util.concurrent.atomic.AtomicInteger
|
||||||
|
|
||||||
|
class MutableCatalogContractTest {
|
||||||
|
private lateinit var server: MockWebServer
|
||||||
|
private lateinit var repository: RemoteRepository
|
||||||
|
|
||||||
|
@Before fun setup() {
|
||||||
|
server = MockWebServer().apply { start() }
|
||||||
|
repository = RemoteRepository(server.url("/").toString(), object : SessionPersistence {
|
||||||
|
private var session: AuthSession? = AuthSession("access", "2099-01-01T00:00:00Z", "refresh", "2099-02-01T00:00:00Z",
|
||||||
|
User(1, "[email protected]", "Jana", "Nováková", role = "STUDENT"))
|
||||||
|
override fun read() = session
|
||||||
|
override fun write(session: AuthSession) { this.session = session }
|
||||||
|
override fun clear() { session = null }
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
@After fun teardown() { server.shutdown() }
|
||||||
|
|
||||||
|
@Test fun `explicit refresh picks up renamed new and deactivated categories without reloading per row`() = runBlocking {
|
||||||
|
val revision = AtomicInteger()
|
||||||
|
server.dispatcher = object : Dispatcher() {
|
||||||
|
override fun dispatch(request: RecordedRequest): MockResponse {
|
||||||
|
assertEquals("Bearer access", request.getHeader("Authorization"))
|
||||||
|
// Ordinary catalog access must not request administrator-only inactive rows.
|
||||||
|
assertNull(request.requestUrl!!.queryParameter("includeInactive"))
|
||||||
|
return when (request.requestUrl!!.encodedPath) {
|
||||||
|
"/api/buildings" -> json(buildings(if (revision.get() == 0) "Budova A" else "Hlavní budova"))
|
||||||
|
"/api/issue-categories" -> json(if (revision.get() == 0)
|
||||||
|
"""[{"id":1,"name":"Technika","isActive":true},{"id":2,"name":"Stará kategorie","isActive":true}]"""
|
||||||
|
else """[{"id":1,"name":"Technické vybavení","isActive":true},{"id":5,"name":"Nová kategorie","isActive":true}]""")
|
||||||
|
"/api/proposal-categories" -> json(if (revision.get() == 0)
|
||||||
|
"""[{"id":3,"name":"Prostředí","isActive":true}]"""
|
||||||
|
else """[{"id":4,"name":"Výuka","isActive":true}]""")
|
||||||
|
else -> MockResponse().setResponseCode(404)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
val original = repository.catalogs()
|
||||||
|
revision.set(1)
|
||||||
|
assertSame(original, repository.catalogs())
|
||||||
|
assertEquals(3, server.requestCount)
|
||||||
|
|
||||||
|
val updated = repository.catalogs(refresh = true)
|
||||||
|
assertEquals("Hlavní budova", updated.buildings.single().name)
|
||||||
|
assertEquals("Technické vybavení", updated.issueCategories.first { it.id == 1 }.name)
|
||||||
|
assertEquals(setOf(1, 5), updated.issueCategories.map { it.id }.toSet())
|
||||||
|
assertEquals(listOf(4), updated.proposalCategories.map { it.id })
|
||||||
|
assertSame(updated, repository.catalogs())
|
||||||
|
assertEquals(6, server.requestCount)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test fun `failed refresh does not replace any part of the previously complete catalog`() = runBlocking {
|
||||||
|
val failing = AtomicBoolean(false)
|
||||||
|
server.dispatcher = object : Dispatcher() {
|
||||||
|
override fun dispatch(request: RecordedRequest): MockResponse = when (request.requestUrl!!.encodedPath) {
|
||||||
|
"/api/buildings" -> json(buildings(if (failing.get()) "Nový název" else "Budova A"))
|
||||||
|
"/api/issue-categories" -> if (failing.get()) MockResponse().setResponseCode(503)
|
||||||
|
else json("""[{"id":1,"name":"Technika","isActive":true}]""")
|
||||||
|
"/api/proposal-categories" -> json("""[{"id":3,"name":"Prostředí","isActive":true}]""")
|
||||||
|
else -> MockResponse().setResponseCode(404)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
val original = repository.catalogs()
|
||||||
|
failing.set(true)
|
||||||
|
try {
|
||||||
|
repository.catalogs(refresh = true)
|
||||||
|
fail("Expected service failure")
|
||||||
|
} catch (error: ApiException) { assertEquals(503, error.status) }
|
||||||
|
val cached = repository.catalogs()
|
||||||
|
assertSame(original, cached)
|
||||||
|
assertEquals("Budova A", cached.buildings.single().name)
|
||||||
|
assertEquals("Technika", cached.issueCategories.single().name)
|
||||||
|
assertEquals(5, server.requestCount)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun buildings(name: String) = """[{"id":1,"code":"A","name":"$name","isActive":true}]"""
|
||||||
|
private fun json(value: String) = MockResponse().setHeader("Content-Type", "application/json").setBody(value)
|
||||||
|
}
|
||||||
@@ -0,0 +1,69 @@
|
|||||||
|
package cz.ntbug.mobile.data
|
||||||
|
|
||||||
|
import kotlinx.coroutines.runBlocking
|
||||||
|
import okhttp3.mockwebserver.MockResponse
|
||||||
|
import okhttp3.mockwebserver.MockWebServer
|
||||||
|
import org.junit.After
|
||||||
|
import org.junit.Assert.*
|
||||||
|
import org.junit.Before
|
||||||
|
import org.junit.Test
|
||||||
|
import java.util.concurrent.TimeUnit
|
||||||
|
|
||||||
|
class RegistrationDeliveryContractTest {
|
||||||
|
private lateinit var server: MockWebServer
|
||||||
|
private lateinit var repository: RemoteRepository
|
||||||
|
private var session: AuthSession? = null
|
||||||
|
|
||||||
|
@Before fun setup() {
|
||||||
|
server = MockWebServer().apply { start() }
|
||||||
|
repository = RemoteRepository(server.url("/").toString(), object : SessionPersistence {
|
||||||
|
override fun read() = session
|
||||||
|
override fun write(session: AuthSession) { this@RegistrationDeliveryContractTest.session = session }
|
||||||
|
override fun clear() { session = null }
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
@After fun teardown() { server.shutdown() }
|
||||||
|
|
||||||
|
@Test fun `failed email delivery is shown without retry and same registration can be manually resent`() = runBlocking {
|
||||||
|
val message = "E-mail se nepodařilo odeslat. Zkuste požadavek později."
|
||||||
|
server.enqueue(json("""{"status":503,"title":"$message"}""").setResponseCode(503))
|
||||||
|
try {
|
||||||
|
register()
|
||||||
|
fail("Expected email delivery failure")
|
||||||
|
} catch (error: ApiException) {
|
||||||
|
assertEquals(503, error.status)
|
||||||
|
assertEquals(message, error.message)
|
||||||
|
}
|
||||||
|
val failed = server.takeRequest()
|
||||||
|
assertEquals("/api/auth/register", failed.path)
|
||||||
|
assertEquals("POST", failed.method)
|
||||||
|
val failedBody = failed.body.readUtf8()
|
||||||
|
assertNull(server.takeRequest(100, TimeUnit.MILLISECONDS))
|
||||||
|
assertNull(session)
|
||||||
|
|
||||||
|
server.enqueue(json("""{"id":1,"email":"[email protected]","firstName":"Jana","lastName":"Nováková","role":"STUDENT","emailNotificationsEnabled":true}""").setResponseCode(201))
|
||||||
|
register()
|
||||||
|
val repeated = server.takeRequest()
|
||||||
|
assertEquals("/api/auth/register", repeated.path)
|
||||||
|
assertEquals(failedBody, repeated.body.readUtf8())
|
||||||
|
assertEquals(2, server.requestCount)
|
||||||
|
assertNull("Registration must not sign in an unverified account", session)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test fun `service failure without problem details has a Czech fallback`() = runBlocking {
|
||||||
|
server.enqueue(MockResponse().setResponseCode(503))
|
||||||
|
try {
|
||||||
|
register()
|
||||||
|
fail("Expected service failure")
|
||||||
|
} catch (error: ApiException) {
|
||||||
|
assertEquals(503, error.status)
|
||||||
|
assertEquals("Služba je dočasně nedostupná. Zkuste požadavek později.", error.message)
|
||||||
|
}
|
||||||
|
assertEquals(1, server.requestCount)
|
||||||
|
assertNull(session)
|
||||||
|
}
|
||||||
|
|
||||||
|
private suspend fun register() = repository.register("[email protected]", "test-password", "Jana", "Nováková")
|
||||||
|
private fun json(value: String) = MockResponse().setHeader("Content-Type", "application/json").setBody(value)
|
||||||
|
}
|
||||||
@@ -0,0 +1,47 @@
|
|||||||
|
package cz.ntbug.mobile.ui
|
||||||
|
|
||||||
|
import org.junit.Assert.*
|
||||||
|
import org.junit.Test
|
||||||
|
|
||||||
|
class EmailActionTokenTest {
|
||||||
|
@Test fun acceptsRawTokenWithoutChangingItsContents() {
|
||||||
|
assertEquals("header.payload.signature", extractEmailActionToken(" header.payload.signature ", EmailAction.CONFIRM))
|
||||||
|
assertEquals("opaque-token_123", extractEmailActionToken("opaque-token_123", EmailAction.RESET))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test fun acceptsConfiguredWebHostAndPrefixRatherThanRequiringTheApiHost() {
|
||||||
|
assertEquals("token.value", extractEmailActionToken("HTTPS://portal.univerzita.cz/helpdesk/confirm-email?token=token%2Evalue", EmailAction.CONFIRM))
|
||||||
|
assertEquals("reset-token", extractEmailActionToken("https://portal.univerzita.cz/reset-password/?source=mail&token=reset-token", EmailAction.RESET))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test fun rejectsLinkForAnotherActionBeforeSubmittingItsSingleUseToken() {
|
||||||
|
rejects("https://portal.univerzita.cz/reset-password?token=secret", EmailAction.CONFIRM)
|
||||||
|
rejects("https://portal.univerzita.cz/confirm-email?token=secret", EmailAction.RESET)
|
||||||
|
rejects("https://portal.univerzita.cz/other?token=secret")
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test fun rejectsMissingEmptyDuplicateAndWhitespaceTokens() {
|
||||||
|
listOf(
|
||||||
|
"https://portal.univerzita.cz/confirm-email",
|
||||||
|
"https://portal.univerzita.cz/confirm-email?token=",
|
||||||
|
"https://portal.univerzita.cz/confirm-email?token=one&token=two",
|
||||||
|
"https://portal.univerzita.cz/confirm-email?token=one&%74oken=two",
|
||||||
|
"https://portal.univerzita.cz/confirm-email?token=bad%20token",
|
||||||
|
" ", "header. payload.signature",
|
||||||
|
).forEach { rejects(it) }
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test fun rejectsNonWebAmbiguousAndMalformedLinks() {
|
||||||
|
listOf(
|
||||||
|
"ftp://portal.univerzita.cz/confirm-email?token=secret",
|
||||||
|
"https://[email protected]/confirm-email?token=secret",
|
||||||
|
"https://portal.univerzita.cz/confirm-email?token=secret#another-token",
|
||||||
|
"https://portal.univerzita.cz/confirm-email?token=%XX",
|
||||||
|
"https:/confirm-email?token=secret",
|
||||||
|
).forEach { rejects(it) }
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun rejects(value: String, action: EmailAction = EmailAction.CONFIRM) {
|
||||||
|
assertThrows(IllegalArgumentException::class.java) { extractEmailActionToken(value, action) }
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,63 @@
|
|||||||
|
package cz.ntbug.mobile.ui.features
|
||||||
|
|
||||||
|
import cz.ntbug.mobile.data.Building
|
||||||
|
import cz.ntbug.mobile.data.Catalogs
|
||||||
|
import cz.ntbug.mobile.data.Category
|
||||||
|
import cz.ntbug.mobile.data.Issue
|
||||||
|
import org.junit.Assert.*
|
||||||
|
import org.junit.Test
|
||||||
|
|
||||||
|
class CatalogSelectionTest {
|
||||||
|
private val issue = Issue(7, "Závada", "Popis", "RECEIVED", 9, "Původní kategorie",
|
||||||
|
buildingId = 20, buildingName = "Původní budova", reporterId = 1, reporterName = "Jana Nováková", createdAt = "2026-11-19T10:00:00Z")
|
||||||
|
private val catalogs = Catalogs(
|
||||||
|
buildings = listOf(Building(20, "A", "Přejmenovaná budova", isActive = false), Building(21, "B", "Aktivní budova"), Building(22, "C", "Jiná neaktivní budova", isActive = false)),
|
||||||
|
issueCategories = listOf(Category(1, "Aktivní kategorie"), Category(9, "Přejmenovaná kategorie", isActive = false), Category(10, "Jiná neaktivní kategorie", isActive = false)),
|
||||||
|
proposalCategories = listOf(Category(2, "Aktivní oblast"), Category(3, "Neaktivní oblast", isActive = false)),
|
||||||
|
)
|
||||||
|
|
||||||
|
@Test fun `new reports and proposals can select only active catalog entries`() {
|
||||||
|
assertEquals(listOf(1), issueCategoryOptions(catalogs, null).map { it.id })
|
||||||
|
assertEquals(listOf(-1, 21), issueBuildingOptions(catalogs, null).map { it.id })
|
||||||
|
assertEquals(listOf(2), proposalCategoryOptions(catalogs).map { it.id })
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test fun `edit retains only its own inactive references and their current catalog names`() {
|
||||||
|
val categories = issueCategoryOptions(catalogs, issue)
|
||||||
|
assertEquals(listOf(1, 9), categories.map { it.id })
|
||||||
|
assertEquals("Přejmenovaná kategorie (již není v nabídce)", categoryOptionLabel(categories.last()))
|
||||||
|
val buildings = issueBuildingOptions(catalogs, issue)
|
||||||
|
assertEquals(listOf(-1, 21, 20), buildings.map { it.id })
|
||||||
|
assertEquals("A · Přejmenovaná budova (již není v nabídce)", buildingOptionLabel(buildings.last()))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test fun `edit preserves IDs and names when historical references are absent from the response`() {
|
||||||
|
val empty = Catalogs(emptyList(), emptyList(), emptyList())
|
||||||
|
val category = issueCategoryOptions(empty, issue).single()
|
||||||
|
assertEquals(9, category.id)
|
||||||
|
assertEquals("Původní kategorie", category.name)
|
||||||
|
assertFalse(category.isActive)
|
||||||
|
val building = issueBuildingOptions(empty, issue).last()
|
||||||
|
assertEquals(20, building.id)
|
||||||
|
assertEquals("Původní budova", building.name)
|
||||||
|
assertFalse(building.isActive)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test fun `active original references use fresh catalog names without duplicate choices`() {
|
||||||
|
val fresh = catalogs.copy(
|
||||||
|
issueCategories = listOf(Category(9, "Aktuální název")),
|
||||||
|
buildings = listOf(Building(20, "A", "Aktuální budova")),
|
||||||
|
)
|
||||||
|
assertEquals("Aktuální název", categoryOptionLabel(issueCategoryOptions(fresh, issue).single()))
|
||||||
|
assertEquals(listOf(-1, 20), issueBuildingOptions(fresh, issue).map { it.id })
|
||||||
|
assertEquals("A · Aktuální budova", buildingOptionLabel(issueBuildingOptions(fresh, issue).last()))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test fun `missing historical names use readable IDs and no original building stays optional`() {
|
||||||
|
val empty = Catalogs(emptyList(), emptyList(), emptyList())
|
||||||
|
val unnamed = issue.copy(categoryName = "", buildingName = null)
|
||||||
|
assertEquals("Kategorie #9 (již není v nabídce)", categoryOptionLabel(issueCategoryOptions(empty, unnamed).single()))
|
||||||
|
assertEquals("Budova #20 (již není v nabídce)", buildingOptionLabel(issueBuildingOptions(empty, unnamed).last()))
|
||||||
|
assertEquals(listOf(-1), issueBuildingOptions(empty, unnamed.copy(buildingId = null)).map { it.id })
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in new issue
Block a user