Compare commits

10 Commits
68 changed files with 2916 additions and 326 deletions

No files matched your search

+13 -5
View File
@@ -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, přidejte do `deploy/.env` například `API_PORT=8081`. 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 `API_PORT=8081` 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`. Odesílání e-mailů je zatím jen do logu – odkaz pro ověření e-mailu po registraci najdete v `docker compose -f deploy/docker-compose.yml logs api`. Při prvním startu se vytvoří účet administrátora, pokud vyplníte `ADMIN_EMAIL` a `ADMIN_PASSWORD`. V režimu `Development` s prázdnými hodnotami `SMTP_MAILBOX` a `SMTP_PASSWORD` najdete ověřovací odkazy a odkazy pro obnovu hesla v logu služby `api`.
Pro nasazení nastavte v `deploy/.env` režim `Production`, veřejnou HTTPS adresu webu v `PUBLIC_BASE_URL` a skutečné univerzitní domény v `STUDENT_EMAIL_DOMAIN` a `TEACHER_EMAIL_DOMAIN`. Pro Email Profi vyplňte `SMTP_MAILBOX` celou adresou schránky a nastavte `SMTP_PASSWORD`. API odesílá přes `smtp.seznam.cz:465` s TLS.
Reverse proxy ukončuje HTTPS a předává požadavky přes HTTP na adresu `PROXY_UPSTREAM_BIND_ADDRESS` a port `API_HTTP_PORT`. Výchozí hodnoty `127.0.0.1` a `8080` odpovídají proxy běžící přímo na stejném hostiteli.
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 v `deploy/.env` nastavili `API_PORT=8081`, zadejte v aplikaci `http://10.0.2.2:8081/`. 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).
+2
View File
@@ -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
+28 -1
View File
@@ -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);
throw new ConflictException("Účet s tímto e-mailem už existuje."); if (user is null)
{
var user = User.Create(request.Email, passwordHasher.Hash(request.Password), request.FirstName, request.LastName, role); user = User.Create(request.Email, passwordHasher.Hash(request.Password), request.FirstName, request.LastName, role);
db.Users.Add(user); db.Users.Add(user);
await db.SaveChangesAsync(ct); 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.");
}
await SendEmailTokenAsync(user, TokenType.EmailConfirm, ct); await SendEmailTokenAsync(user, TokenType.EmailConfirm, ct);
return UserDto.From(user); return UserDto.From(user);
@@ -123,9 +128,18 @@ 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
View File
@@ -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
+2
View File
@@ -0,0 +1,2 @@
FROM mariadb:11.4
COPY --chmod=0644 01-accounts.sh /docker-entrypoint-initdb.d/01-accounts.sh
+12 -5
View File
@@ -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
View File
@@ -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í |
+36 -23
View File
@@ -4,8 +4,8 @@ Nativní český klient univerzitního helpdesku pro Android 8.0+ (API 26), naps
## Spuštění ## Spuštění
1. Použijte Android Studio **Meerkat (2024.3.1) nebo novější s podporou AGP 8.9.x**. Staré Android Studio Flamingo podporuje nejvýše AGP 8.0.x a tento projekt v něm nelze synchronizovat. V Android Studiu otevřete **tuto složku `mobile`** jako projekt. 1. Použijte Android Studio **Narwhal 3 Feature Drop (2025.1.3) nebo novější kompatibilní verzi s podporou AGP 8.13.x**. V Android Studiu otevřete **tuto složku `mobile`** jako projekt. Podporované kombinace uvádí [oficiální tabulka kompatibility](https://developer.android.com/build/releases/about-agp).
2. Použijte Gradle JDK 17 nebo novější kompatibilní s Gradle 8.12.1. Doporučený je JDK 17; Gradle wrapper je součástí repozitáře. 2. Použijte Gradle JDK 17 nebo novější kompatibilní s Gradle 8.13. Gradle wrapper je součástí repozitáře.
3. Nainstalujte Android SDK Platform 35 a Build Tools 35.0.0. Android Studio SDK vyhledá automaticky, případně nastavte `sdk.dir` v necommitovaném `local.properties`. 3. Nainstalujte Android SDK Platform 35 a Build Tools 35.0.0. Android Studio SDK vyhledá automaticky, případně nastavte `sdk.dir` v necommitovaném `local.properties`.
4. Spusťte modul `app` na emulátoru nebo připojeném telefonu. 4. Spusťte modul `app` na emulátoru nebo připojeném telefonu.
@@ -22,7 +22,7 @@ Na Linuxu/macOS použijte `sh ./gradlew`. Debug APK se vytvoří v `app/build/ou
### Chyba „Latest supported version is AGP 8.0.2“ ### Chyba „Latest supported version is AGP 8.0.2“
Tato hláška označuje omezení nainstalovaného Android Studia. Aktualizujte IDE přes **Help → Check for Updates**, případně nainstalujte stabilní verzi z [oficiální stránky](https://developer.android.com/studio). Projekt používá AGP 8.9.2, Gradle wrapper 8.12.1 a SDK 35; po aktualizaci otevřete složku `mobile` a zvolte **File → Sync Project with Gradle Files**. V **Settings → Build, Execution, Deployment → Build Tools → Gradle** používejte Gradle wrapper projektu a Gradle JDK 17 (nebo kompatibilní novější JDK). Tato hláška označuje omezení nainstalovaného Android Studia. Aktualizujte IDE přes **Help → Check for Updates**, případně nainstalujte stabilní verzi z [oficiální stránky](https://developer.android.com/studio). Projekt používá AGP 8.13.2, Gradle wrapper 8.13 a SDK 35; po aktualizaci otevřete složku `mobile` a zvolte **File → Sync Project with Gradle Files**. V **Settings → Build, Execution, Deployment → Build Tools → Gradle** používejte Gradle wrapper projektu a Gradle JDK 17 (nebo kompatibilní novější JDK).
Samotná změna AGP na 8.0.2 není vhodná: API 35 oficiálně vyžaduje minimálně AGP 8.6.0 a bylo by nutné společně upravit SDK i knihovny. Přehled podporovaných kombinací: [Android Studio a AGP](https://developer.android.com/build/releases/about-agp). Samotná změna AGP na 8.0.2 není vhodná: API 35 oficiálně vyžaduje minimálně AGP 8.6.0 a bylo by nutné společně upravit SDK i knihovny. Přehled podporovaných kombinací: [Android Studio a AGP](https://developer.android.com/build/releases/about-agp).
@@ -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 `API_PORT=8081` | `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ý, přidejte do `deploy/.env` například `API_PORT=8081` 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). 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; současný backend zapisuje odkaz do logu místo skutečného odeslání. 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,27 +55,30 @@ 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í |
| Nástěnka, seznam a detail vlastních závad, filtry, stránkování | Hotovo, budoucí API adaptér + ukázka | Zatím pouze návrh | | Správa kategorií a statistiky vedení | Mimo rozsah mobilních obrazovek | Implementovány příslušné administrační a statistické endpointy |
| Nová závada, úprava přijaté závady, fotografie a soubory | Hotovo, budoucí API adaptér + ukázka | Zatím pouze návrh | | Nástěnka, seznam a detail vlastních závad, filtry, stránkování | Napojeno na skutečné API | Implementován |
| Komentáře, časová osa, stažení příloh | Hotovo, budoucí API adaptér + ukázka | Zatím pouze návrh | | Nová závada, úprava přijaté závady, fotografie a soubory | Napojeno na skutečné API | Implementován |
| Pracovní fronta řešitele a serverem povolené změny stavu | Hotovo, podle `allowedActions` | Zatím pouze návrh | | Komentáře, časová osa, stažení příloh | Napojeno na skutečné API | Implementován |
| Seznam, detail, nový návrh, hlas pro/proti/zrušení | Hotovo, budoucí API adaptér + ukázka | Zatím pouze návrh | | Pracovní fronta řešitele a serverem povolené změny stavu | Napojeno podle `allowedActions` a `rowVersion` | Implementován |
| Seznam oznámení, označení přečtení a otevření záznamu | Hotovo, budoucí API adaptér + ukázka | Zatím pouze návrh | | Seznam, detail, nový návrh, hlas pro/proti/zrušení | Napojeno včetně uzavřeného hlasování | Implementován |
| Push notifikace (Firebase Cloud Messaging) | Nezapojeno | Chybí `/devices` a doručová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 | Registrace `/devices` a doručovací fronta implementovány; vyžaduje `FIREBASE_SERVICE_ACCOUNT_JSON` |
Při chybějícím endpointu aplikace zobrazí vysvětlení, nesimuluje úspěch. Funkce závad, návrhů a oznámení proto nyní lze celé projít v ukázce. Jejich skutečná integrace potřebuje implementaci serveru a sjednocení detailních DTO, která návrhový dokument dosud nedefinuje. Administrační a analytické obrazovky 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.
Budoucí adaptér vychází z [návrhu REST API](../docs/navrh-aplikace.md#11-návrh-rest-api). Přesný **předpokládaný** tvar odpovědí a požadavků je v `data/Models.kt` a rozhraní endpointů v `data/RemoteRepository.kt`: 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.
- Detail závady obsahuje názvy budovy/kategorie/osob, `rowVersion` jako celé číslo, `allowedActions` a přílohy `{ id, fileName, contentType }`. Události se čtou samostatně přes `GET /issues/{id}/events` jako pole `{ id, authorName, type, text, createdAt }`. - 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.
- `allowedActions` může obsahovat endpointové kódy `start`, `submit-for-verification`, `confirm`, `reopen`, `reject`, `comment`, `attachments`, `edit` nebo odpovídající kódy `START_WORK`, `SUBMIT_FOR_VERIFICATION`, `CONFIRM_RESOLUTION`, `ADD_COMMENT`, `ADD_ATTACHMENT`, `EDIT`. Pravidla a povolené přechody zůstávají na serveru. - 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.
- Vytvoření hlášení posílá `{ title, description, categoryId, buildingId, location }`; úprava přidává `rowVersion`. Přechody posílají `rowVersion`, důvod v `reason` a poznámku v `note`. Konflikt 409 znovu načte detail. - 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 }`.
- Přílohy se nahrávají samostatně jako multipart pole `files` na již vytvořené hlášení, nejvýše 5 × 10 MB, JPG/PNG/HEIC/HEIF/PDF/DOCX. Při selhání uploadu zůstane hlášení uložené a aplikace vyzve k doplnění příloh v detailu; nevytvoří druhé hlášení. - `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í.
- Návrh obsahuje `score`, `myVote` (`1`, `-1` nebo `null`), `note` a údaje autora. Vlastní návrh neumožňuje hlasování. - Vytvoření hlášení posílá `{ title, description, categoryId, buildingId, locationDetail }`; úprava přidává `rowVersion`. Přechody mají vlastní DTO: samotná verze pro zahájení/potvrzení, `reason` pro znovuotevření/zamítnutí nebo `note` pro předání k ověření. Po komentáři a uploadu se také načítá nová verze detailu.
- Oznámení obsahuje `isRead`, volitelné `issueId` / `proposalId`, datum, název a text. - Přílohy se nahrávají samostatně jako multipart pole `files` na již vytvořené hlášení, nejvýše 5 × 10 MB, JPG/JPEG/PNG/HEIC/PDF/DOCX. HEIF server nepodporuje. Při selhání uploadu zůstane hlášení uložené a aplikace vyzve k doplnění příloh v detailu; nevytvoří druhé hlášení. Kontrolu skutečného obsahu souboru provádí server.
- Návrh obsahuje 64bitové `votesFor`, `votesAgainst`, `score` a `myVote` (`1`, `-1` nebo `null`). Detail doplňuje popis a události; vyjádření vedení se čte ze změn stavu v událostech. Hlasování včetně odebrání hlasu je otevřené pouze ve stavech `SUBMITTED` a `UNDER_REVIEW`; autor nemůže hlasovat o vlastním návrhu.
- Oznámení vrací `message` a `readAt`; klient z nich odvozuje text a příznak přečtení. Celkový počet nepřečtených bere z `/notifications/unread-count`, nezapočítává jen načtených 20 položek. „Označit vše“ proto funguje i pro oznámení mimo aktuální stránku.
- Datum/čas používá ISO 8601 s časovou zónou. Chyby odpovídají `ProblemDetails`, včetně validačního `errors`. - Datum/čas používá ISO 8601 s časovou zónou. Chyby odpovídají `ProblemDetails`, včetně validačního `errors`.
## Struktura a bezpečnost ## Struktura a bezpečnost
@@ -82,6 +89,12 @@ Budoucí adaptér vychází z [návrhu REST API](../docs/navrh-aplikace.md#11-n
- `src/test/`: JUnit testy autentizace, rotace tokenů a chyb proti MockWebServer, ukázkové mutace a limity příloh. - `src/test/`: JUnit testy autentizace, rotace tokenů a chyb proti MockWebServer, ukázkové mutace a limity příloh.
- `src/androidTest/`: Compose testy hlavních uživatelských scénářů. - `src/androidTest/`: Compose testy hlavních uživatelských scénářů.
Volitelný `LiveBackendTest` ověřuje skutečné požadavky Android repozitáře proti lokálnímu API a MariaDB: vytvoření/úpravu závady, konflikt verzí, komentáře, upload/download PNG, pracovní frontu a celý životní cyklus závady, hlasování a vyjádření vedení, přečtení oznámení i odhlášení. Spouštějte jej pouze proti samostatnému testovacímu serveru; vytváří testovací záznamy. Vyžaduje proměnné `NTBUG_LIVE_API_URL` (localhost/127.0.0.1), `NTBUG_LIVE_PASSWORD`, `NTBUG_LIVE_REPORTER`, `NTBUG_LIVE_MANAGER` a `NTBUG_LIVE_STAFF`: ověřené účty se společným testovacím heslem, role vedení a správce budov pro příslušné dva účty. Bez URL je test přeskočen. Potom ze složky `mobile` spusťte:
```powershell
.\gradlew.bat :app:testDebugUnitTest --tests 'cz.ntbug.mobile.integration.LiveBackendTest'
```
Hesla se neukládají. Tokeny a profil relace jsou šifrované AES-GCM, klíč zůstává v Android Keystore; zálohování aplikace je vypnuté. Jednorázové refresh tokeny se rotují pod mutexem, dokončení rotace není přerušeno změnou obrazovky; při nejednoznačném výsledku se vyžádá nové přihlášení. Automatické síťové opakování a přesměrování jsou vypnuté. Odhlášení se pokusí zneplatnit tokeny na serveru a vždy smaže místní relaci; pokud server odhlášení nepotvrdí, aplikace to oznámí. Hesla se neukládají. Tokeny a profil relace jsou šifrované AES-GCM, klíč zůstává v Android Keystore; zálohování aplikace je vypnuté. Jednorázové refresh tokeny se rotují pod mutexem, dokončení rotace není přerušeno změnou obrazovky; při nejednoznačném výsledku se vyžádá nové přihlášení. Automatické síťové opakování a přesměrování jsou vypnuté. Odhlášení se pokusí zneplatnit tokeny na serveru a vždy smaže místní relaci; pokud server odhlášení nepotvrdí, aplikace to oznámí.
Fotografie nevyžadují široký přístup k úložišti ani vlastní oprávnění CAMERA: používá se systémový fotoaparát a omezený `FileProvider`. Stažené přílohy se ukládají do soukromé cache a otevírají přes dočasné oprávnění URI. Neodeslané přílohy se ukládají do cache a obnovují přes uložená metadata, takže se zachovají při otočení telefonu i obnovení aktivity; velká data se nevkládají do Android Bundle. Pokud systém cache mezitím odstraní, aplikace vyzve k opětovnému výběru souborů. Aplikace nemá offline frontu ani automatické odesílání na pozadí. Fotografie nevyžadují široký přístup k úložišti ani vlastní oprávnění CAMERA: používá se systémový fotoaparát a omezený `FileProvider`. Stažené přílohy se ukládají do soukromé cache a otevírají přes dočasné oprávnění URI. Neodeslané přílohy se ukládají do cache a obnovují přes uložená metadata, takže se zachovají při otočení telefonu i obnovení aktivity; velká data se nevkládají do Android Bundle. Pokud systém cache mezitím odstraní, aplikace vyzve k opětovnému výběru souborů. Aplikace nemá offline frontu ani automatické odesílání na pozadí.
@@ -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) }
}
}
@@ -3,10 +3,16 @@ package cz.ntbug.mobile
import android.content.Context import android.content.Context
import android.graphics.Bitmap import android.graphics.Bitmap
import androidx.compose.ui.graphics.asAndroidBitmap import androidx.compose.ui.graphics.asAndroidBitmap
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.SideEffect
import androidx.compose.ui.semantics.SemanticsProperties
import androidx.compose.ui.text.AnnotatedString
import androidx.compose.ui.test.* import androidx.compose.ui.test.*
import androidx.compose.ui.test.junit4.createAndroidComposeRule import androidx.compose.ui.test.junit4.createAndroidComposeRule
import androidx.compose.ui.test.junit4.createComposeRule
import androidx.core.view.WindowCompat import androidx.core.view.WindowCompat
import androidx.core.view.WindowInsetsCompat import androidx.core.view.WindowInsetsCompat
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.LargeTest import androidx.test.filters.LargeTest
import androidx.test.platform.app.InstrumentationRegistry import androidx.test.platform.app.InstrumentationRegistry
@@ -16,6 +22,14 @@ import org.junit.rules.ExternalResource
import org.junit.rules.RuleChain import org.junit.rules.RuleChain
import org.junit.runner.RunWith import org.junit.runner.RunWith
import java.io.File import java.io.File
import cz.ntbug.mobile.data.Notice
import cz.ntbug.mobile.data.Issue
import cz.ntbug.mobile.data.Upload
import cz.ntbug.mobile.ui.NTBugTheme
import cz.ntbug.mobile.ui.features.NoticesScreen
import cz.ntbug.mobile.ui.features.IssueDetailScreen
import cz.ntbug.mobile.ui.features.DraftAttachmentsViewModel
import org.junit.Assert.assertEquals
/** Exercises the shipped app through its public UI, without a backend or test-only routes. */ /** Exercises the shipped app through its public UI, without a backend or test-only routes. */
@RunWith(AndroidJUnit4::class) @RunWith(AndroidJUnit4::class)
@@ -70,6 +84,52 @@ class MobileSmokeTest {
compose.onNode(hasText("Pro") and hasClickAction()).assertIsNotSelected() compose.onNode(hasText("Pro") and hasClickAction()).assertIsNotSelected()
} }
@Test
fun closedProposalKeepsExistingVoteAndShowsManagementTimeline() {
enterDemo()
compose.onNodeWithText("Nápady").performClick()
awaitText("Návrhy na zlepšení")
scrollTo("Pítka v univerzitním kampusu")
compose.onNodeWithText("Pítka v univerzitním kampusu").performClick()
awaitText("Detail nápadu")
scrollTo("Co si o návrhu myslíte?")
// This is somebody else's implemented proposal with a previous positive vote.
// It must block changing AND removing that vote, independently of author restrictions.
compose.onNode(hasText("Pro") and hasClickAction()).assertIsSelected().assertIsNotEnabled()
compose.onNode(hasText("Proti") and hasClickAction()).assertIsNotEnabled()
compose.onNode(hasText("Pro") and hasClickAction()).performClick()
compose.onNode(hasText("Pro") and hasClickAction()).assertIsSelected()
scrollTo("Hlasování je uzavřené. Hlas již nelze změnit ani zrušit.")
compose.onNodeWithText("Hlasování je uzavřené. Hlas již nelze změnit ani zrušit.").assertIsDisplayed()
scrollTo("Přijat → Realizován")
compose.onNodeWithText("Přijat → Realizován").assertIsDisplayed()
compose.onAllNodesWithText("Vyjádření vedení").onFirst().assertExists()
scrollTo("Pítka jsou nainstalována a připravena k používání.")
compose.onNodeWithText("Pítka jsou nainstalována a připravena k používání.").assertIsDisplayed()
}
@Test
fun serverActionsAllowCommentAttachmentsAndResolutionConfirmation() {
enterDemo()
scrollTo("Nesvítí světlo na chodbě")
compose.onNodeWithText("Nesvítí světlo na chodbě").performClick()
awaitText("Detail hlášení")
scrollTo("Napsat komentář")
field("Napsat komentář").assertIsEnabled()
scrollTo("Doplnit přílohy")
compose.onNodeWithText("Vyfotit").assertIsEnabled()
compose.onNodeWithText("Přiložit").assertIsEnabled()
// Demo uses the real COMMENT, ADD_ATTACHMENTS and CONFIRM server action codes.
scrollTo("Potvrdit vyřešení")
compose.onNodeWithText("Potvrdit vyřešení").performClick()
awaitText("Stav hlášení byl aktualizován.")
scrollTo("HLÁŠENÍ #103")
compose.onNodeWithText("Vyřešena").assertIsDisplayed()
}
@Test @Test
fun issueRequiresCategoryAndPersistsCreationAndComment() { fun issueRequiresCategoryAndPersistsCreationAndComment() {
val title = "Testovací závada ve studovně" val title = "Testovací závada ve studovně"
@@ -80,7 +140,10 @@ class MobileSmokeTest {
scrollTo("Název závady *") scrollTo("Název závady *")
field("Název závady *").performTextInput(title) field("Název závady *").performTextInput(title)
hideKeyboard()
scrollTo("Co se stalo? *") scrollTo("Co se stalo? *")
field("Co se stalo? *").performClick()
compose.waitForIdle()
field("Co se stalo? *").performTextInput("Zásuvka u stolu nefunguje ani s jinou nabíječkou.") field("Co se stalo? *").performTextInput("Zásuvka u stolu nefunguje ani s jinou nabíječkou.")
hideKeyboard() hideKeyboard()
scrollTo("Odeslat hlášení") scrollTo("Odeslat hlášení")
@@ -97,7 +160,7 @@ class MobileSmokeTest {
compose.onNodeWithText("Odeslat hlášení").performClick() compose.onNodeWithText("Odeslat hlášení").performClick()
awaitText("Detail hlášení") awaitText("Detail hlášení")
awaitText(title) awaitText(title)
compose.onNodeWithText("Přijata").assertExists() compose.onAllNodesWithText("Přijata").onFirst().assertExists()
scrollTo("Napsat komentář") scrollTo("Napsat komentář")
field("Napsat komentář").performTextInput(comment) field("Napsat komentář").performTextInput(comment)
@@ -154,3 +217,87 @@ class MobileSmokeTest {
compose.waitForIdle() compose.waitForIdle()
} }
} }
@RunWith(AndroidJUnit4::class)
class NoticesSummaryUiTest {
@get:Rule
val compose = createComposeRule()
@Test
fun readAllUsesTotalUnreadCountBeyondTheLoadedPage() {
var readAllCalls = 0
val readPage = (1..20).map { id -> Notice(id, "Oznámení $id", "Již přečtená zpráva", "2026-11-19T10:00:00Z", isRead = true) }
compose.setContent {
NTBugTheme {
NoticesScreen(readPage, onOpen = {}, onReadAll = { readAllCalls++ }, onLoadMore = {}, hasMore = true, unreadCount = 3)
}
}
compose.onNodeWithText("Označit vše jako přečtené").assertIsDisplayed().performClick()
compose.runOnIdle { assertEquals(1, readAllCalls) }
}
}
@RunWith(AndroidJUnit4::class)
class IssueMutationAcknowledgementTest {
@get:Rule
val compose = createComposeRule()
@Test
fun acknowledgedCommentClearsDraftWithoutRefreshedIssue() {
val issue = unchangedIssue()
var submitted: String? = null
compose.setContent {
NTBugTheme {
IssueDetailScreen(issue, busy = false,
onComment = { text, acknowledged -> submitted = text; acknowledged() },
onAction = { _, _ -> }, onAttachments = { _, _ -> })
}
}
scrollTo("Napsat komentář")
val editor = compose.onNode(hasSetTextAction() and hasText("Napsat komentář"))
editor.performTextInput("Komentář potvrzený serverem")
scrollTo("Odeslat komentář")
compose.onNodeWithText("Odeslat komentář").performClick()
// The immutable Issue still has no events: only the POST acknowledgement can clear this.
editor.assert(SemanticsMatcher.expectValue(SemanticsProperties.EditableText, AnnotatedString("")))
compose.onNodeWithText("Odeslat komentář").assertIsNotEnabled()
compose.runOnIdle { assertEquals("Komentář potvrzený serverem", submitted); assertEquals(0, issue.events.size) }
}
@Test
fun acknowledgedUploadClearsCachedDraftWithoutRefreshedIssue() {
val issue = unchangedIssue()
var draft: DraftAttachmentsViewModel? = null
var uploads = 0
val file = Upload("rozepsana.pdf", "application/pdf", "%PDF-1.4\nDraft".toByteArray())
compose.setContent {
NTBugTheme {
val holder: DraftAttachmentsViewModel = viewModel()
SideEffect { draft = holder }
LaunchedEffect(Unit) { holder.replace(listOf(file)) }
IssueDetailScreen(issue, busy = false, onComment = { _, _ -> }, onAction = { _, _ -> },
onAttachments = { files, acknowledged -> uploads += files.size; acknowledged() })
}
}
compose.waitUntil(15_000) { draft?.let { !it.busy && it.files.size == 1 } == true }
scrollTo("Nahrát přílohy")
compose.onNodeWithText("Nahrát přílohy").performClick()
compose.waitUntil(15_000) { draft?.let { !it.busy && it.files.isEmpty() } == true }
// No GET refresh or attachment list update occurs; acknowledged files cannot be sent again.
compose.onNodeWithText("Nahrát přílohy").assertDoesNotExist()
compose.runOnIdle { assertEquals(1, uploads); assertEquals(0, issue.attachments.size) }
}
private fun scrollTo(text: String) {
compose.onNode(hasScrollToIndexAction()).performScrollToNode(hasText(text))
}
private fun unchangedIssue() = Issue(
id = 9, title = "Oprava dveří", description = "Dveře se nedovírají.", status = "IN_PROGRESS",
categoryId = 1, categoryName = "Ostatní", reporterId = 1, reporterName = "Testovací uživatel",
createdAt = "2026-11-19T10:00:00Z", allowedActions = listOf("COMMENT", "ADD_ATTACHMENTS"),
)
}
@@ -11,19 +11,26 @@ class DemoRepository : HelpdeskRepository {
listOf(Category(1, "Studium"), Category(2, "Služby"), Category(3, "Prostředí"), Category(4, "Ostatní")), listOf(Category(1, "Studium"), Category(2, "Služby"), Category(3, "Prostředí"), Category(4, "Ostatní")),
) )
private val issueItems = mutableListOf( private val issueItems = mutableListOf(
Issue(104, "Nefunkční projektor v B-205", "Projektor po zapnutí bliká a nezobrazuje obraz. Vyzkoušeli jsme také jiný HDMI kabel.", "IN_PROGRESS", 1, "Technické vybavení", 2, "Budova B", "Učebna B-205, 2. patro", 1, "Jana Nováková", "Petr Svoboda", "2026-11-03T09:15:00Z", 3, listOf("comment", "attachments"), Issue(104, "Nefunkční projektor v B-205", "Projektor po zapnutí bliká a nezobrazuje obraz. Vyzkoušeli jsme také jiný HDMI kabel.", "IN_PROGRESS", 1, "Technické vybavení", 2, "Budova B", "Učebna B-205, 2. patro", 1, "Jana Nováková", "Petr Svoboda", "2026-11-03T09:15:00Z", 3, listOf("COMMENT", "ADD_ATTACHMENTS"),
listOf(IssueEvent(1, "Jana Nováková", "CREATED", "Závada byla přijata.", "2026-11-03T09:15:00Z"), IssueEvent(2, "Vedení školy", "ASSIGNED", "Přiřazeno správci Petr Svoboda.", "2026-11-03T11:30:00Z"), IssueEvent(3, "Petr Svoboda", "COMMENTED", "Projektor zkontroluji a objednám náhradní lampu.", "2026-11-04T08:30:00Z"))), listOf(IssueEvent(1, "Jana Nováková", "CREATED", "Závada byla přijata.", "2026-11-03T09:15:00Z"), IssueEvent(2, "Vedení školy", "ASSIGNED", "Přiřazeno správci Petr Svoboda.", "2026-11-03T11:30:00Z"), IssueEvent(3, "Petr Svoboda", "COMMENTED", "Projektor zkontroluji a objednám náhradní lampu.", "2026-11-04T08:30:00Z"))),
Issue(103, "Nesvítí světlo na chodbě", "Na chodbě u učebny A-112 nesvítí jedno ze stropních světel.", "PENDING_VERIFICATION", 2, "Elektroinstalace", 1, "Budova A", "Chodba, 1. patro", 1, "Jana Nováková", "Petr Svoboda", "2026-11-02T13:00:00Z", 4, listOf("confirm", "reopen", "comment", "attachments"), Issue(103, "Nesvítí světlo na chodbě", "Na chodbě u učebny A-112 nesvítí jedno ze stropních světel.", "PENDING_VERIFICATION", 2, "Elektroinstalace", 1, "Budova A", "Chodba, 1. patro", 1, "Jana Nováková", "Petr Svoboda", "2026-11-02T13:00:00Z", 4, listOf("CONFIRM", "REOPEN", "COMMENT", "ADD_ATTACHMENTS"),
listOf(IssueEvent(4, "Jana Nováková", "CREATED", "Závada byla přijata.", "2026-11-02T13:00:00Z"), IssueEvent(5, "Petr Svoboda", "STATUS_CHANGED", "Svítidlo je opravené. Prosím o ověření.", "2026-11-04T14:00:00Z"))), listOf(IssueEvent(4, "Jana Nováková", "CREATED", "Závada byla přijata.", "2026-11-02T13:00:00Z"), IssueEvent(5, "Petr Svoboda", "STATUS_CHANGED", "Svítidlo je opravené. Prosím o ověření.", "2026-11-04T14:00:00Z"))),
Issue(102, "Uvolněná klika u studovny", "Klika u vstupu do tiché studovny se viklá.", "RECEIVED", 5, "Ostatní", 3, "Knihovna", "Tichá studovna", 1, "Jana Nováková", null, "2026-11-01T10:00:00Z", 1, listOf("edit", "comment", "attachments"), Issue(102, "Uvolněná klika u studovny", "Klika u vstupu do tiché studovny se viklá.", "RECEIVED", 5, "Ostatní", 3, "Knihovna", "Tichá studovna", 1, "Jana Nováková", null, "2026-11-01T10:00:00Z", 1, listOf("EDIT", "COMMENT", "ADD_ATTACHMENTS"),
listOf(IssueEvent(6, "Jana Nováková", "CREATED", "Závada byla přijata.", "2026-11-01T10:00:00Z"))), listOf(IssueEvent(6, "Jana Nováková", "CREATED", "Závada byla přijata.", "2026-11-01T10:00:00Z"))),
Issue(101, "Kapající kohoutek", "Na toaletách v přízemí kapala voda z kohoutku.", "RESOLVED", 3, "Voda a topení", 1, "Budova A", "Toalety v přízemí", 1, "Jana Nováková", "Petr Svoboda", "2026-10-27T08:00:00Z", 5, emptyList(), Issue(101, "Kapající kohoutek", "Na toaletách v přízemí kapala voda z kohoutku.", "RESOLVED", 3, "Voda a topení", 1, "Budova A", "Toalety v přízemí", 1, "Jana Nováková", "Petr Svoboda", "2026-10-27T08:00:00Z", 5, emptyList(),
listOf(IssueEvent(7, "Jana Nováková", "CREATED", "Závada byla přijata.", "2026-10-27T08:00:00Z"), IssueEvent(8, "Jana Nováková", "STATUS_CHANGED", "Vyřešení potvrzeno. Děkuji za opravu!", "2026-10-29T10:00:00Z"))), listOf(IssueEvent(7, "Jana Nováková", "CREATED", "Závada byla přijata.", "2026-10-27T08:00:00Z"), IssueEvent(8, "Jana Nováková", "STATUS_CHANGED", "Vyřešení potvrzeno. Děkuji za opravu!", "2026-10-29T10:00:00Z"))),
) ).apply {
replaceAll { issue -> if (issue.assigneeName != null) issue.copy(assigneeId = 2) else issue }
}
private val proposalItems = mutableListOf( private val proposalItems = mutableListOf(
Proposal(21, "Více zásuvek ve studovně", "Doplňme zásuvky ke stolům v knihovně, abychom mohli pohodlně pracovat na notebooku i během delšího studia.", 3, "Prostředí", 2, "Adam Dvořák", "UNDER_REVIEW", 42, null, "2026-10-30T10:00:00Z", "Ověřujeme možnosti doplnění zásuvek."), Proposal(21, "Více zásuvek ve studovně", "Doplňme zásuvky ke stolům v knihovně, abychom mohli pohodlně pracovat na notebooku i během delšího studia.", 3, "Prostředí", 2, "Adam Dvořák", "UNDER_REVIEW", 42, null, "2026-10-30T10:00:00Z", "Ověřujeme možnosti doplnění zásuvek.", votesFor = 45, votesAgainst = 3,
Proposal(22, "Delší otevírací doba knihovny", "Během zkouškového období bychom uvítali otevření knihovny až do 22 hodin.", 2, "Služby", 3, "Tereza Malá", "SUBMITTED", 28, null, "2026-11-02T12:00:00Z"), events = listOf(ProposalEvent(1, "Adam Dvořák", "CREATED", "Návrh byl podán.", "2026-10-30T10:00:00Z", 2, null, "SUBMITTED"), ProposalEvent(2, "Vedení školy", "STATUS_CHANGED", "Ověřujeme možnosti doplnění zásuvek.", "2026-11-02T08:00:00Z", 5, "SUBMITTED", "UNDER_REVIEW"))),
Proposal(23, "Stojany na kola u budovy B", "Kryté stojany by zpříjemnily dojíždění do školy na kole.", 3, "Prostředí", 1, "Jana Nováková", "ACCEPTED", 17, null, "2026-10-28T09:00:00Z", "Návrh byl přijat. Instalaci plánujeme na jaro."), Proposal(22, "Delší otevírací doba knihovny", "Během zkouškového období bychom uvítali otevření knihovny až do 22 hodin.", 2, "Služby", 3, "Tereza Malá", "SUBMITTED", 28, null, "2026-11-02T12:00:00Z", votesFor = 30, votesAgainst = 2,
events = listOf(ProposalEvent(3, "Tereza Malá", "CREATED", "Návrh byl podán.", "2026-11-02T12:00:00Z", 3, null, "SUBMITTED"))),
Proposal(23, "Stojany na kola u budovy B", "Kryté stojany by zpříjemnily dojíždění do školy na kole.", 3, "Prostředí", 1, "Jana Nováková", "ACCEPTED", 17, null, "2026-10-28T09:00:00Z", "Návrh byl přijat. Instalaci plánujeme na jaro.", votesFor = 18, votesAgainst = 1,
events = listOf(ProposalEvent(4, "Jana Nováková", "CREATED", "Návrh byl podán.", "2026-10-28T09:00:00Z", 1, null, "SUBMITTED"), ProposalEvent(5, "Vedení školy", "STATUS_CHANGED", "Návrh byl přijat. Instalaci plánujeme na jaro.", "2026-11-03T09:00:00Z", 5, "SUBMITTED", "ACCEPTED"))),
Proposal(24, "Pítka v univerzitním kampusu", "Na frekventovaných místech kampusu budou dostupná pítka s pitnou vodou.", 3, "Prostředí", 4, "Martin Černý", "IMPLEMENTED", 35, 1, "2026-10-20T09:00:00Z", "Pítka jsou nainstalována a připravena k používání.", votesFor = 40, votesAgainst = 5,
events = listOf(ProposalEvent(6, "Martin Černý", "CREATED", "Návrh byl podán.", "2026-10-20T09:00:00Z", 4, null, "SUBMITTED"), ProposalEvent(7, "Vedení školy", "STATUS_CHANGED", "Instalaci pítek jsme schválili.", "2026-10-25T09:00:00Z", 5, "SUBMITTED", "ACCEPTED"), ProposalEvent(8, "Vedení školy", "STATUS_CHANGED", "Pítka jsou nainstalována a připravena k používání.", "2026-11-03T11:00:00Z", 5, "ACCEPTED", "IMPLEMENTED"))),
) )
private val noticeItems = mutableListOf( private val noticeItems = mutableListOf(
Notice(1, "Ověřte opravu světla", "Správce dokončil opravu. Potvrďte, zda světlo na chodbě opět funguje.", "2026-11-04T14:00:00Z", false, issueId = 103), Notice(1, "Ověřte opravu světla", "Správce dokončil opravu. Potvrďte, zda světlo na chodbě opět funguje.", "2026-11-04T14:00:00Z", false, issueId = 103),
@@ -45,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,
) )
@@ -54,8 +61,8 @@ class DemoRepository : HelpdeskRepository {
require(issue.title.isNotBlank() && issue.description.isNotBlank()) { "Vyplňte název a popis závady." } require(issue.title.isNotBlank() && issue.description.isNotBlank()) { "Vyplňte název a popis závady." }
val category = catalog.issueCategories.firstOrNull { it.id == issue.categoryId } ?: throw IllegalArgumentException("Vyberte kategorii.") val category = catalog.issueCategories.firstOrNull { it.id == issue.categoryId } ?: throw IllegalArgumentException("Vyberte kategorii.")
val building = issue.buildingId?.let { id -> catalog.buildings.first { it.id == id } } val building = issue.buildingId?.let { id -> catalog.buildings.first { it.id == id } }
val created = Issue((issueItems.maxOfOrNull { it.id } ?: 0) + 1, issue.title.trim(), issue.description.trim(), "RECEIVED", category.id, category.name, building?.id, building?.name, issue.location.trim(), user.id, name(), null, now(), 1, listOf("edit", "comment", "attachments"), val created = Issue((issueItems.maxOfOrNull { it.id } ?: 0) + 1, issue.title.trim(), issue.description.trim(), "RECEIVED", category.id, category.name, building?.id, building?.name, issue.location.trim(), user.id, name(), null, now(), 0, listOf("EDIT", "COMMENT", "ADD_ATTACHMENTS"),
listOf(IssueEvent(nextEventId(), name(), "CREATED", "Závada byla přijata.", now()))) listOf(IssueEvent(nextEventId(), name(), "CREATED", "Závada byla přijata.", now(), user.id, null, "RECEIVED")))
issueItems.add(0, created) issueItems.add(0, created)
addNotice("Hlášení bylo přijato", created.title, issueId = created.id) addNotice("Hlášení bylo přijato", created.title, issueId = created.id)
return created return created
@@ -69,18 +76,19 @@ class DemoRepository : HelpdeskRepository {
if (old.reporterId != user.id || old.status != "RECEIVED") throw ApiException(403, "Upravit lze pouze vlastní hlášení ve stavu Přijata.") if (old.reporterId != user.id || old.status != "RECEIVED") throw ApiException(403, "Upravit lze pouze vlastní hlášení ve stavu Přijata.")
old.copy(title = issue.title.trim(), description = issue.description.trim(), categoryId = category.id, categoryName = category.name, old.copy(title = issue.title.trim(), description = issue.description.trim(), categoryId = category.id, categoryName = category.name,
buildingId = building?.id, buildingName = building?.name, location = issue.location.trim(), buildingId = building?.id, buildingName = building?.name, location = issue.location.trim(),
events = old.events + IssueEvent(nextEventId(), name(), "UPDATED", "Hlášení bylo upraveno.", now())) events = old.events + IssueEvent(nextEventId(), name(), "UPDATED", "Hlášení bylo upraveno.", now(), user.id, null, old.status))
} }
return this.issue(id) return this.issue(id)
} }
override suspend fun addAttachments(id: Int, files: List<Upload>) { override suspend fun addAttachments(id: Int, files: List<Upload>) {
validateUploads(files) validateUploads(files)
changeIssue(id) { old -> changeIssue(id) { old ->
ensureAllowed(old, "attachments") ensureAllowed(old, "ADD_ATTACHMENTS")
old.copy(attachments = old.attachments + files.map { upload -> old.copy(attachments = old.attachments + files.map { upload ->
val attachmentId = nextAttachmentId++ val attachmentId = nextAttachmentId++
uploadedFiles[attachmentId] = upload.copy(bytes = upload.bytes.copyOf()) val name = uploadBaseName(upload.name)
Attachment(attachmentId, upload.name, upload.mimeType) uploadedFiles[attachmentId] = upload.copy(name = name, bytes = upload.bytes.copyOf())
Attachment(attachmentId, name, upload.mimeType)
}) })
} }
} }
@@ -89,14 +97,22 @@ class DemoRepository : HelpdeskRepository {
override suspend fun comment(id: Int, text: String) { override suspend fun comment(id: Int, text: String) {
require(text.isNotBlank()) { "Napište komentář." } require(text.isNotBlank()) { "Napište komentář." }
changeIssue(id) { old -> changeIssue(id) { old ->
ensureAllowed(old, "comment") ensureAllowed(old, "COMMENT")
old.copy(events = old.events + IssueEvent(nextEventId(), name(), "COMMENTED", text.trim(), now())) old.copy(events = old.events + IssueEvent(nextEventId(), name(), "COMMENTED", text.trim(), now(), user.id, null, old.status))
} }
} }
override suspend fun issueAction(id: Int, action: String, rowVersion: Int, reason: String) { override suspend fun issueAction(id: Int, action: String, rowVersion: Int, reason: String) {
changeIssue(id) { old -> changeIssue(id) { old ->
if (old.rowVersion != rowVersion) throw ApiException(409, "Záznam se mezitím změnil. Obnovte jej.") if (old.rowVersion != rowVersion) throw ApiException(409, "Záznam se mezitím změnil. Obnovte jej.")
ensureAllowed(old, action) val serverAction = when (action) {
"start" -> "START_WORK"
"submit-for-verification" -> "SUBMIT_FOR_VERIFICATION"
"confirm" -> "CONFIRM"
"reopen" -> "REOPEN"
"reject" -> "REJECT"
else -> throw IllegalArgumentException("Neznámá akce.")
}
ensureAllowed(old, serverAction)
if (action in listOf("reopen", "reject")) require(reason.isNotBlank()) { "Uveďte důvod." } if (action in listOf("reopen", "reject")) require(reason.isNotBlank()) { "Uveďte důvod." }
val status = when (action) { val status = when (action) {
"start", "reopen" -> "IN_PROGRESS" "start", "reopen" -> "IN_PROGRESS"
@@ -107,10 +123,10 @@ class DemoRepository : HelpdeskRepository {
} }
val actions = when (status) { val actions = when (status) {
"RESOLVED", "REJECTED" -> emptyList() "RESOLVED", "REJECTED" -> emptyList()
"PENDING_VERIFICATION" -> listOf("confirm", "reopen", "comment", "attachments") "PENDING_VERIFICATION" -> listOf("CONFIRM", "REOPEN", "COMMENT", "ADD_ATTACHMENTS")
else -> listOf("comment", "attachments") else -> listOf("COMMENT", "ADD_ATTACHMENTS")
} }
old.copy(status = status, allowedActions = actions, events = old.events + IssueEvent(nextEventId(), name(), "STATUS_CHANGED", reason.ifBlank { if (status == "RESOLVED") "Vyřešení bylo potvrzeno." else "Změna stavu hlášení." }, now())) old.copy(status = status, allowedActions = actions, events = old.events + IssueEvent(nextEventId(), name(), "STATUS_CHANGED", reason.ifBlank { if (status == "RESOLVED") "Vyřešení bylo potvrzeno." else "Změna stavu hlášení." }, now(), user.id, old.status, status))
} }
} }
override suspend fun proposals(page: Int, query: String, sort: String): Page<Proposal> { override suspend fun proposals(page: Int, query: String, sort: String): Page<Proposal> {
@@ -121,7 +137,8 @@ class DemoRepository : HelpdeskRepository {
override suspend fun createProposal(proposal: NewProposal): Proposal { override suspend fun createProposal(proposal: NewProposal): Proposal {
require(proposal.title.isNotBlank() && proposal.description.isNotBlank()) { "Vyplňte název a popis návrhu." } require(proposal.title.isNotBlank() && proposal.description.isNotBlank()) { "Vyplňte název a popis návrhu." }
val category = catalog.proposalCategories.firstOrNull { it.id == proposal.categoryId } ?: throw IllegalArgumentException("Vyberte oblast.") val category = catalog.proposalCategories.firstOrNull { it.id == proposal.categoryId } ?: throw IllegalArgumentException("Vyberte oblast.")
val created = Proposal((proposalItems.maxOfOrNull { it.id } ?: 0) + 1, proposal.title.trim(), proposal.description.trim(), category.id, category.name, user.id, name(), "SUBMITTED", 0, null, now()) val created = Proposal((proposalItems.maxOfOrNull { it.id } ?: 0) + 1, proposal.title.trim(), proposal.description.trim(), category.id, category.name, user.id, name(), "SUBMITTED", 0, null, now(),
events = listOf(ProposalEvent((proposalItems.flatMap { it.events }.maxOfOrNull { it.id } ?: 0) + 1, name(), "CREATED", "Návrh byl podán.", now(), user.id, null, "SUBMITTED")))
proposalItems.add(0, created) proposalItems.add(0, created)
return created return created
} }
@@ -129,10 +146,14 @@ class DemoRepository : HelpdeskRepository {
require(value == null || value == 1 || value == -1) { "Neplatná hodnota hlasu." } require(value == null || value == 1 || value == -1) { "Neplatná hodnota hlasu." }
val proposal = proposal(id) val proposal = proposal(id)
if (proposal.authorId == user.id) throw ApiException(403, "Pro vlastní návrh nemůžete hlasovat.") if (proposal.authorId == user.id) throw ApiException(403, "Pro vlastní návrh nemůžete hlasovat.")
if (proposal.status !in listOf("SUBMITTED", "UNDER_REVIEW")) throw ApiException(409, "Hlasování je uzavřeno.")
val index = proposalItems.indexOfFirst { it.id == id } val index = proposalItems.indexOfFirst { it.id == id }
proposalItems[index] = proposal.copy(score = proposal.score - (proposal.myVote ?: 0) + (value ?: 0), myVote = value) val votesFor = proposal.votesFor - (if (proposal.myVote == 1) 1L else 0L) + (if (value == 1) 1L else 0L)
val votesAgainst = proposal.votesAgainst - (if (proposal.myVote == -1) 1L else 0L) + (if (value == -1) 1L else 0L)
proposalItems[index] = proposal.copy(score = votesFor - votesAgainst, myVote = value, votesFor = votesFor, votesAgainst = votesAgainst)
} }
override suspend fun notices(page: Int): Page<Notice> = paginate(noticeItems.sortedByDescending { it.createdAt }, page) override suspend fun notices(page: Int): Page<Notice> = paginate(noticeItems.sortedByDescending { it.createdAt }, page)
override suspend fun unreadCount(): Int = noticeItems.count { !it.isRead }
override suspend fun readNotice(id: Int) { override suspend fun readNotice(id: Int) {
val index = noticeItems.indexOfFirst { it.id == id } val index = noticeItems.indexOfFirst { it.id == id }
if (index >= 0) noticeItems[index] = noticeItems[index].copy(isRead = true) if (index >= 0) noticeItems[index] = noticeItems[index].copy(isRead = true)
@@ -22,19 +22,23 @@ data class Category(val id: Int, val name: String, val description: String? = nu
data class Catalogs(val buildings: List<Building>, val issueCategories: List<Category>, val proposalCategories: List<Category>) data class Catalogs(val buildings: List<Building>, val issueCategories: List<Category>, val proposalCategories: List<Category>)
/** Contract for the planned issue endpoints; the current server does not expose them yet. */ /** Screen model; REST summaries/details are mapped separately in WireDtos.kt. */
@Serializable @Serializable
data class Issue( data class Issue(
val id: Int, val title: String, val description: String, val status: String, val id: Int, val title: String, val description: String, val status: String,
val categoryId: Int, val categoryName: String, val buildingId: Int? = null, val categoryId: Int, val categoryName: String, val buildingId: Int? = null,
val buildingName: String? = null, val location: String = "", val reporterId: Int, val buildingName: String? = null, val location: String = "", val reporterId: Int,
val reporterName: String, val assigneeName: String? = null, val createdAt: String, val reporterName: String, val assigneeName: String? = null, val createdAt: String,
val rowVersion: Int = 1, val allowedActions: List<String> = emptyList(), val rowVersion: Int = 0, val allowedActions: List<String> = emptyList(),
val events: List<IssueEvent> = emptyList(), val attachments: List<Attachment> = emptyList(), val events: List<IssueEvent> = emptyList(), val attachments: List<Attachment> = emptyList(),
val assigneeId: Int? = null, val priority: String = "NORMAL",
) )
@Serializable @Serializable
data class IssueEvent(val id: Int, val authorName: String, val type: String, val text: String, val createdAt: String) data class IssueEvent(
val id: Int, val authorName: String, val type: String, val text: String, val createdAt: String,
val actorId: Int? = null, val fromStatus: String? = null, val toStatus: String? = null,
)
@Serializable @Serializable
data class Attachment(val id: Int, val fileName: String, val contentType: String) data class Attachment(val id: Int, val fileName: String, val contentType: String)
@@ -43,7 +47,14 @@ data class Attachment(val id: Int, val fileName: String, val contentType: String
data class Proposal( data class Proposal(
val id: Int, val title: String, val description: String, val categoryId: Int, val id: Int, val title: String, val description: String, val categoryId: Int,
val categoryName: String, val authorId: Int, val authorName: String, val status: String, val categoryName: String, val authorId: Int, val authorName: String, val status: String,
val score: Int, val myVote: Int? = null, val createdAt: String, val note: String? = null, val score: Long, val myVote: Int? = null, val createdAt: String, val note: String? = null,
val votesFor: Long = 0, val votesAgainst: Long = 0, val events: List<ProposalEvent> = emptyList(),
)
@Serializable
data class ProposalEvent(
val id: Int, val authorName: String, val type: String, val text: String, val createdAt: String,
val actorId: Int? = null, val fromStatus: String? = null, val toStatus: String? = null,
) )
@Serializable @Serializable
@@ -77,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
@@ -91,6 +102,7 @@ interface HelpdeskRepository {
suspend fun createProposal(proposal: NewProposal): Proposal suspend fun createProposal(proposal: NewProposal): Proposal
suspend fun vote(id: Int, value: Int?) suspend fun vote(id: Int, value: Int?)
suspend fun notices(page: Int = 1): Page<Notice> suspend fun notices(page: Int = 1): Page<Notice>
suspend fun unreadCount(): Int
suspend fun readNotice(id: Int) suspend fun readNotice(id: Int)
suspend fun readAllNotices() suspend fun readAllNotices()
} }
@@ -65,11 +65,14 @@ class RemoteRepository(baseUrl: String, private val store: SessionPersistence) :
.addConverterFactory(json.asConverterFactory("application/json".toMediaType())) .addConverterFactory(json.asConverterFactory("application/json".toMediaType()))
.build().create(HelpdeskApi::class.java) .build().create(HelpdeskApi::class.java)
private val refreshLock = Mutex() private val refreshLock = Mutex()
private val catalogLock = Mutex()
@Volatile private var catalogCache: Catalogs? = null
@Volatile private var session: AuthSession? = store.read() @Volatile private var session: AuthSession? = store.read()
override suspend fun login(email: String, password: String): User = mapped { override suspend fun login(email: String, password: String): User = mapped {
val response = api.login(LoginRequest(email.trim(), password)) val response = api.login(LoginRequest(email.trim(), password))
store.write(response) store.write(response)
catalogCache = null
session = response session = response
response.user response.user
} }
@@ -117,31 +120,48 @@ class RemoteRepository(baseUrl: String, private val store: SessionPersistence) :
return user return user
} }
override suspend fun catalogs(): Catalogs = Catalogs( override suspend fun catalogs(refresh: Boolean): Catalogs = catalogLock.withLock {
// 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 }
}
override suspend fun issues(page: Int, query: String, status: String?, assigned: Boolean): Page<Issue> = authorized(planned = true) { override suspend fun issues(page: Int, query: String, status: String?, assigned: Boolean): Page<Issue> {
val result = authorized {
api.issues(it, page, query.takeIf(String::isNotBlank), status, !assigned, if (assigned) requireSession().user.id else null) api.issues(it, page, query.takeIf(String::isNotBlank), status, !assigned, if (assigned) requireSession().user.id else null)
} }
override suspend fun issue(id: Int): Issue = authorized(planned = true) { bearer -> if (result.items.isEmpty()) return Page(emptyList(), result.totalCount, result.page, result.pageSize)
val issue = api.issue(bearer, id) val catalog = catalogs()
issue.copy(events = api.events(bearer, id)) val current = requireSession().user
return Page(result.items.map { it.toModel(catalog, current) }, result.totalCount, result.page, result.pageSize)
} }
override suspend fun createIssue(issue: NewIssue): Issue = authorized(planned = true) { api.createIssue(it, issue) } override suspend fun issue(id: Int): Issue {
override suspend fun updateIssue(id: Int, issue: NewIssue, rowVersion: Int): Issue = authorized(planned = true) { val detail = authorized { api.issue(it, id) }
api.updateIssue(it, id, UpdateIssueRequest(issue.title, issue.description, issue.categoryId, issue.buildingId, issue.location, rowVersion)) val events = authorized { api.events(it, id) }
return detail.toModel(catalogs(), requireSession().user, events)
}
override suspend fun createIssue(issue: NewIssue): Issue {
val catalog = catalogs()
val current = requireSession().user
return authorized { api.createIssue(it, issue.toCreateRequest()) }.toModel(catalog, current)
}
override suspend fun updateIssue(id: Int, issue: NewIssue, rowVersion: Int): Issue {
val catalog = catalogs()
val current = requireSession().user
return authorized { api.updateIssue(it, id, issue.toEditRequest(rowVersion)) }.toModel(catalog, current)
} }
override suspend fun addAttachments(id: Int, files: List<Upload>) { override suspend fun addAttachments(id: Int, files: List<Upload>) {
validateUploads(files) validateUploads(files)
if (files.isEmpty()) return if (files.isEmpty()) return
authorized(planned = true) { bearer -> authorized { bearer ->
api.attachments(bearer, id, files.map { file -> api.attachments(bearer, id, files.map { file ->
MultipartBody.Part.createFormData("files", file.name, file.bytes.toRequestBody(file.mimeType.toMediaType())) MultipartBody.Part.createFormData("files", uploadBaseName(file.name), file.bytes.toRequestBody(file.mimeType.toMediaType()))
}) })
} }
} }
override suspend fun downloadAttachment(id: Int): Upload = authorized(planned = true) { bearer -> override suspend fun downloadAttachment(id: Int): Upload = authorized { bearer ->
val response = api.downloadAttachment(bearer, id) val response = api.downloadAttachment(bearer, id)
if (!response.isSuccessful) throw HttpException(response) if (!response.isSuccessful) throw HttpException(response)
val responseBody = response.body() ?: throw ApiException(0, "Server nevrátil obsah přílohy.") val responseBody = response.body() ?: throw ApiException(0, "Server nevrátil obsah přílohy.")
@@ -167,26 +187,52 @@ class RemoteRepository(baseUrl: String, private val store: SessionPersistence) :
} }
} }
} }
override suspend fun comment(id: Int, text: String) = authorized(planned = true) { api.comment(it, id, CommentRequest(text.trim())) } override suspend fun comment(id: Int, text: String) {
authorized { api.comment(it, id, CommentRequest(text.trim())) }
}
override suspend fun issueAction(id: Int, action: String, rowVersion: Int, reason: String) { override suspend fun issueAction(id: Int, action: String, rowVersion: Int, reason: String) {
require(action in listOf("start", "submit-for-verification", "confirm", "reopen", "reject")) { "Neznámá akce závady." } require(action in listOf("start", "submit-for-verification", "confirm", "reopen", "reject")) { "Neznámá akce závady." }
authorized(planned = true) { api.issueAction(it, id, action, ActionRequest(rowVersion, reason.trim(), reason.trim())) } authorized { bearer ->
when (action) {
"start" -> api.startIssue(bearer, id, IssueVersionRequest(rowVersion))
"submit-for-verification" -> api.submitIssue(bearer, id, VerifyIssueRequest(rowVersion, reason.trim().takeIf(String::isNotBlank)))
"confirm" -> api.confirmIssue(bearer, id, IssueVersionRequest(rowVersion))
"reopen" -> api.reopenIssue(bearer, id, IssueReasonRequest(rowVersion, reason.trim()))
"reject" -> api.rejectIssue(bearer, id, IssueReasonRequest(rowVersion, reason.trim()))
else -> throw IllegalArgumentException("Neznámá akce závady.")
} }
override suspend fun proposals(page: Int, query: String, sort: String): Page<Proposal> = authorized(planned = true) {
api.proposals(it, page, query.takeIf(String::isNotBlank), sort)
} }
override suspend fun proposal(id: Int): Proposal = authorized(planned = true) { api.proposal(it, id) } }
override suspend fun createProposal(proposal: NewProposal): Proposal = authorized(planned = true) { api.createProposal(it, proposal) } override suspend fun proposals(page: Int, query: String, sort: String): Page<Proposal> {
val result = authorized { api.proposals(it, page, query.takeIf(String::isNotBlank), sort) }
if (result.items.isEmpty()) return Page(emptyList(), result.totalCount, result.page, result.pageSize)
val catalog = catalogs()
val current = requireSession().user
return Page(result.items.map { it.toModel(catalog, current) }, result.totalCount, result.page, result.pageSize)
}
override suspend fun proposal(id: Int): Proposal {
val result = authorized { api.proposal(it, id) }
return result.toModel(catalogs(), requireSession().user)
}
override suspend fun createProposal(proposal: NewProposal): Proposal {
val catalog = catalogs()
val current = requireSession().user
return authorized { api.createProposal(it, proposal) }.toModel(catalog, current)
}
override suspend fun vote(id: Int, value: Int?) { override suspend fun vote(id: Int, value: Int?) {
require(value == null || value == 1 || value == -1) { "Hlas musí být pro, proti nebo zrušen." } require(value == null || value == 1 || value == -1) { "Hlas musí být pro, proti nebo zrušen." }
authorized(planned = true) { if (value == null) api.removeVote(it, id) else api.vote(it, id, VoteRequest(value)) } authorized { if (value == null) api.removeVote(it, id) else api.vote(it, id, VoteRequest(value)) }
} }
override suspend fun notices(page: Int): Page<Notice> = authorized(planned = true) { api.notices(it, page) } override suspend fun notices(page: Int): Page<Notice> {
override suspend fun readNotice(id: Int) = authorized(planned = true) { api.readNotice(it, id) } val result = authorized { api.notices(it, page) }
override suspend fun readAllNotices() = authorized(planned = true) { api.readAllNotices(it) } return Page(result.items.map(WireNotice::toModel), result.totalCount, result.page, result.pageSize)
}
override suspend fun unreadCount(): Int = authorized { api.unreadCount(it) }.count
override suspend fun readNotice(id: Int) = authorized { api.readNotice(it, id) }
override suspend fun readAllNotices() = authorized { api.readAllNotices(it) }
private fun requireSession(): AuthSession = session ?: throw ApiException(401, "Přihlášení vypršelo. Přihlaste se znovu.") private fun requireSession(): AuthSession = session ?: throw ApiException(401, "Přihlášení vypršelo. Přihlaste se znovu.")
private fun clearSession() { session = null; store.clear() } private fun clearSession() { session = null; catalogCache = null; store.clear() }
private suspend fun token(): String { private suspend fun token(): String {
val current = requireSession() val current = requireSession()
@@ -215,7 +261,7 @@ class RemoteRepository(baseUrl: String, private val store: SessionPersistence) :
} }
} }
private suspend fun <T> authorized(planned: Boolean = false, block: suspend (String) -> T): T = mapped(planned) { private suspend fun <T> authorized(block: suspend (String) -> T): T = mapped {
val access = token() val access = token()
try { block("Bearer $access") } try { block("Bearer $access") }
catch (error: HttpException) { catch (error: HttpException) {
@@ -231,21 +277,22 @@ class RemoteRepository(baseUrl: String, private val store: SessionPersistence) :
} }
} }
private suspend fun <T> mapped(planned: Boolean = false, block: suspend () -> T): T = try { block() } private suspend fun <T> mapped(block: suspend () -> T): T = try { block() }
catch (error: CancellationException) { throw error } catch (error: CancellationException) { throw error }
catch (error: HttpException) { catch (error: HttpException) {
val fallback = when (error.code()) { val fallback = when (error.code()) {
400 -> "Zkontrolujte vyplněné údaje." 400 -> "Zkontrolujte vyplněné údaje."
401 -> "Přihlášení vypršelo nebo jsou přihlašovací údaje nesprávné." 401 -> "Přihlášení vypršelo nebo jsou přihlašovací údaje nesprávné."
403 -> "K této akci nemáte oprávnění." 403 -> "K této akci nemáte oprávnění."
404, 501 -> if (planned) "Tato funkce nebo záznam zatím není na serveru dostupný. Backend musí doplnit API pro závady, návrhy a oznámení." else "Požadovaný záznam nebyl nalezen." 404 -> "Požadovaný záznam nebyl nalezen."
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()
val message = if (planned && error.code() in listOf(404, 501)) fallback else problemMessage(body) ?: fallback val message = problemMessage(body) ?: fallback
throw ApiException(error.code(), message) throw ApiException(error.code(), message)
} }
catch (error: SerializationException) { throw ApiException(0, "Server vrátil odpověď v neočekávaném formátu.") } catch (error: SerializationException) { throw ApiException(0, "Server vrátil odpověď v neočekávaném formátu.") }
@@ -262,13 +309,24 @@ class RemoteRepository(baseUrl: String, private val store: SessionPersistence) :
fun validateUploads(files: List<Upload>) { fun validateUploads(files: List<Upload>) {
require(files.size <= 5) { "Najednou můžete přiložit nejvýše 5 souborů." } require(files.size <= 5) { "Najednou můžete přiložit nejvýše 5 souborů." }
val allowed = setOf("image/jpeg", "image/png", "image/heic", "image/heif", "application/pdf", "application/vnd.openxmlformats-officedocument.wordprocessingml.document")
files.forEach { files.forEach {
require(it.bytes.isNotEmpty() && it.bytes.size <= 10 * 1024 * 1024) { "Každý soubor musí mít velikost 1 B až 10 MB." } require(it.bytes.isNotEmpty() && it.bytes.size <= 10 * 1024 * 1024) { "Každý soubor musí mít velikost 1 B až 10 MB." }
require(it.mimeType in allowed) { "Povolené formáty příloh jsou JPG, PNG, HEIC, PDF a DOCX." } val name = uploadBaseName(it.name)
require(name.isNotBlank() && name.length <= 255 && name.none(Character::isISOControl)) { "Název přílohy musí mít 1 až 255 znaků a nesmí obsahovat řídicí znaky." }
val expectedType = when (name.substringAfterLast('.', "").lowercase()) {
"jpg", "jpeg" -> "image/jpeg"
"png" -> "image/png"
"heic" -> "image/heic"
"pdf" -> "application/pdf"
"docx" -> "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
else -> throw IllegalArgumentException("Povolené formáty příloh jsou JPG, PNG, HEIC, PDF a DOCX.")
}
require(it.mimeType == expectedType) { "Typ přílohy neodpovídá příponě souboru." }
} }
} }
internal fun uploadBaseName(name: String) = name.replace('\\', '/').substringAfterLast('/').trim()
@Serializable private data class LoginRequest(val email: String, val password: String) @Serializable private data class LoginRequest(val email: String, val password: String)
@Serializable private data class RegisterRequest(val email: String, val password: String, val firstName: String, val lastName: String) @Serializable private data class RegisterRequest(val email: String, val password: String, val firstName: String, val lastName: String)
@Serializable private data class RefreshRequest(val refreshToken: String) @Serializable private data class RefreshRequest(val refreshToken: String)
@@ -276,9 +334,7 @@ fun validateUploads(files: List<Upload>) {
@Serializable private data class EmailRequest(val email: String) @Serializable private data class EmailRequest(val email: String)
@Serializable private data class ResetRequest(val token: String, val newPassword: String) @Serializable private data class ResetRequest(val token: String, val newPassword: String)
@Serializable private data class CommentRequest(val text: String) @Serializable private data class CommentRequest(val text: String)
@Serializable private data class ActionRequest(val rowVersion: Int, val reason: String, val note: String)
@Serializable private data class VoteRequest(val value: Int) @Serializable private data class VoteRequest(val value: Int)
@Serializable private data class UpdateIssueRequest(val title: String, val description: String, val categoryId: Int, val buildingId: Int?, val location: String, val rowVersion: Int)
private const val MAX_ATTACHMENT_BYTES = 10 * 1024 * 1024 private const val MAX_ATTACHMENT_BYTES = 10 * 1024 * 1024
@@ -305,21 +361,26 @@ private interface HelpdeskApi {
@GET("buildings") suspend fun buildings(@Header("Authorization") bearer: String): List<Building> @GET("buildings") suspend fun buildings(@Header("Authorization") bearer: String): List<Building>
@GET("issue-categories") suspend fun issueCategories(@Header("Authorization") bearer: String): List<Category> @GET("issue-categories") suspend fun issueCategories(@Header("Authorization") bearer: String): List<Category>
@GET("proposal-categories") suspend fun proposalCategories(@Header("Authorization") bearer: String): List<Category> @GET("proposal-categories") suspend fun proposalCategories(@Header("Authorization") bearer: String): List<Category>
@GET("issues") suspend fun issues(@Header("Authorization") bearer: String, @Query("page") page: Int, @Query("q") query: String?, @Query("status") status: String?, @Query("mine") mine: Boolean, @Query("assigneeId") assignee: Int?, @Query("pageSize") size: Int = 20): Page<Issue> @GET("issues") suspend fun issues(@Header("Authorization") bearer: String, @Query("page") page: Int, @Query("q") query: String?, @Query("status") status: String?, @Query("mine") mine: Boolean, @Query("assigneeId") assignee: Int?, @Query("pageSize") size: Int = 20): Page<WireIssueSummary>
@GET("issues/{id}") suspend fun issue(@Header("Authorization") bearer: String, @Path("id") id: Int): Issue @GET("issues/{id}") suspend fun issue(@Header("Authorization") bearer: String, @Path("id") id: Int): WireIssueDetail
@GET("issues/{id}/events") suspend fun events(@Header("Authorization") bearer: String, @Path("id") id: Int): List<IssueEvent> @GET("issues/{id}/events") suspend fun events(@Header("Authorization") bearer: String, @Path("id") id: Int): List<WireIssueEvent>
@POST("issues") suspend fun createIssue(@Header("Authorization") bearer: String, @Body request: NewIssue): Issue @POST("issues") suspend fun createIssue(@Header("Authorization") bearer: String, @Body request: CreateIssueRequest): WireIssueDetail
@PUT("issues/{id}") suspend fun updateIssue(@Header("Authorization") bearer: String, @Path("id") id: Int, @Body request: UpdateIssueRequest): Issue @PUT("issues/{id}") suspend fun updateIssue(@Header("Authorization") bearer: String, @Path("id") id: Int, @Body request: EditIssueRequest): WireIssueDetail
@Multipart @POST("issues/{id}/attachments") suspend fun attachments(@Header("Authorization") bearer: String, @Path("id") id: Int, @Part files: List<MultipartBody.Part>) @Multipart @POST("issues/{id}/attachments") suspend fun attachments(@Header("Authorization") bearer: String, @Path("id") id: Int, @Part files: List<MultipartBody.Part>): List<WireAttachment>
@Streaming @GET("attachments/{id}") suspend fun downloadAttachment(@Header("Authorization") bearer: String, @Path("id") id: Int): retrofit2.Response<ResponseBody> @Streaming @GET("attachments/{id}") suspend fun downloadAttachment(@Header("Authorization") bearer: String, @Path("id") id: Int): retrofit2.Response<ResponseBody>
@POST("issues/{id}/comments") suspend fun comment(@Header("Authorization") bearer: String, @Path("id") id: Int, @Body request: CommentRequest) @POST("issues/{id}/comments") suspend fun comment(@Header("Authorization") bearer: String, @Path("id") id: Int, @Body request: CommentRequest): WireIssueEvent
@POST("issues/{id}/{action}") suspend fun issueAction(@Header("Authorization") bearer: String, @Path("id") id: Int, @Path("action") action: String, @Body request: ActionRequest) @POST("issues/{id}/start") suspend fun startIssue(@Header("Authorization") bearer: String, @Path("id") id: Int, @Body request: IssueVersionRequest): WireIssueDetail
@GET("proposals") suspend fun proposals(@Header("Authorization") bearer: String, @Query("page") page: Int, @Query("q") query: String?, @Query("sort") sort: String, @Query("pageSize") size: Int = 20): Page<Proposal> @POST("issues/{id}/submit-for-verification") suspend fun submitIssue(@Header("Authorization") bearer: String, @Path("id") id: Int, @Body request: VerifyIssueRequest): WireIssueDetail
@GET("proposals/{id}") suspend fun proposal(@Header("Authorization") bearer: String, @Path("id") id: Int): Proposal @POST("issues/{id}/confirm") suspend fun confirmIssue(@Header("Authorization") bearer: String, @Path("id") id: Int, @Body request: IssueVersionRequest): WireIssueDetail
@POST("proposals") suspend fun createProposal(@Header("Authorization") bearer: String, @Body request: NewProposal): Proposal @POST("issues/{id}/reopen") suspend fun reopenIssue(@Header("Authorization") bearer: String, @Path("id") id: Int, @Body request: IssueReasonRequest): WireIssueDetail
@POST("issues/{id}/reject") suspend fun rejectIssue(@Header("Authorization") bearer: String, @Path("id") id: Int, @Body request: IssueReasonRequest): WireIssueDetail
@GET("proposals") suspend fun proposals(@Header("Authorization") bearer: String, @Query("page") page: Int, @Query("q") query: String?, @Query("sort") sort: String, @Query("pageSize") size: Int = 20): Page<WireProposalSummary>
@GET("proposals/{id}") suspend fun proposal(@Header("Authorization") bearer: String, @Path("id") id: Int): WireProposalDetail
@POST("proposals") suspend fun createProposal(@Header("Authorization") bearer: String, @Body request: NewProposal): WireProposalDetail
@PUT("proposals/{id}/vote") suspend fun vote(@Header("Authorization") bearer: String, @Path("id") id: Int, @Body request: VoteRequest) @PUT("proposals/{id}/vote") suspend fun vote(@Header("Authorization") bearer: String, @Path("id") id: Int, @Body request: VoteRequest)
@DELETE("proposals/{id}/vote") suspend fun removeVote(@Header("Authorization") bearer: String, @Path("id") id: Int) @DELETE("proposals/{id}/vote") suspend fun removeVote(@Header("Authorization") bearer: String, @Path("id") id: Int)
@GET("notifications") suspend fun notices(@Header("Authorization") bearer: String, @Query("page") page: Int, @Query("pageSize") size: Int = 20): Page<Notice> @GET("notifications") suspend fun notices(@Header("Authorization") bearer: String, @Query("page") page: Int, @Query("pageSize") size: Int = 20): Page<WireNotice>
@GET("notifications/unread-count") suspend fun unreadCount(@Header("Authorization") bearer: String): WireUnreadCount
@POST("notifications/{id}/read") suspend fun readNotice(@Header("Authorization") bearer: String, @Path("id") id: Int) @POST("notifications/{id}/read") suspend fun readNotice(@Header("Authorization") bearer: String, @Path("id") id: Int)
@POST("notifications/read-all") suspend fun readAllNotices(@Header("Authorization") bearer: String) @POST("notifications/read-all") suspend fun readAllNotices(@Header("Authorization") bearer: String)
} }
@@ -0,0 +1,166 @@
package cz.ntbug.mobile.data
import kotlinx.serialization.Serializable
/** Exact JSON contracts from Helpdesk.Application. Lists deliberately use summary DTOs. */
@Serializable
internal data class WireIssueSummary(
val id: Int, val title: String, val categoryId: Int, val buildingId: Int?,
val locationDetail: String?, val status: String, val priority: String,
val reporterId: Int, val assigneeId: Int?, val createdAt: String,
)
@Serializable
internal data class WireIssueDetail(
val id: Int, val title: String, val description: String, val categoryId: Int,
val buildingId: Int?, val locationDetail: String?, val status: String, val priority: String,
val reporterId: Int, val assigneeId: Int?, val createdAt: String, val rowVersion: Int,
val allowedActions: List<String>, val attachments: List<WireAttachment>,
)
@Serializable
internal data class WireIssueEvent(
val id: Int, val eventType: String, val fromStatus: String?, val toStatus: String,
val actorId: Int, val actorName: String, val note: String?, val occurredAt: String,
)
@Serializable
internal data class WireAttachment(
val id: Int, val fileName: String, val contentType: String, val sizeBytes: Long, val createdAt: String,
)
@Serializable
internal data class WireProposalSummary(
val id: Int, val title: String, val categoryId: Int, val authorId: Int, val status: String,
val createdAt: String, val votesFor: Long, val votesAgainst: Long, val score: Long, val myVote: Int?,
)
@Serializable
internal data class WireProposalDetail(
val id: Int, val title: String, val categoryId: Int, val authorId: Int, val status: String,
val createdAt: String, val votesFor: Long, val votesAgainst: Long, val score: Long, val myVote: Int?,
val description: String, val events: List<WireProposalEvent>,
)
@Serializable
internal data class WireProposalEvent(
val id: Int, val eventType: String, val fromStatus: String?, val toStatus: String,
val actorId: Int, val actorName: String, val note: String?, val occurredAt: String,
)
@Serializable
internal data class WireNotice(
val id: Int, val type: String, val title: String, val message: String,
val issueId: Int?, val proposalId: Int?, val createdAt: String, val readAt: String?,
)
@Serializable internal data class WireUnreadCount(val count: Int)
@Serializable
internal data class CreateIssueRequest(
val title: String, val description: String, val categoryId: Int, val buildingId: Int?, val locationDetail: String?,
)
@Serializable
internal data class EditIssueRequest(
val title: String, val description: String, val categoryId: Int, val buildingId: Int?,
val locationDetail: String?, val rowVersion: Int,
)
@Serializable internal data class IssueVersionRequest(val rowVersion: Int)
@Serializable internal data class VerifyIssueRequest(val rowVersion: Int, val note: String?)
@Serializable internal data class IssueReasonRequest(val rowVersion: Int, val reason: String)
internal fun NewIssue.toCreateRequest() = CreateIssueRequest(title, description, categoryId, buildingId, location.trim().takeIf(String::isNotBlank))
internal fun NewIssue.toEditRequest(rowVersion: Int) = EditIssueRequest(title, description, categoryId, buildingId, location.trim().takeIf(String::isNotBlank), rowVersion)
internal fun WireIssueSummary.toModel(catalogs: Catalogs, current: User): Issue = Issue(
id = id, title = title, description = "", status = status,
categoryId = categoryId, categoryName = catalogs.issueCategoryName(categoryId),
buildingId = buildingId, buildingName = catalogs.buildingName(buildingId), location = locationDetail.orEmpty(),
reporterId = reporterId, reporterName = current.nameFor(reporterId), assigneeName = assigneeId?.let(current::nameFor),
createdAt = createdAt, rowVersion = 0, assigneeId = assigneeId, priority = priority,
)
internal fun WireIssueDetail.toModel(catalogs: Catalogs, current: User, timeline: List<WireIssueEvent> = emptyList()): Issue {
fun personName(id: Int): String = if (id == current.id) current.nameFor(id)
else timeline.lastOrNull { it.actorId == id && it.actorName.isNotBlank() }?.actorName ?: current.nameFor(id)
val assignedName = assigneeId?.let { assignedId ->
if (assignedId == current.id || timeline.any { it.actorId == assignedId && it.actorName.isNotBlank() }) personName(assignedId)
else timeline.lastOrNull { it.eventType == "ASSIGNED" }?.note?.takeIf(String::isNotBlank) ?: personName(assignedId)
}
return Issue(
id = id, title = title, description = description, status = status,
categoryId = categoryId, categoryName = catalogs.issueCategoryName(categoryId),
buildingId = buildingId, buildingName = catalogs.buildingName(buildingId), location = locationDetail.orEmpty(),
reporterId = reporterId, reporterName = personName(reporterId), assigneeName = assignedName,
createdAt = createdAt, rowVersion = rowVersion, allowedActions = allowedActions,
events = timeline.map(WireIssueEvent::toModel), attachments = attachments.map { Attachment(it.id, it.fileName, it.contentType) },
assigneeId = assigneeId, priority = priority,
)
}
internal fun WireIssueEvent.toModel(): IssueEvent = IssueEvent(
id, actorName.ifBlank { "Uživatel #$actorId" }, eventType,
eventText(eventType, note, fromStatus, toStatus, proposal = false), occurredAt,
actorId, fromStatus, toStatus,
)
internal fun WireProposalSummary.toModel(catalogs: Catalogs, current: User): Proposal = Proposal(
id = id, title = title, description = "", categoryId = categoryId, categoryName = catalogs.proposalCategoryName(categoryId),
authorId = authorId, authorName = current.nameFor(authorId), status = status, score = score,
myVote = myVote, createdAt = createdAt, votesFor = votesFor, votesAgainst = votesAgainst,
)
internal fun WireProposalDetail.toModel(catalogs: Catalogs, current: User): Proposal = Proposal(
id = id, title = title, description = description, categoryId = categoryId, categoryName = catalogs.proposalCategoryName(categoryId),
authorId = authorId, authorName = if (authorId == current.id) current.nameFor(authorId)
else events.lastOrNull { it.actorId == authorId && it.actorName.isNotBlank() }?.actorName ?: current.nameFor(authorId),
status = status, score = score, myVote = myVote, createdAt = createdAt,
note = events.lastOrNull { it.eventType == "STATUS_CHANGED" && !it.note.isNullOrBlank() }?.note,
votesFor = votesFor, votesAgainst = votesAgainst, events = events.map(WireProposalEvent::toModel),
)
internal fun WireProposalEvent.toModel(): ProposalEvent = ProposalEvent(
id, actorName.ifBlank { "Uživatel #$actorId" }, eventType,
eventText(eventType, note, fromStatus, toStatus, proposal = true), occurredAt,
actorId, fromStatus, toStatus,
)
internal fun WireNotice.toModel() = Notice(id, title, message, createdAt, readAt != null, issueId, proposalId)
private fun User.nameFor(userId: Int): String = if (id == userId) "$firstName $lastName".trim().ifBlank { "Uživatel #$userId" } else "Uživatel #$userId"
private fun Catalogs.issueCategoryName(id: Int) = issueCategories.firstOrNull { it.id == id }?.name ?: "Kategorie #$id"
private fun Catalogs.proposalCategoryName(id: Int) = proposalCategories.firstOrNull { it.id == id }?.name ?: "Oblast #$id"
private fun Catalogs.buildingName(id: Int?) = id?.let { buildingId -> buildings.firstOrNull { it.id == buildingId }?.name ?: "Budova #$buildingId" }
private fun eventText(type: String, note: String?, from: String?, to: String, proposal: Boolean): String {
val message = note?.trim()?.takeIf(String::isNotBlank)
val subject = if (proposal) "Návrh" else "Hlášení"
val text = when (type) {
"CREATED" -> if (proposal) "Návrh byl podán." else "Hlášení bylo přijato."
"UPDATED" -> if (proposal) "Návrh byl upraven." else "Hlášení bylo upraveno."
"ASSIGNED" -> "Hlášení bylo přiřazeno řešiteli."
"COMMENTED" -> return message ?: "Komentář."
"STATUS_CHANGED" -> if (from == null) "$subject: ${statusLabel(to, proposal)}." else "Změna stavu: ${statusLabel(from, proposal)} → ${statusLabel(to, proposal)}."
else -> "$subject má novou událost."
}
return if (message == null) text else "$text\n$message"
}
private fun statusLabel(status: String, proposal: Boolean): String = if (proposal) when (status) {
"SUBMITTED" -> "Podán"
"UNDER_REVIEW" -> "V posouzení"
"ACCEPTED" -> "Přijat"
"REJECTED" -> "Zamítnut"
"IMPLEMENTED" -> "Realizován"
else -> "Neznámý stav"
} else when (status) {
"RECEIVED" -> "Přijata"
"ASSIGNED" -> "Přiřazena"
"IN_PROGRESS" -> "V řešení"
"PENDING_VERIFICATION" -> "Čeká na ověření"
"RESOLVED" -> "Vyřešena"
"REJECTED" -> "Zamítnuta"
else -> "Neznámý stav"
}
@@ -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,10 +27,12 @@ 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(),
val notices: List<Notice> = emptyList(), val notices: List<Notice> = emptyList(),
val unreadCount: Int = 0,
val issue: Issue? = null, val issue: Issue? = null,
val proposal: Proposal? = null, val proposal: Proposal? = null,
val issueQuery: String = "", val issueQuery: String = "",
@@ -99,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 {
try {
repository.register(email.trim(), password, firstName.trim(), lastName.trim()) repository.register(email.trim(), password, firstName.trim(), lastName.trim())
state.update { it.copy(authMessage = "Registrace je hotová. Ověřte e-mail odkazem ze zprávy a pak se přihlaste.") } } 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) {
@@ -144,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
@@ -152,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)
@@ -186,20 +209,22 @@ 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 {
// Each section may be implemented on the server at a different time. // Keep usable sections visible when another request temporarily fails.
val issues = async { runCatching { repository.issues() }.getOrThrowCancellation() } val issues = async { runCatching { repository.issues() }.getOrThrowCancellation() }
val proposals = async { runCatching { repository.proposals() }.getOrThrowCancellation() } val proposals = async { runCatching { repository.proposals() }.getOrThrowCancellation() }
val notices = async { runCatching { repository.notices() }.getOrThrowCancellation() } val notices = async { runCatching { repository.notices() }.getOrThrowCancellation() }
val i = issues.await(); val p = proposals.await(); val n = notices.await() val unread = async { runCatching { repository.unreadCount() }.getOrThrowCancellation() }
listOfNotNull(i.exceptionOrNull(), p.exceptionOrNull(), n.exceptionOrNull()) val i = issues.await(); val p = proposals.await(); val n = notices.await(); val u = unread.await()
listOfNotNull(i.exceptionOrNull(), p.exceptionOrNull(), n.exceptionOrNull(), u.exceptionOrNull())
.filterIsInstance<ApiException>().firstOrNull { it.status == 401 }?.let { throw it } .filterIsInstance<ApiException>().firstOrNull { it.status == 401 }?.let { throw it }
state.update { it.copy( state.update { it.copy(
issues = i.getOrNull()?.items.orEmpty(), proposals = p.getOrNull()?.items.orEmpty(), issues = i.getOrNull()?.items.orEmpty(), proposals = p.getOrNull()?.items.orEmpty(),
notices = n.getOrNull()?.items.orEmpty(), notices = n.getOrNull()?.items.orEmpty(),
error = listOfNotNull(i.exceptionOrNull(), p.exceptionOrNull(), n.exceptionOrNull()).firstOrNull()?.message, unreadCount = u.getOrNull() ?: it.unreadCount,
error = listOfNotNull(i.exceptionOrNull(), p.exceptionOrNull(), n.exceptionOrNull(), u.exceptionOrNull()).firstOrNull()?.message,
) } ) }
} }
@@ -232,6 +257,8 @@ class AppViewModel(application: Application) : AndroidViewModel(application) {
private suspend fun loadNotices(append: Boolean) { private suspend fun loadNotices(append: Boolean) {
val page = repository.notices(if (append) state.value.noticePage + 1 else 1) val page = repository.notices(if (append) state.value.noticePage + 1 else 1)
state.update { it.copy(notices = (if (append) it.notices + page.items else page.items).distinctBy(Notice::id), noticePage = page.page, moreNotices = page.page * page.pageSize < page.totalCount) } state.update { it.copy(notices = (if (append) it.notices + page.items else page.items).distinctBy(Notice::id), noticePage = page.page, moreNotices = page.page * page.pageSize < page.totalCount) }
val unread = repository.unreadCount()
state.update { it.copy(unreadCount = unread) }
} }
fun createIssue(request: NewIssue, attachments: List<Upload>, onCreated: (Int) -> Unit) = operation { fun createIssue(request: NewIssue, attachments: List<Upload>, onCreated: (Int) -> Unit) = operation {
@@ -283,15 +310,25 @@ class AppViewModel(application: Application) : AndroidViewModel(application) {
try { context.startActivity(intent) } try { context.startActivity(intent) }
catch (_: android.content.ActivityNotFoundException) { state.update { it.copy(message = "Pro otevření této přílohy není nainstalovaná vhodná aplikace.") } } catch (_: android.content.ActivityNotFoundException) { state.update { it.copy(message = "Pro otevření této přílohy není nainstalovaná vhodná aplikace.") } }
} }
fun comment(id: Int, text: String) = operation { fun comment(id: Int, text: String, onSaved: () -> Unit = {}) = operation {
repository.comment(id, text.trim()) repository.comment(id, text.trim())
val detail = repository.issue(id) onSaved()
state.update { it.copy(issue = detail, message = "Komentář byl přidán.") } refreshIssueAfterSave(id, "Komentář byl přidán.", "Komentář je uložený")
} }
fun attachments(id: Int, uploads: List<Upload>) = operation { fun attachments(id: Int, uploads: List<Upload>, onSaved: () -> Unit = {}) = operation {
repository.addAttachments(id, uploads) repository.addAttachments(id, uploads)
onSaved()
refreshIssueAfterSave(id, "Přílohy byly přidány.", "Přílohy jsou uložené")
}
private suspend fun refreshIssueAfterSave(id: Int, success: String, saved: String) {
state.update { it.copy(message = success) }
try {
val detail = repository.issue(id) val detail = repository.issue(id)
state.update { it.copy(issue = detail, message = "Přílohy byly přidány.") } state.update { it.copy(issue = detail) }
} catch (e: Exception) {
if (e is CancellationException || e is ApiException && e.status == 401) throw e
state.update { it.copy(error = "$saved, ale detail se nepodařilo obnovit. Použijte tlačítko Obnovit.") }
}
} }
fun issueAction(id: Int, action: String, reason: String) = operation { fun issueAction(id: Int, action: String, reason: String) = operation {
val detail = state.value.issue ?: return@operation val detail = state.value.issue ?: return@operation
@@ -307,18 +344,36 @@ class AppViewModel(application: Application) : AndroidViewModel(application) {
state.update { it.copy(issue = latest, message = "Stav hlášení byl aktualizován.") } state.update { it.copy(issue = latest, message = "Stav hlášení byl aktualizován.") }
} }
fun vote(id: Int, value: Int?) = operation { fun vote(id: Int, value: Int?) = operation {
repository.vote(id, value) try { repository.vote(id, value) }
catch (e: ApiException) {
if (e.status == 409) {
val latest = repository.proposal(id)
updateProposal(latest)
}
throw e
}
val proposal = repository.proposal(id) val proposal = repository.proposal(id)
state.update { it.copy(proposal = if (it.proposal?.id == id) proposal else it.proposal, proposals = it.proposals.map { p -> if (p.id == id) proposal else p }) } updateProposal(proposal)
}
private fun updateProposal(proposal: Proposal) {
state.update { s ->
val items = s.proposals.map { if (it.id == proposal.id) proposal else it }
s.copy(proposal = if (s.proposal?.id == proposal.id) proposal else s.proposal,
proposals = if (s.proposalSort == "score") items.sortedWith(compareByDescending<Proposal> { it.score }.thenByDescending { it.createdAt }.thenByDescending { it.id }) else items)
}
} }
fun readNotice(notice: Notice, onRead: () -> Unit) = operation { fun readNotice(notice: Notice, onRead: () -> Unit) = operation {
repository.readNotice(notice.id) repository.readNotice(notice.id)
state.update { it.copy(notices = it.notices.map { n -> if (n.id == notice.id) n.copy(isRead = true) else n }) } state.update { s ->
val wasUnread = s.notices.firstOrNull { it.id == notice.id }?.isRead == false
s.copy(notices = s.notices.map { n -> if (n.id == notice.id) n.copy(isRead = true) else n },
unreadCount = (s.unreadCount - if (wasUnread) 1 else 0).coerceAtLeast(0))
}
onRead() onRead()
} }
fun readAll() = operation { fun readAll() = operation {
repository.readAllNotices() repository.readAllNotices()
state.update { it.copy(notices = it.notices.map { n -> n.copy(isRead = true) }) } state.update { it.copy(notices = it.notices.map { n -> n.copy(isRead = true) }, unreadCount = 0) }
} }
private fun failure(e: Exception) { private fun failure(e: Exception) {
@@ -333,8 +388,14 @@ class AppViewModel(application: Application) : AndroidViewModel(application) {
private fun operation(block: suspend () -> Unit) { private fun operation(block: suspend () -> Unit) {
if (state.value.busy) return if (state.value.busy) return
// A response started before a mutation must not restore an obsolete inbox/count.
if (state.value.user != null) {
loadJob?.cancel()
loadSequence++
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) } }
@@ -342,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()
}
@@ -81,7 +81,7 @@ private fun SignedInApp(s: AppState, vm: AppViewModel) {
launchSingleTop = true; restoreState = true launchSingleTop = true; restoreState = true
} }
}, icon = { }, icon = {
if (tab.route == "notices" && s.notices.any { !it.isRead }) BadgedBox(badge = { Badge { Text(s.notices.count { !it.isRead }.toString()) } }) { Icon(tab.icon, null) } if (tab.route == "notices" && s.unreadCount > 0) BadgedBox(badge = { Badge { Text(if (s.unreadCount > 99) "99+" else s.unreadCount.toString()) } }) { Icon(tab.icon, null) }
else Icon(tab.icon, null) else Icon(tab.icon, null)
}, label = { Text(tab.title, maxLines = 1) }) }, label = { Text(tab.title, maxLines = 1) })
} }
@@ -103,16 +103,16 @@ private fun SignedInApp(s: AppState, vm: AppViewModel) {
} }
} }
NavHost(nav, startDestination = "home", modifier = Modifier.weight(1f)) { NavHost(nav, startDestination = "home", modifier = Modifier.weight(1f)) {
composable("home") { DashboardScreen(user, s.issues, s.proposals, s.notices, { open("new-issue") }, { open("issue/$it") }, { open("proposal/$it") }, { open("issues") }, { open("proposals") }) } composable("home") { DashboardScreen(user, s.issues, s.proposals, s.notices, { open("new-issue") }, { open("issue/$it") }, { open("proposal/$it") }, { open("issues") }, { open("proposals") }, unreadCount = s.unreadCount) }
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, { vm.comment(issue.id, it) }, { action, reason -> vm.issueAction(issue.id, action, reason) }, { vm.attachments(issue.id, it) }, { 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) } 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) }
} }
} }
@@ -102,7 +102,7 @@ internal fun AttachmentPicker(files: List<Upload>, onFilesChanged: (List<Upload>
} }
OutlinedButton(onClick = { OutlinedButton(onClick = {
try { try {
documents.launch(arrayOf("image/jpeg", "image/png", "image/heic", "image/heif", "application/pdf", "application/vnd.openxmlformats-officedocument.wordprocessingml.document")) documents.launch(arrayOf("image/jpeg", "image/png", "image/heic", "application/pdf", "application/vnd.openxmlformats-officedocument.wordprocessingml.document"))
} catch (_: Exception) { } catch (_: Exception) {
error = "Výběr souborů se nepodařilo otevřít." error = "Výběr souborů se nepodařilo otevřít."
} }
@@ -144,14 +144,12 @@ private fun readUpload(context: android.content.Context, uri: Uri): Upload {
"jpg", "jpeg" -> "image/jpeg" "jpg", "jpeg" -> "image/jpeg"
"png" -> "image/png" "png" -> "image/png"
"heic" -> "image/heic" "heic" -> "image/heic"
"heif" -> "image/heif"
"pdf" -> "application/pdf" "pdf" -> "application/pdf"
"docx" -> "application/vnd.openxmlformats-officedocument.wordprocessingml.document" "docx" -> "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
else -> null else -> null
} }
val providedType = context.contentResolver.getType(uri) // The server determines the format from the extension and verifies the file signature.
val allowedTypes = setOf("image/jpeg", "image/png", "image/heic", "image/heif", "application/pdf", "application/vnd.openxmlformats-officedocument.wordprocessingml.document") val type = extensionType ?: throw IllegalArgumentException("$name: tento typ souboru není podporován.")
val type = providedType?.takeIf { it in allowedTypes } ?: extensionType ?: throw IllegalArgumentException("$name: tento typ souboru není podporován.")
val bytes = context.contentResolver.openInputStream(uri)?.use { input -> val bytes = context.contentResolver.openInputStream(uri)?.use { input ->
val output = ByteArrayOutputStream() val output = ByteArrayOutputStream()
val buffer = ByteArray(8192) val buffer = ByteArray(8192)
@@ -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)"
}
@@ -7,6 +7,8 @@ import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.rounded.ArrowForward import androidx.compose.material.icons.automirrored.rounded.ArrowForward
import androidx.compose.material.icons.rounded.Inbox import androidx.compose.material.icons.rounded.Inbox
import androidx.compose.material.icons.rounded.ChatBubbleOutline
import androidx.compose.material.icons.rounded.CheckCircleOutline
import androidx.compose.material3.* import androidx.compose.material3.*
import androidx.compose.runtime.Composable import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue import androidx.compose.runtime.getValue
@@ -53,13 +55,13 @@ internal fun EmptyState(title: String, description: String, icon: ImageVector =
} }
} }
internal fun statusLabel(status: String): String = when (status.uppercase()) { internal fun statusLabel(status: String, isProposal: Boolean = false): String = when (status.uppercase()) {
"RECEIVED" -> "Přijata" "RECEIVED" -> "Přijata"
"ASSIGNED" -> "Přiřazena" "ASSIGNED" -> "Přiřazena"
"IN_PROGRESS" -> "V řešení" "IN_PROGRESS" -> "V řešení"
"PENDING_VERIFICATION" -> "K ověření" "PENDING_VERIFICATION" -> "K ověření"
"RESOLVED" -> "Vyřešena" "RESOLVED" -> "Vyřešena"
"REJECTED" -> "Zamítnuta" "REJECTED" -> if (isProposal) "Zamítnut" else "Zamítnuta"
"SUBMITTED" -> "Podán" "SUBMITTED" -> "Podán"
"UNDER_REVIEW" -> "V posouzení" "UNDER_REVIEW" -> "V posouzení"
"ACCEPTED" -> "Přijat" "ACCEPTED" -> "Přijat"
@@ -68,7 +70,7 @@ internal fun statusLabel(status: String): String = when (status.uppercase()) {
} }
@Composable @Composable
internal fun StatusBadge(status: String) { internal fun StatusBadge(status: String, isProposal: Boolean = false) {
val tint = when (status.uppercase()) { val tint = when (status.uppercase()) {
"ASSIGNED" -> Color(0xFF3267A0) "ASSIGNED" -> Color(0xFF3267A0)
"IN_PROGRESS" -> Color(0xFF986015) "IN_PROGRESS" -> Color(0xFF986015)
@@ -80,7 +82,7 @@ internal fun StatusBadge(status: String) {
Surface(color = tint.copy(alpha = .11f), shape = RoundedCornerShape(8.dp)) { Surface(color = tint.copy(alpha = .11f), shape = RoundedCornerShape(8.dp)) {
Row(Modifier.padding(horizontal = 9.dp, vertical = 5.dp), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp)) { Row(Modifier.padding(horizontal = 9.dp, vertical = 5.dp), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp)) {
Box(Modifier.size(5.dp).background(tint, CircleShape)) Box(Modifier.size(5.dp).background(tint, CircleShape))
Text(statusLabel(status), style = MaterialTheme.typography.labelMedium, color = tint) Text(statusLabel(status, isProposal), style = MaterialTheme.typography.labelMedium, color = tint)
} }
} }
} }
@@ -108,11 +110,40 @@ internal fun ProposalCard(proposal: Proposal, onClick: () -> Unit, footer: @Comp
Column(Modifier.padding(18.dp), verticalArrangement = Arrangement.spacedBy(10.dp)) { Column(Modifier.padding(18.dp), verticalArrangement = Arrangement.spacedBy(10.dp)) {
Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) { Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) {
Text(proposal.categoryName, modifier = Modifier.weight(1f), style = MaterialTheme.typography.labelMedium, color = MaterialTheme.colorScheme.onSurfaceVariant) Text(proposal.categoryName, modifier = Modifier.weight(1f), style = MaterialTheme.typography.labelMedium, color = MaterialTheme.colorScheme.onSurfaceVariant)
StatusBadge(proposal.status) StatusBadge(proposal.status, isProposal = true)
} }
Text(proposal.title, style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.SemiBold, maxLines = 2, overflow = TextOverflow.Ellipsis) Text(proposal.title, style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.SemiBold, maxLines = 2, overflow = TextOverflow.Ellipsis)
Text(proposal.description, style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant, maxLines = 2, overflow = TextOverflow.Ellipsis) if (proposal.description.isNotBlank()) Text(proposal.description, style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant, maxLines = 2, overflow = TextOverflow.Ellipsis)
if (footer != null) footer() else Text("${proposal.score} bodů podpory · ${proposal.authorName}", style = MaterialTheme.typography.labelMedium, color = MaterialTheme.colorScheme.primary) if (footer != null) footer() else Text(listOf("Skóre ${proposal.score}", proposal.authorName.takeIf { it.isNotBlank() }).filterNotNull().joinToString(" · "), style = MaterialTheme.typography.labelMedium, color = MaterialTheme.colorScheme.primary)
}
}
}
@Composable
internal fun TimelineEventCard(authorName: String, type: String, text: String, createdAt: String, fromStatus: String?, toStatus: String?, isProposal: Boolean = false) {
val title = when (type) {
"CREATED" -> if (isProposal) "Návrh podán" else "Hlášení přijato"
"UPDATED" -> if (isProposal) "Návrh upraven" else "Hlášení upraveno"
"ASSIGNED" -> "Přiřazen řešitel"
"STATUS_CHANGED" -> "Změna stavu"
"COMMENTED" -> "Komentář"
else -> "Aktualizace"
}
OutlinedCard(Modifier.fillMaxWidth(), shape = RoundedCornerShape(16.dp)) {
Column(Modifier.padding(16.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {
Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(10.dp), verticalAlignment = Alignment.CenterVertically) {
Icon(if (type == "COMMENTED") Icons.Rounded.ChatBubbleOutline else Icons.Rounded.CheckCircleOutline, null, tint = MaterialTheme.colorScheme.primary, modifier = Modifier.size(18.dp))
Text(title, style = MaterialTheme.typography.labelLarge, fontWeight = FontWeight.SemiBold)
}
if (toStatus != null && type in setOf("CREATED", "STATUS_CHANGED", "ASSIGNED") && (fromStatus != toStatus || type == "CREATED")) {
Text(if (fromStatus == null) statusLabel(toStatus, isProposal) else "${statusLabel(fromStatus, isProposal)} → ${statusLabel(toStatus, isProposal)}", style = MaterialTheme.typography.bodyMedium, fontWeight = FontWeight.SemiBold)
}
if (text.isNotBlank()) {
if (isProposal && type == "STATUS_CHANGED") Text("Vyjádření vedení", style = MaterialTheme.typography.labelMedium, color = MaterialTheme.colorScheme.primary)
Text(text, style = MaterialTheme.typography.bodyMedium)
}
if (authorName.isNotBlank()) Text(authorName, style = MaterialTheme.typography.labelMedium, color = MaterialTheme.colorScheme.onSurfaceVariant)
Text(formatDate(createdAt), style = MaterialTheme.typography.labelSmall, color = MaterialTheme.colorScheme.onSurfaceVariant)
} }
} }
} }
@@ -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")
} }
@@ -76,36 +80,17 @@ private fun IssueForm(catalogs: Catalogs, busy: Boolean, initial: Issue?, onSubm
} }
@Composable @Composable
fun IssueDetailScreen(issue: Issue, busy: Boolean, onComment: (String) -> Unit, onAction: (String, String) -> Unit, onAttachments: (List<Upload>) -> Unit, onEdit: () -> Unit = {}, onAttachment: (Attachment) -> Unit = {}) { fun IssueDetailScreen(issue: Issue, busy: Boolean, onComment: (String, () -> Unit) -> Unit, onAction: (String, String) -> Unit, onAttachments: (List<Upload>, () -> Unit) -> Unit, onEdit: () -> Unit = {}, onAttachment: (Attachment) -> Unit = {}) {
var comment by rememberSaveable(issue.id) { mutableStateOf("") } var comment by rememberSaveable(issue.id) { mutableStateOf("") }
var pendingComment by remember { mutableStateOf<String?>(null) }
var pendingEventCount by remember { mutableIntStateOf(issue.events.size) }
var actionDialog by rememberSaveable(issue.id) { mutableStateOf<String?>(null) } var actionDialog by rememberSaveable(issue.id) { mutableStateOf<String?>(null) }
var reason by rememberSaveable(issue.id) { mutableStateOf("") } var reason by rememberSaveable(issue.id) { mutableStateOf("") }
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) }
var pendingAttachmentCount by remember { mutableIntStateOf(issue.attachments.size) } val actions = issue.allowedActions.toSet()
val actions = issue.allowedActions.map { val canComment = "COMMENT" in actions
when (val action = it.lowercase().replace('_', '-')) { val canAttach = "ADD_ATTACHMENTS" in actions
"start-work" -> "start" val supportedActions = issueActionEndpoints.filterKeys { it in actions }.values
"confirm-resolution" -> "confirm"
"add-attachment", "add-attachments" -> "attachments"
else -> action
}
}.toSet()
val canComment = actions.any { it in setOf("comment", "comments", "add-comment") }
val canAttach = actions.any { it in setOf("attachments", "attach", "add-attachment", "add-attachments") }
val supportedActions = listOf("start", "submit-for-verification", "confirm", "reopen", "reject").filter { it in actions }
LaunchedEffect(issue.events.size) {
if (issue.events.size > pendingEventCount && pendingComment != null && issue.events.any { it.text == pendingComment }) {
if (comment.trim() == pendingComment) comment = ""
pendingComment = null
}
}
LaunchedEffect(issue.attachments.size) {
if (issue.attachments.size > pendingAttachmentCount) draft.replace(emptyList())
}
LazyColumn(contentPadding = screenPadding, verticalArrangement = Arrangement.spacedBy(20.dp), modifier = Modifier.fillMaxSize().imePadding()) { LazyColumn(contentPadding = screenPadding, verticalArrangement = Arrangement.spacedBy(20.dp), modifier = Modifier.fillMaxSize().imePadding()) {
item { item {
Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) { Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) {
@@ -119,14 +104,15 @@ fun IssueDetailScreen(issue: Issue, busy: Boolean, onComment: (String) -> Unit,
Column(Modifier.padding(18.dp), verticalArrangement = Arrangement.spacedBy(12.dp)) { Column(Modifier.padding(18.dp), verticalArrangement = Arrangement.spacedBy(12.dp)) {
DetailLine("Kategorie", issue.categoryName) DetailLine("Kategorie", issue.categoryName)
DetailLine("Místo", listOfNotNull(issue.buildingName, issue.location.takeIf { it.isNotBlank() }).joinToString(" · ").ifBlank { "Neuvedeno" }) DetailLine("Místo", listOfNotNull(issue.buildingName, issue.location.takeIf { it.isNotBlank() }).joinToString(" · ").ifBlank { "Neuvedeno" })
DetailLine("Nahlásil/a", issue.reporterName) DetailLine("Nahlásil/a", issue.reporterName.ifBlank { "Uživatel #${issue.reporterId}" })
DetailLine("Řešitel", issue.assigneeName ?: "Zatím nepřiřazen") DetailLine("Řešitel", issue.assigneeName?.takeIf { it.isNotBlank() } ?: issue.assigneeId?.let { "Uživatel #$it" } ?: "Zatím nepřiřazen")
DetailLine("Priorita", when (issue.priority) { "LOW" -> "Nízká"; "HIGH" -> "Vysoká"; else -> "Běžná" })
DetailLine("Vytvořeno", formatDate(issue.createdAt)) DetailLine("Vytvořeno", formatDate(issue.createdAt))
} }
} }
} }
item { Text(issue.description, style = MaterialTheme.typography.bodyLarge) } if (issue.description.isNotBlank()) item { Text(issue.description, style = MaterialTheme.typography.bodyLarge) }
if ("edit" in actions) item { if ("EDIT" in actions) item {
OutlinedButton(onClick = onEdit, enabled = !busy, modifier = Modifier.fillMaxWidth()) { OutlinedButton(onClick = onEdit, enabled = !busy, modifier = Modifier.fillMaxWidth()) {
Icon(Icons.Rounded.Edit, null, modifier = Modifier.size(18.dp)) Icon(Icons.Rounded.Edit, null, modifier = Modifier.size(18.dp))
Spacer(Modifier.width(8.dp)) Spacer(Modifier.width(8.dp))
@@ -160,21 +146,15 @@ fun IssueDetailScreen(issue: Issue, busy: Boolean, onComment: (String) -> Unit,
item { SectionHeading("Časová osa a komentáře") } item { SectionHeading("Časová osa a komentáře") }
if (issue.events.isEmpty()) item { Text("Zatím nejsou k dispozici žádné události.", style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant) } if (issue.events.isEmpty()) item { Text("Zatím nejsou k dispozici žádné události.", style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant) }
items(issue.events, key = { it.id }) { event -> items(issue.events, key = { it.id }) { event ->
OutlinedCard(Modifier.fillMaxWidth(), shape = RoundedCornerShape(16.dp)) { TimelineEventCard(event.authorName, event.type, event.text, event.createdAt, event.fromStatus, event.toStatus)
Column(Modifier.padding(16.dp), verticalArrangement = Arrangement.spacedBy(7.dp)) {
Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(10.dp)) {
Icon(if (event.type.equals("COMMENTED", true)) Icons.Rounded.ChatBubbleOutline else Icons.Rounded.CheckCircleOutline, null, tint = MaterialTheme.colorScheme.primary, modifier = Modifier.size(18.dp))
Text(event.authorName, style = MaterialTheme.typography.labelLarge, fontWeight = FontWeight.SemiBold, modifier = Modifier.weight(1f))
}
Text(event.text.ifBlank { eventLabel(event.type) }, style = MaterialTheme.typography.bodyMedium)
Text(formatDate(event.createdAt), style = MaterialTheme.typography.labelSmall, color = MaterialTheme.colorScheme.onSurfaceVariant)
}
}
} }
if (canComment) item { if (canComment) item {
Column(verticalArrangement = Arrangement.spacedBy(10.dp)) { Column(verticalArrangement = Arrangement.spacedBy(10.dp)) {
OutlinedTextField(value = comment, onValueChange = { comment = it.take(5000) }, label = { Text("Napsat komentář") }, modifier = Modifier.fillMaxWidth(), minLines = 2, maxLines = 8, enabled = !busy, keyboardOptions = KeyboardOptions(capitalization = KeyboardCapitalization.Sentences)) OutlinedTextField(value = comment, onValueChange = { comment = it.take(5000) }, label = { Text("Napsat komentář") }, modifier = Modifier.fillMaxWidth(), minLines = 2, maxLines = 8, enabled = !busy, keyboardOptions = KeyboardOptions(capitalization = KeyboardCapitalization.Sentences))
Button(onClick = { pendingComment = comment.trim(); pendingEventCount = issue.events.size; onComment(comment.trim()) }, enabled = !busy && comment.isNotBlank(), modifier = Modifier.fillMaxWidth()) { Text("Odeslat komentář") } Button(onClick = {
val submitted = comment.trim()
onComment(submitted) { if (comment.trim() == submitted) comment = "" }
}, enabled = !busy && comment.isNotBlank(), modifier = Modifier.fillMaxWidth()) { Text("Odeslat komentář") }
} }
} }
if (canAttach) item { if (canAttach) item {
@@ -183,7 +163,7 @@ fun IssueDetailScreen(issue: Issue, busy: Boolean, onComment: (String) -> Unit,
AttachmentPicker(files, draft::replace, enabled = !busy && !draft.busy, onReading = { readingFiles = it }) AttachmentPicker(files, draft::replace, enabled = !busy && !draft.busy, onReading = { readingFiles = it })
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 (files.isNotEmpty()) Button(onClick = { pendingAttachmentCount = issue.attachments.size; onAttachments(files) }, enabled = !busy && !readingFiles && !draft.busy, modifier = Modifier.fillMaxWidth()) { Text("Nahrát přílohy") } if (files.isNotEmpty()) Button(onClick = { onAttachments(files) { draft.replace(emptyList()) } }, enabled = !busy && !readingFiles && !draft.busy, modifier = Modifier.fillMaxWidth()) { Text("Nahrát přílohy") }
} }
} }
} }
@@ -212,11 +192,11 @@ private fun actionLabel(action: String): String = when (action) {
else -> action else -> action
} }
private fun eventLabel(type: String): String = when (type.uppercase()) { /** Server action codes are distinct from the URL paths used by action requests. */
"CREATED" -> "Hlášení přijato." private val issueActionEndpoints = linkedMapOf(
"ASSIGNED" -> "Byl přiřazen řešitel." "START_WORK" to "start",
"STATUS_CHANGED" -> "Změna stavu hlášení." "SUBMIT_FOR_VERIFICATION" to "submit-for-verification",
"UPDATED" -> "Hlášení bylo upraveno." "CONFIRM" to "confirm",
"COMMENTED" -> "Nový komentář." "REOPEN" to "reopen",
else -> "Aktualizace hlášení." "REJECT" to "reject",
} )
@@ -22,7 +22,7 @@ import androidx.compose.ui.unit.sp
import cz.ntbug.mobile.data.* import cz.ntbug.mobile.data.*
@Composable @Composable
fun DashboardScreen(user: User, issues: List<Issue>, proposals: List<Proposal>, notices: List<Notice>, onNewIssue: () -> Unit, onIssue: (Int) -> Unit, onProposal: (Int) -> Unit, onAllIssues: () -> Unit, onAllProposals: () -> Unit) { fun DashboardScreen(user: User, issues: List<Issue>, proposals: List<Proposal>, notices: List<Notice>, onNewIssue: () -> Unit, onIssue: (Int) -> Unit, onProposal: (Int) -> Unit, onAllIssues: () -> Unit, onAllProposals: () -> Unit, unreadCount: Int = notices.count { !it.isRead }) {
val myIssues = issues.filter { it.reporterId == user.id } val myIssues = issues.filter { it.reporterId == user.id }
val openIssues = myIssues.filter { it.status !in listOf("RESOLVED", "REJECTED") } val openIssues = myIssues.filter { it.status !in listOf("RESOLVED", "REJECTED") }
LazyColumn(contentPadding = screenPadding, verticalArrangement = Arrangement.spacedBy(18.dp), modifier = Modifier.fillMaxSize()) { LazyColumn(contentPadding = screenPadding, verticalArrangement = Arrangement.spacedBy(18.dp), modifier = Modifier.fillMaxSize()) {
@@ -54,10 +54,10 @@ fun DashboardScreen(user: User, issues: List<Issue>, proposals: List<Proposal>,
item { item {
Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(12.dp)) { Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(12.dp)) {
MetricCard(openIssues.size.toString(), "Otevřená v přehledu", Modifier.weight(1f)) MetricCard(openIssues.size.toString(), "Otevřená v přehledu", Modifier.weight(1f))
MetricCard(notices.count { !it.isRead }.toString(), "Nová v přehledu", Modifier.weight(1f)) MetricCard(unreadCount.toString(), "Nepřečtená oznámení", Modifier.weight(1f))
} }
} }
item { Text("Souhrn z ${myIssues.size} načtených hlášení a ${notices.size} oznámení.", style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant) } item { Text("Otevřená hlášení v posledních ${myIssues.size} načtených záznamech.", style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant) }
item { SectionHeading("Moje hlášení", "Všechna", onAllIssues) } item { SectionHeading("Moje hlášení", "Všechna", onAllIssues) }
if (myIssues.isEmpty()) item { EmptyState("Zatím žádná hlášení", "Novou závadu můžete nahlásit tlačítkem nahoře.", Icons.Rounded.TaskAlt) } if (myIssues.isEmpty()) item { EmptyState("Zatím žádná hlášení", "Novou závadu můžete nahlásit tlačítkem nahoře.", Icons.Rounded.TaskAlt) }
items(myIssues.take(3), key = { "issue-${it.id}" }) { issue -> IssueCard(issue) { onIssue(issue.id) } } items(myIssues.take(3), key = { "issue-${it.id}" }) { issue -> IssueCard(issue) { onIssue(issue.id) } }
@@ -109,10 +109,10 @@ fun IssuesScreen(issues: List<Issue>, query: String, status: String?, assigned:
} }
@Composable @Composable
fun NoticesScreen(notices: List<Notice>, onOpen: (Notice) -> Unit, onReadAll: () -> Unit, onLoadMore: () -> Unit, hasMore: Boolean) { fun NoticesScreen(notices: List<Notice>, onOpen: (Notice) -> Unit, onReadAll: () -> Unit, onLoadMore: () -> Unit, hasMore: Boolean, unreadCount: Int = notices.count { !it.isRead }) {
LazyColumn(contentPadding = screenPadding, verticalArrangement = Arrangement.spacedBy(14.dp), modifier = Modifier.fillMaxSize()) { LazyColumn(contentPadding = screenPadding, verticalArrangement = Arrangement.spacedBy(14.dp), modifier = Modifier.fillMaxSize()) {
item { SectionHeading("Oznámení") } item { SectionHeading("Oznámení") }
if (notices.any { !it.isRead }) item { TextButton(onClick = onReadAll) { Icon(Icons.Rounded.DoneAll, null); Spacer(Modifier.width(8.dp)); Text("Označit vše jako přečtené") } } if (unreadCount > 0) item { TextButton(onClick = onReadAll) { Icon(Icons.Rounded.DoneAll, null); Spacer(Modifier.width(8.dp)); Text("Označit vše jako přečtené") } }
if (notices.isEmpty()) item { EmptyState("Máte přehled", "Změny hlášení a nové zprávy se objeví tady.", Icons.Rounded.NotificationsNone) } if (notices.isEmpty()) item { EmptyState("Máte přehled", "Změny hlášení a nové zprávy se objeví tady.", Icons.Rounded.NotificationsNone) }
items(notices, key = { it.id }) { notice -> items(notices, key = { it.id }) { notice ->
OutlinedCard(onClick = { onOpen(notice) }, modifier = Modifier.fillMaxWidth(), shape = RoundedCornerShape(20.dp), colors = CardDefaults.outlinedCardColors(containerColor = if (notice.isRead) MaterialTheme.colorScheme.surface else MaterialTheme.colorScheme.primaryContainer.copy(alpha = .35f))) { OutlinedCard(onClick = { onOpen(notice) }, modifier = Modifier.fillMaxWidth(), shape = RoundedCornerShape(20.dp), colors = CardDefaults.outlinedCardColors(containerColor = if (notice.isRead) MaterialTheme.colorScheme.surface else MaterialTheme.colorScheme.primaryContainer.copy(alpha = .35f))) {
@@ -54,27 +54,28 @@ fun ProposalDetailScreen(proposal: Proposal, userId: Int, busy: Boolean, onVote:
item { item {
Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) { Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) {
Text("NÁVRH #${proposal.id}", modifier = Modifier.weight(1f), style = MaterialTheme.typography.labelMedium, color = MaterialTheme.colorScheme.onSurfaceVariant) Text("NÁVRH #${proposal.id}", modifier = Modifier.weight(1f), style = MaterialTheme.typography.labelMedium, color = MaterialTheme.colorScheme.onSurfaceVariant)
StatusBadge(proposal.status) StatusBadge(proposal.status, isProposal = true)
} }
} }
item { Text(proposal.title, style = MaterialTheme.typography.headlineMedium, fontWeight = FontWeight.Bold) } item { Text(proposal.title, style = MaterialTheme.typography.headlineMedium, fontWeight = FontWeight.Bold) }
item { item {
Column(verticalArrangement = Arrangement.spacedBy(5.dp)) { Column(verticalArrangement = Arrangement.spacedBy(5.dp)) {
Text(proposal.categoryName, style = MaterialTheme.typography.labelLarge, color = MaterialTheme.colorScheme.primary) Text(proposal.categoryName, style = MaterialTheme.typography.labelLarge, color = MaterialTheme.colorScheme.primary)
Text("${proposal.authorName} · ${formatDate(proposal.createdAt)}", style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant) Text(listOf(proposal.authorName.takeIf { it.isNotBlank() }, formatDate(proposal.createdAt)).filterNotNull().joinToString(" · "), style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant)
} }
} }
item { Text(proposal.description, style = MaterialTheme.typography.bodyLarge) } if (proposal.description.isNotBlank()) item { Text(proposal.description, style = MaterialTheme.typography.bodyLarge) }
item { item {
OutlinedCard(Modifier.fillMaxWidth(), shape = RoundedCornerShape(20.dp)) { OutlinedCard(Modifier.fillMaxWidth(), shape = RoundedCornerShape(20.dp)) {
Column(Modifier.padding(20.dp), verticalArrangement = Arrangement.spacedBy(12.dp)) { Column(Modifier.padding(20.dp), verticalArrangement = Arrangement.spacedBy(12.dp)) {
Text("Co si o návrhu myslíte?", style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.SemiBold) Text("Co si o návrhu myslíte?", style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.SemiBold)
VoteControls(proposal, userId, enabled = !busy, onVote = onVote) VoteControls(proposal, userId, enabled = !busy, onVote = onVote)
Text(if (proposal.authorId == userId) "Pro vlastní návrh nelze hlasovat." else "Jeden hlas na návrh. Svůj hlas můžete kdykoliv změnit nebo zrušit.", style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant) Text(votingExplanation(proposal, userId), style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant)
} }
} }
} }
proposal.note?.takeIf { it.isNotBlank() }?.let { note -> // The API stores management statements in status events; the legacy note is only a fallback.
proposal.note?.takeIf { it.isNotBlank() && proposal.events.none { event -> event.type == "STATUS_CHANGED" && event.text.isNotBlank() } }?.let { note ->
item { item {
Card(colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.secondaryContainer), shape = RoundedCornerShape(20.dp)) { Card(colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.secondaryContainer), shape = RoundedCornerShape(20.dp)) {
Column(Modifier.padding(20.dp), verticalArrangement = Arrangement.spacedBy(10.dp)) { Column(Modifier.padding(20.dp), verticalArrangement = Arrangement.spacedBy(10.dp)) {
@@ -84,16 +85,22 @@ fun ProposalDetailScreen(proposal: Proposal, userId: Int, busy: Boolean, onVote:
} }
} }
} }
if (proposal.events.isNotEmpty()) item { SectionHeading("Průběh návrhu") }
items(proposal.events, key = { it.id }) { event ->
TimelineEventCard(event.authorName, event.type, event.text, event.createdAt, event.fromStatus, event.toStatus, isProposal = true)
}
} }
} }
@Composable @Composable
private fun VoteControls(proposal: Proposal, userId: Int, enabled: Boolean = true, onVote: (Int?) -> Unit) { private fun VoteControls(proposal: Proposal, userId: Int, enabled: Boolean = true, onVote: (Int?) -> Unit) {
val canVote = enabled && proposal.authorId != userId val votingOpen = proposal.status in openVotingStatuses
val canVote = enabled && proposal.authorId != userId && votingOpen
Column(verticalArrangement = Arrangement.spacedBy(4.dp)) {
Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) { Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) {
FilterChip(selected = proposal.myVote == 1, onClick = { onVote(if (proposal.myVote == 1) null else 1) }, enabled = canVote, FilterChip(selected = proposal.myVote == 1, onClick = { if (canVote) onVote(if (proposal.myVote == 1) null else 1) }, enabled = canVote,
label = { Text("Pro") }, leadingIcon = { Icon(Icons.Rounded.ThumbUp, null, Modifier.size(16.dp)) }) label = { Text("Pro") }, leadingIcon = { Icon(Icons.Rounded.ThumbUp, null, Modifier.size(16.dp)) })
FilterChip(selected = proposal.myVote == -1, onClick = { onVote(if (proposal.myVote == -1) null else -1) }, enabled = canVote, FilterChip(selected = proposal.myVote == -1, onClick = { if (canVote) onVote(if (proposal.myVote == -1) null else -1) }, enabled = canVote,
label = { Text("Proti") }, leadingIcon = { Icon(Icons.Rounded.ThumbDown, null, Modifier.size(16.dp)) }) label = { Text("Proti") }, leadingIcon = { Icon(Icons.Rounded.ThumbDown, null, Modifier.size(16.dp)) })
Spacer(Modifier.weight(1f)) Spacer(Modifier.weight(1f))
Column(horizontalAlignment = Alignment.End) { Column(horizontalAlignment = Alignment.End) {
@@ -101,6 +108,17 @@ private fun VoteControls(proposal: Proposal, userId: Int, enabled: Boolean = tru
Text("skóre", style = MaterialTheme.typography.labelSmall, color = MaterialTheme.colorScheme.onSurfaceVariant) Text("skóre", style = MaterialTheme.typography.labelSmall, color = MaterialTheme.colorScheme.onSurfaceVariant)
} }
} }
Text("Pro: ${proposal.votesFor} · Proti: ${proposal.votesAgainst}", style = MaterialTheme.typography.labelSmall, color = MaterialTheme.colorScheme.onSurfaceVariant)
if (!votingOpen) Text("Hlasování uzavřeno", style = MaterialTheme.typography.labelMedium, color = MaterialTheme.colorScheme.onSurfaceVariant)
}
}
private val openVotingStatuses = setOf("SUBMITTED", "UNDER_REVIEW")
private fun votingExplanation(proposal: Proposal, userId: Int): String = when {
proposal.status !in openVotingStatuses -> "Hlasování je uzavřené. Hlas již nelze změnit ani zrušit."
proposal.authorId == userId -> "Pro vlastní návrh nelze hlasovat."
else -> "Jeden hlas na návrh. Svůj hlas můžete kdykoliv změnit nebo zrušit."
} }
@Composable @Composable
@@ -109,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,353 @@
package cz.ntbug.mobile.data
import java.util.Base64
import java.util.concurrent.CopyOnWriteArrayList
import java.util.concurrent.atomic.AtomicInteger
import kotlinx.coroutines.async
import kotlinx.coroutines.runBlocking
import kotlinx.serialization.json.Json
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
/**
* Wire fixtures follow the C# IssueDtos, ProposalDtos and NotificationService records,
* and the response codes/payloads in the corresponding API controllers. In particular,
* list rows intentionally omit detail fields and server-side display-name joins.
*/
class BackendContractTest {
private lateinit var server: MockWebServer
private lateinit var repository: RemoteRepository
private val requests = CopyOnWriteArrayList<RecordedRequest>()
@Before fun setup() {
server = MockWebServer().apply { start() }
repository = RemoteRepository(server.url("/").toString(), ContractSessionStore())
}
@After fun teardown() { server.shutdown() }
@Test fun `summary pages map catalog names without fetching a detail for every row`() = runBlocking {
serve { request -> when (request.pathOnly()) {
"/api/issues" -> json(page("$issueSummary,${issueSummary.replace("\"id\":42", "\"id\":43")}"))
"/api/proposals" -> json(page(proposalSummary))
else -> null
} }
login()
val issuePage = async { repository.issues(page = 2, query = "projektor", status = "IN_PROGRESS") }
val proposalPage = async { repository.proposals(query = "zásuvky", sort = "newest") }
val issues = issuePage.await().items
val proposal = proposalPage.await().items.single()
repository.issues()
assertEquals(2, issues.size)
assertEquals("Technické vybavení", issues.first().categoryName)
assertEquals("Budova A", issues.first().buildingName)
assertEquals("Učebna A-205", issues.first().location)
assertEquals("", issues.first().description)
assertEquals("Jana Nováková", issues.first().reporterName)
assertEquals("Prostředí", proposal.categoryName)
assertEquals("", proposal.description)
listOf("/api/buildings", "/api/issue-categories", "/api/proposal-categories").forEach { path ->
assertEquals("Shared catalog cache for $path", 1, requests.count { it.pathOnly() == path })
}
assertFalse(requests.any { it.pathOnly().matches(Regex("/api/(issues|proposals)/[0-9]+")) })
val filtered = requests.first { it.pathOnly() == "/api/issues" }
assertEquals("2", filtered.requestUrl!!.queryParameter("page"))
assertEquals("projektor", filtered.requestUrl!!.queryParameter("q"))
assertEquals("IN_PROGRESS", filtered.requestUrl!!.queryParameter("status"))
assertEquals("true", filtered.requestUrl!!.queryParameter("mine"))
}
@Test fun `assigned queue sends assignee filter and does not request management-only user catalog`() = runBlocking {
serve { request -> when (request.pathOnly()) {
"/api/auth/login" -> json(sessionJson(role = "FACILITY_MANAGER"))
"/api/issues" -> json(page(issueSummary))
else -> null
} }
login()
repository.issues(assigned = true)
val request = requests.single { it.pathOnly() == "/api/issues" }
assertEquals("false", request.requestUrl!!.queryParameter("mine"))
assertEquals("1", request.requestUrl!!.queryParameter("assigneeId"))
assertFalse(requests.any { it.pathOnly() == "/api/users/assignable" })
}
@Test fun `issue detail maps actual event fields and derives participants from event actors`() = runBlocking {
serve { request -> when (request.pathOnly()) {
"/api/issues/42" -> json(issueDetail)
"/api/issues/42/events" -> json(issueEvents)
else -> null
} }
login()
val issue = repository.issue(42)
assertEquals("Popis problému", issue.description)
assertEquals("Učebna A-205", issue.location)
assertEquals(7, issue.rowVersion)
assertEquals("HIGH", issue.priority)
assertEquals(2, issue.assigneeId)
assertEquals("Jana Nováková", issue.reporterName)
assertEquals("Petr Správce", issue.assigneeName)
assertEquals(setOf("COMMENT", "ADD_ATTACHMENTS"), issue.allowedActions.toSet())
val event = issue.events.last()
assertEquals("COMMENTED", event.type)
assertEquals("Petr Správce", event.authorName)
assertEquals("Objednal jsem novou lampu.", event.text)
assertEquals("2026-11-19T09:00:00Z", event.createdAt)
assertEquals(2, event.actorId)
assertNull(event.fromStatus)
assertEquals("IN_PROGRESS", event.toStatus)
assertEquals("foto.png", issue.attachments.single().fileName)
assertEquals("image/png", issue.attachments.single().contentType)
assertEquals(1, requests.count { it.pathOnly() == "/api/issues/42/events" })
}
@Test fun `create and edit issue use locationDetail and preserve zero optimistic version`() = runBlocking {
serve { request -> when (request.pathOnly()) {
"/api/issues" -> json(receivedIssueDetail(0)).setResponseCode(201)
"/api/issues/42" -> json(receivedIssueDetail(1))
else -> null
} }
login()
val input = NewIssue("Projektor", "Popis problému", 1, 1, "Učebna A-205")
val created = repository.createIssue(input)
val edited = repository.updateIssue(42, input.copy(location = "A-206"), 0)
assertEquals(0, created.rowVersion)
assertEquals(1, edited.rowVersion)
assertJson("""{"title":"Projektor","description":"Popis problému","categoryId":1,"buildingId":1,"locationDetail":"Učebna A-205"}""",
requests.single { it.method == "POST" && it.pathOnly() == "/api/issues" })
assertJson("""{"title":"Projektor","description":"Popis problému","categoryId":1,"buildingId":1,"locationDetail":"A-206","rowVersion":0}""",
requests.single { it.method == "PUT" && it.pathOnly() == "/api/issues/42" })
assertFalse(requests.any { it.pathOnly() == "/api/issues/42/events" })
}
@Test fun `issue actions send only their controller-specific version note or reason payload`() = runBlocking {
serve { request -> if (request.pathOnly().startsWith("/api/issues/42/")) json(issueDetail) else null }
login()
repository.issueAction(42, "start", 7)
repository.issueAction(42, "confirm", 8)
repository.issueAction(42, "submit-for-verification", 9, " Opraveno ")
repository.issueAction(42, "reopen", 10, " Stále nefunguje ")
repository.issueAction(42, "reject", 11, " Duplicitní hlášení ")
val expected = mapOf(
"start" to """{"rowVersion":7}""",
"confirm" to """{"rowVersion":8}""",
"submit-for-verification" to """{"rowVersion":9,"note":"Opraveno"}""",
"reopen" to """{"rowVersion":10,"reason":"Stále nefunguje"}""",
"reject" to """{"rowVersion":11,"reason":"Duplicitní hlášení"}""",
)
expected.forEach { (action, body) ->
val request = requests.single { it.pathOnly() == "/api/issues/42/$action" }
assertEquals("POST", request.method)
assertJson(body, request)
}
}
@Test fun `catalog failure cannot disguise an already committed create as a failed operation`() = runBlocking {
serve { request -> when (request.pathOnly()) {
"/api/buildings" -> json("""{"status":503,"title":"Služba je dočasně nedostupná."}""").setResponseCode(503)
"/api/issues" -> json(receivedIssueDetail(0)).setResponseCode(201)
else -> null
} }
login()
val error = expectApiError { repository.createIssue(NewIssue("Projektor", "Popis", 1, 1, "A-205")) }
assertEquals(503, error.status)
assertFalse("A failed lookup must not leave a hidden issue to duplicate on retry", requests.any { it.pathOnly() == "/api/issues" })
}
@Test fun `optimistic conflict keeps the server explanation and never replays the edit`() = runBlocking {
serve { request -> when (request.pathOnly()) {
"/api/issues/42" -> json("""{"status":409,"title":"Závada se mezitím změnila. Načtěte aktuální stav."}""").setResponseCode(409)
else -> null
} }
login()
val error = expectApiError { repository.updateIssue(42, NewIssue("Projektor", "Popis", 1, null, ""), 4) }
assertEquals(409, error.status)
assertEquals("Závada se mezitím změnila. Načtěte aktuální stav.", error.message)
val edits = requests.filter { it.pathOnly() == "/api/issues/42" }
assertEquals(1, edits.size)
assertJson("""{"title":"Projektor","description":"Popis","categoryId":1,"buildingId":null,"locationDetail":null,"rowVersion":4}""", edits.single())
}
@Test fun `comment and multipart upload accept successful JSON response bodies`() = runBlocking {
serve { request -> when (request.pathOnly()) {
"/api/issues/42/comments" -> json("""{"id":10,"eventType":"COMMENTED","fromStatus":null,"toStatus":"IN_PROGRESS","actorId":1,"actorName":"Jana Nováková","note":"Doplňuji fotografii.","occurredAt":"2026-11-19T09:00:00Z"}""")
"/api/issues/42/attachments" -> json("""[{"id":8,"fileName":"foto.png","contentType":"image/png","sizeBytes":68,"createdAt":"2026-11-19T09:00:00Z"}]""")
else -> null
} }
login()
repository.comment(42, " Doplňuji fotografii. ")
val png = Base64.getDecoder().decode("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+aX2kAAAAASUVORK5CYII=")
repository.addAttachments(42, listOf(Upload("C:\\camera\\foto.png", "image/png", png)))
assertJson("""{"text":"Doplňuji fotografii."}""", requests.single { it.pathOnly().endsWith("/comments") })
val upload = requests.single { it.pathOnly().endsWith("/attachments") }
assertEquals("POST", upload.method)
assertTrue(upload.getHeader("Content-Type")!!.startsWith("multipart/form-data; boundary="))
val multipart = upload.body.clone().readUtf8()
assertTrue(multipart.contains("name=\"files\"; filename=\"foto.png\""))
assertFalse(multipart.contains("C:\\camera"))
assertTrue(multipart.contains("Content-Type: image/png"))
assertTrue(upload.body.readByteArray().asList().windowed(png.size).any { it == png.asList() })
}
@Test fun `proposal summary and detail preserve long vote totals and management events`() = runBlocking {
serve { request -> when (request.pathOnly()) {
"/api/proposals" -> json(page(proposalSummary))
"/api/proposals/21" -> json(proposalDetail)
else -> null
} }
login()
val summary = repository.proposals().items.single()
val detail = repository.proposal(21)
assertEquals(3_000_000_000L, summary.score)
assertEquals(3_000_000_002L, summary.votesFor)
assertEquals(2L, summary.votesAgainst)
assertEquals(-1, summary.myVote)
assertEquals("Prostředí", summary.categoryName)
assertEquals("", summary.description)
assertEquals("Doplňme zásuvky ke stolům.", detail.description)
assertEquals("Adam Autor", detail.authorName)
assertEquals("Instalace byla schválena.", detail.note)
assertEquals(4, detail.events.size)
val event = detail.events[2]
assertEquals("STATUS_CHANGED", event.type)
assertEquals("Věra Vedení", event.authorName)
assertEquals("UNDER_REVIEW", event.fromStatus)
assertEquals("ACCEPTED", event.toStatus)
assertEquals("2026-11-18T12:00:00Z", event.createdAt)
}
@Test fun `proposal creation and changing or removing a vote match controller contracts`() = runBlocking {
serve { request -> when {
request.pathOnly() == "/api/proposals" -> json("""{"id":22,"title":"Více zásuvek","categoryId":3,"authorId":1,"status":"SUBMITTED","createdAt":"2026-11-19T08:00:00Z","votesFor":0,"votesAgainst":0,"score":0,"myVote":null,"description":"Doplňme zásuvky ke stolům.","events":[{"id":1,"eventType":"CREATED","fromStatus":null,"toStatus":"SUBMITTED","actorId":1,"actorName":"Jana Nováková","note":null,"occurredAt":"2026-11-19T08:00:00Z"}]}""").setResponseCode(201)
request.pathOnly() == "/api/proposals/21/vote" -> MockResponse().setResponseCode(204)
else -> null
} }
login()
val created = repository.createProposal(NewProposal("Více zásuvek", "Doplňme zásuvky ke stolům.", 3))
assertEquals(22, created.id)
assertEquals("Jana Nováková", created.authorName)
repository.vote(21, 1)
repository.vote(21, -1)
repository.vote(21, null)
assertJson("""{"title":"Více zásuvek","description":"Doplňme zásuvky ke stolům.","categoryId":3}""",
requests.single { it.pathOnly() == "/api/proposals" })
val votes = requests.filter { it.pathOnly() == "/api/proposals/21/vote" }
assertEquals(listOf("PUT", "PUT", "DELETE"), votes.map { it.method })
assertJson("""{"value":1}""", votes[0])
assertJson("""{"value":-1}""", votes[1])
assertEquals(0L, votes[2].bodySize)
}
@Test fun `notification message readAt and unread count map independently of loaded page`() = runBlocking {
serve { request -> when (request.pathOnly()) {
"/api/notifications" -> json("""{"items":[{"id":1,"type":"ISSUE_COMMENT_ADDED","title":"Nový komentář","message":"Správce odpověděl.","issueId":42,"proposalId":null,"createdAt":"2026-11-19T09:00:00Z","readAt":null},{"id":2,"type":"PROPOSAL_STATUS_CHANGED","title":"Návrh přijat","message":"Vedení přijalo návrh.","issueId":null,"proposalId":21,"createdAt":"2026-11-18T09:00:00Z","readAt":"2026-11-19T10:00:00Z"}],"totalCount":40,"page":2,"pageSize":20}""")
"/api/notifications/unread-count" -> json("""{"count":37}""")
"/api/notifications/1/read", "/api/notifications/read-all" -> MockResponse().setResponseCode(204)
else -> null
} }
login()
val notices = repository.notices(page = 2)
assertEquals("Správce odpověděl.", notices.items[0].text)
assertFalse(notices.items[0].isRead)
assertEquals(42, notices.items[0].issueId)
assertTrue(notices.items[1].isRead)
assertEquals(21, notices.items[1].proposalId)
assertEquals(40, notices.totalCount)
assertEquals(37, repository.unreadCount())
repository.readNotice(1)
repository.readAllNotices()
assertEquals("2", requests.single { it.pathOnly() == "/api/notifications" }.requestUrl!!.queryParameter("page"))
listOf("/api/notifications/1/read", "/api/notifications/read-all").forEach { path ->
assertEquals("POST", requests.single { it.pathOnly() == path }.method)
}
assertFalse(requests.any { it.pathOnly() in catalogPaths })
}
@Test fun `expired access token is proactively renewed once across different inbox requests`() = runBlocking {
val refreshes = AtomicInteger()
serve { request -> when (request.pathOnly()) {
"/api/auth/login" -> json(sessionJson(expiration = "2000-01-01T00:00:00Z"))
"/api/auth/refresh" -> { refreshes.incrementAndGet(); json(sessionJson(access = "new-access", refresh = "new-refresh")) }
"/api/issues", "/api/proposals", "/api/notifications" -> json(page(""))
"/api/notifications/unread-count" -> json("""{"count":0}""")
else -> null
} }
login()
val issues = async { repository.issues() }
val proposals = async { repository.proposals() }
val notices = async { repository.notices() }
val unread = async { repository.unreadCount() }
assertTrue(issues.await().items.isEmpty())
assertTrue(proposals.await().items.isEmpty())
assertTrue(notices.await().items.isEmpty())
assertEquals(0, unread.await())
assertEquals(1, refreshes.get())
requests.filter { !it.pathOnly().startsWith("/api/auth/") }.forEach {
assertEquals("Bearer new-access", it.getHeader("Authorization"))
}
}
private suspend fun login() { repository.login("[email protected]", "fixture-password") }
private suspend fun expectApiError(block: suspend () -> Unit): ApiException {
try { block() } catch (error: ApiException) { return error }
throw AssertionError("Expected ApiException")
}
private fun serve(route: (RecordedRequest) -> MockResponse?) {
server.dispatcher = object : Dispatcher() {
override fun dispatch(request: RecordedRequest): MockResponse {
requests += request
return route(request) ?: when (request.pathOnly()) {
"/api/auth/login" -> json(sessionJson())
"/api/buildings" -> json("""[{"id":1,"code":"A","name":"Budova A","address":null,"isActive":true}]""")
"/api/issue-categories" -> json("""[{"id":1,"name":"Technické vybavení","description":null,"isActive":true}]""")
"/api/proposal-categories" -> json("""[{"id":3,"name":"Prostředí","description":null,"isActive":true}]""")
else -> json("""{"status":404,"title":"Záznam neexistuje."}""").setResponseCode(404)
}
}
}
}
private fun assertJson(expected: String, request: RecordedRequest) {
assertEquals(Json.parseToJsonElement(expected), Json.parseToJsonElement(request.body.clone().readUtf8()))
assertEquals("Bearer old-access", request.getHeader("Authorization"))
}
private fun json(value: String) = MockResponse().setHeader("Content-Type", "application/json").setBody(value)
private fun page(items: String) = """{"items":[$items],"totalCount":${if (items.isBlank()) 0 else 40},"page":2,"pageSize":20}"""
private fun sessionJson(access: String = "old-access", refresh: String = "old-refresh", expiration: String = "2099-01-01T00:00:00Z", role: String = "STUDENT") =
"""{"accessToken":"$access","accessTokenExpiresAt":"$expiration","refreshToken":"$refresh","refreshTokenExpiresAt":"2099-02-01T00:00:00Z","user":{"id":1,"email":"[email protected]","firstName":"Jana","lastName":"Nováková","phone":null,"role":"$role","emailNotificationsEnabled":true}}"""
private val catalogPaths = setOf("/api/buildings", "/api/issue-categories", "/api/proposal-categories")
private val issueSummary = """{"id":42,"title":"Projektor","categoryId":1,"buildingId":1,"locationDetail":"Učebna A-205","status":"IN_PROGRESS","priority":"HIGH","reporterId":1,"assigneeId":2,"createdAt":"2026-11-19T08:00:00Z"}"""
private val issueDetail = """{"id":42,"title":"Projektor","description":"Popis problému","categoryId":1,"buildingId":1,"locationDetail":"Učebna A-205","status":"IN_PROGRESS","priority":"HIGH","reporterId":1,"assigneeId":2,"createdAt":"2026-11-19T08:00:00Z","rowVersion":7,"allowedActions":["COMMENT","ADD_ATTACHMENTS"],"attachments":[{"id":8,"fileName":"foto.png","contentType":"image/png","sizeBytes":68,"createdAt":"2026-11-19T08:00:00Z"}]}"""
private fun receivedIssueDetail(version: Int) = """{"id":42,"title":"Projektor","description":"Popis problému","categoryId":1,"buildingId":1,"locationDetail":"Učebna A-205","status":"RECEIVED","priority":"NORMAL","reporterId":1,"assigneeId":null,"createdAt":"2026-11-19T08:00:00Z","rowVersion":$version,"allowedActions":["EDIT","COMMENT","ADD_ATTACHMENTS"],"attachments":[]}"""
private val issueEvents = """[{"id":1,"eventType":"CREATED","fromStatus":null,"toStatus":"RECEIVED","actorId":1,"actorName":"Jana Nováková","note":null,"occurredAt":"2026-11-19T08:00:00Z"},{"id":2,"eventType":"COMMENTED","fromStatus":null,"toStatus":"IN_PROGRESS","actorId":2,"actorName":"Petr Správce","note":"Objednal jsem novou lampu.","occurredAt":"2026-11-19T09:00:00Z"}]"""
private val proposalSummary = """{"id":21,"title":"Více zásuvek","categoryId":3,"authorId":5,"status":"IMPLEMENTED","createdAt":"2026-11-17T08:00:00Z","votesFor":3000000002,"votesAgainst":2,"score":3000000000,"myVote":-1}"""
private val proposalDetail = proposalSummary.dropLast(1) + ""","description":"Doplňme zásuvky ke stolům.","events":[{"id":1,"eventType":"CREATED","fromStatus":null,"toStatus":"SUBMITTED","actorId":5,"actorName":"Adam Autor","note":null,"occurredAt":"2026-11-17T08:00:00Z"},{"id":2,"eventType":"STATUS_CHANGED","fromStatus":"SUBMITTED","toStatus":"UNDER_REVIEW","actorId":2,"actorName":"Věra Vedení","note":"Prověřujeme možnosti.","occurredAt":"2026-11-18T08:00:00Z"},{"id":3,"eventType":"STATUS_CHANGED","fromStatus":"UNDER_REVIEW","toStatus":"ACCEPTED","actorId":2,"actorName":"Věra Vedení","note":"Instalace byla schválena.","occurredAt":"2026-11-18T12:00:00Z"},{"id":4,"eventType":"STATUS_CHANGED","fromStatus":"ACCEPTED","toStatus":"IMPLEMENTED","actorId":2,"actorName":"Věra Vedení","note":null,"occurredAt":"2026-11-19T08:00:00Z"}]}"""
}
private fun RecordedRequest.pathOnly() = requestUrl!!.encodedPath
private class ContractSessionStore : SessionPersistence {
private var session: AuthSession? = null
override fun read() = session
override fun write(session: AuthSession) { this.session = session }
override fun clear() { session = null }
}
@@ -42,13 +42,29 @@ class DemoRepositoryTest {
@Test fun `new issue persists within demo session and notifications can be marked read`() = runBlocking { @Test fun `new issue persists within demo session and notifications can be marked read`() = runBlocking {
val repository = DemoRepository() val repository = DemoRepository()
val unreadBefore = repository.unreadCount()
val created = repository.createIssue(NewIssue("Rozbitá židle", "Ulomená noha židle", 5, 1, "A-101")) val created = repository.createIssue(NewIssue("Rozbitá židle", "Ulomená noha židle", 5, 1, "A-101"))
assertEquals(created, repository.issue(created.id)) assertEquals(created, repository.issue(created.id))
assertEquals("RECEIVED", created.status) assertEquals("RECEIVED", created.status)
assertTrue(repository.issues(query = "židle").items.any { it.id == created.id }) assertTrue(repository.issues(query = "židle").items.any { it.id == created.id })
assertTrue(repository.notices().items.any { !it.isRead && it.issueId == created.id }) assertTrue(repository.notices().items.any { !it.isRead && it.issueId == created.id })
assertEquals(unreadBefore + 1, repository.unreadCount())
repository.readAllNotices() repository.readAllNotices()
assertTrue(repository.notices().items.all { it.isRead }) assertTrue(repository.notices().items.all { it.isRead })
assertEquals(0, repository.unreadCount())
}
@Test fun `closed proposals reject changing and removing an existing vote just like the server`() = runBlocking {
val repository = DemoRepository()
val closed = repository.proposal(24)
assertEquals("IMPLEMENTED", closed.status)
assertEquals(1, closed.myVote)
listOf(1, -1, null).forEach { value ->
try { repository.vote(closed.id, value); fail("Closed voting must reject changes and removal") }
catch (error: ApiException) { assertEquals(409, error.status) }
}
assertEquals(closed.score, repository.proposal(closed.id).score)
assertEquals(closed.myVote, repository.proposal(closed.id).myVote)
} }
@Test fun `upload validation rejects oversized disallowed and too many files`() { @Test fun `upload validation rejects oversized disallowed and too many files`() {
@@ -57,6 +73,9 @@ class DemoRepositoryTest {
try { validateUploads(List(6) { file }); fail("Too many files") } catch (_: IllegalArgumentException) { } try { validateUploads(List(6) { file }); fail("Too many files") } catch (_: IllegalArgumentException) { }
try { validateUploads(listOf(file.copy(mimeType = "application/octet-stream"))); fail("Disallowed type") } catch (_: IllegalArgumentException) { } try { validateUploads(listOf(file.copy(mimeType = "application/octet-stream"))); fail("Disallowed type") } catch (_: IllegalArgumentException) { }
try { validateUploads(listOf(file.copy(bytes = ByteArray(10 * 1024 * 1024 + 1)))); fail("Oversized file") } catch (_: IllegalArgumentException) { } try { validateUploads(listOf(file.copy(bytes = ByteArray(10 * 1024 * 1024 + 1)))); fail("Oversized file") } catch (_: IllegalArgumentException) { }
try { validateUploads(listOf(file.copy(name = "photo.heif", mimeType = "image/heic"))); fail("Server does not accept HEIF extensions") } catch (_: IllegalArgumentException) { }
try { validateUploads(listOf(file.copy(name = "photo.png"))); fail("MIME must match the extension") } catch (_: IllegalArgumentException) { }
try { validateUploads(listOf(file.copy(name = "bad\nname.jpg"))); fail("Control characters in filenames") } catch (_: IllegalArgumentException) { }
} }
@Test fun `received issue edit enforces version and later states reject edits`() = runBlocking { @Test fun `received issue edit enforces version and later states reject edits`() = runBlocking {
@@ -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)
}
@@ -65,13 +65,14 @@ class RepositoryTest {
assertEquals("new-refresh", store.session?.refreshToken) assertEquals("new-refresh", store.session?.refreshToken)
} }
@Test fun `missing planned endpoints report unsupported backend and never supply demo items`() = runBlocking { @Test fun `missing resource preserves server problem details and does not imply unsupported backend`() = runBlocking {
server.enqueue(json(sessionJson())) server.enqueue(json(sessionJson()))
repository.login("[email protected]", "password") repository.login("[email protected]", "password")
server.enqueue(MockResponse().setResponseCode(404)) server.enqueue(json("""{"status":404,"title":"Závada neexistuje."}""").setResponseCode(404))
val error = expectApiError { repository.issues() } val error = expectApiError { repository.issue(987) }
assertEquals(404, error.status) assertEquals(404, error.status)
assertTrue(error.message!!.contains("Backend musí doplnit API")) assertEquals("Závada neexistuje.", error.message)
assertFalse(error.message!!.contains("Backend musí doplnit API"))
assertNotNull(store.session) assertNotNull(store.session)
} }
@@ -153,19 +154,6 @@ class RepositoryTest {
assertEquals(413, expectApiError { repository.downloadAttachment(8) }.status) assertEquals(413, expectApiError { repository.downloadAttachment(8) }.status)
} }
@Test fun `issue edit uses PUT and includes optimistic version in flat payload`() = runBlocking {
server.enqueue(json(sessionJson()))
repository.login("[email protected]", "password")
server.takeRequest()
server.enqueue(json("""{"id":102,"title":"Nový název","description":"Nový popis","status":"RECEIVED","categoryId":5,"categoryName":"Ostatní","reporterId":1,"reporterName":"Jana","createdAt":"2026-11-01T00:00:00Z","rowVersion":2}"""))
val edited = repository.updateIssue(102, NewIssue("Nový název", "Nový popis", 5, 1, "A-101"), 1)
assertEquals(2, edited.rowVersion)
val request = server.takeRequest()
assertEquals("PUT", request.method)
assertEquals("/api/issues/102", request.path)
assertEquals("{\"title\":\"Nový název\",\"description\":\"Nový popis\",\"categoryId\":5,\"buildingId\":1,\"location\":\"A-101\",\"rowVersion\":1}", request.body.readUtf8())
}
private suspend fun expectApiError(block: suspend () -> Unit): ApiException { private suspend fun expectApiError(block: suspend () -> Unit): ApiException {
try { block() } catch (error: ApiException) { return error } try { block() } catch (error: ApiException) { return error }
throw AssertionError("Expected ApiException") throw AssertionError("Expected ApiException")
@@ -0,0 +1,155 @@
package cz.ntbug.mobile.integration
import cz.ntbug.mobile.data.*
import kotlinx.coroutines.runBlocking
import kotlinx.serialization.json.buildJsonObject
import kotlinx.serialization.json.put
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.RequestBody.Companion.toRequestBody
import org.junit.Assert.*
import org.junit.Assume.assumeTrue
import org.junit.Test
import java.net.URI
import java.util.Base64
/** Opt-in round trip against an isolated copy of the real API and MariaDB, not a mock. */
class LiveBackendTest {
@Test fun actualBackendSupportsMobileWorkflows(): Unit = runBlocking {
val baseUrl = System.getenv("NTBUG_LIVE_API_URL")
assumeTrue("Set NTBUG_LIVE_API_URL for a disposable local test server.", !baseUrl.isNullOrBlank())
require(URI(baseUrl!!).host in setOf("localhost", "127.0.0.1")) { "Live tests require a local test server." }
val password = requiredEnv("NTBUG_LIVE_PASSWORD")
val reporterStore = LiveSessionStore()
val managerStore = LiveSessionStore()
val staffStore = LiveSessionStore()
val reporter = RemoteRepository(baseUrl, reporterStore)
val manager = RemoteRepository(baseUrl, managerStore)
val staff = RemoteRepository(baseUrl, staffStore)
val actor = reporter.login(requiredEnv("NTBUG_LIVE_REPORTER"), password)
assertEquals("MANAGEMENT", manager.login(requiredEnv("NTBUG_LIVE_MANAGER"), password).role)
val assignee = staff.login(requiredEnv("NTBUG_LIVE_STAFF"), password)
assertEquals("FACILITY_MANAGER", assignee.role)
val suffix = System.nanoTime().toString()
try {
val catalogs = reporter.catalogs()
val category = catalogs.issueCategories.first { it.isActive }
val created = reporter.createIssue(NewIssue("Mobilní test $suffix", "Ověření skutečného klienta.", category.id, null, "Studovna A-101"))
assertEquals(0, created.rowVersion)
assertEquals("Studovna A-101", created.location)
assertEquals(category.name, created.categoryName)
assertEquals(actor.id, created.reporterId)
assertTrue(created.allowedActions.containsAll(listOf("COMMENT", "ADD_ATTACHMENTS", "EDIT")))
assertTrue(reporter.issues(query = suffix).items.any { it.id == created.id })
val original = reporter.issue(created.id)
assertEquals(actor.firstName + " " + actor.lastName, original.events.first().authorName)
val edited = reporter.updateIssue(created.id,
NewIssue("Upravený mobilní test $suffix", "Doplněný popis.", category.id, null, "Studovna A-102"), original.rowVersion)
assertEquals("Studovna A-102", edited.location)
expectStatus(409) {
reporter.updateIssue(created.id, NewIssue("Stará verze", "Nemá přepsat novější.", category.id, null, ""), original.rowVersion)
}
reporter.comment(created.id, "Komentář z Android klienta.")
val png = Base64.getDecoder().decode("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAusB9Y9ZlS0AAAAASUVORK5CYII=")
reporter.addAttachments(created.id, listOf(Upload("mobilni-fotografie.png", "image/png", png)))
var detail = reporter.issue(created.id)
assertTrue(detail.events.any { it.type == "COMMENTED" && it.text == "Komentář z Android klienta." })
val attachment = detail.attachments.single()
val download = reporter.downloadAttachment(attachment.id)
assertEquals(attachment.fileName, download.name)
assertEquals("image/png", download.mimeType)
assertArrayEquals(png, download.bytes)
// Assignment is a web management action; mobile then exercises the assignee queue.
managementPost(baseUrl, managerStore, "issues/${detail.id}/assign", buildJsonObject {
put("assigneeId", assignee.id); put("rowVersion", detail.rowVersion); put("priority", "HIGH")
}.toString())
assertTrue(staff.issues(assigned = true).items.any { it.id == detail.id })
detail = staff.issue(detail.id)
assertTrue("START_WORK" in detail.allowedActions)
staff.issueAction(detail.id, "start", detail.rowVersion)
staff.comment(detail.id, "Oprava byla provedena.")
detail = staff.issue(detail.id)
staff.issueAction(detail.id, "submit-for-verification", detail.rowVersion, "Prosím o ověření.")
detail = reporter.issue(detail.id)
assertEquals("PENDING_VERIFICATION", detail.status)
reporter.issueAction(detail.id, "reopen", detail.rowVersion, "Ještě je potřeba zkontrolovat kabel.")
detail = staff.issue(detail.id)
assertEquals("IN_PROGRESS", detail.status)
staff.issueAction(detail.id, "submit-for-verification", detail.rowVersion, "Kabel je vyměněný.")
detail = reporter.issue(detail.id)
reporter.issueAction(detail.id, "confirm", detail.rowVersion)
detail = reporter.issue(detail.id)
assertEquals("RESOLVED", detail.status)
assertTrue(detail.allowedActions.isEmpty())
expectStatus(409) { reporter.comment(detail.id, "Uzavřená závada.") }
val proposalCategory = catalogs.proposalCategories.first { it.isActive }
val proposal = reporter.createProposal(NewProposal("Návrh $suffix", "Zlepšení studovny.", proposalCategory.id))
assertEquals(0L, proposal.score)
assertEquals(proposalCategory.name, proposal.categoryName)
assertTrue(reporter.proposals(query = suffix).items.any { it.id == proposal.id })
expectStatus(403) { reporter.vote(proposal.id, 1) }
manager.vote(proposal.id, 1)
assertEquals(1L, manager.proposal(proposal.id).score)
manager.vote(proposal.id, -1)
assertEquals(-1L, manager.proposal(proposal.id).score)
manager.vote(proposal.id, null)
assertNull(manager.proposal(proposal.id).myVote)
managementPost(baseUrl, managerStore, "proposals/${proposal.id}/status", buildJsonObject {
put("status", "UNDER_REVIEW"); put("note", "Posuzujeme možnosti.")
}.toString())
managementPost(baseUrl, managerStore, "proposals/${proposal.id}/status", buildJsonObject {
put("status", "ACCEPTED"); put("note", "Realizace schválena.")
}.toString())
val accepted = reporter.proposal(proposal.id)
assertEquals("ACCEPTED", accepted.status)
assertEquals("Realizace schválena.", accepted.note)
assertTrue(accepted.events.size >= 3)
expectStatus(409) { manager.vote(proposal.id, 1) }
val unread = reporter.unreadCount()
assertTrue(unread > 0)
val notices = reporter.notices().items
assertTrue(notices.any { it.text.isNotBlank() && !it.isRead })
val notice = notices.first { !it.isRead }
reporter.readNotice(notice.id)
assertEquals(unread - 1, reporter.unreadCount())
reporter.readNotice(notice.id)
assertEquals(unread - 1, reporter.unreadCount())
assertTrue(reporter.notices().items.first { it.id == notice.id }.isRead)
reporter.readAllNotices()
assertEquals(0, reporter.unreadCount())
assertTrue(reporter.notices().items.all { it.isRead })
expectStatus(404) { reporter.issue(Int.MAX_VALUE) }
} finally {
listOf(reporter, manager, staff).forEach { repository -> runCatching { repository.logout() } }
}
assertNull(reporterStore.read())
assertNull(managerStore.read())
assertNull(staffStore.read())
}
private fun managementPost(baseUrl: String, store: LiveSessionStore, path: String, body: String) {
val request = Request.Builder().url(normalizeBaseUrl(baseUrl) + path)
.header("Authorization", "Bearer ${store.read()!!.accessToken}")
.post(body.toRequestBody("application/json".toMediaType())).build()
OkHttpClient().newCall(request).execute().use { response ->
assertEquals("Management fixture action $path: ${response.body?.string()}", 200, response.code)
}
}
private suspend fun expectStatus(status: Int, action: suspend () -> Unit) {
try { action(); fail("Expected HTTP $status") }
catch (error: ApiException) { assertEquals(error.message, status, error.status) }
}
private fun requiredEnv(name: String) = requireNotNull(System.getenv(name)?.takeIf { it.isNotBlank() }) { "Missing $name for the isolated test fixture." }
}
private class LiveSessionStore : SessionPersistence {
private var session: AuthSession? = null
override fun read() = session
override fun write(session: AuthSession) { this.session = session }
override fun clear() { session = null }
}
@@ -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 })
}
}